From 9da59323072506ec18992aff497dc3a35bac4d9a Mon Sep 17 00:00:00 2001 From: Michael Vorburger Date: Sun, 14 Jun 2020 17:55:15 +0200 Subject: [PATCH] bulk auto reformat ca. 2900 files using ./gradlew :spotlessApply [FINERACT-1006] --- fineract-provider/build.gradle | 102 +- .../config/checkstyle/checkstyle.xml | 24 +- fineract-provider/dependencies.gradle | 40 +- .../properties/oauth/application.properties | 2 +- .../AccountNumberPreferencesTest.java | 109 +- .../integrationtests/AccountTransferTest.java | 28 +- .../AccountingScenarioIntegrationTest.java | 111 +- .../ActuatorIntegrationTest.java | 5 +- .../integrationtests/BatchApiTest.java | 20 +- .../BatchRequestsIntegrationTest.java | 5 +- .../CenterIntegrationTest.java | 32 +- .../ClientLoanIntegrationTest.java | 1483 ++--- .../ClientSavingsIntegrationTest.java | 582 +- .../integrationtests/ClientStatusChecker.java | 16 +- ...ndoRejectAndWithdrawalIntegrationTest.java | 39 +- .../ConcurrencyIntegrationTest.java | 12 +- .../integrationtests/CurrenciesTest.java | 3 +- .../CurrencyIntegrationTest.java | 1 - .../DisbursalAndRepaymentScheduleTest.java | 586 +- .../ExternalServicesConfigurationTest.java | 9 +- .../FinancialActivityAccountsTest.java | 14 +- .../integrationtests/FixedDepositTest.java | 460 +- ...SavingsInterestPostingIntegrationTest.java | 17 +- .../FundsIntegrationTest.java | 100 +- ...hargedFromDateSameAsDisbursalDateTest.java | 28 +- .../GlobalConfigurationTest.java | 58 +- .../GroupLoanIntegrationTest.java | 49 +- .../GroupSavingsIntegrationTest.java | 49 +- .../fineract/integrationtests/GroupTest.java | 5 +- .../integrationtests/HookIntegrationTest.java | 13 +- .../LoanApplicationApprovalTest.java | 26 +- .../LoanApplicationUndoLastTrancheTest.java | 19 +- .../LoanDisbursalDateValidationTest.java | 35 +- ...oanDisbursementDetailsIntegrationTest.java | 57 +- ...RepaymentRescheduleAtDisbursementTest.java | 34 +- .../LoanRescheduleRequestTest.java | 55 +- .../LoanReschedulingWithinCenterTest.java | 44 +- ...iveInterestAndWriteOffIntegrationTest.java | 19 +- ...BetweenDisbursalAndFirstRepaymentTest.java | 2 +- .../integrationtests/NotificationApiTest.java | 3 +- .../OfficeIntegrationTest.java | 11 +- .../PasswordPreferencesIntegrationTest.java | 7 +- .../fineract/integrationtests/RatesTest.java | 52 +- .../RecurringDepositTest.java | 515 +- .../fineract/integrationtests/RolesTest.java | 3 +- .../integrationtests/SchedulerJobsTest.java | 11 +- .../SchedulerJobsTestResults.java | 1913 ++++--- .../SkipRepaymentOnMonthFirstTest.java | 45 +- .../integrationtests/StaffImageApiTest.java | 4 +- .../fineract/integrationtests/StaffTest.java | 6 +- .../SurveyIntegrationTest.java | 2 +- .../integrationtests/SystemCodeTest.java | 15 +- .../TemplateIntegrationTest.java | 6 +- .../UserAdministrationTest.java | 29 +- .../integrationtests/XBRLIntegrationTest.java | 1 + .../client/ClientEntityImportHandlerTest.java | 94 +- .../loan/LoanImportHandlerTest.java | 88 +- .../office/OfficeImportHandlerTest.java | 52 +- .../savings/SavingsImportHandlerTest.java | 89 +- .../ClientEntityWorkbookPopulatorTest.java | 37 +- .../loan/LoanWorkbookPopulatorTest.java | 74 +- .../office/OfficeWorkBookPopulatorTest.java | 21 +- .../savings/SavingsWorkbookPopulateTest.java | 57 +- .../integrationtests/common/BatchHelper.java | 15 +- .../common/CalendarHelper.java | 17 +- .../integrationtests/common/CenterDomain.java | 20 +- .../integrationtests/common/CenterHelper.java | 32 +- .../common/ClientChargesTest.java | 4 +- .../integrationtests/common/ClientHelper.java | 223 +- .../common/CommonConstants.java | 1 - .../common/CurrenciesHelper.java | 7 +- .../common/CurrencyDomain.java | 8 +- .../ExternalServicesConfigurationHelper.java | 22 +- .../common/GlobalConfigurationHelper.java | 74 +- .../integrationtests/common/GroupHelper.java | 71 +- .../common/HolidayHelper.java | 10 +- .../integrationtests/common/HookHelper.java | 16 +- .../integrationtests/common/ImageHelper.java | 4 +- .../common/LoanRescheduleRequestHelper.java | 1 + .../common/NotificationHelper.java | 3 +- .../integrationtests/common/OfficeDomain.java | 33 +- .../integrationtests/common/OfficeHelper.java | 50 +- .../common/PasswordPreferencesHelper.java | 26 +- .../common/PaymentTypeHelper.java | 42 +- .../common/ProvisioningIntegrationTest.java | 131 +- .../common/SchedulerJobHelper.java | 55 +- .../common/StandingInstructionsHelper.java | 16 +- .../integrationtests/common/SurveyHelper.java | 17 +- .../common/TaxComponentHelper.java | 5 +- .../common/TaxGroupHelper.java | 6 +- .../integrationtests/common/Utils.java | 109 +- .../common/WorkingDaysHelper.java | 8 +- .../common/accounting/Account.java | 1 + .../common/accounting/AccountHelper.java | 15 +- .../FinancialActivityAccountHelper.java | 11 +- .../common/accounting/JournalEntry.java | 1 + .../common/charges/ChargesHelper.java | 99 +- .../FixedDepositAccountHelper.java | 117 +- .../FixedDepositAccountStatusChecker.java | 26 +- .../FixedDepositProductHelper.java | 16 +- .../common/funds/FundsHelper.java | 21 +- .../common/funds/FundsResourceHandler.java | 21 +- .../loans/LoanApplicationTestBuilder.java | 29 +- .../loans/LoanDisbursementTestBuilder.java | 48 +- .../common/loans/LoanProductTestBuilder.java | 26 +- .../common/loans/LoanTransactionHelper.java | 238 +- .../common/organisation/CampaignsHelper.java | 62 +- .../common/organisation/Currency.java | 12 +- .../common/organisation/CurrencyHelper.java | 17 +- .../EntityDatatableChecksHelper.java | 13 +- .../EntityDatatableChecksIntegrationTest.java | 1 + .../common/organisation/StaffHelper.java | 39 +- .../provisioning/ProvisioningHelper.java | 10 +- .../ProvisioningTransactionHelper.java | 37 +- .../common/rates/RatesHelper.java | 106 +- .../RecurringDepositAccountHelper.java | 171 +- .../RecurringDepositAccountStatusChecker.java | 28 +- .../RecurringDepositProductHelper.java | 10 +- .../common/report/ReportData.java | 4 +- .../common/savings/AccountTransferHelper.java | 31 +- .../common/savings/SavingsAccountHelper.java | 117 +- .../SavingsApplicationTestBuilder.java | 26 +- .../common/savings/SavingsProductHelper.java | 11 +- .../common/savings/SavingsStatusChecker.java | 56 +- .../shares/DividendsIntegrationTests.java | 107 +- .../common/shares/ShareAccountHelper.java | 103 +- .../shares/ShareAccountIntegrationTests.java | 217 +- .../shares/ShareAccountTransactionHelper.java | 4 +- .../ShareDividendsTransactionHelper.java | 25 +- .../common/shares/ShareProductHelper.java | 138 +- .../shares/ShareProductTransactionHelper.java | 8 +- .../AccountNumberPreferencesHelper.java | 151 +- .../AccountNumberPreferencesTestBuilder.java | 1 + .../common/system/CodeHelper.java | 164 +- .../common/system/DatatableHelper.java | 11 +- .../interoperation/InteropHelper.java | 12 +- .../interoperation/InteropTest.java | 40 +- .../guarantor/GuarantorHelper.java | 4 +- .../loanaccount/guarantor/GuarantorTest.java | 122 +- .../guarantor/GuarantorTestBuilder.java | 3 +- .../useradministration/roles/RolesHelper.java | 11 +- .../useradministration/users/UserHelper.java | 55 +- ...bleInstallmentsDecliningBalanceHelper.java | 42 +- .../VariableInstallmentsFlatHelper.java | 29 +- .../VariableInstallmentsIntegrationTest.java | 555 +- .../VariableIntallmentsTransactionHelper.java | 17 +- .../apache/fineract/ServerApplication.java | 13 +- .../api/AccrualAccountingApiResource.java | 17 +- .../AccrualAccountingApiResourceSwagger.java | 2 + .../ExecutePeriodicAccrualCommandHandler.java | 2 +- .../AccrualAccountingDataValidator.java | 5 +- ...ualAccountingWritePlatformServiceImpl.java | 3 +- .../closure/api/GLClosureJsonInputParams.java | 3 +- .../closure/api/GLClosuresApiResource.java | 45 +- .../api/GLClosuresApiResourceSwagger.java | 19 +- .../closure/command/GLClosureCommand.java | 14 +- .../closure/data/GLClosureData.java | 2 +- .../accounting/closure/domain/GLClosure.java | 5 +- .../GLClosureDuplicateException.java | 7 +- .../GLClosureInvalidDeleteException.java | 2 +- .../exception/GLClosureInvalidException.java | 7 +- .../exception/GLClosureNotFoundException.java | 2 +- .../CreateGLClosureCommandHandler.java | 2 +- .../DeleteGLClosureCommandHandler.java | 2 +- .../UpdateGLClosureCommandHandler.java | 2 +- ...ClosureCommandFromApiJsonDeserializer.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 22 +- .../common/AccountingConstants.java | 110 +- ...AccountingDropdownReadPlatformService.java | 2 +- ...untingDropdownReadPlatformServiceImpl.java | 2 +- .../accounting/common/AccountingRuleType.java | 2 +- .../FinancialActivityAccountsApiResource.java | 40 +- ...ialActivityAccountsApiResourceSwagger.java | 35 +- .../FinancialActivityAccountsConstants.java | 6 +- ...ancialActivityAccountsJsonInputParams.java | 3 +- .../data/FinancialActivityAccountData.java | 3 +- .../domain/FinancialActivityAccount.java | 2 +- .../FinancialActivityAccountRepository.java | 4 +- ...ncialActivityAccountRepositoryWrapper.java | 3 +- ...inancialActivityAccountFoundException.java | 2 +- ...ancialActivityAccountInvalidException.java | 14 +- ...ncialActivityAccountNotFoundException.java | 7 +- ...CreateFinancialActivityAccountHandler.java | 2 +- ...inancialActivityAccountCommandHandler.java | 2 +- ...inancialActivityAccountCommandHandler.java | 2 +- ...FinancialActivityAccountDataValidator.java | 8 +- ...ialActivityAccountReadPlatformService.java | 2 +- ...ctivityAccountReadPlatformServiceImpl.java | 3 +- ...alActivityAccountWritePlatformService.java | 2 +- ...tivityAccountWritePlatformServiceImpl.java | 25 +- .../api/GLAccountJsonInputParams.java | 7 +- .../glaccount/api/GLAccountsApiResource.java | 109 +- .../api/GLAccountsApiResourceSwagger.java | 41 +- .../glaccount/command/GLAccountCommand.java | 14 +- .../glaccount/data/GLAccountData.java | 22 +- .../glaccount/domain/GLAccount.java | 4 +- .../domain/GLAccountRepositoryWrapper.java | 2 +- .../glaccount/domain/GLAccountType.java | 34 +- .../glaccount/domain/TrialBalance.java | 25 +- .../domain/TrialBalanceRepository.java | 5 +- .../domain/TrialBalanceRepositoryWrapper.java | 17 +- .../exception/GLAccountDisableException.java | 6 +- .../GLAccountDuplicateException.java | 2 +- ...AccountInvalidClassificationException.java | 2 +- .../GLAccountInvalidDeleteException.java | 11 +- .../GLAccountInvalidParentException.java | 6 +- .../GLAccountInvalidUpdateException.java | 11 +- .../GLAccountInvalidUsageException.java | 2 +- .../exception/GLAccountNotFoundException.java | 2 +- .../CreateGLAccountCommandHandler.java | 2 +- .../DeleteGLAccountCommandHandler.java | 2 +- .../UpdateGLAccountCommandHandler.java | 2 +- ...AccountCommandFromApiJsonDeserializer.java | 6 +- .../service/GLAccountReadPlatformService.java | 2 +- .../GLAccountReadPlatformServiceImpl.java | 20 +- ...WritePlatformServiceJpaRepositoryImpl.java | 52 +- .../api/JournalEntriesApiResource.java | 115 +- .../api/JournalEntriesApiResourceSwagger.java | 10 +- .../api/JournalEntryJsonInputParams.java | 12 +- .../command/JournalEntryCommand.java | 8 +- .../SingleDebitOrCreditEntryCommand.java | 2 +- .../journalentry/data/CreditDebit.java | 1 + .../journalentry/data/JournalEntryData.java | 58 +- .../data/JournalEntryDataValidator.java | 6 +- .../journalentry/data/LoanTransactionDTO.java | 12 +- .../data/TransactionTypeEnumData.java | 2 +- .../journalentry/domain/JournalEntry.java | 4 +- .../domain/JournalEntryRepository.java | 24 +- .../JournalEntriesNotFoundException.java | 7 +- .../JournalEntryInvalidException.java | 11 +- .../JournalEntryNotFoundException.java | 7 +- .../JournalEntryRuntimeException.java | 1 - .../CreateJournalEntryCommandHandler.java | 2 +- .../ReverseJournalEntryCommandHandler.java | 2 +- ...alEntryCommandFromApiJsonDeserializer.java | 13 +- .../service/AccountingProcessorHelper.java | 188 +- ...ccrualBasedAccountingProcessorForLoan.java | 59 +- .../CashBasedAccountingProcessorForLoan.java | 66 +- ...ashBasedAccountingProcessorForSavings.java | 61 +- ...CashBasedAccountingProcessorForShares.java | 10 +- .../JournalEntryReadPlatformService.java | 2 +- .../JournalEntryReadPlatformServiceImpl.java | 51 +- ...lEntryRunningBalanceUpdateServiceImpl.java | 54 +- .../JournalEntryWritePlatformService.java | 4 +- ...WritePlatformServiceJpaRepositoryImpl.java | 113 +- .../domain/PortfolioProductType.java | 1 + .../domain/ProductToGLAccountMapping.java | 15 +- .../ProductToGLAccountMappingRepository.java | 21 +- ...uctToGLAccountMappingInvalidException.java | 9 +- ...ctToGLAccountMappingNotFoundException.java | 2 +- ...AccountMappingFromApiJsonDeserializer.java | 173 +- .../LoanProductToGLAccountMappingHelper.java | 102 +- .../ProductToGLAccountMappingHelper.java | 83 +- ...ToGLAccountMappingReadPlatformService.java | 2 +- ...AccountMappingReadPlatformServiceImpl.java | 20 +- ...oGLAccountMappingWritePlatformService.java | 2 +- ...ccountMappingWritePlatformServiceImpl.java | 34 +- ...avingsProductToGLAccountMappingHelper.java | 51 +- .../ShareProductToGLAccountMappingHelper.java | 33 +- .../api/ProvisioningEntriesApiResource.java | 52 +- ...ProvisioningEntriesApiResourceSwagger.java | 15 +- .../ProvisioningEntriesApiConstants.java | 8 +- .../LoanProductProvisioningEntryData.java | 64 +- .../data/ProvisioningEntryData.java | 48 +- .../domain/LoanProductProvisioningEntry.java | 66 +- .../domain/ProvisioningEntry.java | 25 +- .../domain/ProvisioningEntryRepository.java | 4 +- ...NoProvisioningCriteriaDefinitionFound.java | 1 - ...visioningEntryAlreadyCreatedException.java | 4 +- .../ProvisioningEntryNotfoundException.java | 1 - ...visioningEntriesRequestCommandHandler.java | 5 +- ...ngJournalEntriesRequestCommandHandler.java | 5 +- ...rovisioningEntryRequestCommandHandler.java | 7 +- ...ningEntriesDefinitionJsonDeserializer.java | 17 +- ...rovisioningEntriesReadPlatformService.java | 15 +- ...sioningEntriesReadPlatformServiceImpl.java | 22 +- ...ovisioningEntriesWritePlatformService.java | 5 +- ...WritePlatformServiceJpaRepositoryImpl.java | 45 +- .../rule/api/AccountingRuleApiResource.java | 81 +- .../api/AccountingRuleApiResourceSwagger.java | 18 +- .../api/AccountingRuleJsonInputParams.java | 6 +- .../rule/data/AccountingRuleData.java | 2 +- .../rule/domain/AccountingRule.java | 11 +- .../rule/domain/AccountingTagRule.java | 3 +- .../AccountingRuleDataException.java | 4 +- .../AccountingRuleDuplicateException.java | 2 +- .../AccountingRuleInvalidDeleteException.java | 2 +- .../AccountingRuleInvalidException.java | 7 +- .../AccountingRuleNotFoundException.java | 2 +- .../CreateAccountingRuleCommandHandler.java | 2 +- .../DeleteAccountingRuleCommandHandler.java | 2 +- .../UpdateAccountingRuleCommandHandler.java | 2 +- ...ingRuleCommandFromApiJsonDeserializer.java | 36 +- ...AccountingRuleReadPlatformServiceImpl.java | 19 +- ...WritePlatformServiceJpaRepositoryImpl.java | 13 +- .../TrialBalanceNotFoundException.java | 8 +- .../adhocquery/api/AdHocApiResource.java | 26 +- .../adhocquery/api/AdHocJsonInputParams.java | 9 +- .../fineract/adhocquery/data/AdHocData.java | 48 +- .../fineract/adhocquery/domain/AdHoc.java | 41 +- .../adhocquery/domain/ReportRunFrequency.java | 13 +- .../exception/AdHocNotFoundException.java | 5 +- .../handler/CreateAdHocCommandHandler.java | 2 +- .../handler/DeleteAdHocCommandHandler.java | 2 +- .../handler/UpdateAdHocCommandHandler.java | 2 +- .../service/AdHocDataValidator.java | 23 +- .../service/AdHocReadPlatformService.java | 3 +- .../service/AdHocReadPlatformServiceImpl.java | 24 +- .../AdHocScheduledJobRunnerService.java | 1 + .../AdHocScheduledJobRunnerServiceImpl.java | 32 +- .../service/AdHocWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 8 +- .../fineract/batch/api/BatchApiResource.java | 29 +- .../batch/api/BatchApiResourceSwagger.java | 7 +- .../batch/command/CommandContext.java | 35 +- .../command/CommandStrategyProvider.java | 20 +- .../ActivateClientCommandStrategy.java | 9 +- .../internal/ApplyLoanCommandStrategy.java | 8 +- .../internal/ApplySavingsCommandStrategy.java | 10 +- .../internal/ApproveLoanCommandStrategy.java | 20 +- .../ApproveLoanRescheduleCommandStrategy.java | 3 +- .../CollectChargesCommandStrategy.java | 8 +- .../internal/CreateChargeCommandStrategy.java | 13 +- .../internal/CreateClientCommandStrategy.java | 4 +- .../internal/DisburseLoanCommandStrategy.java | 18 +- .../internal/RepayLoanCommandStrategy.java | 11 +- .../ClientDetailsNotFoundException.java | 2 +- .../batch/exception/ErrorHandler.java | 15 +- .../serialization/BatchRequestJsonHelper.java | 4 +- .../batch/service/BatchApiService.java | 10 +- .../batch/service/BatchApiServiceImpl.java | 57 +- .../batch/service/ResolutionHelper.java | 4 +- .../commands/annotation/CommandType.java | 3 +- .../commands/api/AuditsApiResource.java | 65 +- .../api/MakercheckersApiResource.java | 53 +- .../api/MakercheckersApiResourceSwagger.java | 14 +- .../fineract/commands/data/AuditData.java | 6 +- .../commands/data/AuditSearchData.java | 2 +- .../commands/data/ProcessingResultLookup.java | 2 +- .../domain/CommandProcessingResultType.java | 2 +- .../commands/domain/CommandSource.java | 13 +- .../domain/CommandSourceRepository.java | 2 +- .../commands/domain/CommandWrapper.java | 30 +- .../CommandNotAwaitingApprovalException.java | 2 +- .../exception/CommandNotFoundException.java | 2 +- .../UnsupportedCommandException.java | 2 +- .../handler/NewCommandSourceHandler.java | 2 +- .../provider/CommandHandlerProvider.java | 30 +- .../service/AuditReadPlatformService.java | 2 +- .../service/AuditReadPlatformServiceImpl.java | 21 +- .../service/CommandProcessingService.java | 4 +- .../service/CommandWrapperBuilder.java | 84 +- ...olioCommandSourceWritePlatformService.java | 2 +- ...CommandSourceWritePlatformServiceImpl.java | 10 +- .../SynchronousCommandProcessingService.java | 7 +- .../api/AccountNumberFormatsApiResource.java | 68 +- ...ccountNumberFormatsApiResourceSwagger.java | 20 +- .../AccountNumberFormatDataValidator.java | 43 +- .../domain/AccountNumberFormat.java | 5 +- .../AccountNumberFormatEnumerations.java | 33 +- .../domain/AccountNumberFormatRepository.java | 4 +- .../AccountNumberFormatRepositoryWrapper.java | 3 +- .../domain/EntityAccountType.java | 9 +- .../AccountNumberFormatNotFoundException.java | 4 +- ...ntNumberFormatReadPlatformServiceImpl.java | 4 +- ...WritePlatformServiceJpaRepositoryImpl.java | 7 +- .../bulkimport/api/BulkImportApiResource.java | 36 +- .../bulkimport/constants/CenterConstants.java | 40 +- .../constants/ChartOfAcountsConstants.java | 33 +- .../constants/ClientEntityConstants.java | 76 +- .../constants/ClientPersonConstants.java | 73 +- .../bulkimport/constants/GroupConstants.java | 46 +- .../constants/GuarantorConstants.java | 20 +- .../constants/JournalEntryConstants.java | 2 +- .../bulkimport/constants/LoanConstants.java | 100 +- .../constants/LoanRepaymentConstants.java | 48 +- .../bulkimport/constants/OfficeConstants.java | 10 +- .../constants/RecurringDepositConstants.java | 1 - .../constants/SavingsConstants.java | 2 +- .../constants/SharedAccountsConstants.java | 44 +- .../bulkimport/constants/StaffConstants.java | 18 +- .../TemplatePopulateImportConstants.java | 210 +- .../bulkimport/constants/UserConstants.java | 23 +- .../bulkimport/data/BulkImportEvent.java | 10 +- .../infrastructure/bulkimport/data/Count.java | 10 +- .../bulkimport/data/GlobalEntityType.java | 57 +- .../bulkimport/data/ImportData.java | 28 +- .../bulkimport/data/ImportFormatType.java | 19 +- .../bulkimport/domain/ImportDocument.java | 23 +- .../domain/ImportDocumentRepository.java | 3 +- .../ImportTypeNotFoundException.java | 2 +- .../importhandler/ImportHandler.java | 2 +- .../importhandler/ImportHandlerUtils.java | 270 +- .../center/CenterImportHandler.java | 152 +- .../ChartOfAccountsImportHandler.java | 94 +- .../client/ClientEntityImportHandler.java | 112 +- .../client/ClientPersonImportHandler.java | 108 +- .../FixedDepositImportHandler.java | 202 +- .../FixedDepositTransactionImportHandler.java | 74 +- .../group/GroupImportHandler.java | 182 +- .../guarantor/GuarantorImportHandler.java | 77 +- .../helper/ClientIdSerializer.java | 8 +- .../helper/CodeValueDataIdSerializer.java | 1 + .../helper/CurrencyDateCodeSerializer.java | 3 +- .../importhandler/helper/DateSerializer.java | 2 +- .../helper/EnumOptionDataIdSerializer.java | 1 + .../helper/EnumOptionDataValueSerializer.java | 1 + .../helper/GroupIdSerializer.java | 7 +- .../JournalEntriesImportHandler.java | 170 +- .../importhandler/loan/LoanImportHandler.java | 277 +- .../LoanRepaymentImportHandler.java | 69 +- .../office/OfficeImportHandler.java | 52 +- .../RecurringDepositImportHandler.java | 160 +- ...urringDepositTransactionImportHandler.java | 81 +- .../savings/SavingsImportHandler.java | 194 +- .../SavingsTransactionImportHandler.java | 72 +- .../SharedAccountImportHandler.java | 110 +- .../staff/StaffImportHandler.java | 71 +- .../users/UserImportHandler.java | 68 +- .../populator/AbstractWorkbookPopulator.java | 191 +- .../populator/CenterSheetPopulator.java | 23 +- .../populator/ClientSheetPopulator.java | 14 +- .../populator/ExtrasSheetPopulator.java | 12 +- .../FixedDepositProductSheetPopulator.java | 119 +- .../populator/GlAccountSheetPopulator.java | 5 +- .../populator/GroupSheetPopulator.java | 45 +- .../populator/LoanProductSheetPopulator.java | 16 +- .../populator/OfficeSheetPopulator.java | 85 +- .../populator/PersonnelSheetPopulator.java | 157 +- ...RecurringDepositProductSheetPopulator.java | 132 +- .../populator/RoleSheetPopulator.java | 12 +- .../SavingsAccountSheetPopulator.java | 50 +- .../SavingsProductSheetPopulator.java | 19 +- .../SharedProductsSheetPopulator.java | 106 +- .../populator/WorkbookPopulator.java | 4 +- .../centers/CentersWorkbookPopulator.java | 154 +- .../ChartOfAccountsWorkbook.java | 258 +- .../client/ClientEntityWorkbookPopulator.java | 397 +- .../client/ClientPersonWorkbookPopulator.java | 637 +-- .../LoanComparatorByStatusActive.java | 18 +- ...edDepositTransactionWorkbookPopulator.java | 124 +- .../FixedDepositWorkbookPopulator.java | 311 +- .../group/GroupsWorkbookPopulator.java | 170 +- .../guarantor/GuarantorWorkbookPopulator.java | 329 +- .../JournalEntriesWorkbookPopulator.java | 137 +- .../populator/loan/LoanWorkbookPopulator.java | 329 +- .../LoanRepaymentWorkbookPopulator.java | 141 +- .../office/OfficeWorkbookPopulator.java | 81 +- ...ngDepositTransactionWorkbookPopulator.java | 137 +- .../RecurringDepositWorkbookPopulator.java | 281 +- .../SavingsTransactionsWorkbookPopulator.java | 124 +- .../savings/SavingsWorkbookPopulator.java | 242 +- .../SharedAccountWorkBookPopulator.java | 241 +- .../staff/StaffWorkbookPopulator.java | 83 +- .../users/UserWorkbookPopulator.java | 92 +- .../service/BulkImportEventListener.java | 100 +- .../BulkImportWorkbookPopulatorService.java | 4 +- ...ulkImportWorkbookPopulatorServiceImpl.java | 529 +- .../service/BulkImportWorkbookService.java | 5 +- .../BulkImportWorkbookServiceImpl.java | 140 +- .../cache/PlatformCacheConfiguration.java | 4 +- .../cache/api/CacheApiResource.java | 19 +- .../cache/api/CacheApiResourceSwagger.java | 12 +- .../command/UpdateCacheCommandHandler.java | 5 +- .../infrastructure/cache/data/CacheData.java | 2 +- .../cache/domain/CacheType.java | 2 +- .../cache/domain/PlatformCache.java | 2 +- .../cache/domain/PlatformCacheRepository.java | 2 +- .../service/CacheWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 2 +- .../RuntimeDelegatingCacheManager.java | 2 +- .../campaigns/constants/CampaignType.java | 4 +- .../campaigns/email/EmailApiConstants.java | 6 +- .../email/ScheduledEmailConstants.java | 26 +- .../campaigns/email/api/EmailApiResource.java | 2 +- .../email/api/EmailCampaignApiResource.java | 61 +- .../api/EmailConfigurationApiResource.java | 14 +- .../email/data/EmailBusinessRulesData.java | 23 +- .../email/data/EmailCampaignData.java | 49 +- .../email/data/EmailCampaignTimeLine.java | 5 +- .../email/data/EmailCampaignValidator.java | 83 +- .../email/data/EmailConfigurationData.java | 1 + .../data/EmailConfigurationValidator.java | 27 +- .../campaigns/email/data/EmailData.java | 40 +- .../email/data/EmailDataValidator.java | 146 +- .../data/EmailMessageWithAttachmentData.java | 18 +- .../data/ScheduledEmailEnumerations.java | 5 +- .../campaigns/email/domain/EmailCampaign.java | 148 +- .../email/domain/EmailCampaignRepository.java | 3 +- .../email/domain/EmailCampaignStatus.java | 15 +- .../EmailCampaignStatusEnumerations.java | 21 +- .../email/domain/EmailCampaignType.java | 12 +- .../email/domain/EmailConfiguration.java | 1 + .../domain/EmailConfigurationRepository.java | 4 +- .../campaigns/email/domain/EmailMessage.java | 50 +- .../email/domain/EmailMessageAssembler.java | 9 +- .../domain/EmailMessageEnumerations.java | 6 +- .../email/domain/EmailMessageRepository.java | 3 +- .../email/domain/EmailMessageStatusType.java | 6 +- .../ScheduledEmailAttachmentFileFormat.java | 23 +- ...ledEmailStretchyReportParamDateOption.java | 24 +- .../exception/EmailBusinessRuleNotFound.java | 3 +- ...paignMustBeClosedToBeDeletedException.java | 5 +- ...ilCampaignMustBeClosedToEditException.java | 1 - .../exception/EmailCampaignNotFound.java | 5 +- ...mailConfigurationSMTPUsernameNotValid.java | 7 +- .../exception/EmailNotFoundException.java | 2 +- .../ActivateEmailCampaignCommandHandler.java | 1 + .../CloseEmailCampaignCommandHandler.java | 5 +- .../handler/CreateEmailCommandHandler.java | 2 +- .../DeleteEmailCampaignCommandHandler.java | 3 +- .../handler/DeleteEmailCommandHandler.java | 2 +- ...ReactivateEmailCampaignCommandHandler.java | 3 +- .../UpdateEmailCampaignCommandHandler.java | 4 +- .../EmailCampaignReadPlatformServiceImpl.java | 91 +- ...mpaignWritePlatformCommandHandlerImpl.java | 9 +- ...lConfigurationReadPlatformServiceImpl.java | 14 +- ...mailConfigurationWritePlatformService.java | 1 - ...ConfigurationWritePlatformServiceImpl.java | 49 +- .../service/EmailMessageJobEmailService.java | 1 - .../EmailMessageJobEmailServiceImpl.java | 43 +- .../service/EmailReadPlatformServiceImpl.java | 28 +- .../service/EmailWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 11 +- .../campaigns/helper/SmsConfigUtils.java | 20 +- .../sms/api/SmsCampaignApiResource.java | 22 +- .../constants/SmsCampaignEnumerations.java | 16 +- .../sms/constants/SmsCampaignTriggerType.java | 1 + .../sms/data/SmsBusinessRulesData.java | 12 +- .../campaigns/sms/data/SmsCampaignData.java | 25 +- .../campaigns/sms/data/SmsProviderData.java | 4 +- .../campaigns/sms/domain/SmsCampaign.java | 32 +- .../sms/domain/SmsCampaignRepository.java | 5 +- .../domain/SmsCampaignStatusEnumerations.java | 22 +- .../exception/ConnectionFailureException.java | 4 +- ...paignMustBeClosedToBeDeletedException.java | 5 +- .../sms/exception/SmsCampaignNotFound.java | 5 +- .../CloseSmsCampaignCommandHandler.java | 5 +- .../DeleteSmsCampaignCommandHandler.java | 3 +- .../ReactivateSmsCampaignCommandHandler.java | 3 +- .../serialization/SmsCampaignValidator.java | 25 +- .../sms/service/SmsCampaignDomainService.java | 3 +- .../service/SmsCampaignDomainServiceImpl.java | 246 +- ...mpaignDropdownReadPlatformServiceImpl.java | 35 +- .../SmsCampaignReadPlatformServiceImpl.java | 9 +- .../SmsCampaignWritePlatformService.java | 4 +- ...msCampaignWritePlatformServiceJpaImpl.java | 142 +- .../infrastructure/codes/CodeConstants.java | 5 +- .../codes/api/CodeValuesApiResource.java | 55 +- .../api/CodeValuesApiResourceSwagger.java | 18 +- .../codes/api/CodesApiResource.java | 29 +- .../codes/api/CodesApiResourceSwagger.java | 18 +- .../infrastructure/codes/data/CodeData.java | 2 +- .../codes/data/CodeValueData.java | 23 +- .../infrastructure/codes/domain/Code.java | 2 +- .../codes/domain/CodeRepository.java | 2 +- .../codes/domain/CodeValue.java | 10 +- .../codes/domain/CodeValueRepository.java | 2 +- .../exception/CodeNotFoundException.java | 2 +- .../exception/CodeValueNotFoundException.java | 10 +- .../handler/CreateCodeCommandHandler.java | 2 +- .../CreateCodeValueCommandHandler.java | 2 +- .../handler/DeleteCodeCommandHandler.java | 2 +- .../DeleteCodeValueCommandHandler.java | 2 +- .../handler/UpdateCodeCommandHandler.java | 2 +- .../UpdateCodeValueCommandHandler.java | 2 +- .../CodeCommandFromApiJsonDeserializer.java | 8 +- ...deValueCommandFromApiJsonDeserializer.java | 17 +- .../service/CodeReadPlatformServiceImpl.java | 2 +- .../service/CodeValueReadPlatformService.java | 2 +- .../CodeValueWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 15 +- .../service/CodeWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 11 +- ...ternalServiceConfigurationApiConstant.java | 3 +- ...ernalServicesConfigurationApiResource.java | 25 +- ...rvicesConfigurationApiResourceSwagger.java | 5 +- .../api/GlobalConfigurationApiResource.java | 45 +- ...GlobalConfigurationApiResourceSwagger.java | 18 +- .../UpdateGlobalConfigurationCommand.java | 2 +- .../data/GlobalConfigurationData.java | 2 +- .../GlobalConfigurationDataValidator.java | 22 +- .../data/GlobalConfigurationPropertyData.java | 8 +- .../data/SMTPCredentialsData.java | 7 +- .../domain/ConfigurationDomainService.java | 2 +- .../domain/ConfigurationDomainServiceJpa.java | 20 +- .../configuration/domain/ExternalService.java | 3 +- .../domain/ExternalServicePropertiesPK.java | 12 +- .../domain/ExternalServicesProperties.java | 1 + .../ExternalServicesPropertiesRepository.java | 5 +- ...alServicesPropertiesRepositoryWrapper.java | 7 +- .../domain/GlobalConfigurationProperty.java | 15 +- .../domain/GlobalConfigurationRepository.java | 6 +- .../GlobalConfigurationRepositoryWrapper.java | 3 +- ...lConfigurationPropertyCannotBeModfied.java | 5 +- ...onfigurationPropertyNotFoundException.java | 2 +- ...dateGlobalConfigurationCommandHandler.java | 2 +- ...urationCommandFromApiJsonDeserializer.java | 6 +- .../ConfigurationReadPlatformService.java | 2 +- .../ConfigurationReadPlatformServiceImpl.java | 8 +- .../service/ExternalServicesConstants.java | 8 +- ...ServicesPropertiesReadPlatformService.java | 2 +- ...icesPropertiesReadPlatformServiceImpl.java | 13 +- ...obalConfigurationWritePlatformService.java | 3 +- ...WritePlatformServiceJpaRepositoryImpl.java | 13 +- .../core/api/ApiParameterHelper.java | 3 +- .../core/api/ApiRequestParameterHelper.java | 2 +- .../infrastructure/core/api/DateAdapter.java | 7 +- .../core/api/JodaLocalDateAdapter.java | 6 +- .../core/api/JodaMonthDayAdapter.java | 6 +- .../infrastructure/core/api/JsonCommand.java | 42 +- .../api/ParameterListExclusionStrategy.java | 2 +- .../api/ParameterListInclusionStrategy.java | 2 +- .../AbstractApplicationConfiguration.java | 15 +- .../core/boot/ApplicationExitUtil.java | 5 +- .../core/boot/JDBCDriverConfig.java | 7 +- .../core/boot/WebFrontEndConfiguration.java | 15 +- .../boot/WebTwoFactorXmlConfiguration.java | 4 +- .../core/boot/WebXmlConfiguration.java | 4 +- .../core/boot/WebXmlOauthConfiguration.java | 11 +- .../core/data/ApiErrorMessageArg.java | 2 +- .../core/data/ApiGlobalErrorResponse.java | 6 +- .../core/data/ApiParameterError.java | 7 +- .../core/data/CommandProcessingResult.java | 25 +- .../data/CommandProcessingResultBuilder.java | 6 +- .../core/data/DataValidatorBuilder.java | 94 +- .../core/data/EnumOptionData.java | 14 +- .../core/data/PaginationParameters.java | 2 +- .../PaginationParametersDataValidator.java | 37 +- .../core/domain/AbstractAuditableCustom.java | 7 +- .../domain/AbstractPersistableCustom.java | 13 +- .../core/domain/Base64EncodedImage.java | 2 +- .../core/domain/EmailDetail.java | 2 +- .../core/domain/FineractPlatformTenant.java | 6 +- .../FineractPlatformTenantConnection.java | 16 +- .../core/domain/JdbcSupport.java | 2 + .../core/domain/LocalDateInterval.java | 2 +- .../core/domain/MySQLDictionaryCustom.java | 32 +- .../infrastructure/core/domain/Tenant.java | 2 +- .../AbstractPlatformDomainRuleException.java | 2 +- ...ractPlatformResourceNotFoundException.java | 2 +- ...ctPlatformServiceUnavailableException.java | 2 +- .../GeneralPlatformDomainRuleException.java | 2 +- .../core/exception/InvalidJsonException.java | 2 +- .../core/exception/MultiException.java | 20 +- .../PlatformApiDataValidationException.java | 2 +- .../PlatformDataIntegrityException.java | 2 +- .../PlatformInternalServerException.java | 2 +- .../UnrecognizedQueryParamException.java | 2 +- .../UnsupportedParameterException.java | 2 +- .../AccessDeniedExceptionMapper.java | 2 +- .../BadCredentialsExceptionMapper.java | 2 +- .../InvalidJsonExceptionMapper.java | 2 +- ...nvalidTenantIdentifierExceptionMapper.java | 2 +- .../JsonSyntaxExceptionMapper.java | 2 +- .../MalformedJsonExceptionMapper.java | 2 +- .../NoAuthorizationExceptionMapper.java | 2 +- ...tformApiDataValidationExceptionMapper.java | 6 +- .../PlatformDataIntegrityExceptionMapper.java | 7 +- .../PlatformDomainRuleExceptionMapper.java | 2 +- ...PlatformInternalServerExceptionMapper.java | 2 +- ...atformResourceNotFoundExceptionMapper.java | 2 +- .../UnAuthenticatedUserExceptionMapper.java | 2 +- ...UnrecognizedQueryParamExceptionMapper.java | 6 +- .../UnsupportedCommandExceptionMapper.java | 10 +- .../UnsupportedParameterExceptionMapper.java | 10 +- .../core/filters/ResponseCorsFilter.java | 5 +- .../AbstractFromApiJsonDeserializer.java | 2 +- .../AbstractFromCommandJsonDeserializer.java | 2 +- .../ApiRequestJsonSerializationSettings.java | 2 +- ...CommandProcessingResultJsonSerializer.java | 2 +- .../core/serialization/CommandSerializer.java | 2 +- .../CommandSerializerDefaultToJson.java | 2 +- ...tatableCommandFromApiJsonDeserializer.java | 32 +- .../DefaultToApiJsonSerializer.java | 8 +- ...tyPrintingOffJsonSerializerGoogleGson.java | 2 +- ...ttyPrintingOnJsonSerializerGoogleGson.java | 2 +- .../FromApiJsonDeserializer.java | 2 +- .../FromCommandJsonDeserializer.java | 2 +- .../core/serialization/FromJsonHelper.java | 5 +- .../GoogleGsonSerializerHelper.java | 7 +- .../core/serialization/JsonParserHelper.java | 91 +- .../serialization/ToApiJsonSerializer.java | 2 +- ...onedConnectionCleanupShutdownListener.java | 19 +- .../core/service/DateUtils.java | 4 +- .../GmailBackedPlatformEmailService.java | 21 +- .../infrastructure/core/service/Page.java | 2 +- .../core/service/PlatformEmailService.java | 3 +- .../core/service/RoutingDataSource.java | 2 +- .../service/RoutingDataSourceService.java | 2 +- .../core/service/SearchParameters.java | 33 +- .../service/TenantDatabaseUpgradeService.java | 93 +- .../core/service/ThreadLocalContextUtil.java | 2 +- .../TomcatJdbcDataSourcePerTenantService.java | 21 +- .../api/CreditBureauConfigurationAPI.java | 37 +- .../data/CreditBureauConfigurationData.java | 9 +- .../creditbureau/data/CreditBureauData.java | 11 +- .../CreditBureauLoanProductMappingData.java | 17 +- .../data/CreditBureauProduct.java | 3 +- .../data/OrganisationCreditBureauData.java | 14 +- .../creditbureau/domain/CreditBureau.java | 1 - .../domain/CreditBureauConfiguration.java | 1 + .../CreditBureauLoanProductMapping.java | 45 +- .../domain/CreditBureauRepository.java | 4 +- .../domain/OrganisationCreditBureau.java | 2 - ...ureauLoanProductMappingCommandHandler.java | 3 +- ...ureauLoanProductMappingCommandHandler.java | 3 +- ...tBureauCommandFromApiJsonDeserializer.java | 33 +- ...ProductCommandFromApiJsonDeserializer.java | 89 +- ...ProductMappingReadPlatformServiceImpl.java | 5 +- ...roductMappingWritePlatformServiceImpl.java | 6 +- ...ditBureauReadConfigurationServiceImpl.java | 10 +- .../CreditBureauReadPlatformServiceImpl.java | 7 +- ...sationCreditBureauReadPlatformService.java | 1 + ...onCreditBureauReadPlatformServiceImpl.java | 11 +- ...CreditBureauWritePlatflormServiceImpl.java | 12 +- .../dataqueries/api/DataTableApiConstant.java | 4 +- .../api/DatatablesApiResource.java | 138 +- .../api/DatatablesApiResourceSwagger.java | 80 +- .../api/EntityDatatableChecksApiResource.java | 48 +- ...tityDatatableChecksApiResourceSwagger.java | 20 +- .../dataqueries/api/ReportsApiResource.java | 38 +- .../api/ReportsApiResourceSwagger.java | 25 +- .../api/RunreportsApiResource.java | 43 +- .../api/RunreportsApiResourceSwagger.java | 4 + .../dataqueries/data/DataTableValidator.java | 3 +- .../dataqueries/data/DatatableData.java | 13 +- .../data/EntityDataTableChecksData.java | 2 +- .../EntityDataTableChecksTemplateData.java | 29 +- .../dataqueries/data/EntityTables.java | 46 +- .../data/GenericResultsetData.java | 2 +- .../dataqueries/data/ReportData.java | 2 +- .../dataqueries/data/ReportParameterData.java | 2 +- .../data/ReportParameterJoinData.java | 2 +- .../data/ResultsetColumnHeaderData.java | 10 +- .../data/ResultsetColumnValueData.java | 2 +- .../dataqueries/data/StatusEnum.java | 2 +- .../domain/EntityDatatableChecks.java | 7 +- .../EntityDatatableChecksRepository.java | 14 +- .../dataqueries/domain/Report.java | 17 +- .../dataqueries/domain/ReportParameter.java | 2 +- .../domain/ReportParameterRepository.java | 2 +- .../domain/ReportParameterUsage.java | 41 +- .../ReportParameterUsageRepository.java | 6 +- .../dataqueries/domain/ReportRepository.java | 2 +- .../domain/ReportRepositoryWrapper.java | 15 +- .../DatatableEntryRequiredException.java | 9 +- .../exception/DatatableNotFoundException.java | 2 +- .../DatatableSystemErrorException.java | 2 +- ...yDatatableCheckAlreadyExistsException.java | 19 +- ...EntityDatatableCheckNotAllowException.java | 8 +- ...tyDatatableCheckNotSupportedException.java | 7 +- ...ntityDatatableChecksNotFoundException.java | 5 +- .../exception/ReportNotFoundException.java | 2 +- .../ReportParameterNotFoundException.java | 2 +- .../CreateDatatableCommandHandler.java | 2 +- .../CreateDatatableEntryCommandHandler.java | 2 +- ...teEntityDatatableChecksCommandHandler.java | 5 +- .../handler/CreateReportCommandHandler.java | 2 +- .../DeleteDatatableCommandHandler.java | 2 +- ...teEntityDatatableChecksCommandHandler.java | 5 +- ...OneToManyDatatableEntryCommandHandler.java | 2 +- ...eOneToOneDatatableEntryCommandHandler.java | 2 +- .../handler/DeleteReportCommandHandler.java | 2 +- .../RegisterDatatableCommandHandler.java | 5 +- .../UpdateDatatableCommandHandler.java | 2 +- ...OneToManyDatatableEntryCommandHandler.java | 6 +- ...eOneToOneDatatableEntryCommandHandler.java | 6 +- .../handler/UpdateReportCommandHandler.java | 2 +- .../ReportCommandFromApiJsonDeserializer.java | 2 +- .../EntityDatatableChecksDataValidator.java | 17 +- ...atatableChecksReadPlatformServiceImpl.java | 2 +- .../EntityDatatableChecksReadService.java | 2 +- ...tyDatatableChecksWritePlatformService.java | 10 +- ...tatableChecksWritePlatformServiceImpl.java | 17 +- .../service/GenericDataService.java | 2 +- .../service/GenericDataServiceImpl.java | 46 +- .../service/ReadReportingService.java | 14 +- .../service/ReadReportingServiceImpl.java | 178 +- .../service/ReadWriteNonCoreDataService.java | 2 +- .../ReadWriteNonCoreDataServiceImpl.java | 218 +- .../service/ReportWritePlatformService.java | 2 +- .../ReportWritePlatformServiceImpl.java | 14 +- .../api/DocumentManagementApiResource.java | 85 +- .../DocumentManagementApiResourceSwagger.java | 14 +- .../api/ImagesApiResource.java | 12 +- .../api/ImagesApiResourceSwagger.java | 1 + .../command/DocumentCommand.java | 2 +- .../command/DocumentCommandValidator.java | 12 +- .../ContentRepositoryUtils.java | 19 +- .../FileSystemContentRepository.java | 5 +- .../S3ContentRepository.java | 5 +- .../documentmanagement/data/DocumentData.java | 2 +- .../documentmanagement/data/ImageData.java | 2 +- .../documentmanagement/domain/Document.java | 2 +- .../domain/DocumentRepository.java | 2 +- .../documentmanagement/domain/Image.java | 2 +- .../domain/ImageRepository.java | 2 +- .../domain/StorageType.java | 1 + .../exception/ContentManagementException.java | 8 +- .../exception/DocumentNotFoundException.java | 4 +- ...ityTypeForDocumentManagementException.java | 2 +- .../service/DocumentReadPlatformService.java | 2 +- .../DocumentReadPlatformServiceImpl.java | 2 +- .../service/DocumentWritePlatformService.java | 5 +- ...WritePlatformServiceJpaRepositoryImpl.java | 26 +- .../service/ImageReadPlatformService.java | 2 +- .../service/ImageReadPlatformServiceImpl.java | 11 +- ...WritePlatformServiceJpaRepositoryImpl.java | 10 +- .../FineractEntityAccessConstants.java | 9 +- .../api/FineractEntityApiResource.java | 4 +- .../FineractEntityApiResourceConstants.java | 4 +- .../data/FineractEntityAccessData.java | 7 +- .../data/FineractEntityDataValidator.java | 28 +- .../data/FineractEntityRelationData.java | 2 +- .../FineractEntityToEntityMappingData.java | 4 +- .../entityaccess/domain/FineractEntity.java | 8 +- .../domain/FineractEntityAccess.java | 34 +- .../FineractEntityAccessRepository.java | 3 +- ...FineractEntityAccessRepositoryWrapper.java | 7 +- .../domain/FineractEntityAccessType.java | 16 +- .../domain/FineractEntityRelation.java | 33 +- .../FineractEntityRelationRepository.java | 2 +- ...neractEntityRelationRepositoryWrapper.java | 11 +- .../domain/FineractEntityToEntityMapping.java | 7 +- ...neractEntityToEntityMappingRepository.java | 8 +- ...ntityToEntityMappingRepositoryWrapper.java | 6 +- .../domain/FineractEntityType.java | 35 +- ...actEntityAccessConfigurationException.java | 11 +- ...FineractEntityAccessNotFoundException.java | 6 +- ...ctEntityMappingConfigurationException.java | 5 +- ...actEntityToEntityMappingDateException.java | 5 +- .../NotOfficeSpecificProductException.java | 8 +- ...teEntityToEntityMappingCommandHandler.java | 2 +- ...teEntityToEntityMappingCommandHandler.java | 2 +- .../FineractEntityAccessReadService.java | 8 +- .../FineractEntityAccessReadServiceImpl.java | 71 +- .../service/FineractEntityAccessUtil.java | 76 +- .../FineractEntityAccessWriteService.java | 4 +- .../FineractEntityAccessWriteServiceImpl.java | 23 +- .../infrastructure/gcm/GcmConstants.java | 4 +- .../api/DeviceRegistrationApiConstants.java | 1 + .../api/DeviceRegistrationApiResource.java | 2 +- .../gcm/domain/DeviceRegistration.java | 3 +- .../gcm/domain/DeviceRegistrationData.java | 9 +- .../domain/DeviceRegistrationRepository.java | 8 +- .../DeviceRegistrationRepositoryWrapper.java | 6 +- .../infrastructure/gcm/domain/Message.java | 20 +- .../gcm/domain/MulticastResult.java | 12 +- .../domain/NotificationConfigurationData.java | 8 +- .../infrastructure/gcm/domain/Result.java | 8 +- .../infrastructure/gcm/domain/Sender.java | 222 +- .../DeviceRegistrationNotFoundException.java | 10 +- .../exception/InvalidRequestException.java | 3 +- ...ceRegistrationReadPlatformServiceImpl.java | 35 +- ...eRegistrationWritePlatformServiceImpl.java | 48 +- .../service/NotificationSenderService.java | 36 +- .../hooks/api/HookApiConstants.java | 12 +- .../hooks/api/HookApiResource.java | 104 +- .../hooks/api/HookApiResourceSwagger.java | 30 +- .../infrastructure/hooks/data/Event.java | 3 +- .../hooks/data/EventResultSetExtractor.java | 20 +- .../infrastructure/hooks/data/Field.java | 10 +- .../infrastructure/hooks/data/HookData.java | 36 +- .../hooks/data/HookTemplateData.java | 6 +- .../infrastructure/hooks/domain/Hook.java | 4 +- .../hooks/domain/HookConfiguration.java | 10 +- .../domain/HookConfigurationRepository.java | 7 +- .../hooks/domain/HookRepository.java | 7 +- .../hooks/domain/HookResource.java | 6 +- .../hooks/domain/HookTemplate.java | 2 +- .../hooks/domain/HookTemplateRepository.java | 4 +- .../infrastructure/hooks/event/HookEvent.java | 3 +- .../exception/HookNotFoundException.java | 9 +- .../HookTemplateNotFoundException.java | 10 +- .../handler/CreateHookCommandHandler.java | 3 +- .../handler/DeleteHookCommandHandler.java | 3 +- .../handler/UpdateHookCommandHandler.java | 6 +- .../hooks/listener/FineractHookListener.java | 17 +- .../hooks/processor/HookProcessor.java | 4 +- .../processor/HookProcessorProvider.java | 9 +- .../hooks/processor/ProcessorHelper.java | 25 +- .../hooks/processor/TwilioHookProcessor.java | 61 +- .../hooks/processor/WebHookProcessor.java | 31 +- .../hooks/processor/WebHookService.java | 22 +- .../HookCommandFromApiJsonDeserializer.java | 72 +- .../service/HookReadPlatformService.java | 2 +- .../service/HookReadPlatformServiceImpl.java | 69 +- ...WritePlatformServiceJpaRepositoryImpl.java | 153 +- .../jobs/annotation/CronMethodParser.java | 14 +- .../jobs/api/SchedulerApiResource.java | 16 +- .../jobs/api/SchedulerApiResourceSwagger.java | 6 +- .../jobs/api/SchedulerJobApiConstants.java | 17 +- .../jobs/api/SchedulerJobApiResource.java | 45 +- .../api/SchedulerJobApiResourceSwagger.java | 11 +- .../jobs/data/JobDetailDataValidator.java | 6 +- .../jobs/data/JobDetailHistoryData.java | 2 +- .../jobs/domain/JobParameter.java | 15 +- .../jobs/domain/JobParameterRepository.java | 2 +- .../domain/ScheduledJobDetailRepository.java | 3 +- .../jobs/domain/ScheduledJobRunHistory.java | 4 +- .../ScheduledJobRunHistoryRepository.java | 4 +- .../jobs/exception/JobNotFoundException.java | 2 +- .../OperationNotAllowedException.java | 6 +- .../infrastructure/jobs/service/JobName.java | 59 +- .../jobs/service/JobRegisterServiceImpl.java | 26 +- ...WritePlatformServiceJpaRepositoryImpl.java | 4 +- .../jobs/service/SchedulerJobListener.java | 14 +- .../SchedulerJobRunnerReadServiceImpl.java | 15 +- .../service/SchedulerServiceConstants.java | 2 +- .../service/SchedulerTriggerListener.java | 8 +- .../openjpa/OpenJpaDialect.java | 38 +- .../openjpa/OpenJpaVendorAdapter.java | 54 +- .../report/annotation/ReportService.java | 2 +- .../ReportingProcessServiceProvider.java | 5 +- .../service/ReportingProcessService.java | 2 +- .../ReportMailingJobConstants.java | 26 +- .../api/ReportMailingJobApiResource.java | 98 +- .../ReportMailingJobApiResourceSwagger.java | 41 +- ...ReportMailingJobRunHistoryApiResource.java | 28 +- ...ailingJobRunHistoryApiResourceSwagger.java | 7 +- .../ReportMailingJobConfigurationData.java | 1 + .../data/ReportMailingJobData.java | 34 +- ...rtMailingJobEmailAttachmentFileFormat.java | 20 +- .../data/ReportMailingJobEmailData.java | 1 + .../ReportMailingJobPreviousRunStatus.java | 9 +- .../data/ReportMailingJobRunHistoryData.java | 9 +- ...ilingJobStretchyReportParamDateOption.java | 32 +- .../data/ReportMailingJobTimelineData.java | 4 +- .../domain/ReportMailingJob.java | 97 +- .../domain/ReportMailingJobConfiguration.java | 6 +- ...portMailingJobConfigurationRepository.java | 4 +- ...rtMailingJobEmailAttachmentFileFormat.java | 24 +- .../domain/ReportMailingJobRepository.java | 4 +- .../ReportMailingJobRepositoryWrapper.java | 11 +- .../domain/ReportMailingJobRunHistory.java | 11 +- .../ReportMailingJobRunHistoryRepository.java | 3 +- ...lingJobConfigurationNotFoundException.java | 7 +- .../ReportMailingJobNotFoundException.java | 7 +- ...MailingJobRunHistoryNotFoundException.java | 8 +- .../CreateReportMailingJobCommandHandler.java | 1 + .../DeleteReportMailingJobCommandHandler.java | 1 + .../UpdateReportMailingJobCommandHandler.java | 1 + .../reportmailingjob/helper/IPv4Helper.java | 54 +- ...ngJobConfigurationReadPlatformService.java | 1 + ...bConfigurationReadPlatformServiceImpl.java | 5 +- .../service/ReportMailingJobEmailService.java | 4 +- .../ReportMailingJobEmailServiceImpl.java | 35 +- .../ReportMailingJobReadPlatformService.java | 7 +- ...portMailingJobReadPlatformServiceImpl.java | 29 +- ...ilingJobRunHistoryReadPlatformService.java | 10 +- ...gJobRunHistoryReadPlatformServiceImpl.java | 12 +- .../ReportMailingJobWritePlatformService.java | 4 + ...ortMailingJobWritePlatformServiceImpl.java | 123 +- .../util/ReportMailingJobDateUtil.java | 27 +- .../validation/ReportMailingJobValidator.java | 151 +- .../api/AuthenticationApiResource.java | 22 +- .../api/AuthenticationApiResourceSwagger.java | 5 +- .../security/api/TwoFactorApiResource.java | 24 +- .../TwoFactorConfigurationApiResource.java | 16 +- .../security/api/UserDetailsApiResource.java | 22 +- .../api/UserDetailsApiResourceSwagger.java | 5 +- ...InvalidateTFAccessTokenCommandHandler.java | 22 +- .../UpdateTwoFactorConfigCommandHandler.java | 9 +- .../TwoFactorConfigurationConstants.java | 20 +- .../data/AuthenticatedOauthUserData.java | 2 +- .../security/data/AuthenticatedUserData.java | 4 +- .../security/data/OTPMetadata.java | 3 +- .../security/data/OTPRequest.java | 7 +- .../security/data/PlatformRequestLog.java | 2 +- .../data/TwoFactorConfigurationValidator.java | 38 +- .../BasicPasswordEncodablePlatformUser.java | 2 +- .../security/domain/OTPRequestRepository.java | 1 - .../security/domain/PlatformUser.java | 2 +- .../domain/PlatformUserRepository.java | 2 +- .../security/domain/TFAccessToken.java | 13 +- .../domain/TFAccessTokenRepository.java | 2 +- .../domain/TwoFactorConfiguration.java | 11 +- .../TwoFactorConfigurationRepository.java | 4 +- .../ForcePasswordResetException.java | 5 +- .../InvalidTenantIdentiferException.java | 2 +- .../exception/NoAuthorizationException.java | 2 +- .../OTPDeliveryMethodInvalidException.java | 4 +- .../exception/ResetPasswordException.java | 5 +- ...InsecureTwoFactorAuthenticationFilter.java | 13 +- .../TenantAwareBasicAuthenticationFilter.java | 20 +- .../TenantAwareTenantIdentifierFilter.java | 23 +- .../filter/TwoFactorAuthenticationFilter.java | 58 +- .../BasicAuthTenantDetailsService.java | 2 +- .../BasicAuthTenantDetailsServiceJdbc.java | 6 +- .../service/JdbcTenantDetailsService.java | 2 +- .../service/PlatformPasswordEncoder.java | 2 +- .../service/PlatformSecurityContext.java | 2 +- .../service/PlatformUserDetailsService.java | 2 +- .../security/service/RandomOTPGenerator.java | 2 +- .../service/RandomPasswordGenerator.java | 2 +- ...SpringSecurityPlatformSecurityContext.java | 19 +- ...antAwareJpaPlatformUserDetailsService.java | 2 +- .../service/TenantDetailsService.java | 2 +- .../TwoFactorConfigurationService.java | 11 +- .../TwoFactorConfigurationServiceImpl.java | 88 +- .../service/TwoFactorServiceImpl.java | 85 +- .../security/service/TwoFactorUtils.java | 8 +- .../security/utils/ColumnValidator.java | 80 +- .../security/utils/SQLBuilder.java | 102 +- .../security/utils/SQLInjectionValidator.java | 66 +- .../vote/SelfServiceUserAccessVote.java | 11 +- .../infrastructure/sms/SmsApiConstants.java | 2 +- .../sms/api/SmsApiResource.java | 6 +- .../infrastructure/sms/data/SmsData.java | 2 +- .../sms/data/SmsDataValidator.java | 9 +- .../data/SmsMessageApiQueueResourceData.java | 1 + .../data/SmsMessageApiReportResourceData.java | 5 +- .../sms/data/SmsMessageApiResponseData.java | 1 + .../data/SmsMessageDeliveryReportData.java | 8 +- .../infrastructure/sms/domain/SmsMessage.java | 22 +- .../sms/domain/SmsMessageAssembler.java | 6 +- .../sms/domain/SmsMessageEnumerations.java | 10 +- .../sms/domain/SmsMessageRepository.java | 2 +- .../sms/domain/SmsMessageStatusType.java | 5 +- .../sms/exception/SmsNotFoundException.java | 2 +- .../sms/handler/CreateSmsCommandHandler.java | 2 +- .../sms/handler/DeleteSmsCommandHandler.java | 2 +- .../sms/handler/UpdateSmsCommandHandler.java | 2 +- .../SmsMessageScheduledJobService.java | 13 +- .../SmsMessageScheduledJobServiceImpl.java | 97 +- .../service/SmsReadPlatformServiceImpl.java | 16 +- .../sms/service/SmsWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 11 +- .../survey/api/PovertyLineApiResource.java | 3 +- .../survey/api/SurveyApiConstants.java | 3 +- .../survey/api/SurveyApiResource.java | 22 +- .../survey/api/SurveyApiResourceSwagger.java | 15 +- .../survey/data/LikelihoodDataValidator.java | 6 +- .../survey/data/LikelihoodStatus.java | 4 +- .../survey/data/PovertyLineData.java | 5 +- .../survey/data/PpiPovertyLineData.java | 5 +- .../survey/data/SurveyData.java | 3 +- .../survey/domain/LikelihoodRepository.java | 6 +- .../handler/FullFilSurveyCommandHandler.java | 3 +- .../handler/RegisterSurveyCommandHandler.java | 1 - .../UpdateLikelihoodCommandHandler.java | 1 - .../service/PovertyLineServiceImpl.java | 18 +- .../survey/service/ReadLikelihoodService.java | 1 + .../survey/service/ReadSurveyServiceImpl.java | 22 +- .../service/WriteLikelihoodServiceImpl.java | 4 +- .../api/InteropApiResource.java | 215 +- .../api/InteropWrapperBuilder.java | 4 +- .../interoperation/data/ExtensionData.java | 8 +- .../interoperation/data/GeoCodeData.java | 8 +- .../data/InteropAccountData.java | 62 +- .../InteropIdentifierAccountResponseData.java | 7 +- .../data/InteropIdentifierRequestData.java | 15 +- .../data/InteropIdentifiersResponseData.java | 3 +- .../data/InteropQuoteRequestData.java | 38 +- .../data/InteropQuoteResponseData.java | 24 +- .../data/InteropRequestData.java | 36 +- .../data/InteropResponseData.java | 15 +- .../data/InteropTransactionData.java | 58 +- .../data/InteropTransactionRequestData.java | 31 +- ...InteropTransactionRequestResponseData.java | 20 +- .../data/InteropTransactionTypeData.java | 23 +- .../data/InteropTransactionsData.java | 5 +- .../data/InteropTransferRequestData.java | 21 +- .../data/InteropTransferResponseData.java | 19 +- .../interoperation/data/MoneyData.java | 12 +- .../domain/InteropActionState.java | 3 +- .../domain/InteropAmountType.java | 3 +- .../domain/InteropIdentifier.java | 33 +- .../domain/InteropIdentifierRepository.java | 3 +- .../domain/InteropIdentifierType.java | 9 +- .../domain/InteropInitiatorType.java | 5 +- .../domain/InteropTransactionRole.java | 5 +- .../domain/InteropTransactionScenario.java | 6 +- .../domain/InteropTransferActionType.java | 4 +- .../handler/CommitInteropTransferHandler.java | 2 +- .../CreateInteropIdentifierHandler.java | 2 +- .../handler/CreateInteropQuoteHandler.java | 2 +- .../handler/CreateInteropRequestHandler.java | 2 +- .../DeleteInteropIdentifierHandler.java | 2 +- .../PrepareInteropTransferHandler.java | 2 +- .../serialization/InteropDataValidator.java | 13 +- .../service/InteropService.java | 12 +- .../service/InteropServiceImpl.java | 126 +- .../interoperation/util/MathUtil.java | 118 +- .../mix/api/MixReportApiResource.java | 8 +- .../mix/api/MixTaxonomyApiResource.java | 12 +- .../api/MixTaxonomyMappingApiResource.java | 6 +- .../fineract/mix/data/MixTaxonomyData.java | 2 +- .../mix/data/MixTaxonomyMappingData.java | 2 +- .../fineract/mix/data/NamespaceData.java | 2 +- .../apache/fineract/mix/data/XBRLData.java | 2 +- .../domain/MixTaxonomyMappingRepository.java | 5 +- ...axonomyMappingReadPlatformServiceImpl.java | 2 +- .../MixTaxonomyReadPlatformServiceImpl.java | 2 +- .../NamespaceReadPlatformServiceImpl.java | 2 +- .../fineract/mix/service/XBRLBuilder.java | 5 +- .../mix/service/XBRLResultService.java | 2 +- .../mix/service/XBRLResultServiceImpl.java | 77 +- .../api/NotificationApiResource.java | 30 +- .../CacheNotificationResponseHeader.java | 4 +- .../config/MessagingConfiguration.java | 22 +- .../notification/data/NotificationData.java | 3 +- .../fineract/notification/data/TopicData.java | 6 +- .../notification/domain/Notification.java | 2 +- .../domain/NotificationMapper.java | 1 - .../domain/NotificationRepository.java | 1 - .../fineract/notification/domain/Topic.java | 3 +- .../notification/domain/TopicRepository.java | 2 + .../notification/domain/TopicSubscriber.java | 3 +- .../domain/TopicSubscriberRepository.java | 1 + .../NotificationEventListener.java | 19 +- .../NotificationEventService.java | 1 + .../eventandlistener/SpringEventListener.java | 19 +- .../SpringEventPublisher.java | 1 + .../NotificationDomainServiceImpl.java | 327 +- ...icationGeneratorReadRepositoryWrapper.java | 2 - ...ionGeneratorReadRepositoryWrapperImpl.java | 2 +- ...ficationGeneratorWritePlatformService.java | 2 +- ...tificationMapperReadRepositoryWrapper.java | 1 - ...otificationMapperWritePlatformService.java | 1 - .../NotificationReadPlatformServiceImpl.java | 53 +- .../NotificationWritePlatformService.java | 9 +- .../NotificationWritePlatformServiceImpl.java | 49 +- .../service/TopicDomainService.java | 18 +- .../service/TopicDomainServiceImpl.java | 36 +- ...opicSubscriberReadPlatformServiceImpl.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 2 +- .../holiday/api/HolidaysApiResource.java | 58 +- .../api/HolidaysApiResourceSwagger.java | 30 +- .../holiday/data/HolidayDataValidator.java | 26 +- .../organisation/holiday/domain/Holiday.java | 17 +- .../domain/HolidayRepositoryWrapper.java | 3 +- .../holiday/domain/HolidayStatusType.java | 2 +- .../holiday/domain/RescheduleType.java | 35 +- .../exception/HolidayNotFoundException.java | 2 +- .../holiday/service/HolidayEnumerations.java | 4 +- .../HolidayReadPlatformServiceImpl.java | 5 +- .../holiday/service/HolidayUtil.java | 5 +- ...WritePlatformServiceJpaRepositoryImpl.java | 27 +- .../monetary/api/CurrenciesApiResource.java | 17 +- .../api/CurrenciesApiResourceSwagger.java | 29 +- .../ApplicationCurrencyConfigurationData.java | 2 +- .../monetary/data/CurrencyData.java | 22 +- .../organisation/monetary/data/MoneyData.java | 2 +- .../monetary/domain/ApplicationCurrency.java | 2 +- .../domain/ApplicationCurrencyRepository.java | 6 +- .../ApplicationCurrencyRepositoryWrapper.java | 2 +- .../monetary/domain/MonetaryCurrency.java | 2 +- .../organisation/monetary/domain/Money.java | 6 +- .../monetary/domain/MoneyHelper.java | 6 +- .../exception/CurrencyInUseException.java | 3 +- .../exception/CurrencyNotFoundException.java | 2 +- ...ganizationalCurrencyNotFoundException.java | 6 +- .../handler/UpdateCurrencyCommandHandler.java | 2 +- ...urrencyCommandFromApiJsonDeserializer.java | 8 +- .../service/CurrencyReadPlatformService.java | 2 +- .../CurrencyReadPlatformServiceImpl.java | 2 +- .../service/CurrencyWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 5 +- ...ganisationCurrencyReadPlatformService.java | 2 +- ...sationCurrencyReadPlatformServiceImpl.java | 2 +- .../api/OfficeTransactionsApiResource.java | 8 +- .../office/api/OfficesApiResource.java | 52 +- .../office/api/OfficesApiResourceSwagger.java | 26 +- .../organisation/office/data/OfficeData.java | 15 +- .../office/data/OfficeTransactionData.java | 2 +- .../organisation/office/domain/Office.java | 2 +- .../domain/OfficeRepositoryWrapper.java | 11 +- .../office/domain/OfficeTransaction.java | 5 +- .../office/domain/OrganisationCurrency.java | 2 +- .../OrganisationCurrencyRepository.java | 4 +- ...OrganisationCurrencyRepositoryWrapper.java | 2 +- .../exception/OfficeNotFoundException.java | 2 +- .../OfficeTransactionNotFoundException.java | 2 +- .../handler/CreateOfficeCommandHandler.java | 2 +- ...CreateOfficeTransactionCommandHandler.java | 2 +- ...DeleteOfficeTransactionCommandHandler.java | 2 +- .../handler/UpdateOfficeCommandHandler.java | 2 +- .../OfficeCommandFromApiJsonDeserializer.java | 12 +- ...sactionCommandFromApiJsonDeserializer.java | 8 +- .../service/OfficeReadPlatformService.java | 2 +- .../OfficeReadPlatformServiceImpl.java | 17 +- .../service/OfficeWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 17 +- .../api/ProvisioningCategoryApiResource.java | 6 +- .../api/ProvisioningCriteriaApiResource.java | 65 +- ...rovisioningCriteriaApiResourceSwagger.java | 22 +- .../ProvisioningCriteriaConstants.java | 1 + .../data/ProvisioningCategoryData.java | 4 +- .../data/ProvisioningCriteriaData.java | 18 +- .../ProvisioningCriteriaDefinitionData.java | 8 +- .../domain/LoanProductProvisionCriteria.java | 9 +- .../ProvisioningCategoryRepository.java | 4 +- .../domain/ProvisioningCriteria.java | 50 +- .../ProvisioningCriteriaDefinition.java | 11 +- ...visioningCriteriaDefinitionRepository.java | 4 +- .../ProvisioningCriteriaRepository.java | 4 +- ...oningCriteriaCannotBeDeletedException.java | 3 +- ...isioningCriteriaRequestCommandHandler.java | 5 +- ...isioningCategoryRequestCommandHandler.java | 3 +- ...isioningCriteriaRequestCommandHandler.java | 3 +- ...ingCriteriaDefinitionJsonDeserializer.java | 117 +- ...ovisioningCategoryReadPlatformService.java | 3 +- ...ioningCategoryReadPlatformServiceImpl.java | 6 +- ...visioningCategoryWritePlatformService.java | 5 +- ...WritePlatformServiceJpaRepositoryImpl.java | 17 +- .../ProvisioningCriteriaAssembler.java | 31 +- ...ovisioningCriteriaReadPlatformService.java | 9 +- ...ioningCriteriaReadPlatformServiceImpl.java | 29 +- ...visioningCriteriaWritePlatformService.java | 5 +- ...WritePlatformServiceJpaRepositoryImpl.java | 89 +- .../staff/api/StaffApiResource.java | 60 +- .../staff/api/StaffApiResourceSwagger.java | 16 +- .../data/BulkTransferLoanOfficerData.java | 2 +- .../StaffAccountSummaryCollectionData.java | 2 +- .../organisation/staff/data/StaffData.java | 17 +- .../staff/domain/StaffEnumerations.java | 2 +- .../domain/StaffOrganisationalRoleType.java | 2 +- .../staff/domain/StaffRepository.java | 2 +- .../staff/domain/StaffRepositoryWrapper.java | 9 +- .../exception/StaffNotFoundException.java | 2 +- .../staff/exception/StaffRoleException.java | 5 +- .../handler/CreateStaffCommandHandler.java | 2 +- .../handler/UpdateStaffCommandHandler.java | 2 +- .../StaffCommandFromApiJsonDeserializer.java | 20 +- .../service/StaffReadPlatformService.java | 2 +- .../service/StaffReadPlatformServiceImpl.java | 92 +- .../service/StaffWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 19 +- .../teller/api/CashierApiResource.java | 6 +- .../teller/api/TellerApiResource.java | 133 +- .../teller/api/TellerApiResourceSwagger.java | 49 +- .../teller/api/TellerJournalApiResource.java | 6 +- .../organisation/teller/data/CashierData.java | 99 +- .../teller/data/CashierTransactionData.java | 36 +- .../data/CashierTransactionDataValidator.java | 81 +- .../CashierTransactionTypeTotalsData.java | 14 +- .../CashierTransactionsWithSummaryData.java | 47 +- .../organisation/teller/data/TellerData.java | 55 +- .../teller/data/TellerJournalData.java | 38 +- .../teller/data/TellerTransactionData.java | 38 +- .../organisation/teller/domain/Cashier.java | 36 +- .../teller/domain/CashierRepository.java | 3 +- .../domain/CashierRepositoryWrapper.java | 4 +- .../teller/domain/CashierTransaction.java | 33 +- .../domain/CashierTransactionRepository.java | 3 +- .../teller/domain/CashierTxnType.java | 39 +- .../organisation/teller/domain/Teller.java | 28 +- .../teller/domain/TellerJournal.java | 3 +- .../teller/domain/TellerRepository.java | 4 +- .../domain/TellerRepositoryWrapper.java | 9 +- .../teller/domain/TellerStatus.java | 7 +- .../domain/TellerTransactionRepository.java | 6 +- .../exception/CashierAlreadyAlloacated.java | 6 +- ...ateRangeOutOfTellerDateRangeException.java | 6 +- .../CashierExistForTellerException.java | 3 +- .../CashierInsufficientAmountException.java | 6 +- .../exception/CashierNotFoundException.java | 3 +- .../exception/InvalidDateInputException.java | 7 +- .../exception/TellerNotFoundException.java | 3 +- .../AllocateCashToCashierCommandHandler.java | 4 +- ...AllocateCashierToTellerCommandHandler.java | 7 +- .../handler/CreateTellerCommandHandler.java | 5 +- ...DeleteCashierAllocationCommandHandler.java | 7 +- .../handler/DeleteTellerCommandHandler.java | 4 +- .../handler/ModifyCashierCommandHandler.java | 5 +- .../SettleCashFromCashierCommandHandler.java | 4 +- ...UpdateCashierAllocationCommandHandler.java | 7 +- .../handler/UpdateTellerCommandHandler.java | 4 +- .../TellerCommandFromApiJsonDeserializer.java | 8 +- .../service/CashierWritePlatformService.java | 3 +- .../TellerManagementReadPlatformService.java | 4 +- ...llerManagementReadPlatformServiceImpl.java | 148 +- ...TellerTransactionWritePlatformService.java | 3 +- .../service/TellerWritePlatformService.java | 32 +- .../TellerWritePlatformServiceJpaImpl.java | 59 +- .../organisation/teller/util/DateRange.java | 5 +- .../api/WorkingDaysApiConstants.java | 8 +- .../api/WorkingDaysApiResource.java | 25 +- .../api/WorkingDaysApiResourceSwagger.java | 9 + .../data/AdjustedDateDetailsDTO.java | 3 +- .../workingdays/data/WorkingDayValidator.java | 16 +- .../workingdays/data/WorkingDaysData.java | 6 +- .../domain/RepaymentRescheduleType.java | 6 +- .../workingdays/domain/WorkingDays.java | 22 +- .../domain/WorkingDaysEnumerations.java | 33 +- .../domain/WorkingDaysRepositoryWrapper.java | 2 +- .../WorkingDaysNotFoundException.java | 2 +- .../UpdateWorkingDaysCommandHandler.java | 4 +- .../WorkingDaysReadPlatformServiceImpl.java | 15 +- .../workingdays/service/WorkingDaysUtil.java | 3 +- .../account/AccountDetailConstants.java | 3 +- .../account/PortfolioAccountType.java | 2 +- .../api/AccountTransfersApiConstants.java | 2 +- .../api/AccountTransfersApiResource.java | 92 +- .../AccountTransfersApiResourceSwagger.java | 141 +- .../api/StandingInstructionApiConstants.java | 9 +- .../api/StandingInstructionApiResource.java | 135 +- ...StandingInstructionApiResourceSwagger.java | 144 +- ...StandingInstructionHistoryApiResource.java | 38 +- ...gInstructionHistoryApiResourceSwagger.java | 24 +- .../account/data/AccountTransferDTO.java | 10 +- .../account/data/AccountTransferData.java | 6 +- .../data/AccountTransfersDataValidator.java | 42 +- .../AccountTransfersDetailDataValidator.java | 6 +- .../account/data/StandingInstructionDTO.java | 4 +- .../account/data/StandingInstructionData.java | 7 +- .../StandingInstructionDataValidator.java | 189 +- .../domain/AccountAssociationType.java | 2 +- .../domain/AccountAssociationsRepository.java | 7 +- .../domain/AccountTransferAssembler.java | 2 +- .../AccountTransferDetailAssembler.java | 8 +- .../AccountTransferDetailRepository.java | 4 +- .../domain/AccountTransferDetails.java | 13 +- .../domain/AccountTransferRecurrenceType.java | 2 +- .../domain/AccountTransferRepository.java | 6 +- .../AccountTransferStandingInstruction.java | 28 +- .../domain/AccountTransferTransaction.java | 13 +- .../account/domain/AccountTransferType.java | 2 +- .../domain/StandingInstructionAssembler.java | 2 +- .../domain/StandingInstructionPriority.java | 2 +- .../domain/StandingInstructionRepository.java | 11 +- .../domain/StandingInstructionStatus.java | 2 +- .../domain/StandingInstructionType.java | 2 +- .../AccountTransferNotFoundException.java | 2 +- .../StandingInstructionNotFoundException.java | 2 +- .../CreateAccountTransferCommandHandler.java | 2 +- .../RefundByTransferCommandHandler.java | 2 +- ...ntAssociationsReadPlatformServiceImpl.java | 15 +- .../service/AccountTransferEnumerations.java | 2 +- .../AccountTransfersReadPlatformService.java | 9 +- ...countTransfersReadPlatformServiceImpl.java | 431 +- .../AccountTransfersWritePlatformService.java | 2 +- ...ountTransfersWritePlatformServiceImpl.java | 72 +- .../PortfolioAccountReadPlatformService.java | 2 +- ...rtfolioAccountReadPlatformServiceImpl.java | 57 +- ...InstructionHistoryReadPlatformService.java | 2 +- ...ructionHistoryReadPlatformServiceImpl.java | 3 +- ...tandingInstructionReadPlatformService.java | 2 +- ...ingInstructionReadPlatformServiceImpl.java | 27 +- ...andingInstructionWritePlatformService.java | 2 +- ...ngInstructionWritePlatformServiceImpl.java | 31 +- .../data/AccountSummaryCollectionData.java | 39 +- .../data/GuarantorAccountSummaryData.java | 10 +- .../data/LoanAccountSummaryData.java | 19 +- .../data/SavingsAccountSummaryData.java | 10 +- .../data/SavingsSummaryCustom.java | 19 +- .../data/ShareAccountSummaryData.java | 23 +- .../accountdetails/domain/AccountType.java | 7 +- .../AccountDetailsReadPlatformService.java | 2 +- ...sReadPlatformServiceJpaRepositoryImpl.java | 301 +- .../service/AccountEnumerations.java | 3 +- .../accounts/api/AccountsApiResource.java | 150 +- .../api/AccountsApiResourceSwagger.java | 125 +- .../constants/AccountsApiConstants.java | 5 +- .../constants/ShareAccountApiConstants.java | 26 +- .../portfolio/accounts/data/AccountData.java | 1 - .../ShareAccountNotFoundException.java | 5 +- .../service/AccountsCommandsService.java | 3 +- .../EntityFieldConfigurationApiResources.java | 23 +- ...FieldConfigurationApiResourcesSwagger.java | 9 +- .../portfolio/address/data/AddressData.java | 61 +- .../address/data/ClientAddressData.java | 4 +- .../address/data/FieldConfigurationData.java | 13 +- .../portfolio/address/domain/Address.java | 21 +- .../exception/AddressNotFoundException.java | 4 +- ...AddressCommandFromApiJsonDeserializer.java | 24 +- .../service/AddressReadPlatformService.java | 1 + .../AddressReadPlatformServiceImpl.java | 36 +- .../service/AddressWritePlatformService.java | 1 + .../AddressWritePlatformServiceImpl.java | 40 +- ...FieldConfigurationReadPlatformService.java | 1 + ...dConfigurationReadPlatformServiceImpl.java | 12 +- .../portfolio/calendar/CalendarConstants.java | 15 +- .../calendar/api/CalendarsApiResource.java | 16 +- .../portfolio/calendar/data/CalendarData.java | 176 +- .../data/CalendarHistoryDataWrapper.java | 8 +- .../portfolio/calendar/domain/Calendar.java | 74 +- .../domain/CalendarFrequencyType.java | 11 +- .../domain/CalendarInstanceRepository.java | 14 +- .../CalendarInstanceRepositoryWrapper.java | 3 +- .../domain/CalendarRepositoryWrapper.java | 3 +- .../calendar/domain/CalendarWeekDaysType.java | 8 +- .../exception/CalendarDateException.java | 2 +- ...lendarEntityTypeNotSupportedException.java | 2 +- .../CalendarInstanceNotFoundException.java | 5 +- .../exception/CalendarNotFoundException.java | 2 +- ...rParameterUpdateNotSupportedException.java | 2 +- .../MeetingFrequencyMismatchException.java | 5 +- .../NotValidRecurringDateException.java | 2 +- .../handler/DeleteCalendarCommandHandler.java | 2 +- ...alendarCommandFromApiJsonDeserializer.java | 127 +- .../CalendarDropdownReadPlatformService.java | 3 +- ...lendarDropdownReadPlatformServiceImpl.java | 1 + .../service/CalendarEnumerations.java | 14 +- .../service/CalendarReadPlatformService.java | 2 - .../CalendarReadPlatformServiceImpl.java | 53 +- .../calendar/service/CalendarUtils.java | 122 +- ...WritePlatformServiceJpaRepositoryImpl.java | 90 +- .../charge/api/ChargesApiResource.java | 40 +- .../charge/api/ChargesApiResourceSwagger.java | 61 +- .../portfolio/charge/data/ChargeData.java | 32 +- .../portfolio/charge/domain/Charge.java | 83 +- .../charge/domain/ChargeAppliesTo.java | 15 +- .../charge/domain/ChargeCalculationType.java | 17 +- .../charge/domain/ChargePaymentMode.java | 2 +- .../charge/domain/ChargeTimeType.java | 17 +- ...tDisbursementCannotBePenaltyException.java | 2 +- .../exception/ChargeIsNotActiveException.java | 2 +- .../ChargeMustBePenaltyException.java | 2 +- ...eParameterUpdateNotSupportedException.java | 2 +- .../LoanChargeCannotBeAddedException.java | 2 +- .../LoanChargeCannotBeDeletedException.java | 9 +- .../LoanChargeCannotBePayedException.java | 9 +- .../LoanChargeCannotBeUpdatedException.java | 9 +- .../LoanChargeCannotBeWaivedException.java | 5 +- .../LoanChargeNotFoundException.java | 2 +- ...nChargeWithoutMandatoryFieldException.java | 2 +- ...sAccountChargeCannotBeWaivedException.java | 9 +- ...SavingsAccountChargeNotFoundException.java | 7 +- ...tChargeWithoutMandatoryFieldException.java | 2 +- ...tChargeWithoutMandatoryFieldException.java | 2 +- .../CreateChargeDefinitionCommandHandler.java | 2 +- .../DeleteChargeDefinitionCommandHandler.java | 2 +- .../UpdateChargeDefinitionCommandHandler.java | 2 +- ...initionCommandFromApiJsonDeserializer.java | 22 +- .../ChargeDropdownReadPlatformService.java | 6 +- ...ChargeDropdownReadPlatformServiceImpl.java | 6 +- .../charge/service/ChargeEnumerations.java | 23 +- .../service/ChargeReadPlatformService.java | 2 +- .../ChargeReadPlatformServiceImpl.java | 4 +- ...WritePlatformServiceJpaRepositoryImpl.java | 35 +- .../client/api/ClientAddressApiResources.java | 63 +- .../api/ClientAddressApiResourcesSwagger.java | 24 +- .../client/api/ClientApiConstants.java | 32 +- .../client/api/ClientChargesApiResource.java | 74 +- .../api/ClientChargesApiResourceSwagger.java | 44 +- .../api/ClientFamilyMembersApiResources.java | 53 +- .../api/ClientIdentifiersApiResource.java | 64 +- .../ClientIdentifiersApiResourceSwagger.java | 40 +- .../api/ClientTransactionsApiResource.java | 31 +- .../ClientTransactionsApiResourceSwagger.java | 29 +- .../client/api/ClientsApiResource.java | 179 +- .../client/api/ClientsApiResourceSwagger.java | 112 +- .../command/ClientIdentifierCommand.java | 17 +- .../client/command/ClientNoteCommand.java | 8 +- .../data/ClientApiCollectionConstants.java | 33 +- .../portfolio/client/data/ClientData.java | 223 +- .../client/data/ClientDataValidator.java | 148 +- .../client/data/ClientFamilyMembersData.java | 50 +- .../client/data/ClientIdentifierData.java | 5 +- .../client/data/ClientNonPersonData.java | 19 +- .../client/data/ClientTimelineData.java | 2 +- .../client/domain/AccountNumberGenerator.java | 10 +- .../portfolio/client/domain/Client.java | 80 +- .../client/domain/ClientAddress.java | 6 +- .../domain/ClientAddressRepository.java | 7 +- .../ClientAddressRepositoryWrapper.java | 8 +- .../domain/ClientChargeRepositoryWrapper.java | 3 +- .../client/domain/ClientEnumerations.java | 5 +- .../client/domain/ClientFamilyMembers.java | 250 +- .../domain/ClientFamilyMembersRepository.java | 3 +- .../client/domain/ClientIdentifier.java | 11 +- .../domain/ClientIdentifierRepository.java | 2 +- .../client/domain/ClientIdentifierStatus.java | 11 +- .../client/domain/ClientNonPerson.java | 22 +- .../domain/ClientNonPersonRepository.java | 2 +- .../ClientNonPersonRepositoryWrapper.java | 8 +- .../client/domain/ClientRepository.java | 2 +- .../domain/ClientRepositoryWrapper.java | 18 +- .../portfolio/client/domain/ClientStatus.java | 14 +- .../client/domain/ClientTransaction.java | 4 +- .../client/domain/ClientTransferDetails.java | 17 +- .../ClientTransferDetailsRepository.java | 2 +- ...lientTransferDetailsRepositoryWrapper.java | 2 +- .../ClientActiveForUpdateException.java | 4 +- .../ClientIdentifierNotFoundException.java | 2 +- ...ientMustBePendingToBeDeletedException.java | 6 +- ...tNonPersonNotFoundByClientIdException.java | 3 +- .../ClientNonPersonNotFoundException.java | 3 +- .../exception/ClientNotFoundException.java | 4 +- ...entTransactionCannotBeUndoneException.java | 2 +- .../DuplicateClientIdentifierException.java | 11 +- .../exception/ImageNotFoundException.java | 2 +- .../handler/ActivateClientCommandHandler.java | 2 +- .../AddClientAddressCommandHandler.java | 1 + .../AddClientFamilyMemberCommandHandler.java | 9 +- .../handler/CloseClientCommandHandler.java | 2 +- .../CreateClientIdentifierCommandHandler.java | 2 +- .../handler/DeleteClientCommandHandler.java | 2 +- ...eleteClientFamilyMemberCommandHandler.java | 7 +- .../DeleteClientIdentifierCommandHandler.java | 2 +- .../handler/RejectClientCommandHandler.java | 6 +- .../UndoRejectClientCommandHandler.java | 11 +- .../handler/UndoWithdrawalCommandHandler.java | 13 +- .../handler/UpdateClientCommandHandler.java | 2 +- ...pdateClientFamilyMemberCommandHandler.java | 6 +- .../UpdateClientIdentifierCommandHandler.java | 2 +- ...ateClientSavingsAccountCommandHandler.java | 2 +- .../handler/WithdrawClientCommandHandler.java | 21 +- ...yMemberCommandFromApiJsonDeserializer.java | 202 +- ...ntifierCommandFromApiJsonDeserializer.java | 4 +- .../ClientAddressReadPlatformServiceImpl.java | 7 +- ...WritePlatformServiceJpaRepositoryImpl.java | 11 +- ...lientFamilyMembersReadPlatformService.java | 3 +- ...tFamilyMembersReadPlatformServiceImpl.java | 55 +- ...ientFamilyMembersWritePlatformService.java | 7 +- ...FamilyMembersWritePlatformServiceImpl.java | 301 +- .../ClientIdentifierReadPlatformService.java | 2 +- ...ientIdentifierReadPlatformServiceImpl.java | 6 +- .../ClientIdentifierWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 21 +- .../service/ClientReadPlatformService.java | 2 +- .../ClientReadPlatformServiceImpl.java | 99 +- .../service/ClientWritePlatformService.java | 3 +- ...WritePlatformServiceJpaRepositoryImpl.java | 183 +- .../client/service/LoanStatusMapper.java | 2 +- .../api/CollateralApiConstants.java | 4 +- .../api/CollateralsApiResource.java | 60 +- .../api/CollateralsApiResourceSwagger.java | 44 +- .../collateral/command/CollateralCommand.java | 24 +- .../collateral/data/CollateralData.java | 2 +- .../collateral/domain/LoanCollateral.java | 38 +- .../CollateralCannotBeCreatedException.java | 9 +- .../CollateralCannotBeDeletedException.java | 9 +- .../CollateralCannotBeUpdatedException.java | 9 +- .../CollateralNotFoundException.java | 2 +- .../CreateCollateralCommandHandler.java | 2 +- .../DeleteCollateralCommandHandler.java | 2 +- .../UpdateCollateralCommandHandler.java | 2 +- ...lateralCommandFromApiJsonDeserializer.java | 5 +- .../CollateralReadPlatformServiceImpl.java | 12 +- .../CollateralWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 29 +- .../CollectionSheetConstants.java | 2 +- .../CollectionSheetApiResourceSwagger.java | 20 +- .../api/CollectionSheetApiResourse.java | 15 +- .../CollectionSheetBulkDisbursalCommand.java | 2 +- .../CollectionSheetBulkRepaymentCommand.java | 2 +- .../command/SingleDisbursalCommand.java | 2 +- .../command/SingleRepaymentCommand.java | 2 +- ...llectionSheetTransactionDataValidator.java | 127 +- .../data/IndividualClientData.java | 4 +- .../data/IndividualCollectionSheetData.java | 2 +- ...IndividualCollectionSheetLoanFlatData.java | 2 +- .../collectionsheet/data/JLGClientData.java | 22 +- .../data/JLGCollectionSheetData.java | 2 +- .../data/JLGCollectionSheetFlatData.java | 8 +- .../collectionsheet/data/JLGGroupData.java | 10 +- .../collectionsheet/data/LoanDueData.java | 2 +- .../collectionsheet/data/SavingsDueData.java | 5 +- ...sbursalCommandFromApiJsonDeserializer.java | 6 +- ...paymentCommandFromApiJsonDeserializer.java | 11 +- ...enerateCommandFromApiJsonDeserializer.java | 16 +- ...ollectionSheetReadPlatformServiceImpl.java | 160 +- ...WritePlatformServiceJpaRepositoryImpl.java | 6 +- .../BusinessEventNotificationConstants.java | 61 +- .../common/domain/DayOfWeekType.java | 12 +- .../common/domain/DaysInMonthType.java | 3 +- .../common/domain/DaysInYearType.java | 2 +- .../portfolio/common/domain/NthDayType.java | 12 +- .../common/domain/PeriodFrequencyType.java | 7 +- .../BusinessEventNotifierServiceImpl.java | 6 +- .../common/service/CommonEnumerations.java | 28 +- .../DropdownReadPlatformServiceImpl.java | 2 +- .../api/FloatingRatesApiResource.java | 81 +- .../api/FloatingRatesApiResourceSwagger.java | 40 +- .../floatingrates/data/FloatingRateData.java | 30 +- .../data/FloatingRatePeriodData.java | 25 +- .../data/InterestRatePeriodData.java | 9 +- .../floatingrates/domain/FloatingRate.java | 97 +- .../domain/FloatingRatePeriod.java | 22 +- .../domain/FloatingRateRepository.java | 12 +- .../domain/FloatingRateRepositoryWrapper.java | 6 +- .../FloatingRateNotFoundException.java | 6 +- .../CreateFloatingRateCommandHandler.java | 6 +- .../UpdateFloatingRateCommandHandler.java | 6 +- .../FloatingRateDataValidator.java | 224 +- .../FloatingRateWritePlatformServiceImpl.java | 57 +- .../FloatingRatesReadPlatformServiceImpl.java | 169 +- .../portfolio/fund/api/FundsApiResource.java | 26 +- .../fund/api/FundsApiResourceSwagger.java | 24 +- .../portfolio/fund/data/FundData.java | 2 +- .../fineract/portfolio/fund/domain/Fund.java | 2 +- .../portfolio/fund/domain/FundRepository.java | 2 +- .../fund/exception/FundNotFoundException.java | 2 +- .../handler/CreateFundCommandHandler.java | 2 +- .../handler/UpdateFundCommandHandler.java | 2 +- .../FundCommandFromApiJsonDeserializer.java | 8 +- .../fund/service/FundReadPlatformService.java | 2 +- .../service/FundReadPlatformServiceImpl.java | 2 +- .../service/FundWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 21 +- .../group/api/CentersApiResource.java | 127 +- .../group/api/CentersApiResourceSwagger.java | 97 +- .../group/api/GroupingTypesApiConstants.java | 28 +- .../group/api/GroupsApiResource.java | 259 +- .../group/api/GroupsApiResourceSwagger.java | 147 +- .../group/api/GroupsLevelApiResource.java | 6 +- .../portfolio/group/data/CenterData.java | 92 +- .../group/data/GroupGeneralData.java | 179 +- .../portfolio/group/data/GroupLevelData.java | 2 +- .../portfolio/group/data/GroupRoleData.java | 14 +- .../portfolio/group/data/GroupSummary.java | 2 +- .../group/data/GroupTimelineData.java | 34 +- .../portfolio/group/domain/Group.java | 27 +- .../portfolio/group/domain/GroupLevel.java | 2 +- .../group/domain/GroupRepositoryWrapper.java | 7 +- .../domain/GroupRoleRepositoryWrapper.java | 3 +- .../domain/GroupingTypeEnumerations.java | 2 +- .../group/domain/GroupingTypeStatus.java | 2 +- .../ClientExistInGroupException.java | 4 +- .../GroupExistsInCenterException.java | 6 +- ...erCountNotInPermissibleRangeException.java | 5 +- .../GroupMemberNotFoundInGSIMException.java | 11 +- ...roupMustBePendingToBeDeletedException.java | 2 +- .../GroupNotExistsInCenterException.java | 2 +- .../handler/ActivateCenterCommandHandler.java | 2 +- .../handler/ActivateGroupCommandHandler.java | 2 +- ...AssociateClientsToGroupCommandHandler.java | 2 +- .../handler/CreateCenterCommandHandler.java | 2 +- .../handler/CreateGroupCommandHandler.java | 2 +- .../handler/DeleteCenterCommandHandler.java | 2 +- .../handler/DeleteGroupCommandHandler.java | 2 +- ...sociateClientsFromGroupCommandHandler.java | 2 +- ...veCenterCollectionSheetCommandHandler.java | 2 +- ...aveGroupCollectionSheetCommandHandler.java | 2 +- .../UnassignGroupStaffCommandHandler.java | 2 +- ...UnassignStaffFromCenterCommandHandler.java | 2 +- .../handler/UpdateCenterCommandHandler.java | 2 +- .../handler/UpdateGroupCommandHandler.java | 2 +- .../GroupRolesDataValidator.java | 6 +- .../GroupingTypesDataValidator.java | 103 +- .../service/AllGroupTypesDataMapper.java | 4 +- .../CenterReadPlatformServiceImpl.java | 73 +- .../service/GroupReadPlatformService.java | 2 +- .../service/GroupReadPlatformServiceImpl.java | 98 +- ...WritePlatformServiceJpaRepositoryImpl.java | 76 +- .../InterestIncentiveApiConstants.java | 6 +- .../InterestRateChartApiConstants.java | 24 +- .../InterestRateChartSlabApiConstants.java | 2 +- .../InterestRateChartSlabsApiResource.java | 60 +- ...erestRateChartSlabsApiResourceSwagger.java | 52 +- .../api/InterestRateChartsApiResource.java | 59 +- .../InterestRateChartsApiResourceSwagger.java | 45 +- .../data/InterestIncentiveDataValidator.java | 10 +- .../data/InterestRateChartData.java | 31 +- .../data/InterestRateChartDataValidator.java | 23 +- .../data/InterestRateChartRepository.java | 2 +- .../InterestRateChartRepositoryWrapper.java | 3 +- .../data/InterestRateChartSlabData.java | 2 +- .../InterestRateChartSlabDataValidator.java | 18 +- .../data/InterestRateChartSlabRepository.java | 5 +- ...nterestRateChartSlabRepositoryWrapper.java | 10 +- .../domain/InterestIncentivesFields.java | 6 +- .../domain/InterestRateChart.java | 57 +- .../domain/InterestRateChartFields.java | 5 +- .../domain/InterestRateChartSlab.java | 6 +- .../domain/InterestRateChartSlabFields.java | 8 +- .../InterestRateChartNotFoundException.java | 2 +- ...nterestRateChartSlabNotFoundException.java | 6 +- ...CreateInterestRateChartCommandHandler.java | 2 +- ...teInterestRateChartSlabCommandHandler.java | 2 +- ...DeleteInterestRateChartCommandHandler.java | 2 +- ...teInterestRateChartSlabCommandHandler.java | 4 +- ...UpdateInterestRateChartCommandHandler.java | 2 +- ...teInterestRateChartSlabCommandHandler.java | 4 +- .../InterestIncentiveAttributeName.java | 2 +- .../InterestIncentiveEntityType.java | 2 +- .../incentive/InterestIncentiveType.java | 2 +- ...tIncentiveDropdownReadPlatformService.java | 2 +- .../InterestIncentivesEnumerations.java | 2 +- .../service/InterestRateChartAssembler.java | 5 +- ...tRateChartDropdownReadPlatformService.java | 2 +- ...eChartDropdownReadPlatformServiceImpl.java | 2 +- .../InterestRateChartEnumerations.java | 16 +- .../InterestRateChartReadPlatformService.java | 6 +- ...erestRateChartReadPlatformServiceImpl.java | 25 +- .../InterestRateChartSlabAssembler.java | 9 +- ...erestRateChartSlabReadPlatformService.java | 2 +- ...tRateChartSlabReadPlatformServiceImpl.java | 19 +- ...restRateChartSlabWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 10 +- ...InterestRateChartWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 2 +- .../loanaccount/api/BulkLoansApiResource.java | 6 +- .../loanaccount/api/LoanApiConstants.java | 8 +- .../api/LoanChargesApiResource.java | 101 +- .../api/LoanChargesApiResourceSwagger.java | 64 +- .../LoanDisbursementDetailApiResource.java | 12 +- .../api/LoanScheduleApiResource.java | 20 +- .../api/LoanScheduleApiResourceSwagger.java | 16 +- .../api/LoanTransactionsApiResource.java | 63 +- .../LoanTransactionsApiResourceSwagger.java | 44 +- .../loanaccount/api/LoansApiResource.java | 405 +- .../api/LoansApiResourceSwagger.java | 136 +- .../command/LoanChargeCommand.java | 2 +- .../command/LoanUpdateCommand.java | 8 +- .../command/UndoStateTransitionCommand.java | 2 +- .../command/UpdateLoanOfficerCommand.java | 14 +- .../loanaccount/data/DisbursementData.java | 39 +- .../loanaccount/data/GLIMContainer.java | 68 +- .../data/GlimRepaymentTemplate.java | 118 +- ...upLoanIndividualMonitoringAccountData.java | 40 +- .../loanaccount/data/LoanAccountData.java | 449 +- .../data/LoanApplicationTimelineData.java | 28 +- .../loanaccount/data/LoanApprovalData.java | 22 +- .../loanaccount/data/LoanChargeData.java | 3 +- .../data/LoanChargePaidByData.java | 6 +- .../data/LoanChargePaidDetail.java | 6 +- .../loanaccount/data/LoanConvenienceData.java | 2 +- .../data/LoanInterestRecalculationData.java | 3 +- .../data/LoanScheduleAccrualData.java | 10 +- .../loanaccount/data/LoanStatusEnumData.java | 2 +- .../loanaccount/data/LoanSummaryData.java | 6 +- .../data/LoanTermVariationsData.java | 4 +- .../data/LoanTermVariationsDataWrapper.java | 6 +- .../loanaccount/data/LoanTransactionData.java | 196 +- .../data/LoanTransactionEnumData.java | 2 +- .../loanaccount/data/PaidInAdvanceData.java | 15 +- .../RepaymentScheduleRelatedLoanData.java | 9 +- .../data/ScheduleGeneratorDTO.java | 13 +- .../DefaultLoanLifecycleStateMachine.java | 2 +- .../domain/GLIMAccountInfoRepository.java | 9 +- .../GroupLoanIndividualMonitoringAccount.java | 169 +- .../portfolio/loanaccount/domain/Loan.java | 572 +- .../domain/LoanAccountDomainService.java | 6 +- .../domain/LoanAccountDomainServiceJpa.java | 105 +- .../loanaccount/domain/LoanCharge.java | 73 +- .../loanaccount/domain/LoanChargePaidBy.java | 3 +- .../domain/LoanDisbursementDetails.java | 11 +- .../domain/LoanInstallmentCharge.java | 7 +- .../LoanInterestRecalculationDetails.java | 11 +- .../domain/LoanRepaymentDataComparator.java | 2 +- .../LoanRepaymentScheduleInstallment.java | 52 +- ...epaymentScheduleInstallmentRepository.java | 4 +- ...oanRepaymentScheduleProcessingWrapper.java | 17 +- ...ntScheduleTransactionProcessorFactory.java | 2 +- .../loanaccount/domain/LoanRepository.java | 2 +- .../domain/LoanRepositoryWrapper.java | 138 +- ...scheduleRequestToTermVariationMapping.java | 5 +- .../loanaccount/domain/LoanStatus.java | 2 +- .../loanaccount/domain/LoanSubStatus.java | 5 +- .../loanaccount/domain/LoanSummary.java | 17 +- .../domain/LoanSummaryWrapper.java | 11 +- .../domain/LoanTermVariationType.java | 8 +- .../domain/LoanTermVariations.java | 6 +- .../loanaccount/domain/LoanTopupDetails.java | 54 +- .../loanaccount/domain/LoanTrancheCharge.java | 12 +- .../domain/LoanTrancheDisbursementCharge.java | 10 +- .../loanaccount/domain/LoanTransaction.java | 101 +- ...ansactionProcessingStrategyRepository.java | 6 +- .../domain/LoanTransactionRepository.java | 2 +- ...TransactionToRepaymentScheduleMapping.java | 6 +- .../domain/LoanTransactionType.java | 9 +- ...RepaymentScheduleTransactionProcessor.java | 40 +- ...RepaymentScheduleTransactionProcessor.java | 2 +- ...RepaymentScheduleTransactionProcessor.java | 9 +- ...RepaymentScheduleTransactionProcessor.java | 6 +- ...RepaymentScheduleTransactionProcessor.java | 9 +- ...RepaymentScheduleTransactionProcessor.java | 4 +- ...RepaymentScheduleTransactionProcessor.java | 13 +- ...RepaymentScheduleTransactionProcessor.java | 13 +- ...RepaymentScheduleTransactionProcessor.java | 22 +- .../exception/DateMismatchException.java | 17 +- .../InvalidLoanStateTransitionException.java | 2 +- .../InvalidLoanTransactionTypeException.java | 2 +- .../exception/InvalidLoanTypeException.java | 2 +- .../InvalidPaidInAdvanceAmountException.java | 7 +- .../exception/InvalidRefundDateException.java | 9 +- ...ndPendingApprovalStateCannotBeDeleted.java | 6 +- ...dPendingApprovalStateCannotBeModified.java | 6 +- .../exception/LoanDisbursalException.java | 5 +- .../exception/LoanNotFoundException.java | 2 +- .../LoanOfficerAssignmentDateException.java | 3 +- .../LoanOfficerAssignmentException.java | 8 +- .../LoanTemplateTypeRequiredException.java | 2 +- .../LoanTransactionNotFoundException.java | 6 +- ...onProcessingStrategyNotFoundException.java | 6 +- ...alAndFirstRepaymentViolationException.java | 6 +- ...NotSupportedLoanTemplateTypeException.java | 2 +- .../UndoLastTrancheDisbursementException.java | 6 +- .../guarantor/GuarantorConstants.java | 8 +- .../guarantor/api/GuarantorsApiResource.java | 31 +- .../guarantor/command/GuarantorCommand.java | 32 +- .../guarantor/data/GuarantorData.java | 39 +- .../guarantor/data/GuarantorFundingData.java | 8 +- .../guarantor/data/ObligeeData.java | 15 +- .../guarantor/domain/Guarantor.java | 13 +- .../domain/GuarantorFundStatusType.java | 2 +- .../domain/GuarantorFundingDetails.java | 2 +- .../domain/GuarantorFundingRepository.java | 4 +- ...GuarantorFundingTransactionRepository.java | 6 +- .../guarantor/domain/GuarantorRepository.java | 2 +- .../guarantor/domain/GuarantorType.java | 1 + .../exception/GuarantorNotFoundException.java | 6 +- .../exception/InvalidGuarantorException.java | 12 +- .../CreateGuarantorCommandHandler.java | 2 +- .../DeleteGuarantorCommandHandler.java | 2 +- .../UpdateGuarantorCommandHandler.java | 2 +- ...arantorCommandFromApiJsonDeserializer.java | 19 +- .../service/GuarantorDomainServiceImpl.java | 7 +- .../service/GuarantorReadPlatformService.java | 3 +- .../GuarantorReadPlatformServiceImpl.java | 47 +- .../GuarantorWritePlatformService.java | 2 +- ...ritePlatformServiceJpaRepositoryIImpl.java | 37 +- ...leteLoanDisburseDetailsCommandHandler.java | 2 +- .../handler/AddLoanChargeCommandHandler.java | 2 +- .../BulkUpdateLoanOfficerCommandHandler.java | 2 +- .../CloseLoanAsRescheduledCommandHandler.java | 2 +- .../handler/CloseLoanCommandHandler.java | 2 +- .../DeleteLoanChargeCommandHandler.java | 2 +- .../handler/DisburseLoanCommandHandler.java | 2 +- .../DisburseLoanToSavingsCommandHandler.java | 2 +- ...LIMApplicationRejectionCommandHandler.java | 25 +- .../GLIMBulkRepaymentCommandHandler.java | 2 +- ...LoanApplicationApprovalCommandHandler.java | 20 +- ...LoanApplicationDisburseCommandHandler.java | 5 +- ...LoanApplicationApprovalCommandHandler.java | 2 +- ...ApplicationApprovalUndoCommandHandler.java | 2 +- ...LoanApplicationDeletionCommandHandler.java | 2 +- ...ApplicationModificationCommandHandler.java | 2 +- ...LoanApplicationRejectedCommandHandler.java | 2 +- ...oanApplicationSubmittalCommandHandler.java | 2 +- ...ionWithdrawnByApplicantCommandHandler.java | 2 +- .../LoanRefundByCashCommandHandler.java | 2 +- ...LoanRepaymentAdjustmentCommandHandler.java | 2 +- .../handler/LoanRepaymentCommandHandler.java | 2 +- .../handler/PayLoanChargeCommandHandler.java | 2 +- .../RemoveLoanOfficerCommandHandler.java | 2 +- .../UndoDisbursalLoanCommandHandler.java | 2 +- .../UndoGLIMLoanApplicationApproval.java | 25 +- .../UndoGLIMLoanDisbursalCommandHandler.java | 7 +- .../UndoLastDisbursalLoanCommandHandler.java | 2 +- .../UndoWriteOffLoanCommandHandler.java | 2 +- .../UpdateLoanChargeCommandHandler.java | 2 +- .../UpdateLoanDisbuseDateCommandHandler.java | 2 +- .../UpdateLoanOfficerCommandHandler.java | 2 +- ...veInterestPortionOnLoanCommandHandler.java | 2 +- .../WaiveLoanChargeCommandHandler.java | 2 +- .../handler/WriteOffLoanCommandHandler.java | 2 +- .../loanschedule/data/LoanScheduleDTO.java | 3 +- .../loanschedule/data/LoanScheduleData.java | 2 +- .../loanschedule/data/LoanScheduleParams.java | 2 +- .../data/LoanSchedulePeriodData.java | 22 +- .../data/OverdueLoanScheduleData.java | 1 - .../domain/AbstractLoanScheduleGenerator.java | 323 +- .../loanschedule/domain/AprCalculator.java | 42 +- ...gBalanceInterestLoanScheduleGenerator.java | 10 +- .../DefaultLoanScheduleGeneratorFactory.java | 2 +- ...aultPaymentPeriodsInOneYearCalculator.java | 4 +- .../domain/DefaultScheduledDateGenerator.java | 17 +- .../domain/FinanicalFunctions.java | 2 +- .../FlatInterestLoanScheduleGenerator.java | 17 +- .../domain/LoanApplicationTerms.java | 248 +- .../domain/LoanRepaymentScheduleHistory.java | 10 +- ...oanRepaymentScheduleHistoryRepository.java | 3 +- .../domain/LoanScheduleGenerator.java | 2 +- .../domain/LoanScheduleModel.java | 4 +- .../LoanScheduleModelDisbursementPeriod.java | 3 +- .../domain/LoanScheduleModelPeriod.java | 1 + .../LoanScheduleModelRepaymentPeriod.java | 3 +- .../PaymentPeriodsInOneYearCalculator.java | 2 +- .../domain/ScheduledDateGenerator.java | 2 +- .../service/LoanScheduleAssembler.java | 159 +- ...cheduleCalculationPlatformServiceImpl.java | 27 +- ...cheduleHistoryReadPlatformServiceImpl.java | 24 +- ...anScheduleHistoryWritePlatformService.java | 5 +- ...heduleHistoryWritePlatformServiceImpl.java | 4 +- .../RescheduleLoansApiConstants.java | 10 +- .../api/RescheduleLoansApiResource.java | 47 +- .../data/LoanRescheduleRequestData.java | 10 +- .../LoanRescheduleRequestDataValidator.java | 93 +- .../LoanRescheduleRequestEnumerations.java | 23 +- .../LoanRescheduleRequestTimelineData.java | 11 +- .../domain/LoanRescheduleModel.java | 15 +- .../domain/LoanRescheduleRequest.java | 43 +- .../LoanRescheduleRequestRepository.java | 3 +- ...oanRescheduleRequestNotFoundException.java | 10 +- ...veLoanRescheduleRequestCommandHandler.java | 4 +- ...teLoanRescheduleRequestCommandHandler.java | 3 +- ...ctLoanRescheduleRequestCommandHandler.java | 4 +- ...nReschedulePreviewPlatformServiceImpl.java | 16 +- ...nRescheduleRequestReadPlatformService.java | 8 +- ...cheduleRequestReadPlatformServiceImpl.java | 6 +- ...heduleRequestWritePlatformServiceImpl.java | 91 +- ...ateLoanScheduleQueryFromApiJsonHelper.java | 61 +- ...anApplicationCommandFromApiJsonHelper.java | 350 +- ...ApplicationTransitionApiJsonValidator.java | 31 +- .../LoanEventApiJsonValidator.java | 82 +- ...nUpdateCommandFromApiJsonDeserializer.java | 2 +- ...iableLoanScheduleFromApiJsonValidator.java | 10 +- .../BulkLoansReadPlatformServiceImpl.java | 2 +- .../GLIMAccountInfoReadPlatformService.java | 22 +- ...LIMAccountInfoReadPlatformServiceImpl.java | 160 +- .../GLIMAccountInfoWritePlatformService.java | 2 +- ...IMAccountInfoWritePlatformServiceImpl.java | 47 +- .../service/LoanAccrualPlatformService.java | 1 + .../LoanAccrualPlatformServiceImpl.java | 5 +- .../LoanAccrualWritePlatformService.java | 3 +- .../LoanAccrualWritePlatformServiceImpl.java | 13 +- .../LoanApplicationWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 623 +-- .../service/LoanArrearsAgingServiceImpl.java | 61 +- .../loanaccount/service/LoanAssembler.java | 43 +- .../service/LoanChargeAssembler.java | 9 +- ...anChargePaidByReadPlatformServiceImpl.java | 71 +- .../LoanChargeReadPlatformService.java | 3 +- .../LoanChargeReadPlatformServiceImpl.java | 7 +- .../service/LoanReadPlatformService.java | 7 +- .../service/LoanReadPlatformServiceImpl.java | 367 +- .../service/LoanSchedularService.java | 3 +- .../service/LoanSchedularServiceImpl.java | 96 +- .../loanaccount/service/LoanUtilService.java | 71 +- .../service/LoanWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 475 +- .../service/RecalculateInterestPoster.java | 22 +- .../loanproduct/LoanProductConstants.java | 11 +- .../api/LoanProductsApiResource.java | 106 +- .../api/LoanProductsApiResourceSwagger.java | 277 +- .../loanproduct/data/LoanOverdueDTO.java | 1 - .../loanproduct/data/LoanProductData.java | 194 +- .../LoanProductInterestRecalculationData.java | 12 +- .../TransactionProcessingStrategyData.java | 2 +- .../domain/AmortizationMethod.java | 3 +- .../InterestCalculationPeriodMethod.java | 3 +- .../loanproduct/domain/InterestMethod.java | 4 +- .../InterestRecalculationPeriodMethod.java | 1 + .../loanproduct/domain/LoanProduct.java | 224 +- .../LoanProductBorrowerCycleVariations.java | 18 +- .../LoanProductConfigurableAttributes.java | 36 +- .../domain/LoanProductFloatingRates.java | 9 +- ...anProductInterestRecalculationDetails.java | 17 +- .../domain/LoanProductMinMaxConstraints.java | 19 +- .../domain/LoanProductParamType.java | 2 +- .../domain/LoanProductRelatedDetail.java | 66 +- .../domain/LoanProductRepository.java | 2 +- .../domain/LoanProductTrancheDetails.java | 3 +- .../domain/LoanProductValueConditionType.java | 2 +- .../domain/LoanRescheduleStrategyMethod.java | 4 +- .../LoanTransactionProcessingStrategy.java | 6 +- .../domain/RecalculationFrequencyType.java | 1 + .../exception/InvalidCurrencyException.java | 2 +- .../exception/InvalidLendingStrategy.java | 2 +- ...eModifiedDueToNonClosedLoansException.java | 3 +- .../LoanProductNotFoundException.java | 2 +- .../exception/NotInMinMaxRangeException.java | 2 +- .../CreateLoanProductCommandHandler.java | 2 +- .../UpdateLoanProductCommandHandler.java | 2 +- .../productmix/api/ProductMixApiResource.java | 7 +- .../productmix/data/ProductMixData.java | 3 +- .../ProductMixDataValidator.java | 6 +- ...WritePlatformServiceJpaRepositoryImpl.java | 3 +- .../LoanProductDataValidator.java | 773 ++- .../LoanDropdownReadPlatformService.java | 4 +- .../LoanDropdownReadPlatformServiceImpl.java | 5 +- .../loanproduct/service/LoanEnumerations.java | 68 +- .../LoanProductReadPlatformService.java | 2 +- .../LoanProductReadPlatformServiceImpl.java | 65 +- .../LoanProductWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 62 +- .../meeting/MeetingApiConstants.java | 2 +- .../meeting/api/MeetingsApiResource.java | 11 +- .../meeting/attendance/AttendanceType.java | 2 +- .../attendance/domain/ClientAttendance.java | 3 +- ...AttendanceDropdownReadPlatformService.java | 2 +- .../service/AttendanceEnumerations.java | 2 +- ...ientAttendanceReadPlatformServiceImpl.java | 2 +- .../meeting/data/MeetingDataValidator.java | 9 +- .../portfolio/meeting/domain/Meeting.java | 24 +- .../domain/MeetingRepositoryWrapper.java | 3 +- .../exception/MeetingDateException.java | 2 +- .../exception/MeetingNotFoundException.java | 2 +- .../MeetingNotSupportedResourceException.java | 2 +- .../handler/DeleteMeetingCommandHandler.java | 2 +- .../MeetingReadPlatformServiceImpl.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 65 +- .../portfolio/note/api/NotesApiResource.java | 65 +- .../note/api/NotesApiResourceSwagger.java | 40 +- .../portfolio/note/command/NoteCommand.java | 2 +- .../portfolio/note/data/NoteData.java | 2 +- .../fineract/portfolio/note/domain/Note.java | 3 +- .../portfolio/note/domain/NoteRepository.java | 2 +- .../portfolio/note/domain/NoteType.java | 5 +- .../note/exception/NoteNotFoundException.java | 6 +- .../NoteResourceNotSupportedException.java | 2 +- .../handler/DeleteNoteCommandHandler.java | 2 +- .../NoteCommandFromApiJsonDeserializer.java | 8 +- .../note/service/NoteReadPlatformService.java | 2 +- .../service/NoteReadPlatformServiceImpl.java | 10 +- ...WritePlatformServiceJpaRepositoryImpl.java | 13 +- .../paymentdetail/PaymentDetailConstants.java | 2 +- .../paymentdetail/data/PaymentDetailData.java | 21 +- .../paymentdetail/domain/PaymentDetail.java | 2 +- .../domain/PaymentDetailRepository.java | 2 +- .../PaymentDetailWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 2 +- .../api/PaymentTypeApiResource.java | 35 +- .../api/PaymentTypeApiResourceConstants.java | 3 +- .../api/PaymentTypeApiResourceSwagger.java | 32 +- .../paymenttype/data/PaymentTypeData.java | 15 +- .../data/PaymentTypeDataValidator.java | 23 +- .../PaymentTypeNotFoundException.java | 4 - .../UpdatePaymentTypeCommandHandler.java | 2 +- .../PaymentTypeReadPlatformService.java | 1 + .../service/PaymentTypeWriteServiceImpl.java | 6 +- .../products/api/ProductsApiResource.java | 54 +- .../api/ProductsApiResourceSwagger.java | 152 +- .../constants/ProductsApiConstants.java | 5 +- .../portfolio/products/data/ProductData.java | 1 - .../exception/ProductNotFoundException.java | 4 +- .../exception/ResourceNotFoundException.java | 5 +- .../service/ProductCommandsService.java | 4 +- .../service/ProductReadPlatformService.java | 2 +- .../portfolio/rate/api/RateApiConstants.java | 10 +- .../portfolio/rate/api/RateApiResource.java | 116 +- .../portfolio/rate/data/RateData.java | 34 +- .../fineract/portfolio/rate/domain/Rate.java | 279 +- .../portfolio/rate/domain/RateAppliesTo.java | 73 +- .../portfolio/rate/domain/RateRepository.java | 8 +- .../rate/domain/RateRepositoryWrapper.java | 53 +- .../exception/RateAlreadyExistException.java | 5 +- .../rate/exception/RateNotFoundException.java | 13 +- .../handler/CreateRateCommandHandler.java | 21 +- .../handler/UpdateRateCommandHandler.java | 23 +- ...initionCommandFromApiJsonDeserializer.java | 112 +- .../portfolio/rate/service/RateAssembler.java | 75 +- .../rate/service/RateEnumerations.java | 32 +- .../rate/service/RateReadService.java | 15 +- .../rate/service/RateReadServiceImpl.java | 197 +- .../rate/service/RateWriteService.java | 3 +- .../rate/service/RateWriteServiceImpl.java | 15 +- .../savings/DepositAccountOnClosureType.java | 10 +- .../DepositAccountOnHoldTransactionType.java | 2 +- .../portfolio/savings/DepositAccountType.java | 2 +- .../savings/DepositsApiConstants.java | 86 +- .../PreClosurePenalInterestOnType.java | 1 + .../savings/RecurringDepositType.java | 1 + .../SavingsAccountTransactionType.java | 11 +- .../savings/SavingsApiConstants.java | 18 +- .../SavingsCompoundingInterestPeriodType.java | 2 +- ...ingsInterestCalculationDaysInYearType.java | 2 +- .../SavingsInterestCalculationType.java | 2 +- .../savings/SavingsPeriodFrequencyType.java | 1 + .../SavingsPostingInterestPeriodType.java | 2 +- .../savings/SavingsWithdrawalFeesType.java | 2 +- ...ountOnHoldFundTransactionsApiResource.java | 11 +- ...DepositAccountTransactionsApiResource.java | 22 +- .../api/FixedDepositAccountsApiResource.java | 172 +- ...ixedDepositAccountsApiResourceSwagger.java | 124 +- .../api/FixedDepositProductsApiResource.java | 50 +- ...ixedDepositProductsApiResourceSwagger.java | 156 +- ...DepositAccountTransactionsApiResource.java | 78 +- ...AccountTransactionsApiResourceSwagger.java | 52 +- .../RecurringDepositAccountsApiResource.java | 164 +- ...ringDepositAccountsApiResourceSwagger.java | 120 +- .../RecurringDepositProductsApiResource.java | 51 +- ...ringDepositProductsApiResourceSwagger.java | 161 +- .../api/SavingsAccountChargesApiResource.java | 108 +- ...vingsAccountChargesApiResourceSwagger.java | 69 +- ...SavingsAccountTransactionsApiResource.java | 19 +- .../api/SavingsAccountsApiResource.java | 213 +- .../SavingsAccountsApiResourceSwagger.java | 96 +- .../savings/api/SavingsApiSetConstants.java | 60 +- .../api/SavingsProductsApiResource.java | 58 +- .../SavingsProductsApiResourceSwagger.java | 212 +- .../data/ClosingOfSavingsAccounts.java | 17 +- .../savings/data/DepositAccountData.java | 56 +- .../data/DepositAccountDataValidator.java | 114 +- .../DepositAccountInterestRateChartData.java | 10 +- ...positAccountInterestRateChartSlabData.java | 8 +- .../DepositAccountOnHoldTransactionData.java | 7 +- ...epositAccountTransactionDataValidator.java | 54 +- .../savings/data/DepositProductData.java | 22 +- .../data/DepositProductDataValidator.java | 178 +- .../savings/data/FixedDepositAccountData.java | 127 +- .../savings/data/FixedDepositProductData.java | 111 +- .../portfolio/savings/data/GSIMContainer.java | 5 +- ...avingsIndividualMonitoringAccountData.java | 148 +- .../data/RecurringDepositAccountData.java | 108 +- .../data/RecurringDepositProductData.java | 98 +- .../data/SavingsAccountAnnualFeeData.java | 2 +- ...SavingsAccountApplicationTimelineData.java | 2 +- .../data/SavingsAccountChargeData.java | 7 +- .../SavingsAccountChargeDataValidator.java | 8 +- .../savings/data/SavingsAccountConstant.java | 37 +- .../savings/data/SavingsAccountData.java | 231 +- .../savings/data/SavingsAccountDataDTO.java | 4 +- .../data/SavingsAccountDataValidator.java | 91 +- .../data/SavingsAccountStatusEnumData.java | 2 +- .../data/SavingsAccountSubStatusEnumData.java | 6 +- .../data/SavingsAccountSummaryData.java | 4 +- .../data/SavingsAccountTransactionDTO.java | 4 +- .../data/SavingsAccountTransactionData.java | 73 +- ...avingsAccountTransactionDataValidator.java | 23 +- .../SavingsAccountTransactionEnumData.java | 2 +- .../savings/data/SavingsActivation.java | 7 +- .../savings/data/SavingsApproval.java | 7 +- .../savings/data/SavingsProductData.java | 92 +- .../data/SavingsProductDataValidator.java | 317 +- .../savings/data/TransactionDateData.java | 2 +- .../domain/DepositAccountAssembler.java | 33 +- .../domain/DepositAccountDomainService.java | 11 +- .../DepositAccountDomainServiceJpa.java | 64 +- .../DepositAccountInterestRateChart.java | 4 +- .../DepositAccountInterestRateChartSlabs.java | 7 +- .../DepositAccountOnHoldTransaction.java | 2 +- ...sitAccountOnHoldTransactionRepository.java | 6 +- .../domain/DepositAccountRecurringDetail.java | 9 +- .../DepositAccountTermAndPreClosure.java | 20 +- .../domain/DepositPreClosureDetail.java | 2 +- .../domain/DepositProductAmountDetails.java | 5 +- .../domain/DepositProductAssembler.java | 26 +- .../domain/DepositProductRecurringDetail.java | 2 +- .../DepositProductTermAndPreClosure.java | 2 +- .../domain/DepositRecurringDetail.java | 2 +- .../savings/domain/DepositTermDetail.java | 20 +- .../savings/domain/FixedDepositAccount.java | 47 +- .../domain/FixedDepositAccountRepository.java | 6 +- .../savings/domain/FixedDepositProduct.java | 20 +- .../domain/FixedDepositProductRepository.java | 6 +- .../savings/domain/GSIMRepositoy.java | 8 +- .../GroupSavingsIndividualMonitoring.java | 160 +- .../domain/RecurringDepositAccount.java | 84 +- .../RecurringDepositAccountRepository.java | 6 +- .../domain/RecurringDepositProduct.java | 2 +- .../RecurringDepositProductRepository.java | 6 +- .../RecurringDepositScheduleInstallment.java | 16 +- .../savings/domain/SavingsAccount.java | 275 +- .../domain/SavingsAccountAssembler.java | 16 +- .../savings/domain/SavingsAccountCharge.java | 50 +- .../domain/SavingsAccountChargeAssembler.java | 8 +- .../SavingsAccountChargeRepository.java | 4 +- ...SavingsAccountChargeRepositoryWrapper.java | 3 +- .../domain/SavingsAccountDomainService.java | 2 +- .../SavingsAccountDomainServiceJpa.java | 11 +- .../domain/SavingsAccountRepository.java | 4 +- .../SavingsAccountRepositoryWrapper.java | 37 +- .../domain/SavingsAccountStatusType.java | 2 +- .../domain/SavingsAccountSubStatusEnum.java | 12 +- .../savings/domain/SavingsAccountSummary.java | 3 +- .../domain/SavingsAccountTransaction.java | 69 +- .../SavingsAccountTransactionComparator.java | 2 +- .../SavingsAccountTransactionRepository.java | 4 +- ...vingsAccountTransactionSummaryWrapper.java | 6 +- .../savings/domain/SavingsHelper.java | 20 +- .../savings/domain/SavingsProduct.java | 39 +- .../domain/SavingsProductAssembler.java | 6 +- .../domain/SavingsProductChargeAssembler.java | 8 +- .../domain/SavingsProductRepository.java | 2 +- .../interest/AnnualCompoundingPeriod.java | 15 +- .../interest/BiAnnualCompoundingPeriod.java | 15 +- .../interest/CompoundInterestHelper.java | 5 +- .../domain/interest/CompoundingPeriod.java | 3 +- .../interest/DailyCompoundingPeriod.java | 14 +- .../domain/interest/EndOfDayBalance.java | 18 +- .../interest/MonthlyCompoundingPeriod.java | 15 +- .../domain/interest/PostingPeriod.java | 94 +- .../interest/QuarterlyCompoundingPeriod.java | 15 +- ...untInterestRateChartNotFoundException.java | 6 +- .../DepositAccountNotFoundException.java | 6 +- ...AccountTransactionNotAllowedException.java | 8 +- .../FixedDepositProductNotFoundException.java | 2 +- .../InsufficientAccountBalanceException.java | 2 +- .../PostInterestAsOnDateException.java | 23 +- ...urringDepositProductNotFoundException.java | 2 +- .../SavingsAccountNotFoundException.java | 5 +- ...gsAccountTransactionNotFoundException.java | 5 +- ...ctivityPriorToClientTransferException.java | 2 +- ...SavingsOfficerAssignmentDateException.java | 5 +- ...vingsOfficerUnassignmentDateException.java | 1 - .../SavingsOfficerUnassignmentException.java | 3 +- .../SavingsProductNotFoundException.java | 2 +- ...erTransactionsCannotBeUndoneException.java | 2 +- .../TransactionUpdateNotAllowedException.java | 5 +- ...vateFixedDepositAccountCommandHandler.java | 2 +- ...RecurringDepositAccountCommandHandler.java | 2 +- .../ActivateSavingsAccountCommandHandler.java | 2 +- ...AddSavingsAccountChargeCommandHandler.java | 2 +- ...AnnualFeeSavingsAccountCommandHandler.java | 2 +- ...restFixedDepositAccountCommandHandler.java | 2 +- ...RecurringDepositAccountCommandHandler.java | 2 +- ...eInterestSavingsAccountCommandHandler.java | 2 +- ...loseFixedDepositAccountCommandHandler.java | 2 +- .../handler/CloseGSIMCommandHandler.java | 6 +- ...RecurringDepositAccountCommandHandler.java | 2 +- ...eateFixedDepositProductCommandHandler.java | 2 +- ...RecurringDepositProductCommandHandler.java | 2 +- .../CreateSavingsProductCommandHandler.java | 2 +- ...leteFixedDepositProductCommandHandler.java | 2 +- ...RecurringDepositProductCommandHandler.java | 2 +- ...eteSavingsAccountChargeCommandHandler.java | 2 +- .../DeleteSavingsProductCommandHandler.java | 2 +- .../DepositSavingsAccountCommandHandler.java | 2 +- ...ountApplicationApprovalCommandHandler.java | 2 +- ...ApplicationApprovalUndoCommandHandler.java | 2 +- ...ountApplicationDeletionCommandHandler.java | 2 +- ...ApplicationModificationCommandHandler.java | 2 +- ...ountApplicationRejectedCommandHandler.java | 2 +- ...untApplicationSubmittalCommandHandler.java | 2 +- ...ionWithdrawnByApplicantCommandHandler.java | 2 +- ...edDepositAccountDepositCommandHandler.java | 2 +- ...itTransactionAdjustmentCommandHandler.java | 2 +- .../GSIMAccountActivationCommandHandler.java | 6 +- ...GSIMApplicationApprovalCommandHandler.java | 10 +- ...ApplicationModificationCommandHandler.java | 27 +- .../GSIMApplicationRejectionHandler.java | 9 +- ...SIMApplicationSubmittalCommandHandler.java | 9 +- .../handler/GSIMDepositCommandHandler.java | 2 - .../GSIMUndoApprovalCommandHandler.java | 6 +- ...PaySavingsAccountChargeCommandHandler.java | 2 +- ...restFixedDepositAccountCommandHandler.java | 2 +- ...RecurringDepositAccountCommandHandler.java | 2 +- ...tInterestSavingsAccountCommandHandler.java | 2 +- ...loseFixedDepositAccountCommandHandler.java | 2 +- ...RecurringDepositAccountCommandHandler.java | 5 +- ...ountApplicationApprovalCommandHandler.java | 6 +- ...ApplicationApprovalUndoCommandHandler.java | 2 +- ...ountApplicationDeletionCommandHandler.java | 2 +- ...ApplicationModificationCommandHandler.java | 2 +- ...ountApplicationRejectedCommandHandler.java | 2 +- ...untApplicationSubmittalCommandHandler.java | 2 +- ...ionWithdrawnByApplicantCommandHandler.java | 2 +- ...ngDepositAccountDepositCommandHandler.java | 2 +- ...ountUpdateDepositAmountCommandHandler.java | 2 +- ...itTransactionAdjustmentCommandHandler.java | 5 +- ...ountApplicationApprovalCommandHandler.java | 2 +- ...ApplicationApprovalUndoCommandHandler.java | 2 +- ...ApplicationModificationCommandHandler.java | 2 +- ...ountApplicationRejectedCommandHandler.java | 2 +- ...untApplicationSubmittalCommandHandler.java | 2 +- ...ionWithdrawnByApplicantCommandHandler.java | 2 +- ...tionFixedDepositAccountCommandHandler.java | 2 +- ...RecurringDepositAccountCommandHandler.java | 5 +- ...ansactionSavingsAccountCommandHandler.java | 2 +- ...dateFixedDepositProductCommandHandler.java | 2 +- ...RecurringDepositProductCommandHandler.java | 2 +- ...ateSavingsAccountChargeCommandHandler.java | 2 +- .../UpdateSavingsProductCommandHandler.java | 2 +- ...thHoldTaxSavingsAccountCommandHandler.java | 2 +- ...iveSavingsAccountChargeCommandHandler.java | 2 +- .../WithdrawSavingsAccountCommandHandler.java | 2 +- ...awalFixedDepositAccountCommandHandler.java | 2 +- ...RecurringDepositAccountCommandHandler.java | 2 +- ...erestRateChartReadPlatformServiceImpl.java | 19 +- ...oldTransactionReadPlatformServiceImpl.java | 3 +- ...eMatureCalculationPlatformServiceImpl.java | 18 +- .../DepositAccountReadPlatformService.java | 3 +- ...DepositAccountReadPlatformServiceImpl.java | 235 +- .../DepositAccountWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 108 +- ...pplicationProcessWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 61 +- ...DepositProductReadPlatformServiceImpl.java | 54 +- .../DepositsDropdownReadPlatformService.java | 2 +- ...positsDropdownReadPlatformServiceImpl.java | 12 +- ...xedDepositProductWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 20 +- .../service/GSIMReadPlatformService.java | 4 +- .../service/GSIMReadPlatformServiceImpl.java | 573 +- ...ividualMonitoringWritePlatformService.java | 7 +- ...ualMonitoringWritePlatformServiceImpl.java | 80 +- ...ingDepositProductWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 16 +- ...ApplicationTransitionApiJsonValidator.java | 2 +- ...sAccountChargeReadPlatformServiceImpl.java | 27 +- .../SavingsAccountReadPlatformService.java | 9 +- ...SavingsAccountReadPlatformServiceImpl.java | 188 +- .../SavingsAccountWritePlatformService.java | 3 +- ...WritePlatformServiceJpaRepositoryImpl.java | 171 +- ...pplicationProcessWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 311 +- .../SavingsDropdownReadPlatformService.java | 2 +- ...avingsDropdownReadPlatformServiceImpl.java | 14 +- .../savings/service/SavingsEnumerations.java | 183 +- ...SavingsProductReadPlatformServiceImpl.java | 26 +- .../SavingsProductWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 20 +- .../service/SavingsSchedularService.java | 1 - .../service/SavingsSchedularServiceImpl.java | 15 +- .../portfolio/search/SearchConstants.java | 11 +- .../search/api/SearchApiResource.java | 41 +- .../search/api/SearchApiResourceSwagger.java | 8 +- .../search/data/AdHocQueryDataValidator.java | 140 +- .../data/AdHocQuerySearchConstants.java | 12 +- .../search/data/SearchConditions.java | 35 +- .../portfolio/search/data/SearchData.java | 5 +- .../SearchReadPlatformServiceImpl.java | 12 +- .../api/SelfAccountTransferApiResource.java | 201 +- ...SelfAccountTransferApiResourceSwagger.java | 29 +- .../api/SelfBeneficiariesTPTApiResource.java | 103 +- ...elfBeneficiariesTPTApiResourceSwagger.java | 39 +- .../account/data/SelfAccountTemplateData.java | 29 +- .../account/data/SelfAccountTransferData.java | 3 +- .../SelfAccountTransferDataValidator.java | 118 +- .../data/SelfBeneficiariesTPTData.java | 10 +- .../SelfBeneficiariesTPTDataValidator.java | 96 +- .../account/domain/SelfBeneficiariesTPT.java | 9 +- .../SelfBeneficiariesTPTRepository.java | 5 +- ...ficiaryTransferLimitExceededException.java | 3 +- ...ansactionAmountLimitExceededException.java | 7 +- .../InvalidAccountInformationException.java | 13 +- .../InvalidBeneficiaryException.java | 7 +- ...AddSelfBeneficiariesTPTCommandHandler.java | 7 +- ...eteSelfBeneficiariesTPTCommandHandler.java | 7 +- ...ateSelfBeneficiariesTPTCommandHandler.java | 7 +- .../SelfAccountTransferReadService.java | 3 +- .../SelfAccountTransferReadServiceImpl.java | 59 +- ...lfBeneficiariesTPTReadPlatformService.java | 3 +- ...neficiariesTPTReadPlatformServiceImpl.java | 84 +- ...eficiariesTPTWritePlatformServiceImpl.java | 67 +- .../client/api/SelfClientsApiResource.java | 144 +- .../api/SelfClientsApiResourceSwagger.java | 88 +- .../client/data/SelfClientDataValidator.java | 21 +- .../AppuserClientMapperReadServiceImpl.java | 16 +- .../loanaccount/api/SelfLoansApiResource.java | 143 +- .../api/SelfLoansApiResourceSwagger.java | 172 +- .../data/SelfLoansDataValidator.java | 94 +- .../AppuserLoansMapperReadServiceImpl.java | 14 +- .../self/pockets/api/PocketApiResource.java | 98 +- .../pockets/api/PocketApiResourceSwagger.java | 36 +- .../data/PocketAccountMappingData.java | 6 +- .../pockets/data/PocketDataValidator.java | 43 +- .../portfolio/self/pockets/domain/Pocket.java | 6 +- .../pockets/domain/PocketAccountMapping.java | 6 +- ...PocketAccountMappingRepositoryWrapper.java | 7 +- .../self/pockets/domain/PocketRepository.java | 2 +- .../domain/PocketRepositoryWrapper.java | 5 +- .../MappingIdNotLinkedToPocketException.java | 5 +- ...elinkAccountsFromPocketCommandHandler.java | 1 + .../service/AccountEntityServiceFactory.java | 19 +- .../AccountEntityServiceForLoanImpl.java | 6 +- .../AccountEntityServiceForSavingsImpl.java | 3 +- ...ountEntityServiceForShareAccountsImpl.java | 1 - ...AccountMappingReadPlatformServiceImpl.java | 10 +- .../service/PocketWritePlatformService.java | 1 - .../PocketWritePlatformServiceImpl.java | 14 +- .../api/SelfLoanProductsApiResource.java | 217 +- .../api/SelfSavingsProductsApiResource.java | 3 +- .../api/SelfShareProductsApiResource.java | 9 +- .../registration/SelfServiceApiConstants.java | 14 +- .../SelfServiceRegistrationApiResource.java | 9 +- .../SelfServiceRegistrationRepository.java | 4 +- ...fServiceRegistrationNotFoundException.java | 4 +- ...eRegistrationWritePlatformServiceImpl.java | 20 +- .../runreport/SelfRunReportApiResource.java | 32 +- .../SelfRunReportApiResourceSwagger.java | 32 +- .../savings/api/SelfSavingsApiResource.java | 89 +- .../api/SelfSavingsApiResourceSwagger.java | 76 +- .../data/SelfSavingsDataValidator.java | 110 +- .../AppuserSavingsMapperReadServiceImpl.java | 17 +- .../api/SelfAuthenticationApiResource.java | 12 +- .../SelfAuthenticationApiResourceSwagger.java | 16 +- .../security/api/SelfUserApiResource.java | 54 +- .../api/SelfUserApiResourceSwagger.java | 16 +- .../api/SelfUserDetailsApiResource.java | 21 +- .../SelfUserDetailsApiResourceSwagger.java | 16 +- .../api/SelfShareAccountsApiResource.java | 205 +- .../SelfShareAccountsApiResourceSwagger.java | 168 +- .../data/SelfShareAccountsDataValidator.java | 14 +- ...AccountsMapperReadPlatformServiceImpl.java | 18 +- .../spm/api/SelfScorecardApiResource.java | 13 +- .../self/spm/api/SelfSpmApiResource.java | 6 +- .../ShareAccountApplicationTimelineData.java | 8 +- .../data/ShareAccountChargeData.java | 12 +- .../shareaccounts/data/ShareAccountData.java | 85 +- .../data/ShareAccountDividendData.java | 12 +- .../data/ShareAccountStatusEnumData.java | 2 +- .../data/ShareAccountTransactionData.java | 16 +- .../data/ShareAccountTransactionEnumData.java | 1 - .../domain/PurchasedSharesStatusType.java | 6 +- .../shareaccounts/domain/ShareAccount.java | 91 +- .../domain/ShareAccountCharge.java | 18 +- .../domain/ShareAccountChargePaidBy.java | 29 +- .../ShareAccountDividendRepository.java | 4 +- .../domain/ShareAccountRepository.java | 1 - .../domain/ShareAccountRepositoryWrapper.java | 12 +- .../domain/ShareAccountStatusType.java | 2 +- .../domain/ShareAccountTransaction.java | 134 +- .../IssueableSharesExceededException.java | 2 +- .../ActivateShareAccountCommandHandler.java | 8 +- .../ApplyAddtionalSharesCommandHandler.java | 8 +- .../ApproveAddtionalSharesCommandHandler.java | 8 +- .../ApproveShareAccountCommandHandler.java | 8 +- .../CloseShareAccountCommandHandler.java | 8 +- .../CreateShareAccountCommandHandler.java | 8 +- .../handler/RedeemSharesCommandHandler.java | 8 +- .../RejectAddtionalSharesCommandHandler.java | 8 +- .../RejectShareAccountCommandHandler.java | 8 +- ...UndoApproveShareAccountCommandHandler.java | 8 +- .../UpdateShareAccountCommandHandler.java | 4 +- .../ShareAccountDataSerializer.java | 355 +- .../PurchasedSharesReadPlatformService.java | 2 +- ...urchasedSharesReadPlatformServiceImpl.java | 59 +- ...ShareAccountChargeReadPlatformService.java | 2 +- ...eAccountChargeReadPlatformServiceImpl.java | 71 +- .../ShareAccountCommandsServiceImpl.java | 35 +- ...ccountDividendReadPlatformServiceImpl.java | 3 +- .../ShareAccountReadPlatformService.java | 3 +- .../ShareAccountReadPlatformServiceImpl.java | 49 +- .../service/ShareAccountSchedularService.java | 2 - .../ShareAccountWritePlatformService.java | 18 +- ...WritePlatformServiceJpaRepositoryImpl.java | 85 +- .../service/SharesEnumerations.java | 36 +- .../SharePeriodFrequencyType.java | 1 + .../api/ShareDividendApiResource.java | 6 +- .../shareproducts/data/ShareProductData.java | 24 +- .../data/ShareProductMarketPriceData.java | 10 +- .../shareproducts/domain/ShareProduct.java | 35 +- .../ShareProductDividendPayOutDetails.java | 2 +- .../ShareProductDividendStatusType.java | 1 - ...roductDividentPayOutDetailsRepository.java | 4 +- ...ividentPayOutDetailsRepositoryWrapper.java | 4 +- .../domain/ShareProductMarketPrice.java | 16 +- .../domain/ShareProductRepository.java | 1 - .../domain/ShareProductRepositoryWrapper.java | 11 +- .../exception/DividendNotFoundException.java | 2 +- .../ShareAccountsNotFoundException.java | 3 +- .../CreateShareProductCommandHandler.java | 4 +- .../UpdateShareProductCommandHandler.java | 4 +- .../ShareProductDataSerializer.java | 112 +- .../ShareProductCommandsServiceImpl.java | 10 +- .../ShareProductDividendAssembler.java | 20 +- ...roductDividendReadPlatformServiceImpl.java | 3 +- ...areProductDropdownReadPlatformService.java | 2 +- ...roductDropdownReadPlatformServiceImpl.java | 4 +- .../ShareProductReadPlatformServiceImpl.java | 8 +- ...WritePlatformServiceJpaRepositoryImpl.java | 52 +- .../tax/api/TaxComponentApiResource.java | 34 +- .../api/TaxComponentApiResourceSwagger.java | 40 +- .../tax/api/TaxGroupApiResource.java | 33 +- .../tax/api/TaxGroupApiResourceSwagger.java | 48 +- .../portfolio/tax/domain/TaxComponent.java | 8 +- .../tax/domain/TaxComponentHistory.java | 13 +- .../domain/TaxComponentRepositoryWrapper.java | 3 +- .../portfolio/tax/domain/TaxGroup.java | 2 +- .../tax/domain/TaxGroupRepositoryWrapper.java | 3 +- .../TaxMappingNotFoundException.java | 2 +- .../tax/serialization/TaxValidator.java | 50 +- .../portfolio/tax/service/TaxAssembler.java | 4 +- .../service/TaxReadPlatformServiceImpl.java | 4 +- .../transfer/api/TransferApiConstants.java | 2 +- .../transfer/data/TransfersDataValidator.java | 38 +- ...tNotAwaitingTransferApprovalException.java | 4 +- ...tingTransferApprovalOrOnHoldException.java | 4 +- .../TransferNotSupportedException.java | 11 +- .../AcceptClientTransferCommandHandler.java | 2 +- ...AndAcceptClientTransferCommandHandler.java | 2 +- .../ProposeClientTransferCommandHandler.java | 2 +- .../RejectClientTransferCommandHandler.java | 2 +- ...ferClientsBetweenGroupsCommandHandler.java | 2 +- .../WithdrawClientTransferCommandHandler.java | 2 +- .../transfer/service/TransferEventType.java | 5 +- .../service/TransferWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 66 +- .../service/ScheduledJobRunnerService.java | 2 +- .../ScheduledJobRunnerServiceImpl.java | 134 +- .../spm/api/LookupTableApiResource.java | 35 +- .../spm/api/ScorecardApiResource.java | 18 +- .../fineract/spm/api/SpmApiResource.java | 27 +- .../fineract/spm/data/ComponentData.java | 3 +- .../fineract/spm/data/LookupTableData.java | 3 +- .../fineract/spm/data/QuestionData.java | 2 +- .../fineract/spm/data/ResponseData.java | 3 +- .../fineract/spm/data/ScorecardValue.java | 3 - .../apache/fineract/spm/data/SurveyData.java | 5 +- .../apache/fineract/spm/domain/Survey.java | 8 +- .../fineract/spm/domain/SurveyValidator.java | 4 +- .../SurveyResponseNotAvailableException.java | 3 +- .../spm/repository/LookupTableRepository.java | 1 + .../spm/repository/ScorecardRepository.java | 1 + .../spm/service/LookupTableService.java | 3 +- .../service/ScorecardReadPlatformService.java | 3 +- .../ScorecardReadPlatformServiceImpl.java | 3 +- .../spm/service/ScorecardService.java | 3 +- .../fineract/spm/service/SpmService.java | 28 +- .../fineract/spm/util/LookupTableMapper.java | 4 +- .../fineract/spm/util/ScorecardMapper.java | 30 +- .../fineract/spm/util/SurveyApiConstants.java | 3 +- .../fineract/spm/util/SurveyMapper.java | 25 +- .../template/api/TemplatesApiResource.java | 48 +- .../api/TemplatesApiResourcesSwagger.java | 17 + .../fineract/template/domain/Template.java | 38 +- .../domain/TemplateEntitySerializer.java | 4 +- .../template/domain/TemplateFunctions.java | 2 +- .../domain/TemplateTypeSerializer.java | 4 +- .../exception/TemplateNotFoundException.java | 2 +- .../service/JpaTemplateDomainService.java | 40 +- .../service/TemplateMergeService.java | 16 +- .../template/service/TrustModifier.java | 9 +- .../api/PasswordPreferencesApiConstants.java | 3 +- .../api/PasswordPreferencesApiResource.java | 23 +- ...PasswordPreferencesApiResourceSwagger.java | 5 + .../api/PermissionsApiResource.java | 33 +- .../api/PermissionsApiResourceSwagger.java | 8 +- .../api/RolesApiResource.java | 59 +- .../api/RolesApiResourceSwagger.java | 32 +- .../api/UsersApiResource.java | 60 +- .../api/UsersApiResourceSwagger.java | 22 + .../command/PermissionsCommand.java | 2 +- .../useradministration/data/AppUserData.java | 44 +- .../data/PasswordValidationPolicyData.java | 2 +- .../data/PermissionData.java | 2 +- .../useradministration/data/RoleData.java | 4 +- .../data/RolePermissionsData.java | 2 +- .../useradministration/domain/AppUser.java | 42 +- .../domain/AppUserClientMapping.java | 16 +- .../domain/AppUserPreviousPassword.java | 2 +- .../AppUserPreviousPasswordRepository.java | 4 +- .../domain/AppUserRepositoryWrapper.java | 12 +- .../domain/JpaUserDomainService.java | 6 +- .../domain/PasswordValidationPolicy.java | 2 +- .../PasswordValidationPolicyRepository.java | 6 +- .../domain/RoleRepository.java | 2 +- .../PasswordPreviouslyUsedException.java | 3 +- ...wordValidationPolicyNotFoundException.java | 5 +- ...issionCantBeMakerCheckerableException.java | 2 +- .../PermissionNotFoundException.java | 2 +- .../exception/RoleAssociatedException.java | 3 +- .../exception/RoleNotFoundException.java | 2 +- .../exception/UserNotFoundException.java | 2 +- .../UsernameAlreadyExistsException.java | 2 +- .../handler/CreateRoleCommandHandler.java | 2 +- .../handler/CreateUserCommandHandler.java | 2 +- .../handler/DeleteUserCommandHandler.java | 2 +- ...MakerCheckerPermissionsCommandHandler.java | 2 +- ...datePasswordPreferencesCommandHandler.java | 2 +- .../handler/UpdateRoleCommandHandler.java | 2 +- .../UpdateRolePermissionsCommandHandler.java | 2 +- .../handler/UpdateUserCommandHandler.java | 2 +- ...issionsCommandFromApiJsonDeserializer.java | 2 +- .../service/AppUserReadPlatformService.java | 2 +- .../AppUserReadPlatformServiceImpl.java | 18 +- .../service/AppUserWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 43 +- ...sswordPreferencesWritePlatformService.java | 2 +- ...rdValidationPolicyReadPlatformService.java | 2 +- ...lidationPolicyReadPlatformServiceImpl.java | 2 +- .../PermissionReadPlatformService.java | 2 +- .../PermissionReadPlatformServiceImpl.java | 5 +- .../PermissionWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 6 +- .../service/RoleDataValidator.java | 2 +- .../service/RoleReadPlatformService.java | 2 +- .../service/RoleReadPlatformServiceImpl.java | 5 +- .../service/RoleWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 17 +- .../service/UserDataValidator.java | 38 +- .../src/main/resources/META-INF/orm.xml | 22 +- .../main/resources/META-INF/persistence.xml | 16 +- .../resources/META-INF/spring/appContext.xml | 152 +- .../main/resources/META-INF/spring/cache.xml | 24 +- .../resources/META-INF/spring/ehcache.xml | 60 +- .../META-INF/spring/hikariDataSource.xml | 14 +- .../META-INF/spring/infrastructure.xml | 44 +- .../resources/META-INF/spring/jdbc.properties | 2 +- .../META-INF/spring/securityContext.xml | 364 +- .../resources/META-INF/spring/spmContext.xml | 6 +- .../resources/META-INF/spring/swagger.xml | 2 +- .../V100__Group_saving_summary_report.sql | 2 +- ...mulitplesof_to_account_transfers_table.sql | 2 +- .../V102__client_attendance_tables.sql | 30 +- .../V103__cluster_support_for_batch_jobs.sql | 12 +- .../V104__permissions_for_transfers.sql | 2 +- ..._track_loan_transaction_against_office.sql | 2 +- .../V106__more_permissions_for_transfers.sql | 2 +- .../core_db/V107__datatable_code_mappings.sql | 10 +- .../V108__client_has_transfer_office.sql | 6 +- ..._transfer_withdrawal_fee_configuration.sql | 4 +- ...0__interest-posting-fields-for-savings.sql | 2 +- ...nse_account_for_existing_loan_products.sql | 2 +- ...int_approach_for_datatables_by_default.sql | 2 +- .../core_db/V112__mixreport_sql_support.sql | 112 +- ...ack_savings_transaction_against_office.sql | 2 +- ...t_for_existing_savings_products - Copy.sql | 2 +- .../V115__permissions_for_cache_api.sql | 2 +- ...16__track_currency_for_journal_entries.sql | 6 +- .../V117__loan_charge_from_savings.sql | 26 +- .../V118_1__savings_charge_patch_update.sql | 4 +- ...licate_fund_source_to_account_mappings.sql | 2 +- ..._account_for_existing_savings_products.sql | 2 +- ...ome_from_penalties_for savings_product.sql | 2 +- ..._move_withdrawal_annual_fee_to_charges.sql | 280 +- ...yments_seperately_in_loan_transactions.sql | 4 +- .../core_db/V118__savings_charge.sql | 72 +- .../core_db/V119__add_template_table.sql | 6 +- .../core_db/V11__add-payment-details.sql | 20 +- .../V120__accounting_running_balance.sql | 4 +- ...nting_running_balance_for_organization.sql | 2 +- ...122__recurring_fee_support_for_savings.sql | 8 +- .../V123__remove_payment_mode_for_savings.sql | 2 +- ...mn_for_actual_fee_amount_or_percentage.sql | 2 +- ...al_database_structure_for_sms_outbound.sql | 2 +- .../core_db/V127__mobile_no_fields.sql | 2 +- .../V128__added_loan_installment_charge.sql | 30 +- .../V129__client_and_group_timeline.sql | 2 +- ...2__add_external_id_to_couple_of_tables.sql | 14 +- .../core_db/V130__calendar-history-table.sql | 36 +- ..._holiday-status-column-and-permissions.sql | 6 +- .../core_db/V132__borrower_cycle_changes.sql | 24 +- ...ding_payment_detail_with_journal_entry.sql | 8 +- ...136_1__update_script_strechy_parameter.sql | 2 +- ...137__added_is_active_column_in_m_staff.sql | 2 +- ...r_m_product_loan_and_m_savings_product.sql | 16 +- ...r_is_active_updated_to_true_in_m_staff.sql | 4 +- ...yment_detail_id_in_ac_gl_journal_entry.sql | 4 +- .../V140__added_loan_charge_status.sql | 2 +- .../V144__spelling_mistake_corrections.sql | 2 +- ...orce_password_reset_in_c_configuration.sql | 2 +- .../core_db/V146__tranche_loans.sql | 42 +- ...147__tranche_loans_column_name_changes.sql | 6 +- .../core_db/V148__overdraft_changes.sql | 14 +- ...__add_created_date_savings_transaction.sql | 4 +- .../core_db/V14__rename_status_id_to_enum.sql | 2 +- .../core_db/V150__basic_savings_report.sql | 2 +- ..._add_default_savings_account_to_client.sql | 4 +- .../V152__added_grace_for_over_due.sql | 4 +- .../V153__Insert_missed_permissions.sql | 2 +- .../core_db/V154__aging_details.sql | 2 +- .../core_db/V155__stretchy_into_pentaho.sql | 2 - .../V156__added_loan_saving_txns_pentaho.sql | 2 +- .../V157__overdue_charge_improvements.sql | 18 +- ...n_id_column_m_portfolio_command_source.sql | 2 +- .../core_db/V15__center_permissions.sql | 2 +- ..._nullValue_For_principal_on_lonProduct.sql | 2 +- .../V160__standing_instruction_changes.sql | 184 +- .../core_db/V161__added_accrual_batch_job.sql | 6 +- .../V162__overdue_charge_batch_job.sql | 2 +- .../core_db/V163__added_npa_for_loans.sql | 6 +- .../V164__fd_and_rd_deposit_tables.sql | 4 +- ...mission_for_disburse_to_saving_account.sql | 2 +- ..._amount_to_product_term_and_preclosure.sql | 8 +- ...xed_deposit_interest_to_linked_account.sql | 6 +- ...ts_to_core_reports_use_report_to_false.sql | 2 +- ...V16__drop_min_max_column_on_loan_table.sql | 12 +- ..._deposit_accounts_maturity_details_job.sql | 2 +- ...added_mandatory_savings_and_rd_changes.sql | 98 +- ...V172__accounting_changes_for_transfers.sql | 18 +- .../sql/migrations/core_db/V173__ppi.sql | 80 +- .../V175__added_incentive_interest_rates.sql | 66 +- ...updates_to_financial_activity_accounts.sql | 8 +- .../V177__cleanup_for_client_incentives.sql | 2 +- ...tes_to_financial_activity_accounts_pt2.sql | 2 +- ...on_names_for_maker_checker_permissions.sql | 2 +- .../V17__update_stretchy_reporting_ddl.sql | 2 +- ...waitingdisbursal_and_groupnamesbystaff.sql | 2 +- .../V181__standing_instruction_logging.sql | 18 +- ...in_required_balance_to_savings_product.sql | 8 +- ...d_min_balance_for_interest_calculation.sql | 4 +- ...n_required_balance_for_savings_product.sql | 4 +- ...accrual_till_date_for_periodic_accrual.sql | 2 +- .../V186__added_periodic_accrual_job.sql | 2 +- ...__added_permission_to_periodic_accrual.sql | 2 +- ...d_savingscharge_inactivate_permissions.sql | 2 +- ...__m_loan_interest_recalculation_tables.sql | 36 +- ...ategroup_disassociategroup_permissions.sql | 2 +- ...e_gl_account_increase_size_of_name_col.sql | 2 +- .../V192__interest_recalculate_job.sql | 2 +- ...93__added_column_joiningDate_for_staff.sql | 2 +- ...stComponent_for_interest_recalculation.sql | 2 +- ..._moved_rest_frequency_to_product_level.sql | 12 +- ...d_loan_running_balance_to_transactions.sql | 2 +- ...d_loan_running_balance_of_transactions.sql | 8 +- ...ed_extra_columns_from_schedule_history.sql | 38 +- .../V1__mifosplatform-core-ddl-latest.sql | 40 +- .../sql/migrations/core_db/V201__webhooks.sql | 2 - .../V202__savings_officer_history_table.sql | 1 - ...cript_for_charges_paid_by_for_accruals.sql | 2 +- ...arge_and_interest_waiver_with_accruals.sql | 6 +- .../V206__interest_posting_configuration.sql | 2 +- .../V207__min_max_clients_per_group.sql | 4 +- .../V208__min_max_clients_in_group_redux.sql | 6 +- ...__track_manually_adjusted_transactions.sql | 2 +- ..._between_disbursal_and_first_repayment.sql | 2 +- ..._add_NthDay_and_DayOfWeek_columns_loan.sql | 2 +- ...d_DayOfWeek_columns_should_be_nullable.sql | 4 +- .../V215__guarantee_on_hold_fund_changes.sql | 24 +- ...6__adding_loan_proposed_amount_to_loan.sql | 4 +- ...nt_substatus_and_codevalue_description.sql | 11 +- ...datetime_for_loan_savings_transactions.sql | 10 +- ...antor_on_hold_fund_changes_for_account.sql | 69 +- ...21__activation-permissions-for-clients.sql | 2 +- .../V220__account_number_preferences.sql | 12 +- ...221__add_version_for_m_savings_account.sql | 2 +- ..._on_hold_fund_changes_for_transactions.sql | 15 +- .../V223__add_version_for_m_loan_account.sql | 2 +- ...V224__client_lifecycle_adding_statuses.sql | 26 +- ..._for_enforcing_calendars_for_jlg_loans.sql | 2 +- .../core_db/V227__loan-refund-permissions.sql | 15 +- .../core_db/V228__entity_to_entity_access.sql | 42 +- .../core_db/V229__teller_cash_management.sql | 206 +- ...-group-for-consistency-add-permissions.sql | 2 +- ...le_status_and_correspoding_permissions.sql | 2 +- ...ashier_transaction_added_currency_code.sql | 2 +- .../V232__insert_center_closure_reason.sql | 2 +- .../V233__Savings_Transaction_Receipt.sql | 6 +- .../core_db/V234__opening_balaces_setup.sql | 46 +- .../V235__add_ugd_template_id_m_hook.sql | 2 +- ...ndividual_collection_sheet_permissions.sql | 2 +- ...d_threshold_config_for_last_instalment.sql | 8 +- ...V238__update_staff_display_name_length.sql | 4 +- ...-configuration-for-client-group-status.sql | 2 +- ...ging_config_for_interest_recalculation.sql | 6 +- .../core_db/V241__fixed_emi_changes.sql | 4 +- .../V242__entitytoentitymappingrelation.sql | 32 +- .../V243__alter_loan_disbursement_details.sql | 2 +- .../V244__staff_assignment_history_table.sql | 2 +- .../core_db/V245__open_rd_changes.sql | 1 - ...p_group_client_foreign_key_from_m_loan.sql | 2 +- ...ng_principalThresholdForLastInstalment.sql | 2 +- ...__added_password_never_expired_to_User.sql | 2 +- .../core_db/V249__workingdays_permissions.sql | 3 - ...t-foreign-key-constraint-in-loan-table.sql | 2 +- .../V250__password_validation_policy.sql | 5 - .../core_db/V251__paymentType_table.sql | 46 +- .../V252__bug_fix_teller_cash_management.sql | 10 +- ...__product_loan_configurable_attributes.sql | 4 +- .../core_db/V254__General_Ledger_Report.sql | 21 +- ...V255__pre_close_interest_period_config.sql | 2 +- ...pdate script for General_Ledger_report.sql | 6 +- .../core_db/V257__staff_image_association.sql | 6 +- .../V258__interest_compounding_changes.sql | 16 +- .../core_db/V259__alter_working_days.sql | 2 +- ...or Client_Loan_Account_Schedule_Report.sql | 4 +- .../V262__accountNumber_for_groups.sql | 2 +- .../core_db/V263__mifos_reports.sql | 3 - .../V265__modify_external_service_schema.sql | 17 +- .../migrations/core_db/V266__client_fees.sql | 97 +- .../V267__client_transaction_permissions.sql | 2 +- .../core_db/V268__update_gmail_password.sql | 2 +- ...V269__increased_calendar_title_length .sql | 6 +- ...support-for-withdrawal-fees-on-savings.sql | 2 +- .../V270__add_rounding_mode_configuration.sql | 4 +- .../V271__accounting_for_client_charges.sql | 8 +- ...V272__loan_tranche_disbursement_charge.sql | 28 +- .../core_db/V273__oauth_changes.sql | 1 - .../V274__Loan_Reschedule_Code_Value.sql | 4 - ...nsaction_to_repayment_schedule_mapping.sql | 28 +- .../V276__loan_recalulated_till_date.sql | 2 +- .../V277__Loan_Product_Provisioning.sql | 129 +- ...278__LoanTransactionProcessingStrategy.sql | 9 +- .../core_db/V279__floating_rates.sql | 76 +- ...27__add-loan-type-column-to-loan-table.sql | 2 +- .../V280__spm_framework_initial_tables.sql | 18 +- ...configuration_param_backdate-penalties.sql | 1 - .../core_db/V282__CustomerSelfService.sql | 16 +- .../core_db/V283__Variable_Installments.sql | 30 +- .../core_db/V284__update_codevalue.sql | 2 +- .../V285__undo_last_tranche_script.sql | 1 - ...6__partial_period_interest_calcualtion.sql | 13 +- .../core_db/V289__client_non_person.sql | 39 +- ...ccounting-abstractions-and-autoposting.sql | 74 +- ...0__shares_dividends_permissions_script.sql | 2 +- .../V291__organisation_start_date_config.sql | 2 +- ...nterest_rate_chart_support_for_amounts.sql | 18 +- ...__skip_repayment_on first-day_of_month.sql | 2 +- .../V297__Adding_Meeting_Time_column.sql | 2 +- .../core_db/V298__savings_interest_tax.sql | 177 +- .../core_db/V299__share_products.sql | 98 +- ...add-support-for-annual-fees-on-savings.sql | 2 +- .../V2__mifosx-base-reference-data-utf8.sql | 30 +- ...ation_for_allow_changing_of_emi_amount.sql | 4 +- ...recurring_moratorium_principal_periods.sql | 6 +- .../V302__add_status_to_client_identifier.sql | 1 - ...mer_self_service_third_party_transfers.sql | 22 +- ...q_and_insertion_script_for_accrual_job.sql | 20 +- ..._domancy_tracking_job_to_savings_group.sql | 6 +- .../core_db/V307__add_share_notes.sql | 2 +- ...erest_recalculation_in_savings_account.sql | 5 +- .../V309__add_loan_write_off_reason_code.sql | 2 +- ...eferenceNumber-to-acc_gl_journal_entry.sql | 2 +- ...oentityaccess_to_entitytoentitymapping.sql | 4 +- .../core_db/V311__foreclosure_details.sql | 6 +- .../V312__add_is_mandatory_to_code_value.sql | 2 +- .../V313__multi_rescheduling_script.sql | 66 +- ...th_disbursement_date_in_m_product_loan.sql | 2 +- .../V316__address_module_tables_metadat.sql | 118 +- .../V317__report_mailing_job_module.sql | 6 +- .../migrations/core_db/V318__topuploan.sql | 23 +- .../core_db/V319__client_undoreject.sql | 6 +- ...21__boolean_field_As_Interest_PostedOn.sql | 2 +- .../V322_1__scheduled_email_campaign.sql | 53 +- .../core_db/V322_2__email_business_rules.sql | 2 +- .../migrations/core_db/V322__sms_campaign.sql | 114 +- .../core_db/V324__datatable_checks.sql | 24 +- .../V325__add_is_staff_client_data.sql | 2 +- ...ata_migration_for_client_tr_gl_entries.sql | 2 +- .../V327__creditbureau_configuration.sql | 8 +- .../V329__sms_messages_without_campaign.sql | 2 +- ...sociate-clients-from-group-permissions.sql | 2 +- ..._savings_account_transaction_releaseId.sql | 13 +- .../core_db/V331__holiday_schema_changes.sql | 2 +- ...V332__self_service_registration_schema.sql | 28 +- .../migrations/core_db/V333__adhocquery.sql | 28 +- .../V334__notification_module_tables.sql | 2 - .../core_db/V335__self_service_user_role.sql | 2 +- .../V336__sms_campaign_notification.sql | 29 +- .../core_db/V337__equal_amortization.sql | 2 +- .../V338__two_factor_authentication.sql | 2 +- .../core_db/V339__report-run-frequency.sql | 2 +- .../core_db/V340__nullable-adhoc-email.sql | 2 +- .../core_db/V341__m_import_document.sql | 2 +- ...ing_recalculate_interest_for_loans_job.sql | 2 +- .../V345__reports_for_self_service_user.sql | 3 +- ...6__nullable_saving_product_description.sql | 2 +- .../core_db/V348__m_trial_balance_table.sql | 14 +- .../core_db/V349__client_transfer_details.sql | 40 +- .../core_db/V351__pocket_mapping.sql | 26 +- .../migrations/core_db/V352__interop_init.sql | 34 +- ...4__self_service_user_unique_for_client.sql | 2 +- .../core_db/V356__GSIM_migration_script.sql | 38 +- .../core_db/V357__GLIM_migration_script.sql | 42 +- .../V358__fixed_deposit_rollover_transfer.sql | 2 +- ...dd_hierarchy_column_for_acc_gl_account.sql | 2 +- ...__add_tag_id_column_for_acc_gl_account.sql | 2 +- .../core_db/V39__payment-channels-updates.sql | 10 +- ...0__add_permissions_for_accounting_rule.sql | 2 +- ...t_value_for_id_for_acc_accounting_rule.sql | 2 +- .../core_db/V43__accounting-for-savings.sql | 2 +- ..._document-increase-size-of-column-type.sql | 2 +- .../V45__create_acc_rule_tags_table.sql | 20 +- .../core_db/V48__adding-S3-Support.sql | 44 +- ...track-loan-charge-payment-transactions.sql | 18 +- ...50__add-grace-settings-to-loan-product.sql | 2 +- ...ils-related-to-installment-performance.sql | 2 +- ...an_support_cols_to_acc_accounting_rule.sql | 2 +- ...vance-and-late-payments-on-installment.sql | 2 +- ...V54__charge-to-income-account-mappings.sql | 4 +- ...onal-transaction-processing-strategies.sql | 2 +- .../V56__track-overpaid-amount-on-loans.sql | 2 +- ...nd_credit_accounts_acc_accounting_rule.sql | 4 +- .../V58__create-holiday-tables_changed.sql | 16 +- ...add_group_roles_schema_and_permissions.sql | 26 +- ...ate-savings-product-and-account-tables.sql | 2 +- .../core_db/V60__quipo_dashboard_reports.sql | 96 +- .../V61__txn_running_balance_example.sql | 64 +- .../V62__add_staff_id_to_m_client_changed.sql | 2 +- ...sbursement_with_meeting_column_to_loan.sql | 2 +- .../V64__add_permission_for_assign_staff.sql | 2 +- .../core_db/V65__fix_rupee_symbol_issues.sql | 2 +- .../V68__quipo_dashboard_reports_updated.sql | 96 +- .../V69__loans_in_advance_initialise.sql | 2 +- ...__add_min_max_principal_column_to_loan.sql | 8 +- .../V70__quipo_program_detail_query_fix.sql | 4 +- ..._reschedule_repayment_to_configuration.sql | 2 +- .../V72__add_m_loan_counter_changes.sql | 26 +- ...led_to_and_processed_column_to_holiday.sql | 4 +- ...__alter_m_loan_counter_table_add_group.sql | 4 +- ...epayments-on-holidays_to_configuration.sql | 2 +- .../V77__alter_m_product_loan_changes.sql | 2 +- .../core_db/V79__schedule_jobs_tables.sql | 50 +- ...7__remove_read_makerchecker_permission.sql | 1 - .../V80__schedule_jobs_tables_updates.sql | 18 +- .../core_db/V81__savings_related_changes.sql | 2 +- ...jobs_tables_updates_for_running_status.sql | 4 +- .../core_db/V83__non-working-days-table.sql | 10 +- ...4__undo_savings_transaction_permission.sql | 2 +- .../V85__product_mix_related_changes.sql | 20 +- .../core_db/V86__update-working-days.sql | 2 +- .../V87__add_permission_for_scheduler.sql | 2 +- ...ed_update_constrain_for_scheduler_jobs.sql | 2 +- .../core_db/V89__added_scheduler_group.sql | 2 +- ...-transaction-permissions-if-they-exist.sql | 1 - ...ettings_for_holiday_and_non_workingday.sql | 2 +- .../V91__apply_annual_fees_permission.sql | 2 +- .../V93__loan_transaction_external_id.sql | 2 +- .../V94__added_savings_accont type.sql | 2 +- .../V96__savings_accounts_transfers_table.sql | 2 +- ...mission_for_adjust_savings_transaction.sql | 2 +- ..._added_currency_roundof_for_multipleof.sql | 12 +- ..._constraint_column_to_loan_loanproduct.sql | 56 +- .../V2__externalize-connection-properties.sql | 2 +- .../list_db/V3__deadlock-retry-properties.sql | 2 +- ...ns_and_tenants_server_connection_table.sql | 77 +- .../migrations/sample_data/barebones_db.sql | 4424 +++++++-------- .../sample_data/interop_sample_data.sql | 2 +- .../sample_data/load_sample_data.sql | 4902 ++++++++--------- .../main/resources/swagger-ui/response.json | 2 +- .../src/main/webapp/WEB-INF/web.xml | 14 +- .../common/AccountingConstantsTest.java | 9 +- .../provider/CommandHandlerProviderTest.java | 5 +- .../org/apache/fineract/common/Utils.java | 5 +- ...ClasspathHellDuplicatesCheckExtension.java | 20 +- .../ClasspathHellDuplicatesCheckRuleTest.java | 9 +- .../ClasspathHellDuplicatesChecker.java | 137 +- ...WithoutDatabaseAndNoJobsConfiguration.java | 6 +- .../core/exception/MultiExceptionTest.java | 4 +- .../security/utils/SQLBuilderTest.java | 11 +- .../mix/report/service/XBRLBuilderTest.java | 7 +- .../fineract/notification/Listener.java | 4 +- .../fineract/notification/StorageTest.java | 45 +- ...ymentScheduleTransactionProcessorTest.java | 3 +- ...ymentScheduleTransactionProcessorTest.java | 3 +- .../LoanProductRelatedDetailTestHelper.java | 10 +- ...anRepaymentScheduleInstallmentBuilder.java | 2 +- .../LoanScheduleTestDataHelper.java | 4 +- .../portfolio/loanaccount/MoneyBuilder.java | 2 +- .../template/TemplateMergeServiceTest.java | 4 +- 2899 files changed, 44572 insertions(+), 46101 deletions(-) mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientSavingsIntegrationTest.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ConcurrencyIntegrationTest.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FinancialActivityAccountsTest.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupTest.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ClientHelper.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CommonConstants.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/GroupHelper.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/OfficeHelper.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/WorkingDaysHelper.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/FinancialActivityAccountHelper.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/charges/ChargesHelper.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanTransactionHelper.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/StaffHelper.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsApplicationTestBuilder.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsStatusChecker.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorHelper.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorTest.java mode change 100755 => 100644 fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorTestBuilder.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/api/AccrualAccountingApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/handler/ExecutePeriodicAccrualCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/serialization/AccrualAccountingDataValidator.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/service/AccrualAccountingWritePlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosureJsonInputParams.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosuresApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosuresApiResourceSwagger.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/command/GLClosureCommand.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/data/GLClosureData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/domain/GLClosure.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureDuplicateException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureInvalidDeleteException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureInvalidException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/CreateGLClosureCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/DeleteGLClosureCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/UpdateGLClosureCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/serialization/GLClosureCommandFromApiJsonDeserializer.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/closure/service/GLClosureWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingDropdownReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingDropdownReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingRuleType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountJsonInputParams.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/data/GLAccountData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccountRepositoryWrapper.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccountType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountDuplicateException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidClassificationException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidDeleteException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidParentException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidUpdateException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidUsageException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/CreateGLAccountCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/DeleteGLAccountCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/UpdateGLAccountCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/serialization/GLAccountCommandFromApiJsonDeserializer.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntriesApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntryJsonInputParams.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/command/JournalEntryCommand.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/command/SingleDebitOrCreditEntryCommand.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/JournalEntryData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/JournalEntryDataValidator.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/LoanTransactionDTO.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/domain/JournalEntry.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/domain/JournalEntryRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntriesNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryInvalidException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/handler/CreateJournalEntryCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/handler/ReverseJournalEntryCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/serialization/JournalEntryCommandFromApiJsonDeserializer.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/AccountingProcessorHelper.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/AccrualBasedAccountingProcessorForLoan.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForLoan.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForSavings.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryRunningBalanceUpdateServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryWritePlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/PortfolioProductType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/ProductToGLAccountMapping.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/ProductToGLAccountMappingRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/exception/ProductToGLAccountMappingInvalidException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/exception/ProductToGLAccountMappingNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/serialization/ProductToGLAccountMappingFromApiJsonDeserializer.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/LoanProductToGLAccountMappingHelper.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingHelper.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/SavingsProductToGLAccountMappingHelper.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleJsonInputParams.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/data/AccountingRuleData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/domain/AccountingRule.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleDuplicateException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleInvalidDeleteException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleInvalidException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/CreateAccountingRuleCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/DeleteAccountingRuleCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/UpdateAccountingRuleCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/serialization/AccountingRuleCommandFromApiJsonDeserializer.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/service/AccountingRuleReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/accounting/rule/service/AccountingRuleWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/commands/api/MakercheckersApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/commands/data/AuditData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandSource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandWrapper.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/commands/service/AuditReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/commands/service/CommandWrapperBuilder.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/commands/service/PortfolioCommandSourceWritePlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/commands/service/SynchronousCommandProcessingService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationPropertyData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationProperty.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/Tenant.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformServiceUnavailableException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/SearchParameters.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/data/JobDetailDataValidator.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/data/JobDetailHistoryData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/exception/JobNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/exception/OperationNotAllowedException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/JobName.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerJobRunnerReadServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerTriggerListener.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffRepositoryWrapper.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDayValidator.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDaysData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDays.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDaysEnumerations.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/exception/WorkingDaysNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/handler/UpdateWorkingDaysCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/service/WorkingDaysReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/AccountDetailConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionHistoryApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransferDTO.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransfersDetailDataValidator.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionDTO.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionDataValidator.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountAssociationType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountAssociationsRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetailAssembler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetailRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetails.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferRecurrenceType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferStandingInstruction.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionAssembler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionPriority.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionStatus.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/exception/StandingInstructionNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionWritePlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionWritePlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountDetailsReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountDetailsReadPlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountEnumerations.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/data/ChargeData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/Charge.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargePaymentMode.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeTimeType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeMustBePenaltyException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeDeletedException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBePayedException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeUpdatedException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeWaivedException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/serialization/ChargeDefinitionCommandFromApiJsonDeserializer.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeEnumerations.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientRepositoryWrapper.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientActiveForUpdateException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientSavingsAccountCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierWritePlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralApiConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralsApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/command/CollateralCommand.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeCreatedException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeDeletedException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeUpdatedException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/CreateCollateralCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/DeleteCollateralCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/UpdateCollateralCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/serialization/CollateralCommandFromApiJsonDeserializer.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralWritePlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/api/CollectionSheetApiResourse.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualClientData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualCollectionSheetData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualCollectionSheetLoanFlatData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/common/BusinessEventNotificationConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DayOfWeekType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DaysInMonthType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DaysInYearType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/NthDayType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/BusinessEventNotifierServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/CommonEnumerations.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/DropdownReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupingTypesApiConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/group/serialization/GroupingTypesDataValidator.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestIncentiveApiConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestIncentiveDataValidator.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestIncentivesFields.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveAttributeName.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveEntityType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestIncentiveDropdownReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestIncentivesEnumerations.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanTransactionsApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargeData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargePaidByData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargePaidDetail.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanScheduleAccrualData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/ScheduleGeneratorDTO.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/Loan.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanAccountDomainService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanAccountDomainServiceJpa.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanCharge.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanChargePaidBy.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanInstallmentCharge.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleInstallmentRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepositoryWrapper.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransaction.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/AbstractLoanRepaymentScheduleTransactionProcessor.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/GuarantorConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/GuarantorFundingData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/Guarantor.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundStatusType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingDetails.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingTransactionRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/CreateGuarantorCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/DeleteGuarantorCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/UpdateGuarantorCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/serialization/GuarantorCommandFromApiJsonDeserializer.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorDomainServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DisburseLoanToSavingsCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/PayLoanChargeCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoWriteOffLoanCommandHandler.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/OverdueLoanScheduleData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryWritePlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryWritePlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualWritePlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualWritePlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanArrearsAgingServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/LoanProductConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanOverdueDTO.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductBorrowerCycleVariations.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductParamType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductValueConditionType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/serialization/LoanProductDataValidator.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/PaymentDetailConstants.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/data/PaymentDetailData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/domain/PaymentDetail.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/domain/PaymentDetailRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/service/PaymentDetailWritePlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/service/PaymentDetailWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountOnHoldTransactionType.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/DepositAccountOnHoldFundTransactionsApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountOnHoldTransactionData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountDataDTO.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionDTO.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountOnHoldTransaction.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountOnHoldTransactionRepository.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccount.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountDomainServiceJpa.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsAccountTransactionNotFoundException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/TransactionUpdateNotAllowedException.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountOnHoldTransactionReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferWritePlatformServiceJpaRepositoryImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/useradministration/api/UsersApiResource.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/useradministration/data/AppUserData.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/useradministration/service/RoleReadPlatformService.java mode change 100755 => 100644 fineract-provider/src/main/java/org/apache/fineract/useradministration/service/RoleReadPlatformServiceImpl.java mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V103__cluster_support_for_batch_jobs.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V107__datatable_code_mappings.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V109__account_transfer_withdrawal_fee_configuration.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V117__loan_charge_from_savings.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V11__add-payment-details.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V120__accounting_running_balance.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V121__accounting_running_balance_for_organization.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V125__added_column_for_actual_fee_amount_or_percentage.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V128__added_loan_installment_charge.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V132__borrower_cycle_changes.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V133__adding_payment_detail_with_journal_entry.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V147__tranche_loans_column_name_changes.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V148__overdraft_changes.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V149__add_created_date_savings_transaction.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V150__basic_savings_report.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V151__add_default_savings_account_to_client.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V152__added_grace_for_over_due.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V157__overdue_charge_improvements.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V160__standing_instruction_changes.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V161__added_accrual_batch_job.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V162__overdue_charge_batch_job.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V163__added_npa_for_loans.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V165__added_permission_for_disburse_to_saving_account.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V168__added_transfer_fixed_deposit_interest_to_linked_account.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V175__added_incentive_interest_rates.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V177__cleanup_for_client_incentives.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V181__standing_instruction_logging.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V183__added_min_balance_for_interest_calculation.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V185__add_accrual_till_date_for_periodic_accrual.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V186__added_periodic_accrual_job.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V187__added_permission_to_periodic_accrual.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V192__interest_recalculate_job.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V194__added_recalculatedInterestComponent_for_interest_recalculation.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V195__moved_rest_frequency_to_product_level.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V196__added_loan_running_balance_to_transactions.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V197__updated_loan_running_balance_of_transactions.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V199__removed_extra_columns_from_schedule_history.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V204__insert_script_for_charges_paid_by_for_accruals.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V205__fix_for_charge_and_interest_waiver_with_accruals.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V219__guarantor_on_hold_fund_changes_for_account.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V222__guarantor_on_hold_fund_changes_for_transactions.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V236__individual_collection_sheet_permissions.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V237__add_threshold_config_for_last_instalment.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V28__accounting-abstractions-and-autoposting.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V39__payment-channels-updates.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V43__accounting-for-savings.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V44__document-increase-size-of-column-type.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V48__adding-S3-Support.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V49__track-loan-charge-payment-transactions.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V54__charge-to-income-account-mappings.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V65__fix_rupee_symbol_issues.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V79__schedule_jobs_tables.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V82__schedule_jobs_tables_updates_for_running_status.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V88__added_update_constrain_for_scheduler_jobs.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V89__added_scheduler_group.sql mode change 100755 => 100644 fineract-provider/src/main/resources/sql/migrations/core_db/V94__added_savings_accont type.sql diff --git a/fineract-provider/build.gradle b/fineract-provider/build.gradle index ef46d5737..f6d15547b 100644 --- a/fineract-provider/build.gradle +++ b/fineract-provider/build.gradle @@ -119,7 +119,7 @@ dependencyManagement { // FINERACT-940 && FINERACT-966 https://github.com/spotbugs/spotbugs/issues/1128 exclude 'xpp3:xpp3' exclude 'pull-parser:pull-parser' - } + } dependencySet(group: 'com.sun.jersey', version: jerseyVersion) { entry 'jersey-core' @@ -156,8 +156,8 @@ project.ext.mysqlPassword='mysql' group = 'org.apache.fineract' buildDir = new File(rootProject.projectDir, "../build") repositories { - jcenter() - // mavenLocal() // useful for local dev using MariaDB4j SNAPSHOTs (not needed for real-world non-SNAPHOT builds) + jcenter() + // mavenLocal() // useful for local dev using MariaDB4j SNAPSHOTs (not needed for real-world non-SNAPHOT builds) } // If we are running Gradle within Eclipse to enhance classes with OpenJPA, @@ -167,7 +167,7 @@ if (project.hasProperty('env') && project.getProperty('env') == 'eclipse') sourceSets.main.java.outputDir = new File(rootProject.projectDir, "bin/main") } -eclipse +eclipse { project { buildCommand([ LaunchConfigHandle: "/.externalToolBuilders/OpenJPA Enhance Builder.launch" ], 'org.eclipse.ui.externaltools.ExternalToolBuilder') @@ -206,12 +206,12 @@ spotless { java { importOrder() //sort imports alphabetically - removeUnusedImports() + removeUnusedImports() eclipse().configFile '../config/fineractdev-formatter.xml' endWithNewline() trimTrailingWhitespace() } - + lineEndings 'UNIX' } @@ -299,25 +299,25 @@ rat { } configurations { - providedRuntime // needed for Spring Boot executable WAR + providedRuntime // needed for Spring Boot executable WAR providedCompile - compile() { - exclude module: 'hibernate-entitymanager' - exclude module: 'hibernate-validator' - exclude module: 'activation' - exclude module: 'bcmail-jdk14' - exclude module: 'bcprov-jdk14' - exclude module: 'bctsp-jdk14' - exclude module: 'c3p0' - exclude module: 'stax-api' - exclude module: 'jaxb-api' - exclude module: 'jaxb-impl' - exclude module: 'jboss-logging' - exclude module: 'itext-rtf' - exclude module: 'classworlds' - } - runtime - all*.exclude module: 'jul-to-slf4j' // see FINERACT-700 re. ClassCircularityError: java/util/logging/LogRecord + compile() { + exclude module: 'hibernate-entitymanager' + exclude module: 'hibernate-validator' + exclude module: 'activation' + exclude module: 'bcmail-jdk14' + exclude module: 'bcprov-jdk14' + exclude module: 'bctsp-jdk14' + exclude module: 'c3p0' + exclude module: 'stax-api' + exclude module: 'jaxb-api' + exclude module: 'jaxb-impl' + exclude module: 'jboss-logging' + exclude module: 'itext-rtf' + exclude module: 'classworlds' + } + runtime + all*.exclude module: 'jul-to-slf4j' // see FINERACT-700 re. ClassCircularityError: java/util/logging/LogRecord } tasks.withType(JavaCompile) { @@ -489,21 +489,21 @@ pmd { */ war { - from('../licenses/binary/') { // notice the parens - into "WEB-INF/licenses/binary/" // no leading slash - } - from('../LICENSE_RELEASE') { // notice the parens - into "WEB-INF/" // no leading slash - } - from('../NOTICE_RELEASE') { // notice the parens - into "WEB-INF/" // no leading slash - } - rename ('LICENSE_RELEASE', 'LICENSE') - rename ('NOTICE_RELEASE', 'NOTICE') + from('../licenses/binary/') { // notice the parens + into "WEB-INF/licenses/binary/" // no leading slash + } + from('../LICENSE_RELEASE') { // notice the parens + into "WEB-INF/" // no leading slash + } + from('../NOTICE_RELEASE') { // notice the parens + into "WEB-INF/" // no leading slash + } + rename ('LICENSE_RELEASE', 'LICENSE') + rename ('NOTICE_RELEASE', 'NOTICE') - from('../DISCLAIMER') { // notice the parens - into "WEB-INF/" // no leading slash - } + from('../DISCLAIMER') { // notice the parens + into "WEB-INF/" // no leading slash + } war.finalizedBy(bootWar) } @@ -588,7 +588,7 @@ if (!(project.hasProperty('env') && project.getProperty('env') == 'dev')) { sourceSets { integrationTest { - compileClasspath += main.output + test.output + compileClasspath += main.output + test.output runtimeClasspath += main.output + test.output } } @@ -608,20 +608,20 @@ task integrationTest(type:Test) { } integrationTest { - useJUnitPlatform() - testLogging { // FINERACT-927 - events "skipped", "failed" - showStandardStreams = false - exceptionFormat "full" - } + useJUnitPlatform() + testLogging { // FINERACT-927 + events "skipped", "failed" + showStandardStreams = false + exceptionFormat "full" + } } test { - useJUnitPlatform() - testLogging { // FINERACT-927 - events "skipped", "failed" - showStandardStreams = false - exceptionFormat "full" - } + useJUnitPlatform() + testLogging { // FINERACT-927 + events "skipped", "failed" + showStandardStreams = false + exceptionFormat "full" + } } diff --git a/fineract-provider/config/checkstyle/checkstyle.xml b/fineract-provider/config/checkstyle/checkstyle.xml index 11098dea8..d9022f09c 100644 --- a/fineract-provider/config/checkstyle/checkstyle.xml +++ b/fineract-provider/config/checkstyle/checkstyle.xml @@ -47,7 +47,7 @@ --> - + @@ -114,7 +114,7 @@ - + @@ -144,14 +144,14 @@ - - - + + + - - - + + + @@ -168,12 +168,12 @@ value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/> - + - + - + @@ -211,7 +211,7 @@ - + diff --git a/fineract-provider/dependencies.gradle b/fineract-provider/dependencies.gradle index e059d85a7..cba17e49c 100644 --- a/fineract-provider/dependencies.gradle +++ b/fineract-provider/dependencies.gradle @@ -22,12 +22,12 @@ dependencies { spotbugsPlugins "jp.skypencil.findbugs.slf4j:bug-pattern:1.5.0@jar" spotbugs 'com.github.spotbugs:spotbugs:4.0.4' - // Never use "compile" scope, but make all dependencies either 'implementation', 'runtimeOnly' or 'testCompile'. - // Note that we never use 'api', because Fineract at least currently is a simple monolithic application ("WAR"), not a library. - // We also (normally should have) no need to ever use 'compileOnly'. + // Never use "compile" scope, but make all dependencies either 'implementation', 'runtimeOnly' or 'testCompile'. + // Note that we never use 'api', because Fineract at least currently is a simple monolithic application ("WAR"), not a library. + // We also (normally should have) no need to ever use 'compileOnly'. - // implementation dependencies are directly used (compiled against) in src/main (and src/test) - // + // implementation dependencies are directly used (compiled against) in src/main (and src/test) + // implementation( //'ch.vorburger.mariaDB4j:mariaDB4j:2.4.0', @@ -79,50 +79,50 @@ dependencies { 'com.github.spotbugs:spotbugs-annotations', ) implementation ('io.swagger:swagger-jersey-jaxrs') { - exclude group: 'javax.validation' + exclude group: 'javax.validation' } implementation ('org.apache.activemq:activemq-broker') { exclude group: 'org.apache.geronimo.specs' } implementation ('org.springframework.boot:spring-boot-starter-data-jpa') { - exclude group: 'org.hibernate' + exclude group: 'org.hibernate' + } + implementation ('org.apache.openjpa:openjpa') { + exclude group: 'org.eclipse.persistence' + exclude group: 'org.apache.geronimo.specs' } - implementation ('org.apache.openjpa:openjpa') { - exclude group: 'org.eclipse.persistence' - exclude group: 'org.apache.geronimo.specs' - } implementation ('org.quartz-scheduler:quartz') { exclude group: 'com.zaxxer', module: 'HikariCP-java7' } implementation ('com.amazonaws:aws-java-sdk-s3') { - exclude group: 'commons-logging' + exclude group: 'commons-logging' } implementation ('org.mnode.ical4j:ical4j') { - exclude group: 'commons-logging' + exclude group: 'commons-logging' } implementation ('org.ehcache:ehcache') { exclude group: 'org.glassfish.jaxb', module: 'jaxb-runtime' } - // runtimeOnly dependencies are things that Fineract code has no direct compile time dependency on, but which must be present at run-time - runtimeOnly( + // runtimeOnly dependencies are things that Fineract code has no direct compile time dependency on, but which must be present at run-time + runtimeOnly( 'org.apache.bval:org.apache.bval.bundle', 'org.springframework.boot:spring-boot-starter-actuator', // Although fineract (at the time of writing) doesn't have any compile time dep. on httpclient, // it's useful to have this for the Spring Boot TestRestTemplate http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-rest-templates-test-utility 'org.apache.httpcomponents:httpclient', - ) + ) - // testCompile dependencies are ONLY used in src/test and/or src/integrationTest, not src/main. - // Do NOT repeat dependencies which are ALREADY in implementation or runtimeOnly! - // + // testCompile dependencies are ONLY used in src/test and/or src/integrationTest, not src/main. + // Do NOT repeat dependencies which are ALREADY in implementation or runtimeOnly! + // testImplementation( 'org.mockito:mockito-core', 'org.mockito:mockito-junit-jupiter', 'org.junit.platform:junit-platform-runner', // required to be able to run tests directly under Eclipse, see FINERACT-943 & FINERACT-1021 'io.github.classgraph:classgraph', 'org.awaitility:awaitility' - ) + ) testImplementation ('io.rest-assured:rest-assured') { exclude group: 'commons-logging' exclude group: 'org.apache.sling' diff --git a/fineract-provider/properties/oauth/application.properties b/fineract-provider/properties/oauth/application.properties index 881ad0e8c..fbe9c9f53 100644 --- a/fineract-provider/properties/oauth/application.properties +++ b/fineract-provider/properties/oauth/application.properties @@ -26,4 +26,4 @@ management.info.git.mode=FULL # FINERACT-914 server.forward-headers-strategy=framework -spring.cache.jcache.config=classpath:/META-INF/spring/ehcache.xml \ No newline at end of file +spring.cache.jcache.config=classpath:/META-INF/spring/ehcache.xml diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountNumberPreferencesTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountNumberPreferencesTest.java index 299f4519a..d10110dd4 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountNumberPreferencesTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountNumberPreferencesTest.java @@ -152,10 +152,11 @@ public class AccountNumberPreferencesTest { Integer id = (Integer) preferenceId.get("id"); HashMap delResponse = this.accountNumberPreferencesHelper.deleteAccountNumberPreference(id, this.responseSpec, ""); - LOG.info("Successfully deleted account number preference (ID: {} )",delResponse.get("resourceId")); + LOG.info("Successfully deleted account number preference (ID: {} )", delResponse.get("resourceId")); } /* Deletion of invalid account preference ID should fail */ - LOG.info("---------------------------------DELETING ACCOUNT NUMBER PREFERENCE WITH INVALID ID------------------------------------------"); + LOG.info( + "---------------------------------DELETING ACCOUNT NUMBER PREFERENCE WITH INVALID ID------------------------------------------"); HashMap deletionError = this.accountNumberPreferencesHelper.deleteAccountNumberPreference(10, this.responseNotFoundError, ""); @@ -180,25 +181,25 @@ public class AccountNumberPreferencesTest { } private void createAccountNumberPreference() { - this.clientAccountNumberPreferenceId = (Integer) this.accountNumberPreferencesHelper.createClientAccountNumberPreference( - this.responseSpec, "resourceId"); - LOG.info("Successfully created account number preferences for Client (ID: {})",this.clientAccountNumberPreferenceId); + this.clientAccountNumberPreferenceId = (Integer) this.accountNumberPreferencesHelper + .createClientAccountNumberPreference(this.responseSpec, "resourceId"); + LOG.info("Successfully created account number preferences for Client (ID: {})", this.clientAccountNumberPreferenceId); - this.loanAccountNumberPreferenceId = (Integer) this.accountNumberPreferencesHelper.createLoanAccountNumberPreference( - this.responseSpec, "resourceId"); + this.loanAccountNumberPreferenceId = (Integer) this.accountNumberPreferencesHelper + .createLoanAccountNumberPreference(this.responseSpec, "resourceId"); LOG.info("Successfully created account number preferences for Loan (ID: {} )", this.loanAccountNumberPreferenceId); - this.savingsAccountNumberPreferenceId = (Integer) this.accountNumberPreferencesHelper.createSavingsAccountNumberPreference( - this.responseSpec, "resourceId"); - LOG.info("Successfully created account number preferences for Savings (ID: {})" , this.savingsAccountNumberPreferenceId); + this.savingsAccountNumberPreferenceId = (Integer) this.accountNumberPreferencesHelper + .createSavingsAccountNumberPreference(this.responseSpec, "resourceId"); + LOG.info("Successfully created account number preferences for Savings (ID: {})", this.savingsAccountNumberPreferenceId); - this.groupsAccountNumberPreferenceId = (Integer) this.accountNumberPreferencesHelper.createGroupsAccountNumberPreference( - this.responseSpec, "resourceId"); - LOG.info("Successfully created account number preferences for Groups (ID: {})" , this.groupsAccountNumberPreferenceId); + this.groupsAccountNumberPreferenceId = (Integer) this.accountNumberPreferencesHelper + .createGroupsAccountNumberPreference(this.responseSpec, "resourceId"); + LOG.info("Successfully created account number preferences for Groups (ID: {})", this.groupsAccountNumberPreferenceId); - this.centerAccountNumberPreferenceId = (Integer) this.accountNumberPreferencesHelper.createCenterAccountNumberPreference( - this.responseSpec, "resourceId"); - LOG.info("Successfully created account number preferences for Center (ID: {})" ,this.centerAccountNumberPreferenceId); + this.centerAccountNumberPreferenceId = (Integer) this.accountNumberPreferencesHelper + .createCenterAccountNumberPreference(this.responseSpec, "resourceId"); + LOG.info("Successfully created account number preferences for Center (ID: {})", this.centerAccountNumberPreferenceId); this.accountNumberPreferencesHelper.verifyCreationOfAccountNumberPreferences(this.clientAccountNumberPreferenceId, this.loanAccountNumberPreferenceId, this.savingsAccountNumberPreferenceId, this.groupsAccountNumberPreferenceId, @@ -211,10 +212,11 @@ public class AccountNumberPreferencesTest { private void createAccountNumberPreferenceDuplicateData(final String accountType, final String prefixType) { /* Creating account Preference with duplicate data should fail */ - LOG.info("---------------------------------CREATING ACCOUNT NUMBER PREFERENCE WITH DUPLICATE DATA------------------------------------------"); + LOG.info( + "---------------------------------CREATING ACCOUNT NUMBER PREFERENCE WITH DUPLICATE DATA------------------------------------------"); - HashMap creationError = this.accountNumberPreferencesHelper.createAccountNumberPreferenceWithInvalidData( - this.responseForbiddenError, accountType, prefixType, ""); + HashMap creationError = this.accountNumberPreferencesHelper + .createAccountNumberPreferenceWithInvalidData(this.responseForbiddenError, accountType, prefixType, ""); Assertions.assertEquals("error.msg.account.number.format.duplicate.account.type", creationError.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); @@ -224,34 +226,36 @@ public class AccountNumberPreferencesTest { private void createAccountNumberPreferenceInvalidData(final String accountType, final String prefixType) { /* Creating account Preference with invalid data should fail */ - LOG.info("---------------------------------CREATING ACCOUNT NUMBER PREFERENCE WITH INVALID DATA------------------------------------------"); + LOG.info( + "---------------------------------CREATING ACCOUNT NUMBER PREFERENCE WITH INVALID DATA------------------------------------------"); - HashMap creationError = this.accountNumberPreferencesHelper.createAccountNumberPreferenceWithInvalidData( - this.responseValidationError, accountType, prefixType, ""); + HashMap creationError = this.accountNumberPreferencesHelper + .createAccountNumberPreferenceWithInvalidData(this.responseValidationError, accountType, prefixType, ""); - if (creationError.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE).equals( - "validation.msg.accountNumberFormat.accountType.is.not.within.expected.range")) { + if (creationError.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE) + .equals("validation.msg.accountNumberFormat.accountType.is.not.within.expected.range")) { Assertions.assertEquals("validation.msg.accountNumberFormat.accountType.is.not.within.expected.range", creationError.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - } else if (creationError.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE).equals( - "validation.msg.accountNumberFormat.prefixType.is.not.one.of.expected.enumerations")) { + } else if (creationError.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE) + .equals("validation.msg.accountNumberFormat.prefixType.is.not.one.of.expected.enumerations")) { Assertions.assertEquals("validation.msg.accountNumberFormat.prefixType.is.not.one.of.expected.enumerations", creationError.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); } } private void updateAccountNumberPreference() { - HashMap accountNumberPreferences = this.accountNumberPreferencesHelper.updateAccountNumberPreference( - this.clientAccountNumberPreferenceId, "101", this.responseSpec, ""); + HashMap accountNumberPreferences = this.accountNumberPreferencesHelper + .updateAccountNumberPreference(this.clientAccountNumberPreferenceId, "101", this.responseSpec, ""); - LOG.info("--------------------------UPDATION SUCCESSFUL FOR ACCOUNT NUMBER PREFERENCE ID {}" - , accountNumberPreferences.get("resourceId")); + LOG.info("--------------------------UPDATION SUCCESSFUL FOR ACCOUNT NUMBER PREFERENCE ID {}", + accountNumberPreferences.get("resourceId")); this.accountNumberPreferencesHelper.verifyUpdationOfAccountNumberPreferences((Integer) accountNumberPreferences.get("resourceId"), this.responseSpec, this.requestSpec); /* Update invalid account preference id should fail */ - LOG.info("---------------------------------UPDATING ACCOUNT NUMBER PREFERENCE WITH INVALID DATA------------------------------------------"); + LOG.info( + "---------------------------------UPDATING ACCOUNT NUMBER PREFERENCE WITH INVALID DATA------------------------------------------"); /* Invalid Account Type */ HashMap updationError = this.accountNumberPreferencesHelper.updateAccountNumberPreference(9999, "101", @@ -260,8 +264,8 @@ public class AccountNumberPreferencesTest { Assertions.assertEquals("error.msg.resource.not.found", updationError.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); } /* Invalid Prefix Type */ - HashMap updationError1 = this.accountNumberPreferencesHelper.updateAccountNumberPreference( - this.clientAccountNumberPreferenceId, "103", this.responseValidationError, ""); + HashMap updationError1 = this.accountNumberPreferencesHelper + .updateAccountNumberPreference(this.clientAccountNumberPreferenceId, "103", this.responseValidationError, ""); Assertions.assertEquals("validation.msg.validation.errors.exist", updationError1.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); @@ -288,8 +292,8 @@ public class AccountNumberPreferencesTest { this.groupAccountNo = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "accountNo"); if (isAccountPreferenceSetUp) { - String groupsPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference( - this.groupsAccountNumberPreferenceId, "prefixType.value"); + String groupsPrefixName = (String) this.accountNumberPreferencesHelper + .getAccountNumberPreference(this.groupsAccountNumberPreferenceId, "prefixType.value"); if (groupsPrefixName.equals(this.officeName)) { @@ -313,8 +317,8 @@ public class AccountNumberPreferencesTest { Assertions.assertTrue(center.getName().equals(name)); if (isAccountPreferenceSetUp) { - String centerPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference( - this.centerAccountNumberPreferenceId, "prefixType.value"); + String centerPrefixName = (String) this.accountNumberPreferencesHelper + .getAccountNumberPreference(this.centerAccountNumberPreferenceId, "prefixType.value"); final String CENTER_URL = "/fineract-provider/api/v1/centers/" + this.centerId + "?" + Utils.TENANT_IDENTIFIER; if (centerPrefixName.equals(this.officeName)) { @@ -326,7 +330,6 @@ public class AccountNumberPreferencesTest { } } - private void createAndValidateClientWithoutAccountPreference() { this.clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec); Assertions.assertNotNull(this.clientId); @@ -337,8 +340,8 @@ public class AccountNumberPreferencesTest { private void createAndValidateClientBasedOnAccountPreference() { final String codeName = "ClientType"; String clientAccountNo = null; - String clientPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference( - this.clientAccountNumberPreferenceId, "prefixType.value"); + String clientPrefixName = (String) this.accountNumberPreferencesHelper + .getAccountNumberPreference(this.clientAccountNumberPreferenceId, "prefixType.value"); if (clientPrefixName.equals(this.clientTypeName)) { /* Retrieve Code id for the Code "ClientType" */ @@ -390,7 +393,7 @@ public class AccountNumberPreferencesTest { .withInterestRateFrequencyTypeAsYear().build(null); this.loanProductId = this.loanTransactionHelper.getLoanProductId(loanProductJSON); - LOG.info("Successfully created loan product (ID: {} )" , this.loanProductId); + LOG.info("Successfully created loan product (ID: {} )", this.loanProductId); } private void createAndValidateLoanEntity(Boolean isAccountPreferenceSetUp) { @@ -405,15 +408,15 @@ public class AccountNumberPreferencesTest { .withSubmittedOnDate(dateString).withExpectedDisbursementDate(dateString).withPrincipalGrace("2").withInterestGrace("2") .build(this.clientId.toString(), this.loanProductId.toString(), null); - LOG.info("Loan Application :{}" , loanApplicationJSON); + LOG.info("Loan Application :{}", loanApplicationJSON); this.loanId = this.loanTransactionHelper.getLoanId(loanApplicationJSON); String loanAccountNo = (String) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, this.loanId, "accountNo"); if (isAccountPreferenceSetUp) { - String loanPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference( - this.loanAccountNumberPreferenceId, "prefixType.value"); + String loanPrefixName = (String) this.accountNumberPreferencesHelper + .getAccountNumberPreference(this.loanAccountNumberPreferenceId, "prefixType.value"); if (loanPrefixName.equals(this.officeName)) { String loanOfficeName = (String) ClientHelper.getClient(requestSpec, responseSpec, this.clientId.toString(), "officeName"); this.validateAccountNumberLengthAndStartsWithPrefix(loanAccountNo, loanOfficeName); @@ -422,10 +425,10 @@ public class AccountNumberPreferencesTest { this.loanProductId, "shortName"); this.validateAccountNumberLengthAndStartsWithPrefix(loanAccountNo, loanShortName); } - LOG.info("SUCCESSFULLY CREATED LOAN APPLICATION BASED ON ACCOUNT PREFERENCES (ID: {} )",this.loanId ); + LOG.info("SUCCESSFULLY CREATED LOAN APPLICATION BASED ON ACCOUNT PREFERENCES (ID: {} )", this.loanId); } else { this.validateAccountNumberLengthAndStartsWithPrefix(loanAccountNo, null); - LOG.info("SUCCESSFULLY CREATED LOAN APPLICATION (ID: {} )",loanId); + LOG.info("SUCCESSFULLY CREATED LOAN APPLICATION (ID: {} )", loanId); } } @@ -449,7 +452,7 @@ public class AccountNumberPreferencesTest { .withMinRequiredBalance(minRequiredBalance).withEnforceMinRequiredBalance(enforceMinRequiredBalance) .withMinimumOpenningBalance(this.MINIMUM_OPENING_BALANCE).build(); this.savingsProductId = SavingsProductHelper.createSavingsProduct(savingsProductJSON, this.requestSpec, this.responseSpec); - LOG.info("Sucessfully created savings product (ID: {} )",this.savingsProductId); + LOG.info("Sucessfully created savings product (ID: {} )", this.savingsProductId); } @@ -458,14 +461,14 @@ public class AccountNumberPreferencesTest { this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - this.savingsId = this.savingsAccountHelper - .applyForSavingsApplication(this.clientId, this.savingsProductId, ACCOUNT_TYPE_INDIVIDUAL); + this.savingsId = this.savingsAccountHelper.applyForSavingsApplication(this.clientId, this.savingsProductId, + ACCOUNT_TYPE_INDIVIDUAL); String savingsAccountNo = (String) this.savingsAccountHelper.getSavingsAccountDetail(this.savingsId, "accountNo"); if (isAccountPreferenceSetUp) { - String savingsPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference( - this.savingsAccountNumberPreferenceId, "prefixType.value"); + String savingsPrefixName = (String) this.accountNumberPreferencesHelper + .getAccountNumberPreference(this.savingsAccountNumberPreferenceId, "prefixType.value"); if (savingsPrefixName.equals(this.officeName)) { String savingsOfficeName = (String) ClientHelper.getClient(requestSpec, responseSpec, this.clientId.toString(), @@ -475,10 +478,10 @@ public class AccountNumberPreferencesTest { String loanShortName = (String) this.savingsAccountHelper.getSavingsAccountDetail(this.savingsId, "shortName"); this.validateAccountNumberLengthAndStartsWithPrefix(savingsAccountNo, loanShortName); } - LOG.info("SUCCESSFULLY CREATED SAVINGS APPLICATION BASED ON ACCOUNT PREFERENCES (ID: {} )",this.loanId); + LOG.info("SUCCESSFULLY CREATED SAVINGS APPLICATION BASED ON ACCOUNT PREFERENCES (ID: {} )", this.loanId); } else { this.validateAccountNumberLengthAndStartsWithPrefix(savingsAccountNo, null); - LOG.info("SUCCESSFULLY CREATED SAVINGS APPLICATION (ID:{} )",this.savingsId); + LOG.info("SUCCESSFULLY CREATED SAVINGS APPLICATION (ID:{} )", this.savingsId); } } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountTransferTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountTransferTest.java index e8a38d431..8989def03 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountTransferTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountTransferTest.java @@ -127,8 +127,8 @@ public class AccountTransferTest { */ @AfterEach public void tearDown() { - Integer deletedFinancialActivityAccountId = financialActivityAccountHelper.deleteFinancialActivityAccount( - financialActivityAccountId, responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); + Integer deletedFinancialActivityAccountId = financialActivityAccountHelper + .deleteFinancialActivityAccount(financialActivityAccountId, responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); Assertions.assertNotNull(deletedFinancialActivityAccountId); Assertions.assertEquals(financialActivityAccountId, deletedFinancialActivityAccountId); } @@ -214,10 +214,10 @@ public class AccountTransferTest { HashMap toSavingsSummaryAfter = this.savingsAccountHelper.getSavingsSummary(toSavingsID); assertEquals(toSavingsBalance, toSavingsSummaryAfter.get("accountBalance"), "Verifying To Savings Account Balance after Account Transfer"); - final JournalEntry[] office1LiabilityEntries = { new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT), - JournalEntry.TransactionType.CREDIT) }; - final JournalEntry[] office2LiabilityEntries = { new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT), - JournalEntry.TransactionType.DEBIT) }; + final JournalEntry[] office1LiabilityEntries = { + new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT), JournalEntry.TransactionType.CREDIT) }; + final JournalEntry[] office2LiabilityEntries = { + new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT), JournalEntry.TransactionType.DEBIT) }; this.journalEntryHelper.checkJournalEntryForLiabilityAccount(fromOfficeId, liabilityTransferAccount, AccountTransferHelper.ACCOUNT_TRANSFER_DATE, office1LiabilityEntries); @@ -311,10 +311,10 @@ public class AccountTransferTest { assertEquals(TRANSFER_AMOUNT_ADJUST, toLoanSummaryAfter.get("totalRepayment"), "Verifying To Loan Repayment Amount after Account Transfer"); - final JournalEntry[] office1LiabilityEntries = { new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT_ADJUST), - JournalEntry.TransactionType.CREDIT) }; - final JournalEntry[] office2LiabilityEntries = { new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT_ADJUST), - JournalEntry.TransactionType.DEBIT) }; + final JournalEntry[] office1LiabilityEntries = { + new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT_ADJUST), JournalEntry.TransactionType.CREDIT) }; + final JournalEntry[] office2LiabilityEntries = { + new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT_ADJUST), JournalEntry.TransactionType.DEBIT) }; this.journalEntryHelper.checkJournalEntryForLiabilityAccount(fromOfficeId, liabilityTransferAccount, AccountTransferHelper.ACCOUNT_TRANSFER_DATE, office1LiabilityEntries); @@ -432,10 +432,10 @@ public class AccountTransferTest { assertEquals(toSavingsBalance, toSavingsSummaryAfter.get("accountBalance"), "Verifying From Savings Account Balance after Account Transfer"); - final JournalEntry[] office1LiabilityEntries = { new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT_ADJUST), - JournalEntry.TransactionType.CREDIT) }; - final JournalEntry[] office2LiabilityEntries = { new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT_ADJUST), - JournalEntry.TransactionType.DEBIT) }; + final JournalEntry[] office1LiabilityEntries = { + new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT_ADJUST), JournalEntry.TransactionType.CREDIT) }; + final JournalEntry[] office2LiabilityEntries = { + new JournalEntry(Float.valueOf(ACCOUNT_TRANSFER_AMOUNT_ADJUST), JournalEntry.TransactionType.DEBIT) }; this.journalEntryHelper.checkJournalEntryForLiabilityAccount(fromOfficeId, liabilityTransferAccount, AccountTransferHelper.ACCOUNT_TRANSFER_DATE, office1LiabilityEntries); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountingScenarioIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountingScenarioIntegrationTest.java index bef78f27e..354034247 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountingScenarioIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/AccountingScenarioIntegrationTest.java @@ -68,6 +68,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "unused", "rawtypes", "unchecked", "static-access" }) public class AccountingScenarioIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(AccountingScenarioIntegrationTest.class); private static RequestSpecification requestSpec; private static ResponseSpecification responseSpec; @@ -94,7 +95,8 @@ public class AccountingScenarioIntegrationTest { Float SP_WITHDRAWAL_AMOUNT = Float.valueOf(WITHDRAWAL_AMOUNT); Float SP_WITHDRAWAL_AMOUNT_ADJUSTED = Float.valueOf(WITHDRAWAL_AMOUNT_ADJUSTED); - private final String[] REPAYMENT_DATE = { "", "04 May 2011", "04 July 2011", "04 September 2011", "04 November 2011", "04 January 2012" }; + private final String[] REPAYMENT_DATE = { "", "04 May 2011", "04 July 2011", "04 September 2011", "04 November 2011", + "04 January 2012" }; private final Float[] REPAYMENT_AMOUNT = { .0f, 2200.0f, 3000.0f, 900.0f, 2000.0f, 2500.0f }; private final Float AMOUNT_TO_BE_WAIVE = 400.0f; @@ -274,8 +276,8 @@ public class AccountingScenarioIntegrationTest { final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(this.SP_BALANCE, JournalEntry.TransactionType.DEBIT) }; final JournalEntry[] liablilityAccountInitialEntry = { new JournalEntry(this.SP_BALANCE, JournalEntry.TransactionType.CREDIT) }; this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.TRANSACTION_DATE, assetAccountInitialEntry); - this.journalEntryHelper - .checkJournalEntryForLiabilityAccount(liabilityAccount, this.TRANSACTION_DATE, liablilityAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, this.TRANSACTION_DATE, + liablilityAccountInitialEntry); // First Transaction-Deposit this.savingsAccountHelper.depositToSavingsAccount(savingsID, DEPOSIT_AMOUNT, SavingsAccountHelper.TRANSACTION_DATE, @@ -285,10 +287,10 @@ public class AccountingScenarioIntegrationTest { assertEquals(balance, summary.get("accountBalance"), "Verifying Balance after Deposit"); LOG.info("----------------------Verifying Journal Entry after the Transaction Deposit----------------------------"); - final JournalEntry[] assetAccountFirstTransactionEntry = { new JournalEntry(this.SP_DEPOSIT_AMOUNT, - JournalEntry.TransactionType.DEBIT) }; - final JournalEntry[] liabililityAccountFirstTransactionEntry = { new JournalEntry(this.SP_DEPOSIT_AMOUNT, - JournalEntry.TransactionType.CREDIT) }; + final JournalEntry[] assetAccountFirstTransactionEntry = { + new JournalEntry(this.SP_DEPOSIT_AMOUNT, JournalEntry.TransactionType.DEBIT) }; + final JournalEntry[] liabililityAccountFirstTransactionEntry = { + new JournalEntry(this.SP_DEPOSIT_AMOUNT, JournalEntry.TransactionType.CREDIT) }; this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.TRANSACTION_DATE, assetAccountFirstTransactionEntry); this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, this.TRANSACTION_DATE, liabililityAccountFirstTransactionEntry); @@ -301,10 +303,10 @@ public class AccountingScenarioIntegrationTest { assertEquals(balance, summary.get("accountBalance"), "Verifying Balance after Withdrawal"); LOG.info("-------------------Verifying Journal Entry after the Transaction Withdrawal----------------------"); - final JournalEntry[] assetAccountSecondTransactionEntry = { new JournalEntry(this.SP_WITHDRAWAL_AMOUNT, - JournalEntry.TransactionType.CREDIT) }; - final JournalEntry[] liabililityAccountSecondTransactionEntry = { new JournalEntry(this.SP_WITHDRAWAL_AMOUNT, - JournalEntry.TransactionType.DEBIT) }; + final JournalEntry[] assetAccountSecondTransactionEntry = { + new JournalEntry(this.SP_WITHDRAWAL_AMOUNT, JournalEntry.TransactionType.CREDIT) }; + final JournalEntry[] liabililityAccountSecondTransactionEntry = { + new JournalEntry(this.SP_WITHDRAWAL_AMOUNT, JournalEntry.TransactionType.DEBIT) }; this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.TRANSACTION_DATE, assetAccountSecondTransactionEntry); this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, this.TRANSACTION_DATE, liabililityAccountSecondTransactionEntry); @@ -322,16 +324,15 @@ public class AccountingScenarioIntegrationTest { Float chargeAmount = (Float) paidCharge.get("amount"); // Withdrawal after adding Charge of type Withdrawal Fee - this.savingsAccountHelper.withdrawalFromSavingsAccount(savingsID, WITHDRAWAL_AMOUNT_ADJUSTED, - SavingsAccountHelper.TRANSACTION_DATE, CommonConstants.RESPONSE_RESOURCE_ID); + this.savingsAccountHelper.withdrawalFromSavingsAccount(savingsID, WITHDRAWAL_AMOUNT_ADJUSTED, SavingsAccountHelper.TRANSACTION_DATE, + CommonConstants.RESPONSE_RESOURCE_ID); summary = this.savingsAccountHelper.getSavingsSummary(savingsID); balance = balance - SP_WITHDRAWAL_AMOUNT_ADJUSTED - chargeAmount; - final JournalEntry[] liabililityAccountThirdTransactionEntry = { - new JournalEntry(chargeAmount, JournalEntry.TransactionType.DEBIT), + final JournalEntry[] liabililityAccountThirdTransactionEntry = { new JournalEntry(chargeAmount, JournalEntry.TransactionType.DEBIT), new JournalEntry(this.SP_WITHDRAWAL_AMOUNT_ADJUSTED, JournalEntry.TransactionType.DEBIT) }; - final JournalEntry[] assetAccountThirdTransactionEntry = { new JournalEntry(this.SP_WITHDRAWAL_AMOUNT_ADJUSTED, - JournalEntry.TransactionType.CREDIT) }; + final JournalEntry[] assetAccountThirdTransactionEntry = { + new JournalEntry(this.SP_WITHDRAWAL_AMOUNT_ADJUSTED, JournalEntry.TransactionType.CREDIT) }; final JournalEntry[] incomeAccountThirdTransactionEntry = { new JournalEntry(chargeAmount, JournalEntry.TransactionType.CREDIT) }; this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.TRANSACTION_DATE, assetAccountThirdTransactionEntry); this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, this.TRANSACTION_DATE, @@ -464,8 +465,8 @@ public class AccountingScenarioIntegrationTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, RecurringDepositTest.WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -529,13 +530,14 @@ public class AccountingScenarioIntegrationTest { LOG.info("--------------------------------APPLYING FOR FIXED DEPOSIT ACCOUNT --------------------------------"); final String fixedDepositApplicationJSON = new FixedDepositAccountHelper(this.requestSpec, this.responseSpec) // .withSubmittedOnDate(submittedOnDate).build(clientID, productID, penalInterestType); - return this.fixedDepositAccountHelper - .applyFixedDepositApplication(fixedDepositApplicationJSON, this.requestSpec, this.responseSpec); + return this.fixedDepositAccountHelper.applyFixedDepositApplication(fixedDepositApplicationJSON, this.requestSpec, + this.responseSpec); } private Integer createRecurringDepositProduct(final String validFrom, final String validTo, Account... accounts) { LOG.info("------------------------------CREATING NEW RECURRING DEPOSIT PRODUCT ---------------------------------------"); - RecurringDepositProductHelper recurringDepositProductHelper = new RecurringDepositProductHelper(this.requestSpec, this.responseSpec); + RecurringDepositProductHelper recurringDepositProductHelper = new RecurringDepositProductHelper(this.requestSpec, + this.responseSpec); final String recurringDepositProductJSON = recurringDepositProductHelper // .withPeriodRangeChart()// .withAccountingRuleAsCashBased(accounts).build(validFrom, validTo); @@ -554,7 +556,7 @@ public class AccountingScenarioIntegrationTest { } @Test - public void checkPeriodicAccrualAccountingFlow() throws InterruptedException,ParseException { + public void checkPeriodicAccrualAccountingFlow() throws InterruptedException, ParseException { final Account assetAccount = this.accountHelper.createAssetAccount(); final Account incomeAccount = this.accountHelper.createIncomeAccount(); final Account expenseAccount = this.accountHelper.createExpenseAccount(); @@ -667,7 +669,7 @@ public class AccountingScenarioIntegrationTest { } @Test - public void checkPeriodicAccrualAccountingFlow_OVER_PAYMENT() throws InterruptedException,ParseException { + public void checkPeriodicAccrualAccountingFlow_OVER_PAYMENT() throws InterruptedException, ParseException { final Account assetAccount = this.accountHelper.createAssetAccount(); final Account incomeAccount = this.accountHelper.createIncomeAccount(); final Account expenseAccount = this.accountHelper.createExpenseAccount(); @@ -715,14 +717,14 @@ public class AccountingScenarioIntegrationTest { final JournalEntry[] assetAccountEntry = { new JournalEntry(15000f, JournalEntry.TransactionType.DEBIT), new JournalEntry(11000f, JournalEntry.TransactionType.CREDIT) }; this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.REPAYMENT_DATE[1], assetAccountEntry); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(overpaymentAccount, this.REPAYMENT_DATE[1], new JournalEntry(4000f, - JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(overpaymentAccount, this.REPAYMENT_DATE[1], + new JournalEntry(4000f, JournalEntry.TransactionType.CREDIT)); LOG.info("Repayment Done......"); } @Test - public void checkPeriodicAccrualAccountingTillCurrentDateFlow() throws InterruptedException,ParseException { + public void checkPeriodicAccrualAccountingTillCurrentDateFlow() throws InterruptedException, ParseException { final Account assetAccount = this.accountHelper.createAssetAccount(); final Account incomeAccount = this.accountHelper.createIncomeAccount(); final Account expenseAccount = this.accountHelper.createExpenseAccount(); @@ -738,8 +740,8 @@ public class AccountingScenarioIntegrationTest { final float PENALTY_PORTION = 100.0f; Integer flat = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, String.valueOf(FEE_PORTION), false)); - Integer flatSpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, String.valueOf(PENALTY_PORTION), true)); + Integer flatSpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper + .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, String.valueOf(PENALTY_PORTION), true)); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); @@ -766,10 +768,8 @@ public class AccountingScenarioIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan(LOAN_DISBURSEMENT_DATE, loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - this.loanTransactionHelper.addChargesForLoan( - loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDate), - dateFormat.format(todayDate.getTime()), String.valueOf(PENALTY_PORTION))); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(flatSpecifiedDueDate), dateFormat.format(todayDate.getTime()), String.valueOf(PENALTY_PORTION))); todayDate.add(Calendar.DATE, 1); this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( String.valueOf(flat), dateFormat.format(todayDate.getTime()), String.valueOf(FEE_PORTION))); @@ -814,7 +814,7 @@ public class AccountingScenarioIntegrationTest { } @Test - public void checkPeriodicAccrualAccountingAPIFlow() throws ParseException{ + public void checkPeriodicAccrualAccountingAPIFlow() throws ParseException { final Account assetAccount = this.accountHelper.createAssetAccount(); final Account incomeAccount = this.accountHelper.createIncomeAccount(); final Account expenseAccount = this.accountHelper.createExpenseAccount(); @@ -833,11 +833,11 @@ public class AccountingScenarioIntegrationTest { Integer flat = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, String.valueOf(FEE_PORTION), false)); - Integer flatSpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, String.valueOf(PENALTY_PORTION), true)); + Integer flatSpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper + .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, String.valueOf(PENALTY_PORTION), true)); - Integer flatNext = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, String.valueOf(NEXT_FEE_PORTION), false)); + Integer flatNext = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper + .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, String.valueOf(NEXT_FEE_PORTION), false)); Integer flatSpecifiedDueDateNext = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, String.valueOf(NEXT_PENALTY_PORTION), true)); @@ -866,29 +866,20 @@ public class AccountingScenarioIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan(LOAN_DISBURSEMENT_DATE, loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - this.loanTransactionHelper.addChargesForLoan( - loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDate), - dateFormat.format(todayDate.getTime()), String.valueOf(PENALTY_PORTION))); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(flatSpecifiedDueDate), dateFormat.format(todayDate.getTime()), String.valueOf(PENALTY_PORTION))); todayDate.add(Calendar.DATE, 1); String runOndate = dateFormat.format(todayDate.getTime()); - this.loanTransactionHelper - .addChargesForLoan( - loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flat), runOndate, - String.valueOf(FEE_PORTION))); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flat), runOndate, String.valueOf(FEE_PORTION))); todayDate.add(Calendar.DATE, 1); - this.loanTransactionHelper.addChargesForLoan( - loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDateNext), - dateFormat.format(todayDate.getTime()), String.valueOf(NEXT_PENALTY_PORTION))); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(flatSpecifiedDueDateNext), dateFormat.format(todayDate.getTime()), String.valueOf(NEXT_PENALTY_PORTION))); - this.loanTransactionHelper.addChargesForLoan( - loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatNext), - dateFormat.format(todayDate.getTime()), String.valueOf(NEXT_FEE_PORTION))); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(flatNext), dateFormat.format(todayDate.getTime()), String.valueOf(NEXT_FEE_PORTION))); // CHECK ACCOUNT ENTRIES LOG.info("Entries ......"); @@ -986,8 +977,8 @@ public class AccountingScenarioIntegrationTest { new JournalEntry(FIRST_PRINCIPAL, JournalEntry.TransactionType.CREDIT) }; this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.REPAYMENT_DATE[1], assetAccountFirstEntry); LOG.info("CHECKING INCOME: ******************************************"); - this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, this.REPAYMENT_DATE[1], new JournalEntry(FIRST_INTEREST, - JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, this.REPAYMENT_DATE[1], + new JournalEntry(FIRST_INTEREST, JournalEntry.TransactionType.CREDIT)); LOG.info("Repayment 1 Done......"); // REPAYMENT 2 @@ -1001,8 +992,8 @@ public class AccountingScenarioIntegrationTest { new JournalEntry(SECOND_PRINCIPAL, JournalEntry.TransactionType.CREDIT), }; this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.REPAYMENT_DATE[2], assetAccountSecondEntry); LOG.info("CHECKING INCOME: ******************************************"); - this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, this.REPAYMENT_DATE[2], new JournalEntry( - SECOND_AND_THIRD_INTEREST, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, this.REPAYMENT_DATE[2], + new JournalEntry(SECOND_AND_THIRD_INTEREST, JournalEntry.TransactionType.CREDIT)); LOG.info("Repayment 2 Done ......"); // WAIVE INTEREST @@ -1053,7 +1044,7 @@ public class AccountingScenarioIntegrationTest { return this.loanTransactionHelper.getLoanProductId(loanProductJSON); } - private LocalDate getDateAsLocalDate(String dateAsString) throws ParseException{ + private LocalDate getDateAsLocalDate(String dateAsString) throws ParseException { DateFormat df = new SimpleDateFormat("dd MMMM yyyy", Locale.US); LocalDate date = new LocalDate(df.parse(dateAsString)); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ActuatorIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ActuatorIntegrationTest.java index d23ecae49..af920e1b2 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ActuatorIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ActuatorIntegrationTest.java @@ -33,9 +33,8 @@ public class ActuatorIntegrationTest { @Test public void testActuatorGitBuildInfo() { - Response response = RestAssured.given() - .headers("Content-Type", ContentType.JSON, "Accept", ContentType.JSON).when() - .get(INFO_URL).then().contentType(ContentType.JSON).extract().response(); + Response response = RestAssured.given().headers("Content-Type", ContentType.JSON, "Accept", ContentType.JSON).when().get(INFO_URL) + .then().contentType(ContentType.JSON).extract().response(); Map gitBuildInfo = response.jsonPath().getMap("git"); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/BatchApiTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/BatchApiTest.java index 1b2d62b17..fbbeca996 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/BatchApiTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/BatchApiTest.java @@ -58,7 +58,8 @@ public class BatchApiTest { /** * Sets up the essential settings for the TEST like contentType, - * expectedStatusCode. It uses the '@BeforeEach' annotation provided by jUnit. + * expectedStatusCode. It uses the '@BeforeEach' annotation provided by + * jUnit. */ @BeforeEach public void setup() { @@ -333,10 +334,10 @@ public class BatchApiTest { } /** - * Tests that batch repayment for loans is happening properly. - * Collected properly 200(OK) status was returned for successful responses. - * It first creates a new loan and then makes two repayments for it - * and then verifies that 200(OK) is returned for the repayment requests. + * Tests that batch repayment for loans is happening properly. Collected + * properly 200(OK) status was returned for successful responses. It first + * creates a new loan and then makes two repayments for it and then verifies + * that 200(OK) is returned for the repayment requests. * * @see org.apache.fineract.batch.command.internal.RepayLoanCommandStrategy */ @@ -482,14 +483,15 @@ public class BatchApiTest { } /** - * Test for the successful create client, apply loan,approval and disbursal of a loan using - * Batch API with enclosingTransaction. A '200' status code is expected on successful activation. + * Test for the successful create client, apply loan,approval and disbursal + * of a loan using Batch API with enclosingTransaction. A '200' status code + * is expected on successful activation. * * @see org.apache.fineract.batch.command.internal.ApproveLoanCommandStrategy * @see org.apache.fineract.batch.command.internal.DisburseLoanCommandStrategy */ @Test - public void shouldReturnOkStatusOnSuccessfulLoanApprovalAndDisburseWithTransaction(){ + public void shouldReturnOkStatusOnSuccessfulLoanApprovalAndDisburseWithTransaction() { final String loanProductJSON = new LoanProductTestBuilder() // .withPrincipal("10000000.00") // .withNumberOfRepayments("24") // @@ -515,7 +517,7 @@ public class BatchApiTest { // Create a disburseLoan Request final BatchRequest br4 = BatchHelper.disburseLoanRequest(4744L, 4743L); - final List batchRequests = Arrays.asList(br1,br2,br3,br4); + final List batchRequests = Arrays.asList(br1, br2, br3, br4); final String jsonifiedRequest = BatchHelper.toJsonString(batchRequests); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/BatchRequestsIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/BatchRequestsIntegrationTest.java index f3709ef55..4bd25bd99 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/BatchRequestsIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/BatchRequestsIntegrationTest.java @@ -58,7 +58,8 @@ public class BatchRequestsIntegrationTest { /** * Sets up the essential settings for the TEST like contentType, - * expectedStatusCode. It uses the '@BeforeEach' annotation provided by jUnit. + * expectedStatusCode. It uses the '@BeforeEach' annotation provided by + * jUnit. */ @BeforeEach public void setup() { @@ -91,7 +92,7 @@ public class BatchRequestsIntegrationTest { for (Integer i = 0; i < clientsCount; i++) { clientIDs[i] = ClientHelper.createClient(this.requestSpec, this.responseSpec); groupID = GroupHelper.associateClient(this.requestSpec, this.responseSpec, groupID.toString(), clientIDs[i].toString()); - LOG.info("client {} has been added to the group {}",clientIDs[i] , groupID); + LOG.info("client {} has been added to the group {}", clientIDs[i], groupID); } // Generate a random count of number of new loan products to be created diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CenterIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CenterIntegrationTest.java index d38e32856..258487a04 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CenterIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CenterIntegrationTest.java @@ -42,6 +42,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CenterIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(CenterIntegrationTest.class); private RequestSpecification requestSpec; private ResponseSpecification responseSpec; @@ -106,8 +107,8 @@ public class CenterIntegrationTest { Assertions.assertNotNull(paginatedList); Assertions.assertNotNull(list); - Assertions.assertTrue(Arrays.equals(paginatedList.toArray(new CenterDomain[paginatedList.size()]), - list.toArray(new CenterDomain[list.size()]))); + Assertions.assertTrue( + Arrays.equals(paginatedList.toArray(new CenterDomain[paginatedList.size()]), list.toArray(new CenterDomain[list.size()]))); } @Test @@ -162,7 +163,7 @@ public class CenterIntegrationTest { Assertions.assertNotNull(center); Assertions.assertEquals(newName, center.getName()); Assertions.assertEquals(newExternalId, center.getExternalId()); - Assertions.assertEquals((Integer)newStaffId, center.getStaffId()); + Assertions.assertEquals((Integer) newStaffId, center.getStaffId()); Assertions.assertArrayEquals(newGroupMembers, center.getGroupMembers()); } @@ -190,8 +191,8 @@ public class CenterIntegrationTest { map.put("active", "true"); map.put("activationDate", "04 March 2011"); - groupMembers[i] = Utils.performServerPost(requestSpec, responseSpec, "/fineract-provider/api/v1/groups?" - + Utils.TENANT_IDENTIFIER, new Gson().toJson(map), "groupId"); + groupMembers[i] = Utils.performServerPost(requestSpec, responseSpec, + "/fineract-provider/api/v1/groups?" + Utils.TENANT_IDENTIFIER, new Gson().toJson(map), "groupId"); } return groupMembers; } @@ -200,7 +201,7 @@ public class CenterIntegrationTest { public void testStaffAssignmentDuringCenterCreation() { final Integer staffId = StaffHelper.createStaff(this.requestSpec, this.responseSpec); - LOG.info("--------------creating first staff with id------------- {}" , staffId); + LOG.info("--------------creating first staff with id------------- {}", staffId); Assertions.assertNotNull(staffId); final int centerWithStaffId = CenterHelper.createCenterWithStaffId(this.requestSpec, this.responseSpec, staffId); @@ -214,15 +215,14 @@ public class CenterIntegrationTest { @Test public void testAssignStaffToCenter() { final Integer staffId = StaffHelper.createStaff(this.requestSpec, this.responseSpec); - LOG.info("--------------creating first staff with id------------- {}" , staffId); + LOG.info("--------------creating first staff with id------------- {}", staffId); Assertions.assertNotNull(staffId); final Integer groupID = CenterHelper.createCenter(this.requestSpec, this.responseSpec); CenterHelper.verifyCenterCreatedOnServer(this.requestSpec, this.responseSpec, groupID); - final HashMap assignStaffToCenterResponseMap = (HashMap) CenterHelper.assignStaff(this.requestSpec, - this.responseSpec, groupID.toString(), - staffId.longValue()); + final HashMap assignStaffToCenterResponseMap = (HashMap) CenterHelper.assignStaff(this.requestSpec, this.responseSpec, + groupID.toString(), staffId.longValue()); assertEquals(assignStaffToCenterResponseMap.get("staffId"), staffId, "Verify assigned staff id is the same as id sent"); final CenterDomain center = CenterHelper.retrieveByID(groupID, requestSpec, responseSpec); @@ -235,24 +235,22 @@ public class CenterIntegrationTest { @Test public void testUnassignStaffToCenter() { final Integer staffId = StaffHelper.createStaff(this.requestSpec, this.responseSpec); - LOG.info("--------------creating first staff with id------------- {}" , staffId); + LOG.info("--------------creating first staff with id------------- {}", staffId); Assertions.assertNotNull(staffId); final Integer groupID = CenterHelper.createCenter(this.requestSpec, this.responseSpec); CenterHelper.verifyCenterCreatedOnServer(this.requestSpec, this.responseSpec, groupID); - final HashMap assignStaffToCenterResponseMap = (HashMap) CenterHelper.assignStaff(this.requestSpec, - this.responseSpec, groupID.toString(), - staffId.longValue()); + final HashMap assignStaffToCenterResponseMap = (HashMap) CenterHelper.assignStaff(this.requestSpec, this.responseSpec, + groupID.toString(), staffId.longValue()); assertEquals(assignStaffToCenterResponseMap.get("staffId"), staffId, "Verify assigned staff id is the same as id sent"); final CenterDomain centerWithStaffAssigned = CenterHelper.retrieveByID(groupID, requestSpec, responseSpec); Assertions.assertNotNull(centerWithStaffAssigned); Assertions.assertTrue(centerWithStaffAssigned.getId().intValue() == groupID); Assertions.assertTrue(centerWithStaffAssigned.getStaffId().intValue() == staffId); - final HashMap unassignStaffToCenterResponseMap = (HashMap) CenterHelper.unassignStaff(this.requestSpec, - this.responseSpec, groupID.toString(), - staffId.longValue()); + final HashMap unassignStaffToCenterResponseMap = (HashMap) CenterHelper.unassignStaff(this.requestSpec, this.responseSpec, + groupID.toString(), staffId.longValue()); assertEquals(unassignStaffToCenterResponseMap.get("staffId"), null, "Verify staffId is null after unassigning "); final CenterDomain centerWithStaffUnssigned = CenterHelper.retrieveByID(groupID, requestSpec, responseSpec); Assertions.assertNotNull(centerWithStaffUnssigned); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientLoanIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientLoanIntegrationTest.java index 8933dd426..669ed0dda 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientLoanIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientLoanIntegrationTest.java @@ -92,8 +92,7 @@ public class ClientLoanIntegrationTest { public void setup() { Utils.initializeRESTAssured(); this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - this.requestSpec.header("Authorization", - "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); this.accountHelper = new AccountHelper(this.requestSpec, this.responseSpec); @@ -108,8 +107,8 @@ public class ClientLoanIntegrationTest { ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer loanProductID = createLoanProduct(false, NONE); final Integer loanID = applyForLoanApplication(clientID, loanProductID, null, null, "12,000.00"); - final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, + loanID); verifyLoanRepaymentSchedule(loanSchedule); } @@ -122,14 +121,13 @@ public class ClientLoanIntegrationTest { final Integer loanProductID = createLoanProduct(false, NONE); List charges = new ArrayList<>(); - Integer flatDisbursement = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanDisbursementJSON()); + Integer flatDisbursement = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanDisbursementJSON()); Integer amountPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1")); addCharges(charges, amountPercentage, "1", null); - Integer amountPlusInterestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1")); + Integer amountPlusInterestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1")); addCharges(charges, amountPlusInterestPercentage, "1", null); Integer interestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_INTEREST, "1")); @@ -141,8 +139,7 @@ public class ClientLoanIntegrationTest { HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap disbursementDetail = loanSchedule.get(0); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -162,17 +159,14 @@ public class ClientLoanIntegrationTest { validateCharge(flatDisbursement, loanCharges, "100.0", "100.0", "0.0", "0.0"); validateNumberForEqual("352.12", String.valueOf(disbursementDetail.get("feeChargesDue"))); - this.loanTransactionHelper.updateChargesForLoan(loanID, - (Integer) getloanCharge(amountPercentage, loanCharges).get("id"), + this.loanTransactionHelper.updateChargesForLoan(loanID, (Integer) getloanCharge(amountPercentage, loanCharges).get("id"), LoanTransactionHelper.getUpdateChargesForLoanAsJSON("2")); - this.loanTransactionHelper.updateChargesForLoan(loanID, - (Integer) getloanCharge(interestPercentage, loanCharges).get("id"), + this.loanTransactionHelper.updateChargesForLoan(loanID, (Integer) getloanCharge(interestPercentage, loanCharges).get("id"), LoanTransactionHelper.getUpdateChargesForLoanAsJSON("2")); this.loanTransactionHelper.updateChargesForLoan(loanID, (Integer) getloanCharge(amountPlusInterestPercentage, loanCharges).get("id"), LoanTransactionHelper.getUpdateChargesForLoanAsJSON("2")); - this.loanTransactionHelper.updateChargesForLoan(loanID, - (Integer) getloanCharge(flatDisbursement, loanCharges).get("id"), + this.loanTransactionHelper.updateChargesForLoan(loanID, (Integer) getloanCharge(flatDisbursement, loanCharges).get("id"), LoanTransactionHelper.getUpdateChargesForLoanAsJSON("150")); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -196,8 +190,8 @@ public class ClientLoanIntegrationTest { validateCharge(flatDisbursement, loanCharges, "150.0", "150.0", "0.0", "0.0"); validateNumberForEqual("570.2", String.valueOf(disbursementDetail.get("feeChargesDue"))); - this.loanTransactionHelper.updateLoan(loanID, updateLoanJson(clientID, loanProductID, - copyChargesForUpdate(loanCharges, flatDisbursement, "1"), null)); + this.loanTransactionHelper.updateLoan(loanID, + updateLoanJson(clientID, loanProductID, copyChargesForUpdate(loanCharges, flatDisbursement, "1"), null)); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); @@ -217,8 +211,7 @@ public class ClientLoanIntegrationTest { validateCharge(flatDisbursement, loanCharges, "100.0", "100.0", "0.0", "0.0"); validateNumberForEqual("100.0", String.valueOf(disbursementDetail.get("feeChargesDue"))); - this.loanTransactionHelper.deleteChargesForLoan(loanID, - (Integer) getloanCharge(flatDisbursement, loanCharges).get("id")); + this.loanTransactionHelper.deleteChargesForLoan(loanID, (Integer) getloanCharge(flatDisbursement, loanCharges).get("id")); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); disbursementDetail = loanSchedule.get(0); @@ -239,8 +232,8 @@ public class ClientLoanIntegrationTest { Integer amountPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1")); addCharges(charges, amountPercentage, "1", null); - Integer amountPlusInterestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1")); + Integer amountPlusInterestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1")); addCharges(charges, amountPlusInterestPercentage, "1", null); Integer interestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_INTEREST, "1")); @@ -252,8 +245,7 @@ public class ClientLoanIntegrationTest { HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap disbursementDetail = loanSchedule.get(0); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -296,18 +288,16 @@ public class ClientLoanIntegrationTest { Integer flat = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "100", false)); Integer flatAccTransfer = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanSpecifiedDueDateWithAccountTransferJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, - "100", false)); + ChargesHelper.getLoanSpecifiedDueDateWithAccountTransferJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "100", false)); - Integer amountPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); + Integer amountPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); addCharges(charges, amountPercentage, "1", "29 September 2011"); - Integer amountPlusInterestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanSpecifiedDueDateJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); + Integer amountPlusInterestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper + .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); addCharges(charges, amountPlusInterestPercentage, "1", "29 September 2011"); - Integer interestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_INTEREST, "1", false)); + Integer interestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_INTEREST, "1", false)); addCharges(charges, interestPercentage, "1", "29 September 2011"); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); @@ -316,8 +306,7 @@ public class ClientLoanIntegrationTest { HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap firstInstallment = loanSchedule.get(1); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -328,8 +317,8 @@ public class ClientLoanIntegrationTest { validateNumberForEqual("252.12", String.valueOf(firstInstallment.get("feeChargesDue"))); - this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper - .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flat), "29 September 2011", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, + LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flat), "29 September 2011", "100")); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); firstInstallment = loanSchedule.get(1); @@ -337,11 +326,9 @@ public class ClientLoanIntegrationTest { validateCharge(flat, loanCharges, "100.0", "100.0", "0.0", "0.0"); validateNumberForEqual("352.12", String.valueOf(firstInstallment.get("feeChargesDue"))); - this.loanTransactionHelper.updateChargesForLoan(loanID, - (Integer) getloanCharge(amountPercentage, loanCharges).get("id"), + this.loanTransactionHelper.updateChargesForLoan(loanID, (Integer) getloanCharge(amountPercentage, loanCharges).get("id"), LoanTransactionHelper.getUpdateChargesForLoanAsJSON("2")); - this.loanTransactionHelper.updateChargesForLoan(loanID, - (Integer) getloanCharge(interestPercentage, loanCharges).get("id"), + this.loanTransactionHelper.updateChargesForLoan(loanID, (Integer) getloanCharge(interestPercentage, loanCharges).get("id"), LoanTransactionHelper.getUpdateChargesForLoanAsJSON("2")); this.loanTransactionHelper.updateChargesForLoan(loanID, (Integer) getloanCharge(amountPlusInterestPercentage, loanCharges).get("id"), @@ -360,8 +347,8 @@ public class ClientLoanIntegrationTest { final Integer savingsId = SavingsAccountHelper.openSavingsAccount(this.requestSpec, this.responseSpec, clientID, MINIMUM_OPENING_BALANCE); - this.loanTransactionHelper.updateLoan(loanID, updateLoanJson(clientID, loanProductID, - copyChargesForUpdate(loanCharges, null, null), String.valueOf(savingsId))); + this.loanTransactionHelper.updateLoan(loanID, + updateLoanJson(clientID, loanProductID, copyChargesForUpdate(loanCharges, null, null), String.valueOf(savingsId))); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); @@ -405,8 +392,8 @@ public class ClientLoanIntegrationTest { LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); - this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper - .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatAccTransfer), "29 September 2011", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, + LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatAccTransfer), "29 September 2011", "100")); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); firstInstallment = loanSchedule.get(1); @@ -418,8 +405,8 @@ public class ClientLoanIntegrationTest { LOG.info("DISBURSE {}", loanStatusHashMap.toString()); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper - .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(amountPercentage), "29 September 2011", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, + LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(amountPercentage), "29 September 2011", "1")); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); firstInstallment = loanSchedule.get(1); @@ -427,8 +414,7 @@ public class ClientLoanIntegrationTest { validateCharge(flatAccTransfer, loanCharges, "100.0", "100.0", "0.0", "0.0"); validateNumberForEqual("200.0", String.valueOf(firstInstallment.get("feeChargesDue"))); - this.loanTransactionHelper.waiveChargesForLoan(loanID, - (Integer) getloanCharge(amountPercentage, loanCharges).get("id"), ""); + this.loanTransactionHelper.waiveChargesForLoan(loanID, (Integer) getloanCharge(amountPercentage, loanCharges).get("id"), ""); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); firstInstallment = loanSchedule.get(1); @@ -438,8 +424,7 @@ public class ClientLoanIntegrationTest { validateNumberForEqual("100.0", String.valueOf(firstInstallment.get("feeChargesOutstanding"))); validateNumberForEqual("100.0", String.valueOf(firstInstallment.get("feeChargesWaived"))); - this.loanTransactionHelper.payChargesForLoan(loanID, - (Integer) getloanCharge(flatAccTransfer, loanCharges).get("id"), + this.loanTransactionHelper.payChargesForLoan(loanID, (Integer) getloanCharge(flatAccTransfer, loanCharges).get("id"), LoanTransactionHelper.getPayChargeJSON(SavingsAccountHelper.TRANSACTION_DATE, null)); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); @@ -462,18 +447,17 @@ public class ClientLoanIntegrationTest { List charges = new ArrayList<>(); Integer flat = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "50", false)); - Integer flatAccTransfer = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanInstallmentWithAccountTransferJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "50", false)); + Integer flatAccTransfer = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanInstallmentWithAccountTransferJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "50", false)); - Integer amountPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); + Integer amountPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); addCharges(charges, amountPercentage, "1", "29 September 2011"); Integer amountPlusInterestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanInstallmentJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); + ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); addCharges(charges, amountPlusInterestPercentage, "1", "29 September 2011"); - Integer interestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_INTEREST, "1", false)); + Integer interestPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_INTEREST, "1", false)); addCharges(charges, interestPercentage, "1", "29 September 2011"); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); @@ -482,8 +466,7 @@ public class ClientLoanIntegrationTest { HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); loanSchedule.remove(0); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -496,19 +479,16 @@ public class ClientLoanIntegrationTest { Float principalFee = principalDue / 100; Float interestFee = interestDue / 100; Float totalInstallmentFee = (principalFee * 2) + (interestFee * 2); - validateNumberForEqualExcludePrecission(String.valueOf(totalInstallmentFee), - String.valueOf(installment.get("feeChargesDue"))); + validateNumberForEqualExcludePrecission(String.valueOf(totalInstallmentFee), String.valueOf(installment.get("feeChargesDue"))); totalPerOfAmout = totalPerOfAmout + principalFee; totalPerOfAmoutPlusInt = totalPerOfAmoutPlusInt + principalFee + interestFee; totalPerOfint = totalPerOfint + interestFee; } - validateChargeExcludePrecission(amountPercentage, loanCharges, "1.0", String.valueOf(totalPerOfAmout), "0.0", + validateChargeExcludePrecission(amountPercentage, loanCharges, "1.0", String.valueOf(totalPerOfAmout), "0.0", "0.0"); + validateChargeExcludePrecission(interestPercentage, loanCharges, "1.0", String.valueOf(totalPerOfint), "0.0", "0.0"); + validateChargeExcludePrecission(amountPlusInterestPercentage, loanCharges, "1.0", String.valueOf(totalPerOfAmoutPlusInt), "0.0", "0.0"); - validateChargeExcludePrecission(interestPercentage, loanCharges, "1.0", String.valueOf(totalPerOfint), "0.0", - "0.0"); - validateChargeExcludePrecission(amountPlusInterestPercentage, loanCharges, "1.0", - String.valueOf(totalPerOfAmoutPlusInt), "0.0", "0.0"); this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getInstallmentChargesForLoanAsJSON(String.valueOf(flat), "50")); @@ -524,26 +504,21 @@ public class ClientLoanIntegrationTest { Float principalFee = principalDue / 100; Float interestFee = interestDue / 100; Float totalInstallmentFee = (principalFee * 2) + (interestFee * 2) + 50; - validateNumberForEqualExcludePrecission(String.valueOf(totalInstallmentFee), - String.valueOf(installment.get("feeChargesDue"))); + validateNumberForEqualExcludePrecission(String.valueOf(totalInstallmentFee), String.valueOf(installment.get("feeChargesDue"))); totalPerOfAmout = totalPerOfAmout + principalFee; totalPerOfAmoutPlusInt = totalPerOfAmoutPlusInt + principalFee + interestFee; totalPerOfint = totalPerOfint + interestFee; } - validateChargeExcludePrecission(amountPercentage, loanCharges, "1.0", String.valueOf(totalPerOfAmout), "0.0", + validateChargeExcludePrecission(amountPercentage, loanCharges, "1.0", String.valueOf(totalPerOfAmout), "0.0", "0.0"); + validateChargeExcludePrecission(interestPercentage, loanCharges, "1.0", String.valueOf(totalPerOfint), "0.0", "0.0"); + validateChargeExcludePrecission(amountPlusInterestPercentage, loanCharges, "1.0", String.valueOf(totalPerOfAmoutPlusInt), "0.0", "0.0"); - validateChargeExcludePrecission(interestPercentage, loanCharges, "1.0", String.valueOf(totalPerOfint), "0.0", - "0.0"); - validateChargeExcludePrecission(amountPlusInterestPercentage, loanCharges, "1.0", - String.valueOf(totalPerOfAmoutPlusInt), "0.0", "0.0"); validateChargeExcludePrecission(flat, loanCharges, "50.0", "200", "0.0", "0.0"); - this.loanTransactionHelper.updateChargesForLoan(loanID, - (Integer) getloanCharge(amountPercentage, loanCharges).get("id"), + this.loanTransactionHelper.updateChargesForLoan(loanID, (Integer) getloanCharge(amountPercentage, loanCharges).get("id"), LoanTransactionHelper.getUpdateChargesForLoanAsJSON("2")); - this.loanTransactionHelper.updateChargesForLoan(loanID, - (Integer) getloanCharge(interestPercentage, loanCharges).get("id"), + this.loanTransactionHelper.updateChargesForLoan(loanID, (Integer) getloanCharge(interestPercentage, loanCharges).get("id"), LoanTransactionHelper.getUpdateChargesForLoanAsJSON("2")); this.loanTransactionHelper.updateChargesForLoan(loanID, (Integer) getloanCharge(amountPlusInterestPercentage, loanCharges).get("id"), @@ -563,25 +538,22 @@ public class ClientLoanIntegrationTest { Float principalFee = principalDue * 2 / 100; Float interestFee = interestDue * 2 / 100; Float totalInstallmentFee = (principalFee * 2) + (interestFee * 2) + 100; - validateNumberForEqualExcludePrecission(String.valueOf(totalInstallmentFee), - String.valueOf(installment.get("feeChargesDue"))); + validateNumberForEqualExcludePrecission(String.valueOf(totalInstallmentFee), String.valueOf(installment.get("feeChargesDue"))); totalPerOfAmout = totalPerOfAmout + principalFee; totalPerOfAmoutPlusInt = totalPerOfAmoutPlusInt + principalFee + interestFee; totalPerOfint = totalPerOfint + interestFee; } - validateChargeExcludePrecission(amountPercentage, loanCharges, "2.0", String.valueOf(totalPerOfAmout), "0.0", + validateChargeExcludePrecission(amountPercentage, loanCharges, "2.0", String.valueOf(totalPerOfAmout), "0.0", "0.0"); + validateChargeExcludePrecission(interestPercentage, loanCharges, "2.0", String.valueOf(totalPerOfint), "0.0", "0.0"); + validateChargeExcludePrecission(amountPlusInterestPercentage, loanCharges, "2.0", String.valueOf(totalPerOfAmoutPlusInt), "0.0", "0.0"); - validateChargeExcludePrecission(interestPercentage, loanCharges, "2.0", String.valueOf(totalPerOfint), "0.0", - "0.0"); - validateChargeExcludePrecission(amountPlusInterestPercentage, loanCharges, "2.0", - String.valueOf(totalPerOfAmoutPlusInt), "0.0", "0.0"); validateChargeExcludePrecission(flat, loanCharges, "100.0", "400", "0.0", "0.0"); final Integer savingsId = SavingsAccountHelper.openSavingsAccount(this.requestSpec, this.responseSpec, clientID, MINIMUM_OPENING_BALANCE); - this.loanTransactionHelper.updateLoan(loanID, updateLoanJson(clientID, loanProductID, - copyChargesForUpdate(loanCharges, null, null), String.valueOf(savingsId))); + this.loanTransactionHelper.updateLoan(loanID, + updateLoanJson(clientID, loanProductID, copyChargesForUpdate(loanCharges, null, null), String.valueOf(savingsId))); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); @@ -595,19 +567,16 @@ public class ClientLoanIntegrationTest { Float principalFee = principalDue * 2 / 100; Float interestFee = interestDue * 2 / 100; Float totalInstallmentFee = (principalFee * 2) + (interestFee * 2) + 100; - validateNumberForEqualExcludePrecission(String.valueOf(totalInstallmentFee), - String.valueOf(installment.get("feeChargesDue"))); + validateNumberForEqualExcludePrecission(String.valueOf(totalInstallmentFee), String.valueOf(installment.get("feeChargesDue"))); totalPerOfAmout = totalPerOfAmout + principalFee; totalPerOfAmoutPlusInt = totalPerOfAmoutPlusInt + principalFee + interestFee; totalPerOfint = totalPerOfint + interestFee; } - validateChargeExcludePrecission(amountPercentage, loanCharges, "2.0", String.valueOf(totalPerOfAmout), "0.0", + validateChargeExcludePrecission(amountPercentage, loanCharges, "2.0", String.valueOf(totalPerOfAmout), "0.0", "0.0"); + validateChargeExcludePrecission(interestPercentage, loanCharges, "2.0", String.valueOf(totalPerOfint), "0.0", "0.0"); + validateChargeExcludePrecission(amountPlusInterestPercentage, loanCharges, "2.0", String.valueOf(totalPerOfAmoutPlusInt), "0.0", "0.0"); - validateChargeExcludePrecission(interestPercentage, loanCharges, "2.0", String.valueOf(totalPerOfint), "0.0", - "0.0"); - validateChargeExcludePrecission(amountPlusInterestPercentage, loanCharges, "2.0", - String.valueOf(totalPerOfAmoutPlusInt), "0.0", "0.0"); validateChargeExcludePrecission(flat, loanCharges, "100.0", "400", "0.0", "0.0"); this.loanTransactionHelper.updateLoan(loanID, @@ -625,19 +594,16 @@ public class ClientLoanIntegrationTest { Float principalFee = principalDue / 100; Float interestFee = interestDue / 100; Float totalInstallmentFee = (principalFee * 2) + (interestFee * 2); - validateNumberForEqualExcludePrecission(String.valueOf(totalInstallmentFee), - String.valueOf(installment.get("feeChargesDue"))); + validateNumberForEqualExcludePrecission(String.valueOf(totalInstallmentFee), String.valueOf(installment.get("feeChargesDue"))); totalPerOfAmout = totalPerOfAmout + principalFee; totalPerOfAmoutPlusInt = totalPerOfAmoutPlusInt + principalFee + interestFee; totalPerOfint = totalPerOfint + interestFee; } - validateChargeExcludePrecission(amountPercentage, loanCharges, "1.0", String.valueOf(totalPerOfAmout), "0.0", + validateChargeExcludePrecission(amountPercentage, loanCharges, "1.0", String.valueOf(totalPerOfAmout), "0.0", "0.0"); + validateChargeExcludePrecission(interestPercentage, loanCharges, "1.0", String.valueOf(totalPerOfint), "0.0", "0.0"); + validateChargeExcludePrecission(amountPlusInterestPercentage, loanCharges, "1.0", String.valueOf(totalPerOfAmoutPlusInt), "0.0", "0.0"); - validateChargeExcludePrecission(interestPercentage, loanCharges, "1.0", String.valueOf(totalPerOfint), "0.0", - "0.0"); - validateChargeExcludePrecission(amountPlusInterestPercentage, loanCharges, "1.0", - String.valueOf(totalPerOfAmoutPlusInt), "0.0", "0.0"); charges.clear(); addCharges(charges, flat, "50", "29 September 2011"); @@ -700,12 +666,10 @@ public class ClientLoanIntegrationTest { for (HashMap installment : loanSchedule) { validateNumberForEqualExcludePrecission("150", String.valueOf(installment.get("feeChargesDue"))); if (waivePeriodnum.equals(installment.get("period"))) { - validateNumberForEqualExcludePrecission("100.0", - String.valueOf(installment.get("feeChargesOutstanding"))); + validateNumberForEqualExcludePrecission("100.0", String.valueOf(installment.get("feeChargesOutstanding"))); validateNumberForEqualExcludePrecission("50.0", String.valueOf(installment.get("feeChargesWaived"))); } else { - validateNumberForEqualExcludePrecission("150.0", - String.valueOf(installment.get("feeChargesOutstanding"))); + validateNumberForEqualExcludePrecission("150.0", String.valueOf(installment.get("feeChargesOutstanding"))); validateNumberForEqualExcludePrecission("0.0", String.valueOf(installment.get("feeChargesWaived"))); } @@ -714,25 +678,21 @@ public class ClientLoanIntegrationTest { validateChargeExcludePrecission(flat, loanCharges, "50.0", "150", "0.0", "50.0"); Integer payPeriodnum = 2; - this.loanTransactionHelper.payChargesForLoan(loanID, - (Integer) getloanCharge(flatAccTransfer, loanCharges).get("id"), LoanTransactionHelper - .getPayChargeJSON(SavingsAccountHelper.TRANSACTION_DATE, String.valueOf(payPeriodnum))); + this.loanTransactionHelper.payChargesForLoan(loanID, (Integer) getloanCharge(flatAccTransfer, loanCharges).get("id"), + LoanTransactionHelper.getPayChargeJSON(SavingsAccountHelper.TRANSACTION_DATE, String.valueOf(payPeriodnum))); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); loanSchedule.remove(0); for (HashMap installment : loanSchedule) { validateNumberForEqualExcludePrecission("150", String.valueOf(installment.get("feeChargesDue"))); if (payPeriodnum.equals(installment.get("period"))) { - validateNumberForEqualExcludePrecission("50.0", - String.valueOf(installment.get("feeChargesOutstanding"))); + validateNumberForEqualExcludePrecission("50.0", String.valueOf(installment.get("feeChargesOutstanding"))); validateNumberForEqualExcludePrecission("100.0", String.valueOf(installment.get("feeChargesPaid"))); } else if (waivePeriodnum.equals(installment.get("period"))) { - validateNumberForEqualExcludePrecission("100.0", - String.valueOf(installment.get("feeChargesOutstanding"))); + validateNumberForEqualExcludePrecission("100.0", String.valueOf(installment.get("feeChargesOutstanding"))); validateNumberForEqualExcludePrecission("50.0", String.valueOf(installment.get("feeChargesWaived"))); } else { - validateNumberForEqualExcludePrecission("150.0", - String.valueOf(installment.get("feeChargesOutstanding"))); + validateNumberForEqualExcludePrecission("150.0", String.valueOf(installment.get("feeChargesOutstanding"))); validateNumberForEqualExcludePrecission("0.0", String.valueOf(installment.get("feeChargesPaid"))); } @@ -754,8 +714,7 @@ public class ClientLoanIntegrationTest { final Integer savingsId = SavingsAccountHelper.openSavingsAccount(this.requestSpec, this.responseSpec, clientID, MINIMUM_OPENING_BALANCE); - final Integer loanID = applyForLoanApplication(clientID, loanProductID, null, savingsId.toString(), - "12,000.00"); + final Integer loanID = applyForLoanApplication(clientID, loanProductID, null, savingsId.toString(), "12,000.00"); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); @@ -771,8 +730,7 @@ public class ClientLoanIntegrationTest { assertEquals(balance, summary.get("accountBalance"), "Verifying opening Balance"); // DISBURSE - loanStatusHashMap = this.loanTransactionHelper.disburseLoanToSavings(SavingsAccountHelper.TRANSACTION_DATE, - loanID); + loanStatusHashMap = this.loanTransactionHelper.disburseLoanToSavings(SavingsAccountHelper.TRANSACTION_DATE, loanID); LOG.info("DISBURSE {}", loanStatusHashMap.toString()); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); @@ -801,8 +759,7 @@ public class ClientLoanIntegrationTest { tranches.add(createTrancheDetail("1 March 2014", "25000")); tranches.add(createTrancheDetail("23 April 2014", "20000")); - final Integer loanID = applyForLoanApplicationWithTranches(clientID, loanProductID, null, null, "45,000.00", - tranches); + final Integer loanID = applyForLoanApplicationWithTranches(clientID, loanProductID, null, null, "45,000.00", tranches); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); @@ -845,8 +802,8 @@ public class ClientLoanIntegrationTest { tranches.add(createTrancheDetail("1 March 2014", "25000")); tranches.add(createTrancheDetail("23 April 2014", "20000")); - final Integer loanID = applyForLoanApplicationWithTranches(clientID, loanProductID, null, savingsId.toString(), - "45,000.00", tranches); + final Integer loanID = applyForLoanApplicationWithTranches(clientID, loanProductID, null, savingsId.toString(), "45,000.00", + tranches); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); @@ -889,31 +846,28 @@ public class ClientLoanIntegrationTest { } - private void validateCharge(Integer amountPercentage, final List loanCharges, final String amount, - final String outstanding, String amountPaid, String amountWaived) { + private void validateCharge(Integer amountPercentage, final List loanCharges, final String amount, final String outstanding, + String amountPaid, String amountWaived) { HashMap chargeDetail = getloanCharge(amountPercentage, loanCharges); - Assertions.assertTrue(Float.valueOf(amount) - .compareTo(Float.valueOf(String.valueOf(chargeDetail.get("amountOrPercentage")))) == 0); - Assertions.assertTrue(Float.valueOf(outstanding) - .compareTo(Float.valueOf(String.valueOf(chargeDetail.get("amountOutstanding")))) == 0); - Assertions.assertTrue(Float.valueOf(amountPaid) - .compareTo(Float.valueOf(String.valueOf(chargeDetail.get("amountPaid")))) == 0); - Assertions.assertTrue(Float.valueOf(amountWaived) - .compareTo(Float.valueOf(String.valueOf(chargeDetail.get("amountWaived")))) == 0); + Assertions.assertTrue(Float.valueOf(amount).compareTo(Float.valueOf(String.valueOf(chargeDetail.get("amountOrPercentage")))) == 0); + Assertions.assertTrue( + Float.valueOf(outstanding).compareTo(Float.valueOf(String.valueOf(chargeDetail.get("amountOutstanding")))) == 0); + Assertions.assertTrue(Float.valueOf(amountPaid).compareTo(Float.valueOf(String.valueOf(chargeDetail.get("amountPaid")))) == 0); + Assertions.assertTrue(Float.valueOf(amountWaived).compareTo(Float.valueOf(String.valueOf(chargeDetail.get("amountWaived")))) == 0); } - private void validateChargeExcludePrecission(Integer amountPercentage, final List loanCharges, - final String amount, final String outstanding, String amountPaid, String amountWaived) { + private void validateChargeExcludePrecission(Integer amountPercentage, final List loanCharges, final String amount, + final String outstanding, String amountPaid, String amountWaived) { DecimalFormat twoDForm = new DecimalFormat("#"); HashMap chargeDetail = getloanCharge(amountPercentage, loanCharges); - Assertions.assertTrue(Float.valueOf(twoDForm.format(Float.valueOf(amount))).compareTo(Float - .valueOf(twoDForm.format(Float.valueOf(String.valueOf(chargeDetail.get("amountOrPercentage")))))) == 0); - Assertions.assertTrue(Float.valueOf(twoDForm.format(Float.valueOf(outstanding))).compareTo(Float - .valueOf(twoDForm.format(Float.valueOf(String.valueOf(chargeDetail.get("amountOutstanding")))))) == 0); - Assertions.assertTrue(Float.valueOf(twoDForm.format(Float.valueOf(amountPaid))).compareTo( - Float.valueOf(twoDForm.format(Float.valueOf(String.valueOf(chargeDetail.get("amountPaid")))))) == 0); - Assertions.assertTrue(Float.valueOf(twoDForm.format(Float.valueOf(amountWaived))).compareTo( - Float.valueOf(twoDForm.format(Float.valueOf(String.valueOf(chargeDetail.get("amountWaived")))))) == 0); + Assertions.assertTrue(Float.valueOf(twoDForm.format(Float.valueOf(amount))) + .compareTo(Float.valueOf(twoDForm.format(Float.valueOf(String.valueOf(chargeDetail.get("amountOrPercentage")))))) == 0); + Assertions.assertTrue(Float.valueOf(twoDForm.format(Float.valueOf(outstanding))) + .compareTo(Float.valueOf(twoDForm.format(Float.valueOf(String.valueOf(chargeDetail.get("amountOutstanding")))))) == 0); + Assertions.assertTrue(Float.valueOf(twoDForm.format(Float.valueOf(amountPaid))) + .compareTo(Float.valueOf(twoDForm.format(Float.valueOf(String.valueOf(chargeDetail.get("amountPaid")))))) == 0); + Assertions.assertTrue(Float.valueOf(twoDForm.format(Float.valueOf(amountWaived))) + .compareTo(Float.valueOf(twoDForm.format(Float.valueOf(String.valueOf(chargeDetail.get("amountWaived")))))) == 0); } private void validateNumberForEqual(String val, String val2) { @@ -921,18 +875,16 @@ public class ClientLoanIntegrationTest { } private void validateNumberForEqualWithMsg(String msg, String val, String val2) { - Assertions.assertTrue(Float.valueOf(val).compareTo(Float.valueOf(val2)) == 0, - msg + "expected " + val + " but was " + val2); + Assertions.assertTrue(Float.valueOf(val).compareTo(Float.valueOf(val2)) == 0, msg + "expected " + val + " but was " + val2); } private void validateNumberForEqualExcludePrecission(String val, String val2) { DecimalFormat twoDForm = new DecimalFormat("#"); - Assertions.assertTrue(Float.valueOf(twoDForm.format(Float.valueOf(val))) - .compareTo(Float.valueOf(twoDForm.format(Float.valueOf(val2)))) == 0); + Assertions.assertTrue( + Float.valueOf(twoDForm.format(Float.valueOf(val))).compareTo(Float.valueOf(twoDForm.format(Float.valueOf(val2)))) == 0); } - private Integer createLoanProduct(final boolean multiDisburseLoan, final String accountingRule, - final Account... accounts) { + private Integer createLoanProduct(final boolean multiDisburseLoan, final String accountingRule, final Account... accounts) { LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); LoanProductTestBuilder builder = new LoanProductTestBuilder() // .withPrincipal("12,000.00") // @@ -952,8 +904,7 @@ public class ClientLoanIntegrationTest { return this.loanTransactionHelper.getLoanProductId(loanProductJSON); } - private Integer createLoanProduct(final String inMultiplesOf, final String digitsAfterDecimal, - final String repaymentStrategy) { + private Integer createLoanProduct(final String inMultiplesOf, final String digitsAfterDecimal, final String repaymentStrategy) { LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); final String loanProductJSON = new LoanProductTestBuilder() // .withPrincipal("10000000.00") // @@ -969,8 +920,8 @@ public class ClientLoanIntegrationTest { return this.loanTransactionHelper.getLoanProductId(loanProductJSON); } - private Integer createLoanProduct(final String inMultiplesOf, final String digitsAfterDecimal, - final String repaymentStrategy, final String accountingRule, final Account... accounts) { + private Integer createLoanProduct(final String inMultiplesOf, final String digitsAfterDecimal, final String repaymentStrategy, + final String accountingRule, final Account... accounts) { LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); final String loanProductJSON = new LoanProductTestBuilder() // .withPrincipal("10000000.00") // @@ -982,13 +933,11 @@ public class ClientLoanIntegrationTest { .withRepaymentStrategy(repaymentStrategy) // .withAmortizationTypeAsEqualPrincipalPayment() // .withInterestTypeAsDecliningBalance() // - .currencyDetails(digitsAfterDecimal, inMultiplesOf).withAccounting(accountingRule, accounts) - .build(null); + .currencyDetails(digitsAfterDecimal, inMultiplesOf).withAccounting(accountingRule, accounts).build(null); return this.loanTransactionHelper.getLoanProductId(loanProductJSON); } - private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID, - String graceOnPrincipalPayment) { + private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID, String graceOnPrincipalPayment) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal("10000000.00") // @@ -1027,8 +976,8 @@ public class ClientLoanIntegrationTest { return this.loanTransactionHelper.getLoanId(loanApplicationJSON); } - private Integer applyForLoanApplicationWithTranches(final Integer clientID, final Integer loanProductID, - List charges, final String savingsId, String principal, List tranches) { + private Integer applyForLoanApplicationWithTranches(final Integer clientID, final Integer loanProductID, List charges, + final String savingsId, String principal, List tranches) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal(principal) // @@ -1049,8 +998,7 @@ public class ClientLoanIntegrationTest { return this.loanTransactionHelper.getLoanId(loanApplicationJSON); } - private String updateLoanJson(final Integer clientID, final Integer loanProductID, List charges, - String savingsId) { + private String updateLoanJson(final Integer clientID, final Integer loanProductID, List charges, String savingsId) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal("10,000.00") // @@ -1069,8 +1017,8 @@ public class ClientLoanIntegrationTest { return loanApplicationJSON; } - private Integer applyForLoanApplicationWithPaymentStrategy(final Integer clientID, final Integer loanProductID, - List charges, final String savingsId, String principal, final String repaymentStrategy) { + private Integer applyForLoanApplicationWithPaymentStrategy(final Integer clientID, final Integer loanProductID, List charges, + final String savingsId, String principal, final String repaymentStrategy) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal(principal) // @@ -1090,9 +1038,8 @@ public class ClientLoanIntegrationTest { return this.loanTransactionHelper.getLoanId(loanApplicationJSON); } - private Integer applyForLoanApplicationWithPaymentStrategyAndPastMonth(final Integer clientID, - final Integer loanProductID, List charges, final String savingsId, String principal, - final String repaymentStrategy, final int month) { + private Integer applyForLoanApplicationWithPaymentStrategyAndPastMonth(final Integer clientID, final Integer loanProductID, + List charges, final String savingsId, String principal, final String repaymentStrategy, final int month) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); Calendar fourMonthsfromNowCalendar = Calendar.getInstance(Utils.getTimeZoneOfTenant()); @@ -1119,239 +1066,129 @@ public class ClientLoanIntegrationTest { } private void verifyLoanRepaymentSchedule(final ArrayList loanSchedule) { - LOG.info( - "--------------------VERIFYING THE PRINCIPAL DUES,INTEREST DUE AND DUE DATE--------------------------"); + LOG.info("--------------------VERIFYING THE PRINCIPAL DUES,INTEREST DUE AND DUE DATE--------------------------"); - assertEquals(new ArrayList<>(Arrays.asList(2011, 10, 20)), - loanSchedule.get(1).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2011, 10, 20)), loanSchedule.get(1).get("dueDate"), "Checking for Due Date for 1st Month"); - assertEquals(Float.valueOf("2911.49"), - loanSchedule.get(1).get("principalOriginalDue"), - "Checking for Principal Due for 1st Month"); - assertEquals(Float.valueOf("240.00"), - loanSchedule.get(1).get("interestOriginalDue"), - "Checking for Interest Due for 1st Month"); + assertEquals(Float.valueOf("2911.49"), loanSchedule.get(1).get("principalOriginalDue"), "Checking for Principal Due for 1st Month"); + assertEquals(Float.valueOf("240.00"), loanSchedule.get(1).get("interestOriginalDue"), "Checking for Interest Due for 1st Month"); - assertEquals(new ArrayList<>(Arrays.asList(2011, 11, 20)), - loanSchedule.get(2).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2011, 11, 20)), loanSchedule.get(2).get("dueDate"), "Checking for Due Date for 2nd Month"); - assertEquals(Float.valueOf("2969.72"), - loanSchedule.get(2).get("principalDue"), - "Checking for Principal Due for 2nd Month"); - assertEquals(Float.valueOf("181.77"), - loanSchedule.get(2).get("interestOriginalDue"), - "Checking for Interest Due for 2nd Month"); + assertEquals(Float.valueOf("2969.72"), loanSchedule.get(2).get("principalDue"), "Checking for Principal Due for 2nd Month"); + assertEquals(Float.valueOf("181.77"), loanSchedule.get(2).get("interestOriginalDue"), "Checking for Interest Due for 2nd Month"); - assertEquals(new ArrayList<>(Arrays.asList(2011, 12, 20)), - loanSchedule.get(3).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2011, 12, 20)), loanSchedule.get(3).get("dueDate"), "Checking for Due Date for 3rd Month"); - assertEquals(Float.valueOf("3029.11"), - loanSchedule.get(3).get("principalDue"), - "Checking for Principal Due for 3rd Month"); - assertEquals(Float.valueOf("122.38"), - loanSchedule.get(3).get("interestOriginalDue"), - "Checking for Interest Due for 3rd Month"); + assertEquals(Float.valueOf("3029.11"), loanSchedule.get(3).get("principalDue"), "Checking for Principal Due for 3rd Month"); + assertEquals(Float.valueOf("122.38"), loanSchedule.get(3).get("interestOriginalDue"), "Checking for Interest Due for 3rd Month"); - assertEquals(new ArrayList<>(Arrays.asList(2012, 1, 20)), - loanSchedule.get(4).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2012, 1, 20)), loanSchedule.get(4).get("dueDate"), "Checking for Due Date for 4th Month"); - assertEquals(Float.valueOf("3089.68"), - loanSchedule.get(4).get("principalDue"), - "Checking for Principal Due for 4th Month"); - assertEquals(Float.valueOf("61.79"), - loanSchedule.get(4).get("interestOriginalDue"), - "Checking for Interest Due for 4th Month"); + assertEquals(Float.valueOf("3089.68"), loanSchedule.get(4).get("principalDue"), "Checking for Principal Due for 4th Month"); + assertEquals(Float.valueOf("61.79"), loanSchedule.get(4).get("interestOriginalDue"), "Checking for Interest Due for 4th Month"); } private void verifyLoanRepaymentScheduleForEqualPrincipal(final ArrayList loanSchedule) { - LOG.info( - "--------------------VERIFYING THE PRINCIPAL DUES,INTEREST DUE AND DUE DATE--------------------------"); + LOG.info("--------------------VERIFYING THE PRINCIPAL DUES,INTEREST DUE AND DUE DATE--------------------------"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 7, 2)), - loanSchedule.get(1).get("dueDate"), - "Checking for Due Date for 1st Month"); - assertEquals(Float.valueOf("416700"), - loanSchedule.get(1).get("principalOriginalDue"), - "Checking for Principal Due for 1st Month"); - assertEquals(Float.valueOf("200000"), - loanSchedule.get(1).get("interestOriginalDue"), - "Checking for Interest Due for 1st Month"); + assertEquals(new ArrayList<>(Arrays.asList(2014, 7, 2)), loanSchedule.get(1).get("dueDate"), "Checking for Due Date for 1st Month"); + assertEquals(Float.valueOf("416700"), loanSchedule.get(1).get("principalOriginalDue"), "Checking for Principal Due for 1st Month"); + assertEquals(Float.valueOf("200000"), loanSchedule.get(1).get("interestOriginalDue"), "Checking for Interest Due for 1st Month"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 8, 2)), - loanSchedule.get(2).get("dueDate"), - "Checking for Due Date for 2nd Month"); - assertEquals(Float.valueOf("416700"), - loanSchedule.get(2).get("principalDue"), - "Checking for Principal Due for 2nd Month"); - assertEquals(Float.valueOf("191700"), - loanSchedule.get(2).get("interestOriginalDue"), - "Checking for Interest Due for 2nd Month"); + assertEquals(new ArrayList<>(Arrays.asList(2014, 8, 2)), loanSchedule.get(2).get("dueDate"), "Checking for Due Date for 2nd Month"); + assertEquals(Float.valueOf("416700"), loanSchedule.get(2).get("principalDue"), "Checking for Principal Due for 2nd Month"); + assertEquals(Float.valueOf("191700"), loanSchedule.get(2).get("interestOriginalDue"), "Checking for Interest Due for 2nd Month"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 9, 2)), - loanSchedule.get(3).get("dueDate"), - "Checking for Due Date for 3rd Month"); - assertEquals(Float.valueOf("416700"), - loanSchedule.get(3).get("principalDue"), - "Checking for Principal Due for 3rd Month"); - assertEquals(Float.valueOf("183300"), - loanSchedule.get(3).get("interestOriginalDue"), - "Checking for Interest Due for 3rd Month"); + assertEquals(new ArrayList<>(Arrays.asList(2014, 9, 2)), loanSchedule.get(3).get("dueDate"), "Checking for Due Date for 3rd Month"); + assertEquals(Float.valueOf("416700"), loanSchedule.get(3).get("principalDue"), "Checking for Principal Due for 3rd Month"); + assertEquals(Float.valueOf("183300"), loanSchedule.get(3).get("interestOriginalDue"), "Checking for Interest Due for 3rd Month"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 10, 2)), - loanSchedule.get(4).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2014, 10, 2)), loanSchedule.get(4).get("dueDate"), "Checking for Due Date for 4th Month"); - assertEquals(Float.valueOf("416700"), - loanSchedule.get(4).get("principalDue"), - "Checking for Principal Due for 4th Month"); - assertEquals(Float.valueOf("175000"), - loanSchedule.get(4).get("interestOriginalDue"), - "Checking for Interest Due for 4th Month"); + assertEquals(Float.valueOf("416700"), loanSchedule.get(4).get("principalDue"), "Checking for Principal Due for 4th Month"); + assertEquals(Float.valueOf("175000"), loanSchedule.get(4).get("interestOriginalDue"), "Checking for Interest Due for 4th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 11, 2)), - loanSchedule.get(5).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2014, 11, 2)), loanSchedule.get(5).get("dueDate"), "Checking for Due Date for 5th Month"); - assertEquals(Float.valueOf("416700"), - loanSchedule.get(5).get("principalDue"), - "Checking for Principal Due for 5th Month"); - assertEquals(Float.valueOf("166700"), - loanSchedule.get(5).get("interestOriginalDue"), - "Checking for Interest Due for 5th Month"); + assertEquals(Float.valueOf("416700"), loanSchedule.get(5).get("principalDue"), "Checking for Principal Due for 5th Month"); + assertEquals(Float.valueOf("166700"), loanSchedule.get(5).get("interestOriginalDue"), "Checking for Interest Due for 5th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 12, 2)), - loanSchedule.get(6).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2014, 12, 2)), loanSchedule.get(6).get("dueDate"), "Checking for Due Date for 6th Month"); - assertEquals(Float.valueOf("416700"), - loanSchedule.get(6).get("principalDue"), - "Checking for Principal Due for 6th Month"); - assertEquals(Float.valueOf("158300"), - loanSchedule.get(6).get("interestOriginalDue"), - "Checking for Interest Due for 6th Month"); + assertEquals(Float.valueOf("416700"), loanSchedule.get(6).get("principalDue"), "Checking for Principal Due for 6th Month"); + assertEquals(Float.valueOf("158300"), loanSchedule.get(6).get("interestOriginalDue"), "Checking for Interest Due for 6th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2015, 4, 2)), - loanSchedule.get(10).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2015, 4, 2)), loanSchedule.get(10).get("dueDate"), "Checking for Due Date for 10th Month"); - assertEquals(Float.valueOf("416700"), - loanSchedule.get(10).get("principalDue"), - "Checking for Principal Due for 10th Month"); - assertEquals(Float.valueOf("125000"), - loanSchedule.get(10).get("interestOriginalDue"), - "Checking for Interest Due for 10th Month"); + assertEquals(Float.valueOf("416700"), loanSchedule.get(10).get("principalDue"), "Checking for Principal Due for 10th Month"); + assertEquals(Float.valueOf("125000"), loanSchedule.get(10).get("interestOriginalDue"), "Checking for Interest Due for 10th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2016, 2, 2)), - loanSchedule.get(20).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2016, 2, 2)), loanSchedule.get(20).get("dueDate"), "Checking for Due Date for 20th Month"); - assertEquals(Float.valueOf("416700"), - loanSchedule.get(20).get("principalDue"), - "Checking for Principal Due for 20th Month"); - assertEquals(Float.valueOf("41700"), - loanSchedule.get(20).get("interestOriginalDue"), - "Checking for Interest Due for 20th Month"); + assertEquals(Float.valueOf("416700"), loanSchedule.get(20).get("principalDue"), "Checking for Principal Due for 20th Month"); + assertEquals(Float.valueOf("41700"), loanSchedule.get(20).get("interestOriginalDue"), "Checking for Interest Due for 20th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2016, 6, 2)), - loanSchedule.get(24).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2016, 6, 2)), loanSchedule.get(24).get("dueDate"), "Checking for Due Date for 24th Month"); - assertEquals(Float.valueOf("415900"), - loanSchedule.get(24).get("principalDue"), - "Checking for Principal Due for 24th Month"); - assertEquals(Float.valueOf("8300"), - loanSchedule.get(24).get("interestOriginalDue"), - "Checking for Interest Due for 24th Month"); + assertEquals(Float.valueOf("415900"), loanSchedule.get(24).get("principalDue"), "Checking for Principal Due for 24th Month"); + assertEquals(Float.valueOf("8300"), loanSchedule.get(24).get("interestOriginalDue"), "Checking for Interest Due for 24th Month"); } private void verifyLoanRepaymentScheduleForEqualPrincipalWithGrace(final ArrayList loanSchedule) { - LOG.info( - "--------------------VERIFYING THE PRINCIPAL DUES,INTEREST DUE AND DUE DATE--------------------------"); + LOG.info("--------------------VERIFYING THE PRINCIPAL DUES,INTEREST DUE AND DUE DATE--------------------------"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 7, 2)), - loanSchedule.get(1).get("dueDate"), - "Checking for Due Date for 1st Month"); - validateNumberForEqualWithMsg("Checking for Principal Due for 1st Month", String.valueOf(loanSchedule.get(1).get("principalOriginalDue")), "0.0"); - assertEquals(Float.valueOf("200000"), - loanSchedule.get(1).get("interestOriginalDue"), - "Checking for Interest Due for 1st Month"); + assertEquals(new ArrayList<>(Arrays.asList(2014, 7, 2)), loanSchedule.get(1).get("dueDate"), "Checking for Due Date for 1st Month"); + validateNumberForEqualWithMsg("Checking for Principal Due for 1st Month", + String.valueOf(loanSchedule.get(1).get("principalOriginalDue")), "0.0"); + assertEquals(Float.valueOf("200000"), loanSchedule.get(1).get("interestOriginalDue"), "Checking for Interest Due for 1st Month"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 8, 2)), - loanSchedule.get(2).get("dueDate"), - "Checking for Due Date for 2nd Month"); - validateNumberForEqualWithMsg("Checking for Principal Due for 2nd Month", "0.0", String.valueOf(loanSchedule.get(2).get("principalOriginalDue"))); - assertEquals(Float.valueOf("200000"), - loanSchedule.get(2).get("interestOriginalDue"), - "Checking for Interest Due for 2nd Month"); + assertEquals(new ArrayList<>(Arrays.asList(2014, 8, 2)), loanSchedule.get(2).get("dueDate"), "Checking for Due Date for 2nd Month"); + validateNumberForEqualWithMsg("Checking for Principal Due for 2nd Month", "0.0", + String.valueOf(loanSchedule.get(2).get("principalOriginalDue"))); + assertEquals(Float.valueOf("200000"), loanSchedule.get(2).get("interestOriginalDue"), "Checking for Interest Due for 2nd Month"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 9, 2)), - loanSchedule.get(3).get("dueDate"), - "Checking for Due Date for 3rd Month"); - validateNumberForEqualWithMsg("Checking for Principal Due for 3rd Month", "0.0", String.valueOf(loanSchedule.get(3).get("principalDue"))); - assertEquals(Float.valueOf("200000"), loanSchedule.get(3).get("interestOriginalDue"), - "Checking for Interest Due for 3rd Month"); + assertEquals(new ArrayList<>(Arrays.asList(2014, 9, 2)), loanSchedule.get(3).get("dueDate"), "Checking for Due Date for 3rd Month"); + validateNumberForEqualWithMsg("Checking for Principal Due for 3rd Month", "0.0", + String.valueOf(loanSchedule.get(3).get("principalDue"))); + assertEquals(Float.valueOf("200000"), loanSchedule.get(3).get("interestOriginalDue"), "Checking for Interest Due for 3rd Month"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 10, 2)), - loanSchedule.get(4).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2014, 10, 2)), loanSchedule.get(4).get("dueDate"), "Checking for Due Date for 4th Month"); - validateNumberForEqualWithMsg("Checking for Principal Due for 4th Month", "0", String.valueOf(loanSchedule.get(4).get("principalDue"))); - assertEquals(Float.valueOf("200000"), - loanSchedule.get(4).get("interestOriginalDue"), - "Checking for Interest Due for 4th Month"); + validateNumberForEqualWithMsg("Checking for Principal Due for 4th Month", "0", + String.valueOf(loanSchedule.get(4).get("principalDue"))); + assertEquals(Float.valueOf("200000"), loanSchedule.get(4).get("interestOriginalDue"), "Checking for Interest Due for 4th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 11, 2)), - loanSchedule.get(5).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2014, 11, 2)), loanSchedule.get(5).get("dueDate"), "Checking for Due Date for 5th Month"); validateNumberForEqualWithMsg("Checking for Principal Due for 5th Month", "0", String.valueOf(loanSchedule.get(5).get("principalDue"))); - assertEquals(Float.valueOf("200000"), - loanSchedule.get(5).get("interestOriginalDue"), - "Checking for Interest Due for 5th Month"); + assertEquals(Float.valueOf("200000"), loanSchedule.get(5).get("interestOriginalDue"), "Checking for Interest Due for 5th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2014, 12, 2)), - loanSchedule.get(6).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2014, 12, 2)), loanSchedule.get(6).get("dueDate"), "Checking for Due Date for 6th Month"); - assertEquals(Float.valueOf("526300"), - loanSchedule.get(6).get("principalDue"), - "Checking for Principal Due for 6th Month"); - assertEquals(Float.valueOf("200000"), - loanSchedule.get(6).get("interestOriginalDue"), - "Checking for Interest Due for 6th Month"); + assertEquals(Float.valueOf("526300"), loanSchedule.get(6).get("principalDue"), "Checking for Principal Due for 6th Month"); + assertEquals(Float.valueOf("200000"), loanSchedule.get(6).get("interestOriginalDue"), "Checking for Interest Due for 6th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2015, 1, 2)), - loanSchedule.get(7).get("dueDate"), - "Checking for Due Date for 7th Month"); - assertEquals(Float.valueOf("526300"), - loanSchedule.get(7).get("principalDue"), - "Checking for Principal Due for 7th Month"); - assertEquals(Float.valueOf("189500"), - loanSchedule.get(7).get("interestOriginalDue"), - "Checking for Interest Due for 7th Month"); + assertEquals(new ArrayList<>(Arrays.asList(2015, 1, 2)), loanSchedule.get(7).get("dueDate"), "Checking for Due Date for 7th Month"); + assertEquals(Float.valueOf("526300"), loanSchedule.get(7).get("principalDue"), "Checking for Principal Due for 7th Month"); + assertEquals(Float.valueOf("189500"), loanSchedule.get(7).get("interestOriginalDue"), "Checking for Interest Due for 7th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2015, 4, 2)), - loanSchedule.get(10).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2015, 4, 2)), loanSchedule.get(10).get("dueDate"), "Checking for Due Date for 10th Month"); - assertEquals(Float.valueOf("526300"), - loanSchedule.get(10).get("principalDue"), - "Checking for Principal Due for 10th Month"); - assertEquals(Float.valueOf("157900"), - loanSchedule.get(10).get("interestOriginalDue"), - "Checking for Interest Due for 10th Month"); + assertEquals(Float.valueOf("526300"), loanSchedule.get(10).get("principalDue"), "Checking for Principal Due for 10th Month"); + assertEquals(Float.valueOf("157900"), loanSchedule.get(10).get("interestOriginalDue"), "Checking for Interest Due for 10th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2016, 2, 2)), - loanSchedule.get(20).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2016, 2, 2)), loanSchedule.get(20).get("dueDate"), "Checking for Due Date for 20th Month"); - assertEquals(Float.valueOf("526300"), - loanSchedule.get(20).get("principalDue"), - "Checking for Principal Due for 20th Month"); - assertEquals(Float.valueOf("52600"), - loanSchedule.get(20).get("interestOriginalDue"), - "Checking for Interest Due for 20th Month"); + assertEquals(Float.valueOf("526300"), loanSchedule.get(20).get("principalDue"), "Checking for Principal Due for 20th Month"); + assertEquals(Float.valueOf("52600"), loanSchedule.get(20).get("interestOriginalDue"), "Checking for Interest Due for 20th Month"); - assertEquals(new ArrayList<>(Arrays.asList(2016, 6, 2)), - loanSchedule.get(24).get("dueDate"), + assertEquals(new ArrayList<>(Arrays.asList(2016, 6, 2)), loanSchedule.get(24).get("dueDate"), "Checking for Due Date for 24th Month"); - assertEquals(Float.valueOf("526600"), - loanSchedule.get(24).get("principalDue"), - "Checking for Principal Due for 24th Month"); - assertEquals(Float.valueOf("10500"), - loanSchedule.get(24).get("interestOriginalDue"), - "Checking for Interest Due for 24th Month"); + assertEquals(Float.valueOf("526600"), loanSchedule.get(24).get("principalDue"), "Checking for Principal Due for 24th Month"); + assertEquals(Float.valueOf("10500"), loanSchedule.get(24).get("interestOriginalDue"), "Checking for Interest Due for 24th Month"); } private void addCharges(List charges, Integer chargeId, String amount, String duedate) { @@ -1412,8 +1249,8 @@ public class ClientLoanIntegrationTest { } /*** - * Test case for checking CashBasedAccounting functionality adding charges with - * calculation type flat + * Test case for checking CashBasedAccounting functionality adding charges + * with calculation type flat */ @Test public void loanWithFlatCahargesAndCashBasedAccountingEnabled() { @@ -1424,8 +1261,7 @@ public class ClientLoanIntegrationTest { // Add charges with payment mode regular List charges = new ArrayList<>(); - Integer flatDisbursement = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanDisbursementJSON()); + Integer flatDisbursement = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanDisbursementJSON()); addCharges(charges, flatDisbursement, "100", null); Integer flatSpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "100", false)); @@ -1439,15 +1275,13 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct(false, CASH_BASED, assetAccount, incomeAccount, expenseAccount, - overpaymentAccount); + final Integer loanProductID = createLoanProduct(false, CASH_BASED, assetAccount, incomeAccount, expenseAccount, overpaymentAccount); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); verifyLoanRepaymentSchedule(loanSchedule); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -1476,12 +1310,10 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan("20 September 2011", loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("100.00"), JournalEntry.TransactionType.DEBIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("100.00"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", assetAccountInitialEntry); this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 September 2011", new JournalEntry(Float.valueOf("100.00"), JournalEntry.TransactionType.CREDIT)); loanCharges.clear(); @@ -1502,16 +1334,14 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 October 2011", new JournalEntry(Float.valueOf("150.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("240.00"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDate), - "29 October 2011", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDate), "29 October 2011", "100")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); secondInstallment = loanSchedule.get(2); validateNumberForEqual("150.00", String.valueOf(secondInstallment.get("feeChargesDue"))); - this.loanTransactionHelper.waiveChargesForLoan(loanID, - (Integer) getloanCharge(flatInstallmentFee, loanCharges).get("id"), + this.loanTransactionHelper.waiveChargesForLoan(loanID, (Integer) getloanCharge(flatInstallmentFee, loanCharges).get("id"), LoanTransactionHelper.getWaiveChargeJSON(String.valueOf(2))); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -1539,9 +1369,8 @@ public class ClientLoanIntegrationTest { Integer flatPenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "100", true)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(flatPenaltySpecifiedDueDate), "29 September 2011", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatPenaltySpecifiedDueDate), "29 September 2011", "100")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(flatPenaltySpecifiedDueDate, loanCharges, "100", "0.00", "100.0", "0.0"); @@ -1567,9 +1396,8 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 November 2011", new JournalEntry(Float.valueOf("50.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("122.38"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(flatPenaltySpecifiedDueDate), "10 January 2012", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatPenaltySpecifiedDueDate), "10 January 2012", "100")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap fourthInstallment = loanSchedule.get(4); @@ -1598,8 +1426,8 @@ public class ClientLoanIntegrationTest { } /*** - * Test case for checking CashBasedAccounting functionality adding charges with - * calculation type percentage of amount + * Test case for checking CashBasedAccounting functionality adding charges + * with calculation type percentage of amount */ @Test public void loanWithCahargesOfTypeAmountPercentageAndCashBasedAccountingEnabled() { @@ -1614,12 +1442,12 @@ public class ClientLoanIntegrationTest { ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1")); addCharges(charges, percentageDisbursementCharge, "1", null); - Integer percentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); + Integer percentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); addCharges(charges, percentageSpecifiedDueDateCharge, "1", "29 September 2011"); - Integer percentageInstallmentFee = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); + Integer percentageInstallmentFee = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); addCharges(charges, percentageInstallmentFee, "1", "29 September 2011"); final Account assetAccount = this.accountHelper.createAssetAccount(); @@ -1627,15 +1455,13 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct(false, CASH_BASED, assetAccount, incomeAccount, expenseAccount, - overpaymentAccount); + final Integer loanProductID = createLoanProduct(false, CASH_BASED, assetAccount, incomeAccount, expenseAccount, overpaymentAccount); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); verifyLoanRepaymentSchedule(loanSchedule); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -1664,12 +1490,10 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan("20 September 2011", loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("120.00"), JournalEntry.TransactionType.DEBIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("120.00"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", assetAccountInitialEntry); this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 September 2011", new JournalEntry(Float.valueOf("120.00"), JournalEntry.TransactionType.CREDIT)); loanCharges.clear(); @@ -1690,16 +1514,14 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 October 2011", new JournalEntry(Float.valueOf("149.11"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("240.00"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(percentageSpecifiedDueDateCharge), "29 October 2011", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(percentageSpecifiedDueDateCharge), "29 October 2011", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); secondInstallment = loanSchedule.get(2); validateNumberForEqual("149.70", String.valueOf(secondInstallment.get("feeChargesDue"))); - this.loanTransactionHelper.waiveChargesForLoan(loanID, - (Integer) getloanCharge(percentageInstallmentFee, loanCharges).get("id"), + this.loanTransactionHelper.waiveChargesForLoan(loanID, (Integer) getloanCharge(percentageInstallmentFee, loanCharges).get("id"), LoanTransactionHelper.getWaiveChargeJSON(String.valueOf(2))); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -1725,11 +1547,10 @@ public class ClientLoanIntegrationTest { HashMap thirdInstallment = loanSchedule.get(3); validateNumberForEqual("60.59", String.valueOf(thirdInstallment.get("interestOutstanding"))); - Integer percentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(percentagePenaltySpecifiedDueDate), "29 September 2011", "1")); + Integer percentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(percentagePenaltySpecifiedDueDate), "29 September 2011", "1")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(percentagePenaltySpecifiedDueDate, loanCharges, "1", "0.00", "120.0", "0.0"); @@ -1755,9 +1576,8 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 November 2011", new JournalEntry(Float.valueOf("30.29"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("122.38"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(percentagePenaltySpecifiedDueDate), "10 January 2012", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(percentagePenaltySpecifiedDueDate), "10 January 2012", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap fourthInstallment = loanSchedule.get(4); @@ -1786,8 +1606,8 @@ public class ClientLoanIntegrationTest { } /*** - * Test case for checking CashBasedAccounting functionality adding charges with - * calculation type percentage of amount plus interest + * Test case for checking CashBasedAccounting functionality adding charges + * with calculation type percentage of amount plus interest */ @Test public void loanWithCahargesOfTypeAmountPlusInterestPercentageAndCashBasedAccountingEnabled() { @@ -1799,18 +1619,15 @@ public class ClientLoanIntegrationTest { // Add charges with payment mode regular List charges = new ArrayList<>(); Integer amountPlusInterestPercentageDisbursementCharge = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanDisbursementJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1")); + ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1")); addCharges(charges, amountPlusInterestPercentageDisbursementCharge, "1", null); - Integer amountPlusInterestPercentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, - responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); + Integer amountPlusInterestPercentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper + .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); addCharges(charges, amountPlusInterestPercentageSpecifiedDueDateCharge, "1", "29 September 2011"); Integer amountPlusInterestPercentageInstallmentFee = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanInstallmentJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); + ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); addCharges(charges, amountPlusInterestPercentageInstallmentFee, "1", "29 September 2011"); final Account assetAccount = this.accountHelper.createAssetAccount(); @@ -1818,15 +1635,13 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct(false, CASH_BASED, assetAccount, incomeAccount, expenseAccount, - overpaymentAccount); + final Integer loanProductID = createLoanProduct(false, CASH_BASED, assetAccount, incomeAccount, expenseAccount, overpaymentAccount); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); verifyLoanRepaymentSchedule(loanSchedule); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -1855,12 +1670,10 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan("20 September 2011", loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("126.06"), JournalEntry.TransactionType.DEBIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("126.06"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", assetAccountInitialEntry); this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 September 2011", new JournalEntry(Float.valueOf("126.06"), JournalEntry.TransactionType.CREDIT)); loanCharges.clear(); @@ -1881,9 +1694,8 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 October 2011", new JournalEntry(Float.valueOf("157.57"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("240.00"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(amountPlusInterestPercentageSpecifiedDueDateCharge), "29 October 2011", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(amountPlusInterestPercentageSpecifiedDueDateCharge), "29 October 2011", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); @@ -1916,12 +1728,10 @@ public class ClientLoanIntegrationTest { HashMap thirdInstallment = loanSchedule.get(3); validateNumberForEqual("60.59", String.valueOf(thirdInstallment.get("interestOutstanding"))); - Integer amountPlusInterestPercentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, - responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "29 September 2011", "1")); + Integer amountPlusInterestPercentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "29 September 2011", "1")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(amountPlusInterestPercentagePenaltySpecifiedDueDate, loanCharges, "1", "0.0", "120.0", "0.0"); @@ -1947,9 +1757,8 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 November 2011", new JournalEntry(Float.valueOf("31.51"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("122.38"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "10 January 2012", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "10 January 2012", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap fourthInstallment = loanSchedule.get(4); @@ -1978,8 +1787,8 @@ public class ClientLoanIntegrationTest { } /*** - * Test case for checking AccuralUpfrontAccounting functionality adding charges - * with calculation type flat + * Test case for checking AccuralUpfrontAccounting functionality adding + * charges with calculation type flat */ @Test public void loanWithFlatCahargesAndUpfrontAccrualAccountingEnabled() { @@ -1990,8 +1799,7 @@ public class ClientLoanIntegrationTest { // Add charges with payment mode regular List charges = new ArrayList<>(); - Integer flatDisbursement = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanDisbursementJSON()); + Integer flatDisbursement = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanDisbursementJSON()); addCharges(charges, flatDisbursement, "100", null); Integer flatSpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "100", false)); @@ -2005,15 +1813,14 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct(false, ACCRUAL_UPFRONT, assetAccount, incomeAccount, - expenseAccount, overpaymentAccount); + final Integer loanProductID = createLoanProduct(false, ACCRUAL_UPFRONT, assetAccount, incomeAccount, expenseAccount, + overpaymentAccount); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); verifyLoanRepaymentSchedule(loanSchedule); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -2041,22 +1848,19 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan("20 September 2011", loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("605.94"), JournalEntry.TransactionType.DEBIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("605.94"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("100.00"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("200.00"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", assetAccountInitialEntry); this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 September 2011", new JournalEntry(Float.valueOf("605.94"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("100.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("200.00"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDate), - "29 September 2011", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDate), "29 September 2011", "100")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -2080,17 +1884,15 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3301.49"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3301.49"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDate), - "29 October 2011", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDate), "29 October 2011", "100")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); secondInstallment = loanSchedule.get(2); validateNumberForEqual("150.00", String.valueOf(secondInstallment.get("feeChargesDue"))); LOG.info("----------- Waive installment charge for 2nd installment ---------"); - this.loanTransactionHelper.waiveChargesForLoan(loanID, - (Integer) getloanCharge(flatInstallmentFee, loanCharges).get("id"), + this.loanTransactionHelper.waiveChargesForLoan(loanID, (Integer) getloanCharge(flatInstallmentFee, loanCharges).get("id"), LoanTransactionHelper.getWaiveChargeJSON(String.valueOf(2))); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -2127,9 +1929,8 @@ public class ClientLoanIntegrationTest { Integer flatPenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "100", true)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(flatPenaltySpecifiedDueDate), "29 September 2011", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatPenaltySpecifiedDueDate), "29 September 2011", "100")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(flatPenaltySpecifiedDueDate, loanCharges, "100", "0.00", "100.0", "0.0"); @@ -2149,9 +1950,8 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 November 2011", new JournalEntry(Float.valueOf("3301.49"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3301.49"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(flatPenaltySpecifiedDueDate), "10 January 2012", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatPenaltySpecifiedDueDate), "10 January 2012", "100")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap fourthInstallment = loanSchedule.get(4); @@ -2176,14 +1976,13 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3139.68"), JournalEntry.TransactionType.CREDIT)); this.journalEntryHelper.checkJournalEntryForLiabilityAccount(overpaymentAccount, "20 January 2012", new JournalEntry(Float.valueOf("80.92"), JournalEntry.TransactionType.CREDIT)); - loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, - loanID, "status"); + loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, loanID, "status"); LoanStatusChecker.verifyLoanAccountIsOverPaid(loanStatusHashMap); } /*** - * Test case for checking AccuralUpfrontAccounting functionality adding charges - * with calculation type percentage of amount + * Test case for checking AccuralUpfrontAccounting functionality adding + * charges with calculation type percentage of amount */ @Test public void loanWithCahargesAndUpfrontAccrualAccountingEnabled() { @@ -2198,12 +1997,12 @@ public class ClientLoanIntegrationTest { ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1")); addCharges(charges, percentageDisbursementCharge, "1", null); - Integer percentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); + Integer percentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); addCharges(charges, percentageSpecifiedDueDateCharge, "1", "29 September 2011"); - Integer percentageInstallmentFee = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); + Integer percentageInstallmentFee = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); addCharges(charges, percentageInstallmentFee, "1", "29 September 2011"); final Account assetAccount = this.accountHelper.createAssetAccount(); @@ -2211,15 +2010,14 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct(false, ACCRUAL_UPFRONT, assetAccount, incomeAccount, - expenseAccount, overpaymentAccount); + final Integer loanProductID = createLoanProduct(false, ACCRUAL_UPFRONT, assetAccount, incomeAccount, expenseAccount, + overpaymentAccount); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); verifyLoanRepaymentSchedule(loanSchedule); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -2248,15 +2046,13 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan("20 September 2011", loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("605.94"), JournalEntry.TransactionType.DEBIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("605.94"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("120.00"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("120.00"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("120.00"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", assetAccountInitialEntry); this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 September 2011", new JournalEntry(Float.valueOf("605.94"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("120.00"), JournalEntry.TransactionType.CREDIT), @@ -2278,17 +2074,15 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3300.60"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3300.60"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(percentageSpecifiedDueDateCharge), "29 October 2011", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(percentageSpecifiedDueDateCharge), "29 October 2011", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); secondInstallment = loanSchedule.get(2); validateNumberForEqual("149.70", String.valueOf(secondInstallment.get("feeChargesDue"))); LOG.info("----------- Waive installment charge for 2nd installment ---------"); - this.loanTransactionHelper.waiveChargesForLoan(loanID, - (Integer) getloanCharge(percentageInstallmentFee, loanCharges).get("id"), + this.loanTransactionHelper.waiveChargesForLoan(loanID, (Integer) getloanCharge(percentageInstallmentFee, loanCharges).get("id"), LoanTransactionHelper.getWaiveChargeJSON(String.valueOf(2))); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -2323,11 +2117,10 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForExpenseAccount(expenseAccount, "20 December 2011", new JournalEntry(Float.valueOf("61.79"), JournalEntry.TransactionType.DEBIT)); - Integer percentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(percentagePenaltySpecifiedDueDate), "29 September 2011", "1")); + Integer percentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(percentagePenaltySpecifiedDueDate), "29 September 2011", "1")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(percentagePenaltySpecifiedDueDate, loanCharges, "1", "0.00", "120.0", "0.0"); @@ -2347,9 +2140,8 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 November 2011", new JournalEntry(Float.valueOf("3301.78"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3301.78"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(percentagePenaltySpecifiedDueDate), "10 January 2012", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(percentagePenaltySpecifiedDueDate), "10 January 2012", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap fourthInstallment = loanSchedule.get(4); @@ -2374,14 +2166,13 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3120.58"), JournalEntry.TransactionType.CREDIT)); this.journalEntryHelper.checkJournalEntryForLiabilityAccount(overpaymentAccount, "20 January 2012", new JournalEntry(Float.valueOf("100.00"), JournalEntry.TransactionType.CREDIT)); - loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, - loanID, "status"); + loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, loanID, "status"); LoanStatusChecker.verifyLoanAccountIsOverPaid(loanStatusHashMap); } /*** - * Test case for checking AccuralUpfrontAccounting functionality adding charges - * with calculation type percentage of amount plus interest + * Test case for checking AccuralUpfrontAccounting functionality adding + * charges with calculation type percentage of amount plus interest */ @Test public void loanWithCahargesOfTypeAmountPlusInterestPercentageAndUpfrontAccrualAccountingEnabled() { @@ -2393,17 +2184,14 @@ public class ClientLoanIntegrationTest { // Add charges with payment mode regular List charges = new ArrayList<>(); Integer amountPlusInterestPercentageDisbursementCharge = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanDisbursementJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1")); + ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1")); addCharges(charges, amountPlusInterestPercentageDisbursementCharge, "1", null); - Integer amountPlusInterestPercentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, - responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); + Integer amountPlusInterestPercentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper + .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); Integer amountPlusInterestPercentageInstallmentFee = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanInstallmentJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); + ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); addCharges(charges, amountPlusInterestPercentageInstallmentFee, "1", "29 September 2011"); final Account assetAccount = this.accountHelper.createAssetAccount(); @@ -2411,15 +2199,14 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct(false, ACCRUAL_UPFRONT, assetAccount, incomeAccount, - expenseAccount, overpaymentAccount); + final Integer loanProductID = createLoanProduct(false, ACCRUAL_UPFRONT, assetAccount, incomeAccount, expenseAccount, + overpaymentAccount); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); verifyLoanRepaymentSchedule(loanSchedule); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -2447,22 +2234,19 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan("20 September 2011", loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("605.94"), JournalEntry.TransactionType.DEBIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("605.94"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("126.06"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("126.04"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", assetAccountInitialEntry); this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 September 2011", new JournalEntry(Float.valueOf("605.94"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("126.06"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("126.04"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(amountPlusInterestPercentageSpecifiedDueDateCharge), "29 September 2011", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(amountPlusInterestPercentageSpecifiedDueDateCharge), "29 September 2011", "1")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -2486,9 +2270,8 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3309.06"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3309.06"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(amountPlusInterestPercentageSpecifiedDueDateCharge), "29 October 2011", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(amountPlusInterestPercentageSpecifiedDueDateCharge), "29 October 2011", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); @@ -2531,12 +2314,10 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForExpenseAccount(expenseAccount, "20 December 2011", new JournalEntry(Float.valueOf("61.79"), JournalEntry.TransactionType.DEBIT)); - Integer amountPlusInterestPercentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, - responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "29 September 2011", "1")); + Integer amountPlusInterestPercentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "29 September 2011", "1")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(amountPlusInterestPercentagePenaltySpecifiedDueDate, loanCharges, "1", "0.0", "120.0", "0.0"); @@ -2556,9 +2337,8 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 November 2011", new JournalEntry(Float.valueOf("3303"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3303"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "10 January 2012", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "10 January 2012", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap fourthInstallment = loanSchedule.get(4); @@ -2583,14 +2363,13 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3121.19"), JournalEntry.TransactionType.CREDIT)); this.journalEntryHelper.checkJournalEntryForLiabilityAccount(overpaymentAccount, "20 January 2012", new JournalEntry(Float.valueOf("100.42"), JournalEntry.TransactionType.CREDIT)); - loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, - loanID, "status"); + loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, loanID, "status"); LoanStatusChecker.verifyLoanAccountIsOverPaid(loanStatusHashMap); } /*** - * Test case for checking AccuralPeriodicAccounting functionality adding charges - * with calculation type flat + * Test case for checking AccuralPeriodicAccounting functionality adding + * charges with calculation type flat */ @Test public void loanWithFlatChargesAndPeriodicAccrualAccountingEnabled() throws InterruptedException { @@ -2601,8 +2380,7 @@ public class ClientLoanIntegrationTest { // Add charges with payment mode regular List charges = new ArrayList<>(); - Integer flatDisbursement = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanDisbursementJSON()); + Integer flatDisbursement = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanDisbursementJSON()); addCharges(charges, flatDisbursement, "100", null); Integer flatSpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "100", false)); @@ -2616,15 +2394,14 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct(false, ACCRUAL_PERIODIC, assetAccount, incomeAccount, - expenseAccount, overpaymentAccount); + final Integer loanProductID = createLoanProduct(false, ACCRUAL_PERIODIC, assetAccount, incomeAccount, expenseAccount, + overpaymentAccount); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); verifyLoanRepaymentSchedule(loanSchedule); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -2653,12 +2430,10 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan("20 September 2011", loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("100.00"), JournalEntry.TransactionType.DEBIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("100.00"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", assetAccountInitialEntry); this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 September 2011", new JournalEntry(Float.valueOf("100.00"), JournalEntry.TransactionType.CREDIT)); loanCharges.clear(); @@ -2677,28 +2452,28 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3301.49"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3301.49"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDate), - "29 October 2011", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatSpecifiedDueDate), "29 October 2011", "100")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); secondInstallment = loanSchedule.get(2); validateNumberForEqual("150.00", String.valueOf(secondInstallment.get("feeChargesDue"))); LOG.info("----------- Waive installment charge for 2nd installment ---------"); - this.loanTransactionHelper.waiveChargesForLoan(loanID, - (Integer) getloanCharge(flatInstallmentFee, loanCharges).get("id"), + this.loanTransactionHelper.waiveChargesForLoan(loanID, (Integer) getloanCharge(flatInstallmentFee, loanCharges).get("id"), LoanTransactionHelper.getWaiveChargeJSON(String.valueOf(2))); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(flatInstallmentFee, loanCharges, "50", "100.00", "50.0", "50.0"); /* - * this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, - * "20 September 2011", new JournalEntry(Float.valueOf("50.0"), + * this.journalEntryHelper.checkJournalEntryForAssetAccount( + * assetAccount, "20 September 2011", new + * JournalEntry(Float.valueOf("50.0"), * JournalEntry.TransactionType.CREDIT)); - * this.journalEntryHelper.checkJournalEntryForExpenseAccount (expenseAccount, - * "20 September 2011", new JournalEntry(Float.valueOf("50.0"), + * this.journalEntryHelper.checkJournalEntryForExpenseAccount + * (expenseAccount, "20 September 2011", new + * JournalEntry(Float.valueOf("50.0"), * JournalEntry.TransactionType.DEBIT)); */ final String jobName = "Add Accrual Transactions"; @@ -2735,9 +2510,8 @@ public class ClientLoanIntegrationTest { Integer flatPenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "100", true)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(flatPenaltySpecifiedDueDate), "29 September 2011", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatPenaltySpecifiedDueDate), "29 September 2011", "100")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(flatPenaltySpecifiedDueDate, loanCharges, "100", "0.00", "100.0", "0.0"); @@ -2758,9 +2532,8 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3301.49"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3301.49"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(flatPenaltySpecifiedDueDate), "10 January 2012", "100")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(flatPenaltySpecifiedDueDate), "10 January 2012", "100")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap fourthInstallment = loanSchedule.get(4); @@ -2783,14 +2556,13 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 January 2012", new JournalEntry(Float.valueOf("3139.68"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3139.68"), JournalEntry.TransactionType.CREDIT)); - loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, - loanID, "status"); + loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, loanID, "status"); LoanStatusChecker.verifyLoanAccountIsClosed(loanStatusHashMap); } /** - * Test case for checking AccuralPeriodicAccounting functionality adding charges - * with calculation type percentage of amount + * Test case for checking AccuralPeriodicAccounting functionality adding + * charges with calculation type percentage of amount */ @Test public void loanWithChargesOfTypeAmountPercentageAndPeriodicAccrualAccountingEnabled() throws InterruptedException { @@ -2805,12 +2577,12 @@ public class ClientLoanIntegrationTest { ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1")); addCharges(charges, percentageDisbursementCharge, "1", null); - Integer percentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); + Integer percentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); addCharges(charges, percentageSpecifiedDueDateCharge, "1", "29 September 2011"); - Integer percentageInstallmentFee = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); + Integer percentageInstallmentFee = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", false)); addCharges(charges, percentageInstallmentFee, "1", "29 September 2011"); final Account assetAccount = this.accountHelper.createAssetAccount(); @@ -2818,15 +2590,14 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct(false, ACCRUAL_PERIODIC, assetAccount, incomeAccount, - expenseAccount, overpaymentAccount); + final Integer loanProductID = createLoanProduct(false, ACCRUAL_PERIODIC, assetAccount, incomeAccount, expenseAccount, + overpaymentAccount); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); verifyLoanRepaymentSchedule(loanSchedule); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -2855,12 +2626,10 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan("20 September 2011", loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("120.00"), JournalEntry.TransactionType.DEBIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("120.00"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", assetAccountInitialEntry); this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 September 2011", new JournalEntry(Float.valueOf("120.00"), JournalEntry.TransactionType.CREDIT)); loanCharges.clear(); @@ -2879,28 +2648,28 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3300.60"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3300.60"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(percentageSpecifiedDueDateCharge), "29 October 2011", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(percentageSpecifiedDueDateCharge), "29 October 2011", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); secondInstallment = loanSchedule.get(2); validateNumberForEqual("149.70", String.valueOf(secondInstallment.get("feeChargesDue"))); LOG.info("----------- Waive installment charge for 2nd installment ---------"); - this.loanTransactionHelper.waiveChargesForLoan(loanID, - (Integer) getloanCharge(percentageInstallmentFee, loanCharges).get("id"), + this.loanTransactionHelper.waiveChargesForLoan(loanID, (Integer) getloanCharge(percentageInstallmentFee, loanCharges).get("id"), LoanTransactionHelper.getWaiveChargeJSON(String.valueOf(2))); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(percentageInstallmentFee, loanCharges, "1", "61.19", "29.11", "29.70"); /* - * this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, - * "20 September 2011", new JournalEntry(Float.valueOf("29.7"), + * this.journalEntryHelper.checkJournalEntryForAssetAccount( + * assetAccount, "20 September 2011", new + * JournalEntry(Float.valueOf("29.7"), * JournalEntry.TransactionType.CREDIT)); - * this.journalEntryHelper.checkJournalEntryForExpenseAccount (expenseAccount, - * "20 September 2011", new JournalEntry(Float.valueOf("29.7"), + * this.journalEntryHelper.checkJournalEntryForExpenseAccount + * (expenseAccount, "20 September 2011", new + * JournalEntry(Float.valueOf("29.7"), * JournalEntry.TransactionType.DEBIT)); */ @@ -2936,11 +2705,10 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForExpenseAccount(expenseAccount, "20 December 2011", new JournalEntry(Float.valueOf("61.79"), JournalEntry.TransactionType.DEBIT)); - Integer percentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(percentagePenaltySpecifiedDueDate), "29 September 2011", "1")); + Integer percentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(percentagePenaltySpecifiedDueDate), "29 September 2011", "1")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(percentagePenaltySpecifiedDueDate, loanCharges, "1", "0.00", "120.0", "0.0"); @@ -2961,9 +2729,8 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3301.78"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3301.78"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(percentagePenaltySpecifiedDueDate), "10 January 2012", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper + .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(percentagePenaltySpecifiedDueDate), "10 January 2012", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap fourthInstallment = loanSchedule.get(4); @@ -2986,18 +2753,16 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 January 2012", new JournalEntry(Float.valueOf("3120.58"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3120.58"), JournalEntry.TransactionType.CREDIT)); - loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, - loanID, "status"); + loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, loanID, "status"); LoanStatusChecker.verifyLoanAccountIsClosed(loanStatusHashMap); } /*** - * Test case for checking AccuralPeriodicAccounting functionality adding charges - * with calculation type percentage of amount and interest + * Test case for checking AccuralPeriodicAccounting functionality adding + * charges with calculation type percentage of amount and interest */ @Test - public void loanWithChargesOfTypeAmountPlusInterestPercentageAndPeriodicAccrualAccountingEnabled() - throws InterruptedException { + public void loanWithChargesOfTypeAmountPlusInterestPercentageAndPeriodicAccrualAccountingEnabled() throws InterruptedException { this.journalEntryHelper = new JournalEntryHelper(this.requestSpec, this.responseSpec); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); @@ -3006,18 +2771,15 @@ public class ClientLoanIntegrationTest { // Add charges with payment mode regular List charges = new ArrayList<>(); Integer amountPlusInterestPercentageDisbursementCharge = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanDisbursementJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1")); + ChargesHelper.getLoanDisbursementJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1")); addCharges(charges, amountPlusInterestPercentageDisbursementCharge, "1", null); - Integer amountPlusInterestPercentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, - responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); + Integer amountPlusInterestPercentageSpecifiedDueDateCharge = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper + .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); addCharges(charges, amountPlusInterestPercentageSpecifiedDueDateCharge, "1", "29 September 2011"); Integer amountPlusInterestPercentageInstallmentFee = ChargesHelper.createCharges(requestSpec, responseSpec, - ChargesHelper.getLoanInstallmentJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); + ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT_AND_INTEREST, "1", false)); addCharges(charges, amountPlusInterestPercentageInstallmentFee, "1", "29 September 2011"); final Account assetAccount = this.accountHelper.createAssetAccount(); @@ -3025,15 +2787,14 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct(false, ACCRUAL_PERIODIC, assetAccount, incomeAccount, - expenseAccount, overpaymentAccount); + final Integer loanProductID = createLoanProduct(false, ACCRUAL_PERIODIC, assetAccount, incomeAccount, expenseAccount, + overpaymentAccount); final Integer loanID = applyForLoanApplication(clientID, loanProductID, charges, null, "12,000.00"); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); verifyLoanRepaymentSchedule(loanSchedule); List loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); @@ -3062,12 +2823,10 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan("20 September 2011", loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("126.06"), JournalEntry.TransactionType.DEBIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("126.06"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 September 2011", assetAccountInitialEntry); this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, "20 September 2011", new JournalEntry(Float.valueOf("126.06"), JournalEntry.TransactionType.CREDIT)); loanCharges.clear(); @@ -3086,9 +2845,8 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3309.06"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3309.06"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(amountPlusInterestPercentageSpecifiedDueDateCharge), "29 October 2011", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(amountPlusInterestPercentageSpecifiedDueDateCharge), "29 October 2011", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); @@ -3103,11 +2861,12 @@ public class ClientLoanIntegrationTest { validateCharge(amountPlusInterestPercentageInstallmentFee, loanCharges, "1", "63.02", "31.51", "31.51"); /* - * this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, - * "20 September 2011", new JournalEntry( Float.valueOf("31.51"), - * JournalEntry.TransactionType.CREDIT)); - * this.journalEntryHelper.checkJournalEntryForExpenseAccount (expenseAccount, - * "20 September 2011", new JournalEntry(Float.valueOf("31.51"), + * this.journalEntryHelper.checkJournalEntryForAssetAccount( + * assetAccount, "20 September 2011", new JournalEntry( + * Float.valueOf("31.51"), JournalEntry.TransactionType.CREDIT)); + * this.journalEntryHelper.checkJournalEntryForExpenseAccount + * (expenseAccount, "20 September 2011", new + * JournalEntry(Float.valueOf("31.51"), * JournalEntry.TransactionType.DEBIT)); */ @@ -3143,12 +2902,10 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForExpenseAccount(expenseAccount, "20 December 2011", new JournalEntry(Float.valueOf("61.79"), JournalEntry.TransactionType.DEBIT)); - Integer amountPlusInterestPercentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, - responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON( - ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "29 September 2011", "1")); + Integer amountPlusInterestPercentagePenaltySpecifiedDueDate = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "1", true)); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "29 September 2011", "1")); loanCharges.clear(); loanCharges = this.loanTransactionHelper.getLoanCharges(loanID); validateCharge(amountPlusInterestPercentagePenaltySpecifiedDueDate, loanCharges, "1", "0.0", "120.0", "0.0"); @@ -3169,9 +2926,8 @@ public class ClientLoanIntegrationTest { new JournalEntry(Float.valueOf("3303"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3303"), JournalEntry.TransactionType.CREDIT)); - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "10 January 2012", "1")); + this.loanTransactionHelper.addChargesForLoan(loanID, LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( + String.valueOf(amountPlusInterestPercentagePenaltySpecifiedDueDate), "10 January 2012", "1")); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap fourthInstallment = loanSchedule.get(4); @@ -3194,8 +2950,7 @@ public class ClientLoanIntegrationTest { this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, "20 January 2012", new JournalEntry(Float.valueOf("3121.19"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("3121.19"), JournalEntry.TransactionType.CREDIT)); - loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, - loanID, "status"); + loanStatusHashMap = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, loanID, "status"); LoanStatusChecker.verifyLoanAccountIsClosed(loanStatusHashMap); } @@ -3207,8 +2962,8 @@ public class ClientLoanIntegrationTest { ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer loanProductID = createLoanProduct("100", "0", LoanProductTestBuilder.DEFAULT_STRATEGY); final Integer loanID = applyForLoanApplication(clientID, loanProductID, null); - final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, + loanID); verifyLoanRepaymentScheduleForEqualPrincipal(loanSchedule); } @@ -3221,8 +2976,8 @@ public class ClientLoanIntegrationTest { ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer loanProductID = createLoanProduct("100", "0", LoanProductTestBuilder.DEFAULT_STRATEGY); final Integer loanID = applyForLoanApplication(clientID, loanProductID, "5"); - final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, + loanID); verifyLoanRepaymentScheduleForEqualPrincipalWithGrace(loanSchedule); } @@ -3248,8 +3003,8 @@ public class ClientLoanIntegrationTest { */ final String savingsId = null; final String principal = "12,000.00"; - final Integer loanID = applyForLoanApplicationWithPaymentStrategy(clientID, loanProductID, null, savingsId, - principal, LoanApplicationTestBuilder.RBI_INDIA_STRATEGY); + final Integer loanID = applyForLoanApplicationWithPaymentStrategy(clientID, loanProductID, null, savingsId, principal, + LoanApplicationTestBuilder.RBI_INDIA_STRATEGY); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); @@ -3263,8 +3018,7 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan("20 September 2011", loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap firstInstallment = loanSchedule.get(1); validateNumberForEqual("3200", String.valueOf(firstInstallment.get("totalOutstandingForPeriod"))); @@ -3297,17 +3051,18 @@ public class ClientLoanIntegrationTest { loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); /*** - * Verify 2nd and 3rd repayments after making excess payment for installment no - * 2 + * Verify 2nd and 3rd repayments after making excess payment for + * installment no 2 */ secondInstallment = loanSchedule.get(2); validateNumberForEqual("0.00", String.valueOf(secondInstallment.get("totalOutstandingForPeriod"))); /*** - * According to RBI Excess payment should go to principal portion of next - * installment, but as interest recalculation is not implemented, it wont make - * any difference to schedule even though if we made excess payment, so excess - * payments will behave the same as regular payment with the excess amount + * According to RBI Excess payment should go to principal portion of + * next installment, but as interest recalculation is not implemented, + * it wont make any difference to schedule even though if we made excess + * payment, so excess payments will behave the same as regular payment + * with the excess amount */ thirdInstallment = loanSchedule.get(3); validateNumberForEqual("3200", String.valueOf(thirdInstallment.get("totalOutstandingForPeriod"))); @@ -3317,15 +3072,16 @@ public class ClientLoanIntegrationTest { validateNumberForEqual("100.00", String.valueOf(thirdInstallment.get("interestOutstanding"))); /*** - * Make payment with due amount of 3rd installment on 4th installment date + * Make payment with due amount of 3rd installment on 4th installment + * date */ this.loanTransactionHelper.makeRepayment("20 January 2012", Float.valueOf("3200"), loanID); loanSchedule.clear(); loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); /*** - * Verify overdue interests are deducted first and then remaining amount for - * interest portion of due installment + * Verify overdue interests are deducted first and then remaining amount + * for interest portion of due installment */ thirdInstallment = loanSchedule.get(3); HashMap fourthInstallment = loanSchedule.get(4); @@ -3354,27 +3110,22 @@ public class ClientLoanIntegrationTest { final HashMap repayment = loanSchedule.get(i); final ArrayList dueDateAsArray = (ArrayList) repayment.get("dueDate"); - final LocalDate transactionDate = new LocalDate(dueDateAsArray.get(0), dueDateAsArray.get(1), - dueDateAsArray.get(2)); + final LocalDate transactionDate = new LocalDate(dueDateAsArray.get(0), dueDateAsArray.get(1), dueDateAsArray.get(2)); final Float interestPortion = BigDecimal.valueOf(Double.valueOf(repayment.get("interestDue").toString())) .subtract(BigDecimal.valueOf(Double.valueOf(repayment.get("interestWaived").toString()))) - .subtract(BigDecimal.valueOf(Double.valueOf(repayment.get("interestWrittenOff").toString()))) - .floatValue(); + .subtract(BigDecimal.valueOf(Double.valueOf(repayment.get("interestWrittenOff").toString()))).floatValue(); final Float feePortion = BigDecimal.valueOf(Double.valueOf(repayment.get("feeChargesDue").toString())) .subtract(BigDecimal.valueOf(Double.valueOf(repayment.get("feeChargesWaived").toString()))) - .subtract(BigDecimal.valueOf(Double.valueOf(repayment.get("feeChargesWrittenOff").toString()))) - .floatValue(); + .subtract(BigDecimal.valueOf(Double.valueOf(repayment.get("feeChargesWrittenOff").toString()))).floatValue(); - final Float penaltyPortion = BigDecimal - .valueOf(Double.valueOf(repayment.get("penaltyChargesDue").toString())) + final Float penaltyPortion = BigDecimal.valueOf(Double.valueOf(repayment.get("penaltyChargesDue").toString())) .subtract(BigDecimal.valueOf(Double.valueOf(repayment.get("penaltyChargesWaived").toString()))) - .subtract(BigDecimal.valueOf(Double.valueOf(repayment.get("penaltyChargesWrittenOff").toString()))) - .floatValue(); + .subtract(BigDecimal.valueOf(Double.valueOf(repayment.get("penaltyChargesWrittenOff").toString()))).floatValue(); - this.loanTransactionHelper.checkAccrualTransactionForRepayment(transactionDate, interestPortion, feePortion, - penaltyPortion, loanID); + this.loanTransactionHelper.checkAccrualTransactionForRepayment(transactionDate, interestPortion, feePortion, penaltyPortion, + loanID); } } @@ -3391,21 +3142,20 @@ public class ClientLoanIntegrationTest { final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final Integer loanProductID = createLoanProductWithInterestRecalculation( - LoanProductTestBuilder.DEFAULT_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, + final Integer loanProductID = createLoanProductWithInterestRecalculation(LoanProductTestBuilder.DEFAULT_STRATEGY, + LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, LoanProductTestBuilder.RECALCULATION_STRATEGY_REDUCE_EMI_AMOUN, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, "0", null, LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, null, null); - final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, null, LoanApplicationTestBuilder.DEFAULT_STRATEGY, new ArrayList(0)); + final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, LOAN_DISBURSEMENT_DATE, null, + LoanApplicationTestBuilder.DEFAULT_STRATEGY, new ArrayList(0)); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); addRepaymentValues(expectedvalues, todaysDate, -1, false, "2482.76", "46.15", "0.0", "0.0"); @@ -3500,21 +3250,20 @@ public class ClientLoanIntegrationTest { final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final Integer loanProductID = createLoanProductWithInterestRecalculation( - LoanProductTestBuilder.DEFAULT_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, + final Integer loanProductID = createLoanProductWithInterestRecalculation(LoanProductTestBuilder.DEFAULT_STRATEGY, + LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, LoanProductTestBuilder.RECALCULATION_STRATEGY_REDUCE_EMI_AMOUN, - LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, "0", null, - preCloseInterestStrategy, null, null, null); + LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, "0", null, preCloseInterestStrategy, null, + null, null); - final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, null, LoanApplicationTestBuilder.DEFAULT_STRATEGY, new ArrayList(0)); + final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, LOAN_DISBURSEMENT_DATE, null, + LoanApplicationTestBuilder.DEFAULT_STRATEGY, new ArrayList(0)); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); addRepaymentValues(expectedvalues, todaysDate, -9, true, "2482.76", "46.15", "0.0", "0.0"); @@ -3580,25 +3329,24 @@ public class ClientLoanIntegrationTest { final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final Integer loanProductID = createLoanProductWithInterestRecalculation( - LoanProductTestBuilder.DEFAULT_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, + final Integer loanProductID = createLoanProductWithInterestRecalculation(LoanProductTestBuilder.DEFAULT_STRATEGY, + LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, LoanProductTestBuilder.RECALCULATION_STRATEGY_REDUCE_EMI_AMOUN, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, "0", null, LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, null, null); List charges = new ArrayList<>(); - Integer installmentCharge = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_INTEREST, "10", false)); + Integer installmentCharge = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_INTEREST, "10", false)); addCharges(charges, installmentCharge, "10", null); - final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, null, LoanApplicationTestBuilder.DEFAULT_STRATEGY, charges); + final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, LOAN_DISBURSEMENT_DATE, null, + LoanApplicationTestBuilder.DEFAULT_STRATEGY, charges); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); addRepaymentValues(expectedvalues, todaysDate, -1, false, "2482.76", "46.15", "4.62", "0.0"); @@ -3679,23 +3427,20 @@ public class ClientLoanIntegrationTest { final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer loanProductID = createLoanProductWithInterestRecalculationAndCompoundingDetails( - LoanProductTestBuilder.RBI_INDIA_STRATEGY, - LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_INTEREST, + LoanProductTestBuilder.RBI_INDIA_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_INTEREST, LoanProductTestBuilder.RECALCULATION_STRATEGY_REDUCE_NUMBER_OF_INSTALLMENTS, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_DAILY, "1", LOAN_DISBURSEMENT_DATE, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_WEEKLY, "1", LOAN_DISBURSEMENT_DATE, - LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, null, dayOfWeek, null, - dayOfWeek); + LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, null, dayOfWeek, null, dayOfWeek); - final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, LoanApplicationTestBuilder.RBI_INDIA_STRATEGY, new ArrayList(0)); + final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, LOAN_DISBURSEMENT_DATE, + LoanApplicationTestBuilder.RBI_INDIA_STRATEGY, new ArrayList(0)); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); addRepaymentValues(expectedvalues, todaysDate, -1, false, "2482.76", "46.15", "0.0", "0.0"); @@ -3724,8 +3469,7 @@ public class ClientLoanIntegrationTest { verifyLoanRepaymentSchedule(loanSchedule, expectedvalues); - loanSchedule = this.loanTransactionHelper.getLoanFutureRepaymentSchedule(this.requestSpec, this.responseSpec, - loanID); + loanSchedule = this.loanTransactionHelper.getLoanFutureRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); addRepaymentValues(expectedvalues, todaysDate, 0, false, "4965.3", "92.52", "0.0", "0.0"); @@ -3806,8 +3550,8 @@ public class ClientLoanIntegrationTest { List charges = new ArrayList<>(2); Integer flat = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "100", false)); - Integer principalPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "2", false)); + Integer principalPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "2", false)); addCharges(charges, flat, "100", LOAN_FLAT_CHARGE_DATE); addCharges(charges, principalPercentage, "2", LOAN_INTEREST_CHARGE_DATE); @@ -3815,23 +3559,21 @@ public class ClientLoanIntegrationTest { final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer loanProductID = createLoanProductWithInterestRecalculationAndCompoundingDetails( - LoanProductTestBuilder.DEFAULT_STRATEGY, - LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_INTEREST_AND_FEE, + LoanProductTestBuilder.DEFAULT_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_INTEREST_AND_FEE, LoanProductTestBuilder.RECALCULATION_STRATEGY_RESCHEDULE_NEXT_REPAYMENTS, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_WEEKLY, "1", REST_START_DATE, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_WEEKLY, "1", LOAN_DISBURSEMENT_DATE, - LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, compoundingDayOfMonth, - compoundingDayOfWeek, restDayOfMonth, restDayOfWeek); + LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, compoundingDayOfMonth, compoundingDayOfWeek, + restDayOfMonth, restDayOfWeek); - final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, LOAN_DISBURSEMENT_DATE, LoanApplicationTestBuilder.DEFAULT_STRATEGY, charges); + final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, LOAN_DISBURSEMENT_DATE, + LOAN_DISBURSEMENT_DATE, LoanApplicationTestBuilder.DEFAULT_STRATEGY, charges); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); addRepaymentValues(expectedvalues, todaysDate, -1, false, "2482.76", "46.15", "100.0", "0.0"); @@ -3941,8 +3683,8 @@ public class ClientLoanIntegrationTest { List charges = new ArrayList<>(2); Integer flat = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "100", false)); - Integer principalPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, ChargesHelper - .getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "2", false)); + Integer principalPercentage = ChargesHelper.createCharges(requestSpec, responseSpec, + ChargesHelper.getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_PERCENTAGE_AMOUNT, "2", false)); addCharges(charges, flat, "100", LOAN_FLAT_CHARGE_DATE); addCharges(charges, principalPercentage, "2", LOAN_INTEREST_CHARGE_DATE); @@ -3950,22 +3692,20 @@ public class ClientLoanIntegrationTest { final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer loanProductID = createLoanProductWithInterestRecalculationAndCompoundingDetails( - LoanProductTestBuilder.DEFAULT_STRATEGY, - LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_INTEREST_AND_FEE, + LoanProductTestBuilder.DEFAULT_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_INTEREST_AND_FEE, LoanProductTestBuilder.RECALCULATION_STRATEGY_RESCHEDULE_NEXT_REPAYMENTS, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_WEEKLY, "1", REST_START_DATE, - LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, null, null, - preCloseInterestStrategy, null, null, null, restDateOfMonth, restDateOfWeek); + LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, null, null, preCloseInterestStrategy, null, + null, null, restDateOfMonth, restDateOfWeek); - final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, REST_START_DATE, LoanApplicationTestBuilder.DEFAULT_STRATEGY, charges); + final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, LOAN_DISBURSEMENT_DATE, + REST_START_DATE, LoanApplicationTestBuilder.DEFAULT_STRATEGY, charges); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); addRepaymentValues(expectedvalues, todaysDate, -9, true, "2482.76", "46.15", "100.0", "0.0"); @@ -4042,25 +3782,22 @@ public class ClientLoanIntegrationTest { ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final String recalculationCompoundingFrequencyInterval = null; final String recalculationCompoundingFrequencyDate = null; - final Integer loanProductID = createLoanProductWithInterestRecalculation( - LoanProductTestBuilder.DEFAULT_STRATEGY, + final Integer loanProductID = createLoanProductWithInterestRecalculation(LoanProductTestBuilder.DEFAULT_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_INTEREST_AND_FEE, LoanProductTestBuilder.RECALCULATION_STRATEGY_RESCHEDULE_NEXT_REPAYMENTS, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_DAILY, "1", REST_START_DATE, - LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, - recalculationCompoundingFrequencyInterval, recalculationCompoundingFrequencyDate, - LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, + LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, recalculationCompoundingFrequencyInterval, + recalculationCompoundingFrequencyDate, LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, overdueFeeChargeId.toString(), false, null, null, null, null); - final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, REST_START_DATE, LoanApplicationTestBuilder.DEFAULT_STRATEGY, null); + final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, LOAN_DISBURSEMENT_DATE, + REST_START_DATE, LoanApplicationTestBuilder.DEFAULT_STRATEGY, null); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); addRepaymentValues(expectedvalues, todaysDate, -2, false, "2482.76", "46.15", "0.0", "0.0"); @@ -4149,31 +3886,30 @@ public class ClientLoanIntegrationTest { final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); Calendar todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); - LOG.info("Disbursal Date Calendar {}" , todaysDate.getTime()); + LOG.info("Disbursal Date Calendar {}", todaysDate.getTime()); todaysDate.add(Calendar.DAY_OF_MONTH, -14); final String LOAN_DISBURSEMENT_DATE = dateFormat.format(todaysDate.getTime()); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); Account[] accounts = { assetAccount, incomeAccount, expenseAccount, overpaymentAccount }; - final Integer loanProductID = createLoanProductWithInterestRecalculation( - LoanProductTestBuilder.DEFAULT_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, + final Integer loanProductID = createLoanProductWithInterestRecalculation(LoanProductTestBuilder.DEFAULT_STRATEGY, + LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, LoanProductTestBuilder.RECALCULATION_STRATEGY_REDUCE_EMI_AMOUN, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, "0", null, LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, accounts, null, null); - final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, null, LoanApplicationTestBuilder.DEFAULT_STRATEGY, new ArrayList(0)); + final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, LOAN_DISBURSEMENT_DATE, null, + LoanApplicationTestBuilder.DEFAULT_STRATEGY, new ArrayList(0)); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); - LOG.info("Date during repayment schedule {}" , todaysDate.getTime()); + LOG.info("Date during repayment schedule {}", todaysDate.getTime()); addRepaymentValues(expectedvalues, todaysDate, -1, false, "2482.76", "46.15", "0.0", "0.0"); addRepaymentValues(expectedvalues, todaysDate, 1, false, "2494.22", "34.69", "0.0", "0.0"); addRepaymentValues(expectedvalues, todaysDate, 1, false, "2505.73", "23.18", "0.0", "0.0"); @@ -4199,19 +3935,15 @@ public class ClientLoanIntegrationTest { verifyLoanRepaymentSchedule(loanSchedule, expectedvalues); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(10000.0f, JournalEntry.TransactionType.CREDIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(10000.0f, JournalEntry.TransactionType.CREDIT), new JournalEntry(10000.0f, JournalEntry.TransactionType.DEBIT), }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, LOAN_DISBURSEMENT_DATE, - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, LOAN_DISBURSEMENT_DATE, assetAccountInitialEntry); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); String runOndate = dateFormat.format(todaysDate.getTime()); - LOG.info("runOndate : {}" , runOndate); + LOG.info("runOndate : {}", runOndate); this.periodicAccrualAccountingHelper.runPeriodicAccrualAccounting(runOndate); - this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant().minusDays(7), - 46.15f, 0f, 0f, loanID); - this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant(), 46.15f, 0f, 0f, - loanID); + this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant().minusDays(7), 46.15f, 0f, 0f, loanID); + this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant(), 46.15f, 0f, 0f, loanID); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); todaysDate.add(Calendar.DAY_OF_MONTH, -7); @@ -4229,10 +3961,8 @@ public class ClientLoanIntegrationTest { verifyLoanRepaymentSchedule(loanSchedule, expectedvalues); this.periodicAccrualAccountingHelper.runPeriodicAccrualAccounting(runOndate); - this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant().minusDays(7), - 46.15f, 0f, 0f, loanID); - this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant(), 34.69f, 0f, 0f, - loanID); + this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant().minusDays(7), 46.15f, 0f, 0f, loanID); + this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant(), 34.69f, 0f, 0f, loanID); HashMap prepayDetail = this.loanTransactionHelper.getPrepayAmount(this.requestSpec, this.responseSpec, loanID); String prepayAmount = String.valueOf(prepayDetail.get("amount")); @@ -4242,10 +3972,8 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanAccountIsClosed(loanStatusHashMap); - this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant().minusDays(7), - 46.15f, 0f, 0f, loanID); - this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant(), 34.69f, 0f, 0f, - loanID); + this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant().minusDays(7), 46.15f, 0f, 0f, loanID); + this.loanTransactionHelper.checkAccrualTransactionForRepayment(Utils.getLocalDateOfTenant(), 34.69f, 0f, 0f, loanID); } @@ -4263,25 +3991,21 @@ public class ClientLoanIntegrationTest { final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer loanProductID = createLoanProductWithInterestRecalculationAndCompoundingDetails( - LoanProductTestBuilder.RBI_INDIA_STRATEGY, - LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_INTEREST, + LoanProductTestBuilder.RBI_INDIA_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_INTEREST, LoanProductTestBuilder.RECALCULATION_STRATEGY_RESCHEDULE_NEXT_REPAYMENTS, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_DAILY, "1", LOAN_DISBURSEMENT_DATE, - LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, "1", - LOAN_DISBURSEMENT_DATE, LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, - getDayOfMonth(todaysDate), getDayOfWeek(todaysDate), getDayOfMonth(todaysDate), - getDayOfWeek(todaysDate)); + LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, "1", LOAN_DISBURSEMENT_DATE, + LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, getDayOfMonth(todaysDate), + getDayOfWeek(todaysDate), getDayOfMonth(todaysDate), getDayOfWeek(todaysDate)); - final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, LOAN_DISBURSEMENT_DATE, LoanApplicationTestBuilder.RBI_INDIA_STRATEGY, - new ArrayList(0)); + final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, LOAN_DISBURSEMENT_DATE, + LOAN_DISBURSEMENT_DATE, LoanApplicationTestBuilder.RBI_INDIA_STRATEGY, new ArrayList(0)); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); addRepaymentValues(expectedvalues, todaysDate, -1, false, "2482.76", "46.15", "0.0", "0.0"); @@ -4341,7 +4065,7 @@ public class ClientLoanIntegrationTest { dateFormat.setTimeZone(Utils.getTimeZoneOfTenant()); Calendar todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); - LOG.info("----timeeeeeeeeeeeeee------> {}" , dateFormat.format(todaysDate.getTime())); + LOG.info("----timeeeeeeeeeeeeee------> {}", dateFormat.format(todaysDate.getTime())); todaysDate.add(Calendar.DAY_OF_MONTH, -14); final String LOAN_DISBURSEMENT_DATE = dateFormat.format(todaysDate.getTime()); @@ -4349,26 +4073,22 @@ public class ClientLoanIntegrationTest { ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final String recalculationCompoundingFrequencyInterval = null; final String recalculationCompoundingFrequencyDate = null; - final Integer loanProductID = createLoanProductWithInterestRecalculation( - LoanProductTestBuilder.RBI_INDIA_STRATEGY, + final Integer loanProductID = createLoanProductWithInterestRecalculation(LoanProductTestBuilder.RBI_INDIA_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_INTEREST, LoanProductTestBuilder.RECALCULATION_STRATEGY_RESCHEDULE_NEXT_REPAYMENTS, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_DAILY, "1", LOAN_DISBURSEMENT_DATE, - LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, - recalculationCompoundingFrequencyInterval, recalculationCompoundingFrequencyDate, - LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, null, true, null, null, - getDayOfMonth(todaysDate), getDayOfWeek(todaysDate)); + LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, recalculationCompoundingFrequencyInterval, + recalculationCompoundingFrequencyDate, LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, null, + true, null, null, getDayOfMonth(todaysDate), getDayOfWeek(todaysDate)); - final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, LOAN_DISBURSEMENT_DATE, LoanApplicationTestBuilder.RBI_INDIA_STRATEGY, - new ArrayList(0)); + final Integer loanID = applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, LOAN_DISBURSEMENT_DATE, + LOAN_DISBURSEMENT_DATE, LoanApplicationTestBuilder.RBI_INDIA_STRATEGY, new ArrayList(0)); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); addRepaymentValues(expectedvalues, todaysDate, -1, false, "2482.76", "46.15", "0.0", "0.0"); @@ -4443,22 +4163,20 @@ public class ClientLoanIntegrationTest { final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final Integer loanProductID = createLoanProductWithInterestRecalculation( - LoanProductTestBuilder.DEFAULT_STRATEGY, LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, + final Integer loanProductID = createLoanProductWithInterestRecalculation(LoanProductTestBuilder.DEFAULT_STRATEGY, + LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, LoanProductTestBuilder.RECALCULATION_STRATEGY_REDUCE_EMI_AMOUN, - LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, "0", null, - preCloseStrategy, null, null, null); + LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_SAME_AS_REPAYMENT_PERIOD, "0", null, preCloseStrategy, null, null, + null); final Integer loanID = applyForLoanApplicationForInterestRecalculationWithMoratorium(clientID, loanProductID, - LOAN_DISBURSEMENT_DATE, LoanApplicationTestBuilder.DEFAULT_STRATEGY, new ArrayList(0), "1", - null); + LOAN_DISBURSEMENT_DATE, LoanApplicationTestBuilder.DEFAULT_STRATEGY, new ArrayList(0), "1", null); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); List> expectedvalues = new ArrayList<>(); todaysDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); todaysDate.add(Calendar.DAY_OF_MONTH, -1); @@ -4498,16 +4216,15 @@ public class ClientLoanIntegrationTest { LoanStatusChecker.verifyLoanAccountIsClosed(loanStatusHashMap); } - private void addRepaymentValues(List> expectedvalues, Calendar todaysDate, int addPeriod, - boolean isAddDays, String principalDue, String interestDue, String feeChargesDue, - String penaltyChargesDue) { + private void addRepaymentValues(List> expectedvalues, Calendar todaysDate, int addPeriod, boolean isAddDays, + String principalDue, String interestDue, String feeChargesDue, String penaltyChargesDue) { Map values = new HashMap<>(3); if (isAddDays) { values.put("dueDate", getDateAsArray(todaysDate, addPeriod)); } else { values.put("dueDate", getDateAsArray(todaysDate, addPeriod * 7)); } - LOG.info("Updated date {}" , values.get("dueDate")); + LOG.info("Updated date {}", values.get("dueDate")); values.put("principalDue", principalDue); values.put("interestDue", interestDue); values.put("feeChargesDue", feeChargesDue); @@ -4521,16 +4238,15 @@ public class ClientLoanIntegrationTest { private List getDateAsArray(Calendar todaysDate, int addvalue, int type) { todaysDate.add(type, addvalue); - return new ArrayList<>(Arrays.asList(todaysDate.get(Calendar.YEAR), todaysDate.get(Calendar.MONTH) + 1, - todaysDate.get(Calendar.DAY_OF_MONTH))); + return new ArrayList<>( + Arrays.asList(todaysDate.get(Calendar.YEAR), todaysDate.get(Calendar.MONTH) + 1, todaysDate.get(Calendar.DAY_OF_MONTH))); } private Integer createLoanProductWithInterestRecalculation(final String repaymentStrategy, final String interestRecalculationCompoundingMethod, final String rescheduleStrategyMethod, final String recalculationRestFrequencyType, final String recalculationRestFrequencyInterval, - final String recalculationRestFrequencyDate, final String preCloseInterestCalculationStrategy, - final Account[] accounts, final Integer recalculationRestFrequencyOnDayType, - final Integer recalculationRestFrequencyDayOfWeekType) { + final String recalculationRestFrequencyDate, final String preCloseInterestCalculationStrategy, final Account[] accounts, + final Integer recalculationRestFrequencyOnDayType, final Integer recalculationRestFrequencyDayOfWeekType) { final String recalculationCompoundingFrequencyType = null; final String recalculationCompoundingFrequencyInterval = null; final String recalculationCompoundingFrequencyDate = null; @@ -4538,11 +4254,10 @@ public class ClientLoanIntegrationTest { final Integer recalculationCompoundingFrequencyDayOfWeekType = null; return createLoanProductWithInterestRecalculation(repaymentStrategy, interestRecalculationCompoundingMethod, rescheduleStrategyMethod, recalculationRestFrequencyType, recalculationRestFrequencyInterval, - recalculationRestFrequencyDate, recalculationCompoundingFrequencyType, - recalculationCompoundingFrequencyInterval, recalculationCompoundingFrequencyDate, - preCloseInterestCalculationStrategy, accounts, null, false, recalculationCompoundingFrequencyOnDayType, - recalculationCompoundingFrequencyDayOfWeekType, recalculationRestFrequencyOnDayType, - recalculationRestFrequencyDayOfWeekType); + recalculationRestFrequencyDate, recalculationCompoundingFrequencyType, recalculationCompoundingFrequencyInterval, + recalculationCompoundingFrequencyDate, preCloseInterestCalculationStrategy, accounts, null, false, + recalculationCompoundingFrequencyOnDayType, recalculationCompoundingFrequencyDayOfWeekType, + recalculationRestFrequencyOnDayType, recalculationRestFrequencyDayOfWeekType); } private Integer createLoanProductWithInterestRecalculationAndCompoundingDetails(final String repaymentStrategy, @@ -4551,16 +4266,14 @@ public class ClientLoanIntegrationTest { final String recalculationRestFrequencyDate, final String recalculationCompoundingFrequencyType, final String recalculationCompoundingFrequencyInterval, final String recalculationCompoundingFrequencyDate, final String preCloseInterestCalculationStrategy, final Account[] accounts, - final Integer recalculationCompoundingFrequencyOnDayType, - final Integer recalculationCompoundingFrequencyDayOfWeekType, + final Integer recalculationCompoundingFrequencyOnDayType, final Integer recalculationCompoundingFrequencyDayOfWeekType, final Integer recalculationRestFrequencyOnDayType, final Integer recalculationRestFrequencyDayOfWeekType) { return createLoanProductWithInterestRecalculation(repaymentStrategy, interestRecalculationCompoundingMethod, rescheduleStrategyMethod, recalculationRestFrequencyType, recalculationRestFrequencyInterval, - recalculationRestFrequencyDate, recalculationCompoundingFrequencyType, - recalculationCompoundingFrequencyInterval, recalculationCompoundingFrequencyDate, - preCloseInterestCalculationStrategy, accounts, null, false, recalculationCompoundingFrequencyOnDayType, - recalculationCompoundingFrequencyDayOfWeekType, recalculationRestFrequencyOnDayType, - recalculationRestFrequencyDayOfWeekType); + recalculationRestFrequencyDate, recalculationCompoundingFrequencyType, recalculationCompoundingFrequencyInterval, + recalculationCompoundingFrequencyDate, preCloseInterestCalculationStrategy, accounts, null, false, + recalculationCompoundingFrequencyOnDayType, recalculationCompoundingFrequencyDayOfWeekType, + recalculationRestFrequencyOnDayType, recalculationRestFrequencyDayOfWeekType); } private Integer createLoanProductWithInterestRecalculation(final String repaymentStrategy, @@ -4570,19 +4283,18 @@ public class ClientLoanIntegrationTest { final String recalculationCompoundingFrequencyInterval, final String recalculationCompoundingFrequencyDate, final String preCloseInterestCalculationStrategy, final Account[] accounts, final String chargeId, boolean isArrearsBasedOnOriginalSchedule, final Integer recalculationCompoundingFrequencyOnDayType, - final Integer recalculationCompoundingFrequencyDayOfWeekType, - final Integer recalculationRestFrequencyOnDayType, final Integer recalculationRestFrequencyDayOfWeekType) { + final Integer recalculationCompoundingFrequencyDayOfWeekType, final Integer recalculationRestFrequencyOnDayType, + final Integer recalculationRestFrequencyDayOfWeekType) { LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); - LoanProductTestBuilder builder = new LoanProductTestBuilder().withPrincipal("10000000.00") - .withNumberOfRepayments("24").withRepaymentAfterEvery("1").withRepaymentTypeAsWeek() - .withinterestRatePerPeriod("2").withInterestRateFrequencyTypeAsMonths() - .withRepaymentStrategy(repaymentStrategy).withAmortizationTypeAsEqualPrincipalPayment() - .withInterestCalculationPeriodTypeAsRepaymentPeriod(true).withInterestTypeAsDecliningBalance() + LoanProductTestBuilder builder = new LoanProductTestBuilder().withPrincipal("10000000.00").withNumberOfRepayments("24") + .withRepaymentAfterEvery("1").withRepaymentTypeAsWeek().withinterestRatePerPeriod("2") + .withInterestRateFrequencyTypeAsMonths().withRepaymentStrategy(repaymentStrategy) + .withAmortizationTypeAsEqualPrincipalPayment().withInterestCalculationPeriodTypeAsRepaymentPeriod(true) + .withInterestTypeAsDecliningBalance() .withInterestRecalculationDetails(interestRecalculationCompoundingMethod, rescheduleStrategyMethod, preCloseInterestCalculationStrategy) - .withInterestRecalculationRestFrequencyDetails(recalculationRestFrequencyType, - recalculationRestFrequencyInterval, recalculationRestFrequencyOnDayType, - recalculationRestFrequencyDayOfWeekType) + .withInterestRecalculationRestFrequencyDetails(recalculationRestFrequencyType, recalculationRestFrequencyInterval, + recalculationRestFrequencyOnDayType, recalculationRestFrequencyDayOfWeekType) .withInterestRecalculationCompoundingFrequencyDetails(recalculationCompoundingFrequencyType, recalculationCompoundingFrequencyInterval, recalculationCompoundingFrequencyOnDayType, recalculationCompoundingFrequencyDayOfWeekType); @@ -4600,27 +4312,26 @@ public class ClientLoanIntegrationTest { private Integer applyForLoanApplicationForInterestRecalculation(final Integer clientID, final Integer loanProductID, final String disbursementDate, final String repaymentStrategy, final List charges) { - return applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, disbursementDate, - repaymentStrategy, charges, null, null); + return applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, disbursementDate, repaymentStrategy, charges, null, + null); } - private Integer applyForLoanApplicationForInterestRecalculationWithMoratorium(final Integer clientID, - final Integer loanProductID, final String disbursementDate, final String repaymentStrategy, - final List charges, final String graceOnInterestPayment, final String graceOnPrincipalPayment) { - return applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, disbursementDate, - repaymentStrategy, charges, graceOnInterestPayment, graceOnPrincipalPayment); + private Integer applyForLoanApplicationForInterestRecalculationWithMoratorium(final Integer clientID, final Integer loanProductID, + final String disbursementDate, final String repaymentStrategy, final List charges, final String graceOnInterestPayment, + final String graceOnPrincipalPayment) { + return applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, disbursementDate, repaymentStrategy, charges, + graceOnInterestPayment, graceOnPrincipalPayment); } private Integer applyForLoanApplicationForInterestRecalculation(final Integer clientID, final Integer loanProductID, - final String disbursementDate, final String compoundingStartDate, final String repaymentStrategy, - final List charges) { - return applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, disbursementDate, - repaymentStrategy, charges, null, null); + final String disbursementDate, final String compoundingStartDate, final String repaymentStrategy, final List charges) { + return applyForLoanApplicationForInterestRecalculation(clientID, loanProductID, disbursementDate, repaymentStrategy, charges, null, + null); } private Integer applyForLoanApplicationForInterestRecalculation(final Integer clientID, final Integer loanProductID, - final String disbursementDate, final String repaymentStrategy, final List charges, - final String graceOnInterestPayment, final String graceOnPrincipalPayment) { + final String disbursementDate, final String repaymentStrategy, final List charges, final String graceOnInterestPayment, + final String graceOnPrincipalPayment) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal("10000.00") // @@ -4643,32 +4354,24 @@ public class ClientLoanIntegrationTest { return this.loanTransactionHelper.getLoanId(loanApplicationJSON); } - private void verifyLoanRepaymentSchedule(final ArrayList loanSchedule, - List> expectedvalues) { + private void verifyLoanRepaymentSchedule(final ArrayList loanSchedule, List> expectedvalues) { int index = 1; verifyLoanRepaymentSchedule(loanSchedule, expectedvalues, index); } - private void verifyLoanRepaymentSchedule(final ArrayList loanSchedule, - List> expectedvalues, int index) { - LOG.info( - "--------------------VERIFYING THE PRINCIPAL DUES,INTEREST DUE AND DUE DATE--------------------------"); + private void verifyLoanRepaymentSchedule(final ArrayList loanSchedule, List> expectedvalues, int index) { + LOG.info("--------------------VERIFYING THE PRINCIPAL DUES,INTEREST DUE AND DUE DATE--------------------------"); for (Map values : expectedvalues) { - assertEquals(values.get("dueDate"), loanSchedule.get(index).get("dueDate"), - "Checking for Due Date for installment " + index); - validateNumberForEqualWithMsg("Checking for Principal Due for installment " + index, - String.valueOf(values.get("principalDue")), + assertEquals(values.get("dueDate"), loanSchedule.get(index).get("dueDate"), "Checking for Due Date for installment " + index); + validateNumberForEqualWithMsg("Checking for Principal Due for installment " + index, String.valueOf(values.get("principalDue")), String.valueOf(loanSchedule.get(index).get("principalDue"))); - validateNumberForEqualWithMsg("Checking for Interest Due for installment " + index, - String.valueOf(values.get("interestDue")), + validateNumberForEqualWithMsg("Checking for Interest Due for installment " + index, String.valueOf(values.get("interestDue")), String.valueOf(loanSchedule.get(index).get("interestDue"))); validateNumberForEqualWithMsg("Checking for Fee charge Due for installment " + index, - String.valueOf(values.get("feeChargesDue")), - String.valueOf(loanSchedule.get(index).get("feeChargesDue"))); + String.valueOf(values.get("feeChargesDue")), String.valueOf(loanSchedule.get(index).get("feeChargesDue"))); validateNumberForEqualWithMsg("Checking for Penalty charge Due for installment " + index, - String.valueOf(values.get("penaltyChargesDue")), - String.valueOf(loanSchedule.get(index).get("penaltyChargesDue"))); + String.valueOf(values.get("penaltyChargesDue")), String.valueOf(loanSchedule.get(index).get("penaltyChargesDue"))); index++; } } @@ -4699,8 +4402,8 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct("0", "0", LoanProductTestBuilder.DEFAULT_STRATEGY, CASH_BASED, - assetAccount, incomeAccount, expenseAccount, overpaymentAccount); + final Integer loanProductID = createLoanProduct("0", "0", LoanProductTestBuilder.DEFAULT_STRATEGY, CASH_BASED, assetAccount, + incomeAccount, expenseAccount, overpaymentAccount); Assertions.assertNotNull(loanProductID); /*** @@ -4716,8 +4419,8 @@ public class ClientLoanIntegrationTest { ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "50", false)); addCharges(charges, flatInstallmentFee, "50", null); - final Integer loanID = applyForLoanApplicationWithPaymentStrategyAndPastMonth(clientID, loanProductID, charges, - savingsId, principal, LoanApplicationTestBuilder.DEFAULT_STRATEGY, -4); + final Integer loanID = applyForLoanApplicationWithPaymentStrategyAndPastMonth(clientID, loanProductID, charges, savingsId, + principal, LoanApplicationTestBuilder.DEFAULT_STRATEGY, -4); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); @@ -4731,14 +4434,11 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan(fourMonthsfromNow, loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, fourMonthsfromNow, - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, fourMonthsfromNow, assetAccountInitialEntry); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap firstInstallment = loanSchedule.get(1); validateNumberForEqual("2290", String.valueOf(firstInstallment.get("totalOutstandingForPeriod"))); @@ -4863,8 +4563,8 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct("0", "0", LoanProductTestBuilder.DEFAULT_STRATEGY, - ACCRUAL_UPFRONT, assetAccount, incomeAccount, expenseAccount, overpaymentAccount);// , + final Integer loanProductID = createLoanProduct("0", "0", LoanProductTestBuilder.DEFAULT_STRATEGY, ACCRUAL_UPFRONT, assetAccount, + incomeAccount, expenseAccount, overpaymentAccount);// , // LoanProductTestBuilder.EQUAL_INSTALLMENTS, // LoanProductTestBuilder.FLAT_BALANCE); Assertions.assertNotNull(loanProductID); @@ -4882,8 +4582,8 @@ public class ClientLoanIntegrationTest { ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "50", false)); addCharges(charges, flatInstallmentFee, "50", null); - final Integer loanID = applyForLoanApplicationWithPaymentStrategyAndPastMonth(clientID, loanProductID, charges, - savingsId, principal, LoanApplicationTestBuilder.DEFAULT_STRATEGY, -4); + final Integer loanID = applyForLoanApplicationWithPaymentStrategyAndPastMonth(clientID, loanProductID, charges, savingsId, + principal, LoanApplicationTestBuilder.DEFAULT_STRATEGY, -4); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); @@ -4897,16 +4597,13 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan(fourMonthsfromNow, loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("1440"), JournalEntry.TransactionType.DEBIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("1440"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("300.00"), JournalEntry.TransactionType.DEBIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, fourMonthsfromNow, - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, fourMonthsfromNow, assetAccountInitialEntry); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap firstInstallment = loanSchedule.get(1); validateNumberForEqual("2290", String.valueOf(firstInstallment.get("totalOutstandingForPeriod"))); @@ -5015,20 +4712,17 @@ public class ClientLoanIntegrationTest { final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, - MINIMUM_OPENING_BALANCE); + final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, MINIMUM_OPENING_BALANCE); Assertions.assertNotNull(savingsProductID); - final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, - ACCOUNT_TYPE_INDIVIDUAL); + final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, ACCOUNT_TYPE_INDIVIDUAL); Assertions.assertNotNull(savingsProductID); HashMap modifications = this.savingsAccountHelper.updateSavingsAccount(clientID, savingsProductID, savingsId, ACCOUNT_TYPE_INDIVIDUAL); Assertions.assertTrue(modifications.containsKey("submittedOnDate")); - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, - savingsId); + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsId); SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); @@ -5046,8 +4740,8 @@ public class ClientLoanIntegrationTest { final Account expenseAccount = this.accountHelper.createExpenseAccount(); final Account overpaymentAccount = this.accountHelper.createLiabilityAccount(); - final Integer loanProductID = createLoanProduct("0", "0", LoanProductTestBuilder.DEFAULT_STRATEGY, CASH_BASED, - assetAccount, incomeAccount, expenseAccount, overpaymentAccount); + final Integer loanProductID = createLoanProduct("0", "0", LoanProductTestBuilder.DEFAULT_STRATEGY, CASH_BASED, assetAccount, + incomeAccount, expenseAccount, overpaymentAccount); Assertions.assertNotNull(loanProductID); /*** @@ -5063,8 +4757,8 @@ public class ClientLoanIntegrationTest { ChargesHelper.getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, "50", false)); addCharges(charges, flatInstallmentFee, "50", null); - final Integer loanID = applyForLoanApplicationWithPaymentStrategyAndPastMonth(clientID, loanProductID, charges, - null, principal, LoanApplicationTestBuilder.DEFAULT_STRATEGY, -4); + final Integer loanID = applyForLoanApplicationWithPaymentStrategyAndPastMonth(clientID, loanProductID, charges, null, principal, + LoanApplicationTestBuilder.DEFAULT_STRATEGY, -4); Assertions.assertNotNull(loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); @@ -5078,14 +4772,11 @@ public class ClientLoanIntegrationTest { loanStatusHashMap = this.loanTransactionHelper.disburseLoan(fourMonthsfromNow, loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.CREDIT), new JournalEntry(Float.valueOf("12000.00"), JournalEntry.TransactionType.DEBIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, fourMonthsfromNow, - assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, fourMonthsfromNow, assetAccountInitialEntry); - ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); HashMap firstInstallment = loanSchedule.get(1); validateNumberForEqual("2290", String.valueOf(firstInstallment.get("totalOutstandingForPeriod"))); @@ -5153,8 +4844,8 @@ public class ClientLoanIntegrationTest { final String FROM_LOAN_ACCOUNT_TYPE = "1"; final String TO_SAVINGS_ACCOUNT_TYPE = "2"; - this.accountTransferHelper.refundLoanByTransfer(now, clientID, loanID, clientID, savingsId, - FROM_LOAN_ACCOUNT_TYPE, TO_SAVINGS_ACCOUNT_TYPE, TRANSFER_AMOUNT.toString()); + this.accountTransferHelper.refundLoanByTransfer(now, clientID, loanID, clientID, savingsId, FROM_LOAN_ACCOUNT_TYPE, + TO_SAVINGS_ACCOUNT_TYPE, TRANSFER_AMOUNT.toString()); Float toSavingsBalance = Float.valueOf(MINIMUM_OPENING_BALANCE); @@ -5186,8 +4877,8 @@ public class ClientLoanIntegrationTest { TRANSFER_AMOUNT = 2000f; - this.accountTransferHelper.refundLoanByTransfer(now, clientID, loanID, clientID, savingsId, - FROM_LOAN_ACCOUNT_TYPE, TO_SAVINGS_ACCOUNT_TYPE, TRANSFER_AMOUNT.toString()); + this.accountTransferHelper.refundLoanByTransfer(now, clientID, loanID, clientID, savingsId, FROM_LOAN_ACCOUNT_TYPE, + TO_SAVINGS_ACCOUNT_TYPE, TRANSFER_AMOUNT.toString()); toSavingsSummaryAfter = this.savingsAccountHelper.getSavingsSummary(savingsId); @@ -5214,8 +4905,8 @@ public class ClientLoanIntegrationTest { } - private Integer createSavingsProduct(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String minOpenningBalance) { + private Integer createSavingsProduct(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String minOpenningBalance) { LOG.info("------------------------------CREATING NEW SAVINGS PRODUCT ---------------------------------------"); SavingsProductHelper savingsProductHelper = new SavingsProductHelper(); @@ -5235,38 +4926,33 @@ public class ClientLoanIntegrationTest { public void testLoanProductConfiguration() { final String proposedAmount = "5000"; JsonObject loanProductConfigurationAsTrue = new JsonObject(); - loanProductConfigurationAsTrue = this.createLoanProductConfigurationDetail(loanProductConfigurationAsTrue, - true); + loanProductConfigurationAsTrue = this.createLoanProductConfigurationDetail(loanProductConfigurationAsTrue, true); JsonObject loanProductConfigurationAsFalse = new JsonObject(); - loanProductConfigurationAsFalse = this.createLoanProductConfigurationDetail(loanProductConfigurationAsFalse, - false); + loanProductConfigurationAsFalse = this.createLoanProductConfigurationDetail(loanProductConfigurationAsFalse, false); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2012"); - Integer loanProductID = this.loanTransactionHelper.getLoanProductId(new LoanProductTestBuilder() - .withAmortizationTypeAsEqualInstallments().withRepaymentTypeAsMonth().withRepaymentAfterEvery("1") - .withRepaymentStrategy(LoanProductTestBuilder.DEFAULT_STRATEGY).withInterestTypeAsDecliningBalance() - .withInterestCalculationPeriodTypeAsDays().withInArrearsTolerance("10").withMoratorium("2", "3") - .withLoanProductConfiguration(loanProductConfigurationAsTrue).build(null)); - LOG.info( - "-----------------------LOAN PRODUCT CREATED WITH ATTRIBUTE CONFIGURATION AS TRUE-------------------------- {}" - , loanProductID); + Integer loanProductID = this.loanTransactionHelper + .getLoanProductId(new LoanProductTestBuilder().withAmortizationTypeAsEqualInstallments().withRepaymentTypeAsMonth() + .withRepaymentAfterEvery("1").withRepaymentStrategy(LoanProductTestBuilder.DEFAULT_STRATEGY) + .withInterestTypeAsDecliningBalance().withInterestCalculationPeriodTypeAsDays().withInArrearsTolerance("10") + .withMoratorium("2", "3").withLoanProductConfiguration(loanProductConfigurationAsTrue).build(null)); + LOG.info("-----------------------LOAN PRODUCT CREATED WITH ATTRIBUTE CONFIGURATION AS TRUE-------------------------- {}", + loanProductID); Integer loanID = applyForLoanApplicationWithProductConfigurationAsTrue(clientID, loanProductID, proposedAmount); - LOG.info("------------------------LOAN CREATED WITH ID------------------------------{}" , loanID); + LOG.info("------------------------LOAN CREATED WITH ID------------------------------{}", loanID); - loanProductID = this.loanTransactionHelper.getLoanProductId(new LoanProductTestBuilder() - .withAmortizationTypeAsEqualInstallments().withRepaymentTypeAsMonth().withRepaymentAfterEvery("1") - .withRepaymentStrategy(LoanProductTestBuilder.DEFAULT_STRATEGY).withInterestTypeAsDecliningBalance() - .withInterestCalculationPeriodTypeAsDays().withInArrearsTolerance("10").withMoratorium("2", "3") - .withLoanProductConfiguration(loanProductConfigurationAsFalse).build(null)); - LOG.info("-------------------LOAN PRODUCT CREATED WITH ATTRIBUTE CONFIGURATION AS FALSE---------------------- {}" - , loanProductID); + loanProductID = this.loanTransactionHelper.getLoanProductId(new LoanProductTestBuilder().withAmortizationTypeAsEqualInstallments() + .withRepaymentTypeAsMonth().withRepaymentAfterEvery("1").withRepaymentStrategy(LoanProductTestBuilder.DEFAULT_STRATEGY) + .withInterestTypeAsDecliningBalance().withInterestCalculationPeriodTypeAsDays().withInArrearsTolerance("10") + .withMoratorium("2", "3").withLoanProductConfiguration(loanProductConfigurationAsFalse).build(null)); + LOG.info("-------------------LOAN PRODUCT CREATED WITH ATTRIBUTE CONFIGURATION AS FALSE---------------------- {}", loanProductID); /* * Try to override attribute values in loan account when attribute * configurations are set to false at product level */ loanID = applyForLoanApplicationWithProductConfigurationAsFalse(clientID, loanProductID, proposedAmount); - LOG.info("--------------------------LOAN CREATED WITH ID------------------------- {}" , loanID); + LOG.info("--------------------------LOAN CREATED WITH ID------------------------- {}", loanID); this.validateIfValuesAreNotOverridden(loanID, loanProductID); } @@ -5324,12 +5010,11 @@ public class ClientLoanIntegrationTest { } private void validateIfValuesAreNotOverridden(Integer loanID, Integer loanProductID) { - String loanProductDetails = this.loanTransactionHelper.getLoanProductDetails(this.requestSpec, - this.responseSpec, loanProductID); + String loanProductDetails = this.loanTransactionHelper.getLoanProductDetails(this.requestSpec, this.responseSpec, loanProductID); String loanDetails = this.loanTransactionHelper.getLoanDetails(this.requestSpec, this.responseSpec, loanID); - List comparisonAttributes = Arrays.asList("amortizationType", "interestType", - "transactionProcessingStrategyId", "interestCalculationPeriodType", "repaymentFrequencyType", - "graceOnPrincipalPayment", "graceOnInterestPayment", "inArrearsTolerance", "graceOnArrearsAgeing"); + List comparisonAttributes = Arrays.asList("amortizationType", "interestType", "transactionProcessingStrategyId", + "interestCalculationPeriodType", "repaymentFrequencyType", "graceOnPrincipalPayment", "graceOnInterestPayment", + "inArrearsTolerance", "graceOnArrearsAgeing"); for (String comparisonAttribute : comparisonAttributes) { Object val1 = JsonPath.from(loanProductDetails).get(comparisonAttribute); @@ -5350,8 +5035,8 @@ public class ClientLoanIntegrationTest { return loanProductConfiguration; } - private Integer applyForLoanApplicationWithProductConfigurationAsTrue(final Integer clientID, - final Integer loanProductID, String principal) { + private Integer applyForLoanApplicationWithProductConfigurationAsTrue(final Integer clientID, final Integer loanProductID, + String principal) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal(principal) // @@ -5368,8 +5053,8 @@ public class ClientLoanIntegrationTest { return this.loanTransactionHelper.getLoanId(loanApplicationJSON); } - private Integer applyForLoanApplicationWithProductConfigurationAsFalse(final Integer clientID, - final Integer loanProductID, String principal) { + private Integer applyForLoanApplicationWithProductConfigurationAsFalse(final Integer clientID, final Integer loanProductID, + String principal) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() // diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientSavingsIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientSavingsIntegrationTest.java old mode 100755 new mode 100644 index 1ba3f74fb..8f0aff5bf --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientSavingsIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientSavingsIntegrationTest.java @@ -61,8 +61,9 @@ import org.slf4j.LoggerFactory; /** * Client Savings Integration Test for checking Savings Application. */ -@SuppressWarnings({ "rawtypes"}) +@SuppressWarnings({ "rawtypes" }) public class ClientSavingsIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(ClientSavingsIntegrationTest.class); public static final String DEPOSIT_AMOUNT = "2000"; public static final String WITHDRAW_AMOUNT = "1000"; @@ -203,8 +204,8 @@ public class ClientSavingsIntegrationTest { Calendar todaysDate = Calendar.getInstance(); final String CLOSEDON_DATE = dateFormat.format(todaysDate.getTime()); String withdrawBalance = "false"; - ArrayList savingsAccountErrorData = (ArrayList) validationErrorHelper.closeSavingsAccountAndGetBackRequiredField( - savingsId, withdrawBalance, CommonConstants.RESPONSE_ERROR, CLOSEDON_DATE); + ArrayList savingsAccountErrorData = (ArrayList) validationErrorHelper + .closeSavingsAccountAndGetBackRequiredField(savingsId, withdrawBalance, CommonConstants.RESPONSE_ERROR, CLOSEDON_DATE); assertEquals("validation.msg.savingsaccount.close.results.in.balance.not.zero", savingsAccountErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); @@ -559,8 +560,8 @@ public class ClientSavingsIntegrationTest { ArrayList savingsAccountErrorData = (ArrayList) validationErrorHelper.inactivateCharge(annualSavingsChargeId, savingsId, CommonConstants.RESPONSE_ERROR); - assertEquals("validation.msg.savingsaccountcharge.inactivation.of.charge.not.allowed.when.charge.is.due", savingsAccountErrorData - .get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + assertEquals("validation.msg.savingsaccountcharge.inactivation.of.charge.not.allowed.when.charge.is.due", + savingsAccountErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.DATE_FORMAT, Locale.US); Calendar cal = Calendar.getInstance(); @@ -604,8 +605,8 @@ public class ClientSavingsIntegrationTest { savingsAccountErrorData = (ArrayList) validationErrorHelper.inactivateCharge(monthlySavingsCharge, savingsId, CommonConstants.RESPONSE_ERROR); - assertEquals("validation.msg.savingsaccountcharge.inactivation.of.charge.not.allowed.when.charge.is.due", savingsAccountErrorData - .get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + assertEquals("validation.msg.savingsaccountcharge.inactivation.of.charge.not.allowed.when.charge.is.due", + savingsAccountErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); this.savingsAccountHelper.waiveCharge((Integer) savingsChargeForWaive.get("id"), savingsId); HashMap waiveCharge = this.savingsAccountHelper.getSavingsCharge(savingsId, (Integer) savingsChargeForWaive.get("id")); @@ -630,8 +631,8 @@ public class ClientSavingsIntegrationTest { savingsAccountErrorData = (ArrayList) validationErrorHelper.inactivateCharge(weeklySavingsFeeId, savingsId, CommonConstants.RESPONSE_ERROR); - assertEquals("validation.msg.savingsaccountcharge.inactivation.of.charge.not.allowed.when.charge.is.due", savingsAccountErrorData - .get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + assertEquals("validation.msg.savingsaccountcharge.inactivation.of.charge.not.allowed.when.charge.is.due", + savingsAccountErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); cal = Calendar.getInstance(); dates = (List) savingsChargeForPay.get("dueDate"); @@ -793,8 +794,8 @@ public class ClientSavingsIntegrationTest { todaysDate = Calendar.getInstance(); final String CLOSEDON_DATE = dateFormat.format(todaysDate.getTime()); String withdrawBalance = "false"; - ArrayList savingsAccountErrorData = (ArrayList) validationErrorHelper.closeSavingsAccountAndGetBackRequiredField( - savingsId, withdrawBalance, CommonConstants.RESPONSE_ERROR, CLOSEDON_DATE); + ArrayList savingsAccountErrorData = (ArrayList) validationErrorHelper + .closeSavingsAccountAndGetBackRequiredField(savingsId, withdrawBalance, CommonConstants.RESPONSE_ERROR, CLOSEDON_DATE); assertEquals("validation.msg.savingsaccount.close.results.in.balance.not.zero", savingsAccountErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); } @@ -802,14 +803,12 @@ public class ClientSavingsIntegrationTest { @SuppressWarnings("unchecked") @Test public void testSavingsAccountPostInterestOnLastDayWithOverdraft() { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, - this.responseSpec); + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); /*** * Create a client to apply for savings account (overdraft account). */ - final Integer clientID = ClientHelper.createClient(this.requestSpec, - this.responseSpec); + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); Assertions.assertNotNull(clientID); final String minBalanceForInterestCalculation = null; @@ -821,33 +820,27 @@ public class ClientSavingsIntegrationTest { final String minRequiredBalance = null; final String enforceMinRequiredBalance = "false"; final boolean allowOverdraft = true; - final Integer savingsProductID = createSavingsProduct(this.requestSpec, - this.responseSpec, zeroOpeningBalance, - minBalanceForInterestCalculation, minRequiredBalance, - enforceMinRequiredBalance, allowOverdraft); + final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, zeroOpeningBalance, + minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft); Assertions.assertNotNull(savingsProductID); /*** * Apply for Savings account */ - final Integer savingsId = this.savingsAccountHelper - .applyForSavingsApplication(clientID, savingsProductID, - ACCOUNT_TYPE_INDIVIDUAL); + final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, ACCOUNT_TYPE_INDIVIDUAL); Assertions.assertNotNull(savingsProductID); - HashMap modifications = this.savingsAccountHelper.updateSavingsAccount( - clientID, savingsProductID, savingsId, ACCOUNT_TYPE_INDIVIDUAL); + HashMap modifications = this.savingsAccountHelper.updateSavingsAccount(clientID, savingsProductID, savingsId, + ACCOUNT_TYPE_INDIVIDUAL); Assertions.assertTrue(modifications.containsKey("submittedOnDate")); - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings( - this.requestSpec, this.responseSpec, savingsId); + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsId); SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); /*** * Approve the savings account */ - savingsStatusHashMap = this.savingsAccountHelper - .approveSavings(savingsId); + savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); @@ -862,26 +855,23 @@ public class ClientSavingsIntegrationTest { * @param activationDate * this value is every time first day of previous month */ - savingsStatusHashMap = activateSavingsAccount(savingsId, - ACTIVATION_DATE); + savingsStatusHashMap = activateSavingsAccount(savingsId, ACTIVATION_DATE); SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); /*** * Verify the account summary */ - final HashMap summaryBefore = this.savingsAccountHelper - .getSavingsSummary(savingsId); + final HashMap summaryBefore = this.savingsAccountHelper.getSavingsSummary(savingsId); this.savingsAccountHelper.calculateInterestForSavings(savingsId); - HashMap summary = this.savingsAccountHelper - .getSavingsSummary(savingsId); + HashMap summary = this.savingsAccountHelper.getSavingsSummary(savingsId); assertEquals(summaryBefore, summary); - final Integer lastDayOfMonth = todaysDate - .getActualMaximum(Calendar.DAY_OF_MONTH); + final Integer lastDayOfMonth = todaysDate.getActualMaximum(Calendar.DAY_OF_MONTH); todaysDate.set(Calendar.DAY_OF_MONTH, lastDayOfMonth); final String WITHDRAWAL_DATE = dateFormat.format(todaysDate.getTime()); Float balance = Float.valueOf(zeroOpeningBalance); - //DateFormat transactionDateFormat = new SimpleDateFormat("dd MMMM yyyy",Locale.US); + // DateFormat transactionDateFormat = new SimpleDateFormat("dd MMMM + // yyyy",Locale.US); Calendar transactionDate = Calendar.getInstance(); transactionDate.set(Calendar.DAY_OF_MONTH, 2); String TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); @@ -893,16 +883,12 @@ public class ClientSavingsIntegrationTest { * @param transactionDate * this value is every time last day of previous month */ - Integer depositTransactionId = (Integer) this.savingsAccountHelper - .depositToSavingsAccount(savingsId, DEPOSIT_AMOUNT, - WITHDRAWAL_DATE, CommonConstants.RESPONSE_RESOURCE_ID); - HashMap depositTransaction = this.savingsAccountHelper - .getSavingsTransaction(savingsId, depositTransactionId); + Integer depositTransactionId = (Integer) this.savingsAccountHelper.depositToSavingsAccount(savingsId, DEPOSIT_AMOUNT, + WITHDRAWAL_DATE, CommonConstants.RESPONSE_RESOURCE_ID); + HashMap depositTransaction = this.savingsAccountHelper.getSavingsTransaction(savingsId, depositTransactionId); balance += Float.valueOf(DEPOSIT_AMOUNT); - assertEquals(Float.valueOf(DEPOSIT_AMOUNT), depositTransaction.get("amount"), - "Verifying Deposit Amount"); - assertEquals(balance, depositTransaction.get("runningBalance"), - "Verifying Balance after Deposit"); + assertEquals(Float.valueOf(DEPOSIT_AMOUNT), depositTransaction.get("amount"), "Verifying Deposit Amount"); + assertEquals(balance, depositTransaction.get("runningBalance"), "Verifying Balance after Deposit"); /*** * Calculate expected interest to be posted, interest should be posted @@ -910,18 +896,13 @@ public class ClientSavingsIntegrationTest { * month before this account balance is negative. */ this.savingsAccountHelper.postInterestForSavings(savingsId); - HashMap accountDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + HashMap accountDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountDetails.get("summary"); - Float accountDetailsPostInterestPosted = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + Float accountDetailsPostInterestPosted = Float.valueOf(summary.get("totalInterestPosted").toString()); - Float nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - HashMap interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - Integer daysInYear = Integer.valueOf(interestCalculationDaysInYearType - .get("id").toString()); + Float nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + HashMap interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + Integer daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); double interestRateInFraction = nominalAnnualInterest / 100; double perDay = (double) 1 / daysInYear; double interestPerDay = interestRateInFraction * perDay; @@ -931,29 +912,20 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - DecimalFormat decimalFormat = new DecimalFormat("", - new DecimalFormatSymbols(Locale.US)); + DecimalFormat decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - HashMap accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, TRANSACTION_DATE); + HashMap accountTransactionDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountDetails.get("summary"); - Float accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + Float accountDetailsPostInterest = Float.valueOf(summary.get("totalInterestPosted").toString()); - nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - daysInYear = Integer.valueOf(interestCalculationDaysInYearType - .get("id").toString()); + nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); interestRateInFraction = nominalAnnualInterest / 100; perDay = (double) 1 / daysInYear; interestPerDay = interestRateInFraction * perDay; @@ -963,33 +935,24 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("-----Post Interest As on Successfully Worked----------"); transactionDate.set(Calendar.DAY_OF_MONTH, 3); TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + accountDetailsPostInterest = Float.valueOf(summary.get("totalInterestPosted").toString()); - nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - daysInYear = Integer.valueOf(interestCalculationDaysInYearType - .get("id").toString()); + nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); interestRateInFraction = nominalAnnualInterest / 100; perDay = (double) 1 / daysInYear; interestPerDay = interestRateInFraction * perDay; @@ -999,36 +962,28 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("-----Post Interest As on Successfully Worked-------"); - //DateFormat transactionFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + // DateFormat transactionFormat = new SimpleDateFormat("dd MMMM yyyy", + // Locale.US); Calendar transactionCalendarDateFormat = Calendar.getInstance(); transactionCalendarDateFormat.add(Calendar.DAY_OF_MONTH, 0); transactionDate.set(Calendar.DAY_OF_MONTH, 22); TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); if (Calendar.DAY_OF_MONTH >= 22) { - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + accountDetailsPostInterest = Float.valueOf(summary.get("totalInterestPosted").toString()); - nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get( - "id").toString()); + nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); interestRateInFraction = nominalAnnualInterest / 100; perDay = (double) 1 / daysInYear; interestPerDay = interestRateInFraction * perDay; @@ -1038,40 +993,28 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("-----Post Interest As on Successfully Worked----------"); } - DateFormat lastTransactionDateFormat = new SimpleDateFormat( - "dd MMMM yyyy", Locale.US); + DateFormat lastTransactionDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); Calendar postedLastDate = Calendar.getInstance(); - int numberOfDateOfMonth = postedLastDate - .getActualMaximum(Calendar.DAY_OF_MONTH); - TRANSACTION_DATE = lastTransactionDateFormat.format(transactionDate - .getTime()); + int numberOfDateOfMonth = postedLastDate.getActualMaximum(Calendar.DAY_OF_MONTH); + TRANSACTION_DATE = lastTransactionDateFormat.format(transactionDate.getTime()); if (Calendar.DAY_OF_MONTH == numberOfDateOfMonth) { - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + accountDetailsPostInterest = Float.valueOf(summary.get("totalInterestPosted").toString()); - nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get( - "id").toString()); + nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); interestRateInFraction = nominalAnnualInterest / 100; perDay = (double) 1 / daysInYear; interestPerDay = interestRateInFraction * perDay; @@ -1081,33 +1024,24 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("-----Post Interest As on Successfully Worked----------"); } transactionDate.set(Calendar.DAY_OF_MONTH, 1); TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + accountDetailsPostInterest = Float.valueOf(summary.get("totalInterestPosted").toString()); - nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - daysInYear = Integer.valueOf(interestCalculationDaysInYearType - .get("id").toString()); + nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); interestRateInFraction = nominalAnnualInterest / 100; perDay = (double) 1 / daysInYear; interestPerDay = interestRateInFraction * perDay; @@ -1117,14 +1051,11 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("-----Post Interest As on Successfully Worked----------"); } @@ -1132,14 +1063,12 @@ public class ClientSavingsIntegrationTest { @SuppressWarnings("unchecked") @Test public void testSavingsAccountPostInterestOnLastDayWithdrawalWithOverdraft() { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, - this.responseSpec); + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); /*** * Create a client to apply for savings account (overdraft account). */ - final Integer clientID = ClientHelper.createClient(this.requestSpec, - this.responseSpec); + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); Assertions.assertNotNull(clientID); final String minBalanceForInterestCalculation = null; @@ -1151,33 +1080,27 @@ public class ClientSavingsIntegrationTest { final String minRequiredBalance = null; final String enforceMinRequiredBalance = "false"; final boolean allowOverdraft = true; - final Integer savingsProductID = createSavingsProduct(this.requestSpec, - this.responseSpec, zeroOpeningBalance, - minBalanceForInterestCalculation, minRequiredBalance, - enforceMinRequiredBalance, allowOverdraft); + final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, zeroOpeningBalance, + minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft); Assertions.assertNotNull(savingsProductID); /*** * Apply for Savings account */ - final Integer savingsId = this.savingsAccountHelper - .applyForSavingsApplication(clientID, savingsProductID, - ACCOUNT_TYPE_INDIVIDUAL); + final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, ACCOUNT_TYPE_INDIVIDUAL); Assertions.assertNotNull(savingsProductID); - HashMap modifications = this.savingsAccountHelper.updateSavingsAccount( - clientID, savingsProductID, savingsId, ACCOUNT_TYPE_INDIVIDUAL); + HashMap modifications = this.savingsAccountHelper.updateSavingsAccount(clientID, savingsProductID, savingsId, + ACCOUNT_TYPE_INDIVIDUAL); Assertions.assertTrue(modifications.containsKey("submittedOnDate")); - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings( - this.requestSpec, this.responseSpec, savingsId); + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsId); SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); /*** * Approve the savings account */ - savingsStatusHashMap = this.savingsAccountHelper - .approveSavings(savingsId); + savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); @@ -1192,31 +1115,28 @@ public class ClientSavingsIntegrationTest { * @param activationDate * this value is every time first day of previous month */ - savingsStatusHashMap = activateSavingsAccount(savingsId, - ACTIVATION_DATE); + savingsStatusHashMap = activateSavingsAccount(savingsId, ACTIVATION_DATE); SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); /*** * Verify the account summary */ - final HashMap summaryBefore = this.savingsAccountHelper - .getSavingsSummary(savingsId); + final HashMap summaryBefore = this.savingsAccountHelper.getSavingsSummary(savingsId); this.savingsAccountHelper.calculateInterestForSavings(savingsId); - HashMap summary = this.savingsAccountHelper - .getSavingsSummary(savingsId); + HashMap summary = this.savingsAccountHelper.getSavingsSummary(savingsId); assertEquals(summaryBefore, summary); - final Integer lastDayOfMonth = todaysDate - .getActualMaximum(Calendar.DAY_OF_MONTH); + final Integer lastDayOfMonth = todaysDate.getActualMaximum(Calendar.DAY_OF_MONTH); todaysDate.set(Calendar.DAY_OF_MONTH, lastDayOfMonth); final String WITHDRAWAL_DATE = dateFormat.format(todaysDate.getTime()); Float balance = Float.valueOf(zeroOpeningBalance); - //DateFormat transactionDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + // DateFormat transactionDateFormat = new SimpleDateFormat("dd MMMM + // yyyy", Locale.US); Calendar transactionDate = Calendar.getInstance(); transactionDate.set(Calendar.DAY_OF_MONTH, 2); String TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); - /*** + /*** * Perform withdraw transaction, verify account balance(account balance * will go to negative as no deposits are there prior to this * transaction) @@ -1248,18 +1168,13 @@ public class ClientSavingsIntegrationTest { * month before this account balance is negative. */ this.savingsAccountHelper.postInterestForSavings(savingsId); - HashMap accountDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + HashMap accountDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountDetails.get("summary"); - Float accountDetailsPostInterestPosted = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + Float accountDetailsPostInterestPosted = Float.valueOf(summary.get("totalInterestPosted").toString()); - Float nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - HashMap interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - Integer daysInYear = Integer.valueOf(interestCalculationDaysInYearType - .get("id").toString()); + Float nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + HashMap interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + Integer daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); double interestRateInFraction = nominalAnnualInterest / 100; double perDay = (double) 1 / daysInYear; double interestPerDay = interestRateInFraction * perDay; @@ -1269,29 +1184,20 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - DecimalFormat decimalFormat = new DecimalFormat("", - new DecimalFormatSymbols(Locale.US)); + DecimalFormat decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - HashMap accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, TRANSACTION_DATE); + HashMap accountTransactionDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountDetails.get("summary"); - Float accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + Float accountDetailsPostInterest = Float.valueOf(summary.get("totalInterestPosted").toString()); - nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - daysInYear = Integer.valueOf(interestCalculationDaysInYearType - .get("id").toString()); + nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); interestRateInFraction = nominalAnnualInterest / 100; perDay = (double) 1 / daysInYear; interestPerDay = interestRateInFraction * perDay; @@ -1301,33 +1207,24 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("-----Post Interest As on Successfully Worked----------"); transactionDate.set(Calendar.DAY_OF_MONTH, 3); TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + accountDetailsPostInterest = Float.valueOf(summary.get("totalInterestPosted").toString()); - nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - daysInYear = Integer.valueOf(interestCalculationDaysInYearType - .get("id").toString()); + nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); interestRateInFraction = nominalAnnualInterest / 100; perDay = (double) 1 / daysInYear; interestPerDay = interestRateInFraction * perDay; @@ -1337,36 +1234,28 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("-----Post Interest As on Successfully Worked-------"); - //DateFormat transactionFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + // DateFormat transactionFormat = new SimpleDateFormat("dd MMMM yyyy", + // Locale.US); Calendar transactionCalendarDateFormat = Calendar.getInstance(); transactionCalendarDateFormat.add(Calendar.DAY_OF_MONTH, 0); transactionDate.set(Calendar.DAY_OF_MONTH, 22); TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); if (Calendar.DAY_OF_MONTH >= 22) { - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + accountDetailsPostInterest = Float.valueOf(summary.get("totalInterestPosted").toString()); - nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get( - "id").toString()); + nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); interestRateInFraction = nominalAnnualInterest / 100; perDay = (double) 1 / daysInYear; interestPerDay = interestRateInFraction * perDay; @@ -1376,40 +1265,28 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("-----Post Interest As on Successfully Worked----------"); } - DateFormat lastTransactionDateFormat = new SimpleDateFormat( - "dd MMMM yyyy", Locale.US); + DateFormat lastTransactionDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); Calendar postedLastDate = Calendar.getInstance(); - int numberOfDateOfMonth = postedLastDate - .getActualMaximum(Calendar.DAY_OF_MONTH); - TRANSACTION_DATE = lastTransactionDateFormat.format(transactionDate - .getTime()); + int numberOfDateOfMonth = postedLastDate.getActualMaximum(Calendar.DAY_OF_MONTH); + TRANSACTION_DATE = lastTransactionDateFormat.format(transactionDate.getTime()); if (Calendar.DAY_OF_MONTH == numberOfDateOfMonth) { - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + accountDetailsPostInterest = Float.valueOf(summary.get("totalInterestPosted").toString()); - nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get( - "id").toString()); + nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); interestRateInFraction = nominalAnnualInterest / 100; perDay = (double) 1 / daysInYear; interestPerDay = interestRateInFraction * perDay; @@ -1419,33 +1296,24 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted, accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("-----Post Interest As on Successfully Worked----------"); } transactionDate.set(Calendar.DAY_OF_MONTH, 1); TRANSACTION_DATE = dateFormat.format(transactionDate.getTime()); - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, - TRANSACTION_DATE); - accountTransactionDetails = this.savingsAccountHelper - .getSavingsDetails(savingsId); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, TRANSACTION_DATE); + accountTransactionDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); summary = (HashMap) accountTransactionDetails.get("summary"); - accountDetailsPostInterest = Float.valueOf(summary.get( - "totalInterestPosted").toString()); + accountDetailsPostInterest = Float.valueOf(summary.get("totalInterestPosted").toString()); - nominalAnnualInterest = Float.valueOf(accountDetails.get( - "nominalAnnualInterestRate").toString()); - interestCalculationDaysInYearType = (HashMap) accountDetails - .get("interestCalculationDaysInYearType"); - daysInYear = Integer.valueOf(interestCalculationDaysInYearType - .get("id").toString()); + nominalAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + interestCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + daysInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); interestRateInFraction = nominalAnnualInterest / 100; perDay = (double) 1 / daysInYear; interestPerDay = interestRateInFraction * perDay; @@ -1455,14 +1323,11 @@ public class ClientSavingsIntegrationTest { * Apply rounding on interestPosted, actualInterestPosted and verify * both are same */ - decimalFormat = new DecimalFormat("", new DecimalFormatSymbols( - Locale.US)); + decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - accountDetailsPostInterestPosted = Float.valueOf( - decimalFormat.format(accountDetailsPostInterestPosted)); - assertEquals(interestPosted,accountDetailsPostInterestPosted, - "Verifying interest posted"); + accountDetailsPostInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("-----Post Interest As on Successfully Worked----------"); } @@ -1553,7 +1418,7 @@ public class ClientSavingsIntegrationTest { HashMap withdrawTransaction = this.savingsAccountHelper.getSavingsTransaction(savingsId, withdrawTransactionId); balance -= Float.valueOf(WITHDRAW_AMOUNT); assertEquals(Float.valueOf(WITHDRAW_AMOUNT), withdrawTransaction.get("amount"), "Verifying Withdrawal Amount"); - assertEquals( balance, withdrawTransaction.get("runningBalance"), "Verifying Balance after Withdrawal"); + assertEquals(balance, withdrawTransaction.get("runningBalance"), "Verifying Balance after Withdrawal"); /*** * Perform Deposit transaction on last day of month and verify account @@ -1608,7 +1473,8 @@ public class ClientSavingsIntegrationTest { DecimalFormat decimalFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); - //actualInterestPosted = Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); + // actualInterestPosted = + // Float.valueOf(decimalFormat.format(accountDetailsPostInterestPosted)); assertEquals(interestPosted, accountDetailsPostInterestPosted, "Verifying interest posted"); LOG.info("------Post Interest As On After doing a post interest Successfully worked--------"); @@ -1623,7 +1489,6 @@ public class ClientSavingsIntegrationTest { final String TODYS_POSTING_DATE = dateFormat.format(todysDate.getTime()); String withdrawBalance = "true"; - if (TODYS_POSTING_DATE.equalsIgnoreCase(INTEREST_POSTING_DATE)) { final SavingsAccountHelper validationErrorHelper = new SavingsAccountHelper(this.requestSpec, responseSpec); validationErrorHelper.closeSavingsAccountPostInterestAndGetBackRequiredField(savingsId, withdrawBalance, @@ -1641,8 +1506,10 @@ public class ClientSavingsIntegrationTest { @Test public void testPostInterestAsOnSavingsAccountWithOverdraft() { this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - //final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build(); - //final SavingsAccountHelper validationErrorHelper = new SavingsAccountHelper(this.requestSpec, errorResponse); + // final ResponseSpecification errorResponse = new + // ResponseSpecBuilder().expectStatusCode(400).build(); + // final SavingsAccountHelper validationErrorHelper = new + // SavingsAccountHelper(this.requestSpec, errorResponse); /*** * Create a client to apply for savings account (overdraft account). @@ -1696,9 +1563,9 @@ public class ClientSavingsIntegrationTest { final String POSTED_TRANSACTION_DATE = dateFormat.format(postedDate.getTime()); Calendar postedLastDate = Calendar.getInstance(); - int countOfDate=postedDate.getActualMaximum(Calendar.DAY_OF_MONTH); - LOG.info("count Of Date---> {}",countOfDate); - postedLastDate.set(Calendar.DAY_OF_MONTH,countOfDate); + int countOfDate = postedDate.getActualMaximum(Calendar.DAY_OF_MONTH); + LOG.info("count Of Date---> {}", countOfDate); + postedLastDate.set(Calendar.DAY_OF_MONTH, countOfDate); final String POSTED_LAST_TRANSACTION_DATE = dateFormat.format(postedLastDate.getTime()); /*** @@ -1754,7 +1621,6 @@ public class ClientSavingsIntegrationTest { summary = (HashMap) accountDetails.get("summary"); Float actualInterestPosted = Float.valueOf(summary.get("totalInterestPosted").toString()); - /*** * Calculate expected interest to be posted, interest should be posted * for one day only because deposit transaction happened on last day of @@ -1776,33 +1642,31 @@ public class ClientSavingsIntegrationTest { decimalFormat.applyPattern("#.###"); interestPosted = Float.valueOf(decimalFormat.format(interestPosted)); actualInterestPosted = Float.valueOf(decimalFormat.format(actualInterestPosted)); - assertEquals(interestPosted, actualInterestPosted, "Verifying interest posted"); - LOG.info("------Post Interest As On Successful Worked--------"); + assertEquals(interestPosted, actualInterestPosted, "Verifying interest posted"); + LOG.info("------Post Interest As On Successful Worked--------"); - this.savingsAccountHelper.postInterestAsOnSavings(savingsId, POSTED_LAST_TRANSACTION_DATE); - HashMap accountLastDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); - summary = (HashMap) accountLastDetails.get("summary"); - Float actualLastInterestPosted = Float.valueOf(summary.get("totalInterestPosted").toString()); + this.savingsAccountHelper.postInterestAsOnSavings(savingsId, POSTED_LAST_TRANSACTION_DATE); + HashMap accountLastDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); + summary = (HashMap) accountLastDetails.get("summary"); + Float actualLastInterestPosted = Float.valueOf(summary.get("totalInterestPosted").toString()); - final Float nominalLastAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); - final HashMap interestLastCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); - final Integer daysLastInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); - double interestLastRateInFraction = nominalAnnualInterest / 100; - double perLastDay = (double) 1 / daysInYear; - double interestLastPerDay = interestLastRateInFraction * perLastDay; - Float interestLastPosted = (float) (interestLastPerDay * balance * 1); + final Float nominalLastAnnualInterest = Float.valueOf(accountDetails.get("nominalAnnualInterestRate").toString()); + final HashMap interestLastCalculationDaysInYearType = (HashMap) accountDetails.get("interestCalculationDaysInYearType"); + final Integer daysLastInYear = Integer.valueOf(interestCalculationDaysInYearType.get("id").toString()); + double interestLastRateInFraction = nominalAnnualInterest / 100; + double perLastDay = (double) 1 / daysInYear; + double interestLastPerDay = interestLastRateInFraction * perLastDay; + Float interestLastPosted = (float) (interestLastPerDay * balance * 1); - DecimalFormat decimalLastFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); - decimalLastFormat.applyPattern("#.###"); - interestLastPosted = Float.valueOf(decimalLastFormat.format(interestLastPosted)); - actualInterestPosted = Float.valueOf(decimalFormat.format(actualInterestPosted)); - assertEquals(interestLastPosted, actualInterestPosted, "Verifying interest posted"); - LOG.info("------Post Interest As On Successful Worked--------"); + DecimalFormat decimalLastFormat = new DecimalFormat("", new DecimalFormatSymbols(Locale.US)); + decimalLastFormat.applyPattern("#.###"); + interestLastPosted = Float.valueOf(decimalLastFormat.format(interestLastPosted)); + actualInterestPosted = Float.valueOf(decimalFormat.format(actualInterestPosted)); + assertEquals(interestLastPosted, actualInterestPosted, "Verifying interest posted"); + LOG.info("------Post Interest As On Successful Worked--------"); } - - @Test public void testSavingsAccount_WITH_WITHHOLD_TAX() { this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); @@ -1816,7 +1680,8 @@ public class ClientSavingsIntegrationTest { final String percentage = "10"; final Integer taxGroupId = createTaxGroup(percentage); final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, MINIMUM_OPENING_BALANCE, - minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft, String.valueOf(taxGroupId), false); + minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft, String.valueOf(taxGroupId), + false); Assertions.assertNotNull(savingsProductID); final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, ACCOUNT_TYPE_INDIVIDUAL); @@ -1864,7 +1729,8 @@ public class ClientSavingsIntegrationTest { final String percentage = "10"; final Integer taxGroupId = createTaxGroup(percentage); final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, MINIMUM_OPENING_BALANCE, - minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft, String.valueOf(taxGroupId), false); + minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft, String.valueOf(taxGroupId), + false); Assertions.assertNotNull(savingsProductID); final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, ACCOUNT_TYPE_INDIVIDUAL); @@ -1914,7 +1780,8 @@ public class ClientSavingsIntegrationTest { final String percentage = "10"; final Integer taxGroupId = createTaxGroup(percentage); final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, MINIMUM_OPENING_BALANCE, - minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft, String.valueOf(taxGroupId), true); + minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft, String.valueOf(taxGroupId), + true); Assertions.assertNotNull(savingsProductID); final Integer savingsChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, @@ -1923,8 +1790,9 @@ public class ClientSavingsIntegrationTest { ArrayList savingsList = new ArrayList<>(); - for(int i=0; i< 5; i++){ - final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, ACCOUNT_TYPE_INDIVIDUAL); + for (int i = 0; i < 5; i++) { + final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, + ACCOUNT_TYPE_INDIVIDUAL); Assertions.assertNotNull(savingsProductID); HashMap modifications = this.savingsAccountHelper.updateSavingsAccount(clientID, savingsProductID, savingsId, @@ -1958,7 +1826,7 @@ public class ClientSavingsIntegrationTest { final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd MMMM yyyy"); LocalDate transactionDate = new LocalDate(); - for(int i=0; i< 4; i++){ + for (int i = 0; i < 4; i++) { String TRANSACTION_DATE = formatter.print(transactionDate); Integer depositTransactionId = (Integer) this.savingsAccountHelper.depositToSavingsAccount(savingsList.get(i), DEPOSIT_AMOUNT, TRANSACTION_DATE, CommonConstants.RESPONSE_RESOURCE_ID); @@ -1968,7 +1836,7 @@ public class ClientSavingsIntegrationTest { SchedulerJobHelper jobHelper = new SchedulerJobHelper(this.requestSpec); jobHelper.executeAndAwaitJob("Update Savings Dormant Accounts"); - //VERIFY WITHIN PROVIDED RANGE DOESN'T INACTIVATE + // VERIFY WITHIN PROVIDED RANGE DOESN'T INACTIVATE savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(0)); SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); savingsStatusHashMap = SavingsStatusChecker.getSubStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(0)); @@ -1979,8 +1847,7 @@ public class ClientSavingsIntegrationTest { balance -= chargeAmt; assertEquals(balance, summary.get("accountBalance"), "Verifying account Balance"); - - //VERIFY INACTIVE + // VERIFY INACTIVE savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(1)); SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); savingsStatusHashMap = SavingsStatusChecker.getSubStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(1)); @@ -1999,7 +1866,7 @@ public class ClientSavingsIntegrationTest { savingsStatusHashMap = SavingsStatusChecker.getSubStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(1)); SavingsStatusChecker.verifySavingsSubStatusNone(savingsStatusHashMap); - //VERIFY DORMANT + // VERIFY DORMANT savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(2)); SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); savingsStatusHashMap = SavingsStatusChecker.getSubStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(2)); @@ -2018,7 +1885,7 @@ public class ClientSavingsIntegrationTest { savingsStatusHashMap = SavingsStatusChecker.getSubStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(2)); SavingsStatusChecker.verifySavingsSubStatusNone(savingsStatusHashMap); - //VERIFY ESCHEAT DUE TO OLD TRANSACTION + // VERIFY ESCHEAT DUE TO OLD TRANSACTION savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(3)); SavingsStatusChecker.verifySavingsAccountIsClosed(savingsStatusHashMap); savingsStatusHashMap = SavingsStatusChecker.getSubStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(3)); @@ -2026,7 +1893,7 @@ public class ClientSavingsIntegrationTest { summary = this.savingsAccountHelper.getSavingsSummary(savingsList.get(3)); assertEquals(2900f, summary.get("accountBalance"), "Verifying account Balance"); - //VERIFY ESCHEAT DUE NO TRANSACTION FROM ACTIVATION + // VERIFY ESCHEAT DUE NO TRANSACTION FROM ACTIVATION savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(4)); SavingsStatusChecker.verifySavingsAccountIsClosed(savingsStatusHashMap); savingsStatusHashMap = SavingsStatusChecker.getSubStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(4)); @@ -2034,16 +1901,14 @@ public class ClientSavingsIntegrationTest { summary = this.savingsAccountHelper.getSavingsSummary(savingsList.get(4)); assertEquals(900f, summary.get("accountBalance"), "Verifying account Balance"); - //VERIFY NON ACTIVE ACCOUNTS ARE NOT AFFECTED + // VERIFY NON ACTIVE ACCOUNTS ARE NOT AFFECTED savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(5)); SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); savingsStatusHashMap = SavingsStatusChecker.getSubStatusOfSavings(this.requestSpec, this.responseSpec, savingsList.get(5)); SavingsStatusChecker.verifySavingsSubStatusNone(savingsStatusHashMap); - } - private HashMap activateSavingsAccount(final Integer savingsId, final String activationDate) { final HashMap status = this.savingsAccountHelper.activateSavingsAccount(savingsId, activationDate); return status; @@ -2066,7 +1931,7 @@ public class ClientSavingsIntegrationTest { final String overDraftLimit = "2000.0"; savingsProductHelper = savingsProductHelper.withOverDraft(overDraftLimit); } - if(withDormancy){ + if (withDormancy) { savingsProductHelper = savingsProductHelper.withDormancy(); } @@ -2085,13 +1950,13 @@ public class ClientSavingsIntegrationTest { return SavingsProductHelper.createSavingsProduct(savingsProductJSON, requestSpec, responseSpec); } - private Integer createTaxGroup(final String percentage){ + private Integer createTaxGroup(final String percentage) { final Integer liabilityAccountId = null; - final Integer taxComponentId = TaxComponentHelper.createTaxComponent(this.requestSpec, this.responseSpec, percentage, liabilityAccountId); + final Integer taxComponentId = TaxComponentHelper.createTaxComponent(this.requestSpec, this.responseSpec, percentage, + liabilityAccountId); return TaxGroupHelper.createTaxGroup(this.requestSpec, this.responseSpec, Arrays.asList(taxComponentId)); } - /* * private void verifySavingsInterest(final Object savingsInterest) { * LOG.info( @@ -2218,14 +2083,16 @@ public class ClientSavingsIntegrationTest { } /** - * incorrect savings account balance when charge transaction is - * reversed during an overdraft recalculate Daily Balances + * incorrect savings account balance when charge transaction is reversed + * during an overdraft recalculate Daily Balances */ @Test public void testAccountBalanceAfterTransactionReversal() { this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - //SavingsAccountHelper savingsAccountHelperValidationError = new SavingsAccountHelper(this.requestSpec,new ResponseSpecBuilder().build()); + // SavingsAccountHelper savingsAccountHelperValidationError = new + // SavingsAccountHelper(this.requestSpec,new + // ResponseSpecBuilder().build()); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); Assertions.assertNotNull(clientID); @@ -2239,22 +2106,18 @@ public class ClientSavingsIntegrationTest { minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft); Assertions.assertNotNull(savingsProductID); - final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, ACCOUNT_TYPE_INDIVIDUAL); Assertions.assertNotNull(savingsId); - HashMap savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); - Integer depositTransactionId = (Integer) this.savingsAccountHelper.depositToSavingsAccount(savingsId, "500", SavingsAccountHelper.TRANSACTION_DATE, CommonConstants.RESPONSE_RESOURCE_ID); - String chargeAmount = "300"; String chargeCurrency = "USD"; @@ -2265,14 +2128,13 @@ public class ClientSavingsIntegrationTest { Integer amount = 300; - - final Integer chargeId = this.savingsAccountHelper.addChargesForSavingsWithDueDate(savingsId, savingsChargeId, SavingsAccountHelper.TRANSACTION_DATE, - amount); + final Integer chargeId = this.savingsAccountHelper.addChargesForSavingsWithDueDate(savingsId, savingsChargeId, + SavingsAccountHelper.TRANSACTION_DATE, amount); Assertions.assertNotNull(chargeId); - final Integer payChargeId = this.savingsAccountHelper.payCharge(chargeId, savingsId, chargeAmount, SavingsAccountHelper.TRANSACTION_DATE); - + final Integer payChargeId = this.savingsAccountHelper.payCharge(chargeId, savingsId, chargeAmount, + SavingsAccountHelper.TRANSACTION_DATE); final Integer undoSavingsTransaction = this.savingsAccountHelper.undoSavingsAccountTransaction(savingsId, depositTransactionId); HashMap reversedDepositTransaction = this.savingsAccountHelper.getSavingsTransaction(savingsId, depositTransactionId); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientStatusChecker.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientStatusChecker.java index 1ba5d4fb9..495a268ed 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientStatusChecker.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientStatusChecker.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClientStatusChecker { + private final static Logger LOG = LoggerFactory.getLogger(ClientStatusChecker.class); public static void verifyClientIsActive(final HashMap clientStatusHashMap) { @@ -32,36 +33,31 @@ public class ClientStatusChecker { } public static void verifyClientClosed(final HashMap clientStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING CLIENT IS CLOSED ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING CLIENT IS CLOSED ------------------------------------"); assertEquals(600, (int) clientStatusHashMap.get("id")); LOG.info("Client Status: {} \n", clientStatusHashMap); } public static void verifyClientPending(final HashMap clientStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING CLIENT IS PENDING ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING CLIENT IS PENDING ------------------------------------"); assertEquals(100, (int) clientStatusHashMap.get("id")); LOG.info("Client Status: {} \n", clientStatusHashMap); } public static void verifyClientRejected(final HashMap clientStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING CLIENT IS REJECTED ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING CLIENT IS REJECTED ------------------------------------"); assertEquals(700, (int) clientStatusHashMap.get("id")); LOG.info("Client Status: {} \n", clientStatusHashMap); } public static void verifyClientActiavted(final HashMap clientStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING CLIENT IS ACTIVATED ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING CLIENT IS ACTIVATED ------------------------------------"); assertEquals(300, (int) clientStatusHashMap.get("id")); LOG.info("Client Status: {} \n", clientStatusHashMap); } public static void verifyClientWithdrawn(final HashMap clientStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING CLIENT IS WITHDRAWN ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING CLIENT IS WITHDRAWN ------------------------------------"); assertEquals(800, (int) clientStatusHashMap.get("id")); LOG.info("Client Status: {} \n", clientStatusHashMap); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientUndoRejectAndWithdrawalIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientUndoRejectAndWithdrawalIntegrationTest.java index 1cbcc05ee..cd61a820f 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientUndoRejectAndWithdrawalIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ClientUndoRejectAndWithdrawalIntegrationTest.java @@ -53,8 +53,7 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { public void setup() { Utils.initializeRESTAssured(); this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - this.requestSpec.header("Authorization", - "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); @@ -69,8 +68,7 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { Assertions.assertNotNull(clientId); // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); ClientStatusChecker.verifyClientPending(status); @@ -93,8 +91,7 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { Assertions.assertNotNull(clientId); // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); ClientStatusChecker.verifyClientPending(status); @@ -122,8 +119,7 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { Assertions.assertNotNull(clientId); // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); ClientStatusChecker.verifyClientPending(status); DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); @@ -152,8 +148,7 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { Assertions.assertNotNull(clientId); // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); ClientStatusChecker.verifyClientPending(status); @@ -182,8 +177,7 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { Assertions.assertNotNull(clientId); // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); ClientStatusChecker.verifyClientPending(status); @@ -207,8 +201,7 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { Assertions.assertNotNull(clientId); // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); ClientStatusChecker.verifyClientPending(status); @@ -236,8 +229,7 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { Assertions.assertNotNull(clientId); // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); Calendar todaysDate = Calendar.getInstance(); @@ -265,8 +257,7 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { Assertions.assertNotNull(clientId); // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); ClientStatusChecker.verifyClientPending(status); @@ -297,16 +288,14 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec); Assertions.assertNotNull(clientId); // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); ClientStatusChecker.verifyClientPending(status); status = this.clientHelper.withdrawClient(clientId); ClientStatusChecker.verifyClientWithdrawn(status); status = this.clientHelper.undoWithdrawn(clientId); ClientStatusChecker.verifyClientPending(status); - ArrayList> clientErrorData = validationErrorHelper.activateClient(clientId, - CommonConstants.RESPONSE_ERROR); + ArrayList> clientErrorData = validationErrorHelper.activateClient(clientId, CommonConstants.RESPONSE_ERROR); assertEquals("error.msg.clients.submittedOnDate.after.reopened.date", clientErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); @@ -315,15 +304,15 @@ public class ClientUndoRejectAndWithdrawalIntegrationTest { @Test public void testReopenedDate() { final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build(); - //final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse); + // final ClientHelper validationErrorHelper = new + // ClientHelper(this.requestSpec, errorResponse); // CREATE CLIENT this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec); final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec); Assertions.assertNotNull(clientId); // GET CLIENT STATUS - HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + HashMap status = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); ClientStatusChecker.verifyClientPending(status); status = this.clientHelper.withdrawClient(clientId); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ConcurrencyIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ConcurrencyIntegrationTest.java old mode 100755 new mode 100644 index 3fef8939f..e8a00833f --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ConcurrencyIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ConcurrencyIntegrationTest.java @@ -41,6 +41,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConcurrencyIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(ConcurrencyIntegrationTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -75,7 +76,7 @@ public class ConcurrencyIntegrationTest { date.set(2011, 9, 20); Float repaymentAmount = 100.0f; for (int i = 0; i < 10; i++) { - LOG.info("Starting concurrent transaction number {}" , i); + LOG.info("Starting concurrent transaction number {}", i); date.add(Calendar.DAY_OF_MONTH, 1); repaymentAmount = repaymentAmount + 100; Runnable worker = new LoanRepaymentExecutor(loanTransactionHelper, loanID, repaymentAmount, date); @@ -152,12 +153,13 @@ public class ConcurrencyIntegrationTest { try { this.loanTransactionHelper.makeRepayment(repaymentDate, repaymentAmount, loanId); } catch (Exception e) { - LOG.info("Found an exception {}" , e.getMessage()); - LOG.info("Details of failed concurrent transaction (date, amount, loanId) are {},{},{}" , repaymentDate, repaymentAmount , loanId); + LOG.info("Found an exception {}", e.getMessage()); + LOG.info("Details of failed concurrent transaction (date, amount, loanId) are {},{},{}", repaymentDate, repaymentAmount, + loanId); throw (e); } - LOG.info("Details of passed concurrent transaction, details (date, amount, loanId) are {},{},{}" , repaymentDate - , repaymentAmount , loanId); + LOG.info("Details of passed concurrent transaction, details (date, amount, loanId) are {},{},{}", repaymentDate, + repaymentAmount, loanId); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CurrenciesTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CurrenciesTest.java index dd9936578..583de979f 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CurrenciesTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CurrenciesTest.java @@ -73,7 +73,6 @@ public class CurrenciesTest { currenciestoUpdate.add("USD"); currenciestoUpdate.add("INR"); - ArrayList currenciesOutput = CurrenciesHelper.updateSelectedCurrencies(this.requestSpec, this.responseSpec, currenciestoUpdate); Assertions.assertNotNull(currenciesOutput); @@ -92,4 +91,4 @@ public class CurrenciesTest { Assertions.assertEquals(currenciesBeforeUpdate, currenciesAfterUpdate, "Verifying Do Selected Currencies Match after Updation"); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CurrencyIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CurrencyIntegrationTest.java index 5c5ffefa5..b07c50b57 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CurrencyIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/CurrencyIntegrationTest.java @@ -33,7 +33,6 @@ public class CurrencyIntegrationTest { private RequestSpecification requestSpec; private SavingsAccountHelper savingsAccountHelper; - @BeforeEach public void setup() { Utils.initializeRESTAssured(); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/DisbursalAndRepaymentScheduleTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/DisbursalAndRepaymentScheduleTest.java index ee4667701..a9bac38ee 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/DisbursalAndRepaymentScheduleTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/DisbursalAndRepaymentScheduleTest.java @@ -53,362 +53,352 @@ import org.junit.jupiter.api.Test; @Disabled public class DisbursalAndRepaymentScheduleTest { - private ResponseSpecification responseSpec; - private ResponseSpecification responseSpecForStatusCode403; - private ResponseSpecification generalResponseSpec; - private RequestSpecification requestSpec; - private LoanTransactionHelper loanTransactionHelper; - private LoanRescheduleRequestHelper loanRescheduleRequestHelper; - private Integer loanRescheduleRequestId; - private Integer clientId; - private Integer groupId; - private Integer groupCalendarId; - private Integer loanProductId; - private Integer loanId; - private final String loanPrincipalAmount = "100000.00"; - private final String numberOfRepayments = "12"; - private final String interestRatePerPeriod = "18"; + private ResponseSpecification responseSpec; + private ResponseSpecification responseSpecForStatusCode403; + private ResponseSpecification generalResponseSpec; + private RequestSpecification requestSpec; + private LoanTransactionHelper loanTransactionHelper; + private LoanRescheduleRequestHelper loanRescheduleRequestHelper; + private Integer loanRescheduleRequestId; + private Integer clientId; + private Integer groupId; + private Integer groupCalendarId; + private Integer loanProductId; + private Integer loanId; + private final String loanPrincipalAmount = "100000.00"; + private final String numberOfRepayments = "12"; + private final String interestRatePerPeriod = "18"; - private final SimpleDateFormat dateFormatterStandard = new SimpleDateFormat("dd MMMM yyyy"); + private final SimpleDateFormat dateFormatterStandard = new SimpleDateFormat("dd MMMM yyyy"); - @BeforeEach - public void setup() { - Utils.initializeRESTAssured(); + @BeforeEach + public void setup() { + Utils.initializeRESTAssured(); + } + + @Test + public void testRescheduleJLGLoanSynk() { + // system.out.println("---------------------------------STARTING + // RESCHEDULE JLG + // LOAN TEST ------------------------------------------"); + + Calendar meetingCalendar = Calendar.getInstance(); + meetingCalendar.setFirstDayOfWeek(Calendar.MONDAY); + meetingCalendar.setTime(new java.util.Date()); + + int today = meetingCalendar.get(Calendar.DAY_OF_WEEK); + // making sure that the meeting calendar is set for the coming monday. + if (today >= Calendar.MONDAY) { + meetingCalendar.add(Calendar.DAY_OF_YEAR, +(Calendar.MONDAY - today + 7)); + } else { + meetingCalendar.add(Calendar.DAY_OF_YEAR, +(Calendar.MONDAY - today)); } - @Test - public void testRescheduleJLGLoanSynk() { - // system.out.println("---------------------------------STARTING RESCHEDULE JLG - // LOAN TEST ------------------------------------------"); + Calendar groupMeetingChangeCalendar = (Calendar) meetingCalendar.clone(); - Calendar meetingCalendar = Calendar.getInstance(); - meetingCalendar.setFirstDayOfWeek(Calendar.MONDAY); - meetingCalendar.setTime(new java.util.Date()); + meetingCalendar.add(Calendar.WEEK_OF_YEAR, -3); - int today = meetingCalendar.get(Calendar.DAY_OF_WEEK); - // making sure that the meeting calendar is set for the coming monday. - if (today >= Calendar.MONDAY) { - meetingCalendar.add(Calendar.DAY_OF_YEAR, +(Calendar.MONDAY - today + 7)); - } else { - meetingCalendar.add(Calendar.DAY_OF_YEAR, +(Calendar.MONDAY - today)); - } + final String groupMeetingDate = this.dateFormatterStandard.format(meetingCalendar.getTime()); - Calendar groupMeetingChangeCalendar = (Calendar) meetingCalendar.clone(); + final String disbursalDate = groupMeetingDate; // first meeting date + // after group creation - meetingCalendar.add(Calendar.WEEK_OF_YEAR, -3); + final String rescheduleSubmittedDate = this.dateFormatterStandard.format(new java.util.Date()); - final String groupMeetingDate = this.dateFormatterStandard.format(meetingCalendar.getTime()); + final String loanType = "jlg"; + final String rescheduleInterestRate = "28.0"; + groupMeetingChangeCalendar.add(Calendar.DAY_OF_YEAR, 1); + final String groupMeetingNewStartDate = this.dateFormatterStandard.format(groupMeetingChangeCalendar.getTime()); + // The date + // from + // which we + // start the + // new group + // meeting + // occasion, + // this is a + // tuesday. + groupMeetingChangeCalendar.add(Calendar.WEEK_OF_YEAR, 2); + final String rescheduleDate = this.dateFormatterStandard.format(groupMeetingChangeCalendar.getTime()); - final String disbursalDate = groupMeetingDate; // first meeting date - // after group creation + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.requestSpec.header("Fineract-Platform-TenantId", "default"); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + this.generalResponseSpec = new ResponseSpecBuilder().build(); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - final String rescheduleSubmittedDate = this.dateFormatterStandard.format(new java.util.Date()); + this.loanRescheduleRequestHelper = new LoanRescheduleRequestHelper(this.requestSpec, this.responseSpec); + // system.out.println("---------------------------------CREATING + // ENTITIES AND + // JLG LOAN ------------------------------------------"); + // create all required entities + this.createRequiredEntitiesForJLGLoanSync(groupMeetingDate); - final String loanType = "jlg"; - final String rescheduleInterestRate = "28.0"; - groupMeetingChangeCalendar.add(Calendar.DAY_OF_YEAR, 1); - final String groupMeetingNewStartDate = this.dateFormatterStandard - .format(groupMeetingChangeCalendar.getTime()); - // The date - // from - // which we - // start the - // new group - // meeting - // occasion, - // this is a - // tuesday. - groupMeetingChangeCalendar.add(Calendar.WEEK_OF_YEAR, 2); - final String rescheduleDate = this.dateFormatterStandard.format(groupMeetingChangeCalendar.getTime()); + final String loanApplicationJSON = new LoanApplicationTestBuilder().withPrincipal(loanPrincipalAmount).withLoanTermFrequency("24") + .withLoanTermFrequencyAsWeeks().withNumberOfRepayments("12").withRepaymentEveryAfter("2") + .withRepaymentFrequencyTypeAsMonths().withAmortizationTypeAsEqualInstallments().withInterestCalculationPeriodTypeAsDays() + .withInterestRatePerPeriod(interestRatePerPeriod).withRepaymentFrequencyTypeAsWeeks().withSubmittedOnDate(disbursalDate) + .withExpectedDisbursementDate(disbursalDate).withLoanType(loanType).withSyncDisbursementWithMeetin() + .withCalendarID(this.groupCalendarId.toString()) + .build(this.clientId.toString(), this.groupId.toString(), this.loanProductId.toString(), null); - this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - this.requestSpec.header("Authorization", - "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - this.requestSpec.header("Fineract-Platform-TenantId", "default"); - this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); - this.generalResponseSpec = new ResponseSpecBuilder().build(); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + this.loanId = this.loanTransactionHelper.getLoanId(loanApplicationJSON); - this.loanRescheduleRequestHelper = new LoanRescheduleRequestHelper(this.requestSpec, this.responseSpec); - // system.out.println("---------------------------------CREATING ENTITIES AND - // JLG LOAN ------------------------------------------"); - // create all required entities - this.createRequiredEntitiesForJLGLoanSync(groupMeetingDate); + // Test for loan account is created + Assertions.assertNotNull(this.loanId); + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, this.loanId); - final String loanApplicationJSON = new LoanApplicationTestBuilder().withPrincipal(loanPrincipalAmount) - .withLoanTermFrequency("24").withLoanTermFrequencyAsWeeks().withNumberOfRepayments("12") - .withRepaymentEveryAfter("2").withRepaymentFrequencyTypeAsMonths() - .withAmortizationTypeAsEqualInstallments().withInterestCalculationPeriodTypeAsDays() - .withInterestRatePerPeriod(interestRatePerPeriod).withRepaymentFrequencyTypeAsWeeks() - .withSubmittedOnDate(disbursalDate).withExpectedDisbursementDate(disbursalDate) - .withLoanType(loanType).withSyncDisbursementWithMeetin() - .withCalendarID(this.groupCalendarId.toString()).build(this.clientId.toString(), - this.groupId.toString(), this.loanProductId.toString(), null); + LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - this.loanId = this.loanTransactionHelper.getLoanId(loanApplicationJSON); + // Test for loan account is created, can be approved + this.loanTransactionHelper.approveLoan(disbursalDate, this.loanId); + loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, this.loanId); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - // Test for loan account is created - Assertions.assertNotNull(this.loanId); - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, - this.loanId); + // Test for loan account approved can be disbursed + this.loanTransactionHelper.disburseLoan(disbursalDate, this.loanId); + loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, this.loanId); + LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); + // system.out.println("---------------------------------CHANGING GROUP + // MEETING + // DATE ------------------------------------------"); + CalendarHelper.updateMeetingCalendarForGroup(this.requestSpec, this.responseSpec, this.groupId, this.groupCalendarId.toString(), + groupMeetingNewStartDate, "2", "2", "2"); // New + // meeting + // dates + // will be + // the + // tuesday + // after the + // coming + // monday - // Test for loan account is created, can be approved - this.loanTransactionHelper.approveLoan(disbursalDate, this.loanId); - loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, this.loanId); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + ArrayList loanRepaymnetSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(requestSpec, generalResponseSpec, + this.loanId); - // Test for loan account approved can be disbursed - this.loanTransactionHelper.disburseLoan(disbursalDate, this.loanId); - loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, this.loanId); - LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); + ArrayList dueDateLoanSchedule = (ArrayList) ((HashMap) loanRepaymnetSchedule.get(2)).get("dueDate"); + Calendar dueDateCalendar = Calendar.getInstance(); + dueDateCalendar.setFirstDayOfWeek(Calendar.MONDAY); + dueDateCalendar.set((Integer) dueDateLoanSchedule.get(0), (Integer) dueDateLoanSchedule.get(1) - 1, + (Integer) dueDateLoanSchedule.get(2)); + assertEquals(3, dueDateCalendar.get(Calendar.DAY_OF_WEEK), "AFTER MEETING CHANGE DATE THE NEXT REPAYMENT SHOULD BE ON TUESDAY"); - // system.out.println("---------------------------------CHANGING GROUP MEETING - // DATE ------------------------------------------"); - CalendarHelper.updateMeetingCalendarForGroup(this.requestSpec, this.responseSpec, this.groupId, - this.groupCalendarId.toString(), groupMeetingNewStartDate, "2", "2", "2"); // New - // meeting - // dates - // will be - // the - // tuesday - // after the - // coming - // monday + // system.out.println("---------------------------------CREATING LOAN + // RESCHEDULE + // REQUEST------------------------------------------"); - ArrayList loanRepaymnetSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(requestSpec, - generalResponseSpec, this.loanId); + String requestJSON = new LoanRescheduleRequestTestBuilder().updateGraceOnInterest("2").updateGraceOnPrincipal("2") + .updateNewInterestRate(rescheduleInterestRate).updateRescheduleFromDate(rescheduleDate) + .updateSubmittedOnDate(rescheduleSubmittedDate).build(this.loanId.toString()); - ArrayList dueDateLoanSchedule = (ArrayList) ((HashMap) loanRepaymnetSchedule.get(2)).get("dueDate"); - Calendar dueDateCalendar = Calendar.getInstance(); - dueDateCalendar.setFirstDayOfWeek(Calendar.MONDAY); - dueDateCalendar.set((Integer) dueDateLoanSchedule.get(0), (Integer) dueDateLoanSchedule.get(1) - 1, - (Integer) dueDateLoanSchedule.get(2)); - assertEquals(3, dueDateCalendar.get(Calendar.DAY_OF_WEEK), - "AFTER MEETING CHANGE DATE THE NEXT REPAYMENT SHOULD BE ON TUESDAY"); + this.loanRescheduleRequestId = this.loanRescheduleRequestHelper.createLoanRescheduleRequest(requestJSON); + this.loanRescheduleRequestHelper.verifyCreationOfLoanRescheduleRequest(this.loanRescheduleRequestId); - // system.out.println("---------------------------------CREATING LOAN RESCHEDULE - // REQUEST------------------------------------------"); - - String requestJSON = new LoanRescheduleRequestTestBuilder().updateGraceOnInterest("2") - .updateGraceOnPrincipal("2").updateNewInterestRate(rescheduleInterestRate) - .updateRescheduleFromDate(rescheduleDate).updateSubmittedOnDate(rescheduleSubmittedDate) - .build(this.loanId.toString()); - - this.loanRescheduleRequestId = this.loanRescheduleRequestHelper - .createLoanRescheduleRequest(requestJSON); - this.loanRescheduleRequestHelper.verifyCreationOfLoanRescheduleRequest(this.loanRescheduleRequestId); - - loanRepaymnetSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(requestSpec, - generalResponseSpec, this.loanId); - dueDateLoanSchedule = (ArrayList) ((HashMap) loanRepaymnetSchedule.get(2)).get("dueDate"); - dueDateCalendar.set((Integer) dueDateLoanSchedule.get(0), (Integer) dueDateLoanSchedule.get(1) - 1, - (Integer) dueDateLoanSchedule.get(2)); - assertEquals(3, dueDateCalendar.get(Calendar.DAY_OF_WEEK), + loanRepaymnetSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(requestSpec, generalResponseSpec, this.loanId); + dueDateLoanSchedule = (ArrayList) ((HashMap) loanRepaymnetSchedule.get(2)).get("dueDate"); + dueDateCalendar.set((Integer) dueDateLoanSchedule.get(0), (Integer) dueDateLoanSchedule.get(1) - 1, + (Integer) dueDateLoanSchedule.get(2)); + assertEquals(3, dueDateCalendar.get(Calendar.DAY_OF_WEEK), "AFTER MEETING CHANGE DATE THE NEXT REPAYMENT SHOULD BE ON TUESDAY, EVEN AFTER LOAN RESCHEDULE REQUEST WAS SENT"); - // system.out.println("Successfully created loan reschedule request (ID: " + - // this.loanRescheduleRequestId + ")"); + // system.out.println("Successfully created loan reschedule request (ID: + // " + + // this.loanRescheduleRequestId + ")"); - // system.out.println("-----------------------------APPROVING LOAN RESCHEDULE - // REQUEST--------------------------"); + // system.out.println("-----------------------------APPROVING LOAN + // RESCHEDULE + // REQUEST--------------------------"); - requestJSON = new LoanRescheduleRequestTestBuilder().updateSubmittedOnDate(rescheduleSubmittedDate) - .getApproveLoanRescheduleRequestJSON(); - this.loanRescheduleRequestHelper.approveLoanRescheduleRequest(this.loanRescheduleRequestId, - requestJSON); + requestJSON = new LoanRescheduleRequestTestBuilder().updateSubmittedOnDate(rescheduleSubmittedDate) + .getApproveLoanRescheduleRequestJSON(); + this.loanRescheduleRequestHelper.approveLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON); - final HashMap response = (HashMap) this.loanRescheduleRequestHelper - .getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum"); - assertTrue((Boolean) response.get("approved")); + final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum"); + assertTrue((Boolean) response.get("approved")); - loanRepaymnetSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(requestSpec, - generalResponseSpec, this.loanId); + loanRepaymnetSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(requestSpec, generalResponseSpec, this.loanId); - dueDateLoanSchedule = (ArrayList) ((HashMap) loanRepaymnetSchedule.get(2)).get("dueDate"); - dueDateCalendar.set((Integer) dueDateLoanSchedule.get(0), (Integer) dueDateLoanSchedule.get(1) - 1, - (Integer) dueDateLoanSchedule.get(2)); - assertEquals(3, dueDateCalendar.get(Calendar.DAY_OF_WEEK), - "AFTER MEETING CHANGE DATE THE NEXT REPAYMENT SHOULD BE ON TUESDAY, EVEN AFTER RESCHEDULE"); - // system.out.println("Successfully changed group meeting date (CAELNDAR ID: " + - // this.groupCalendarId - // + ") and rescheduled loan (RESCHEDULE ID: " + this.loanRescheduleRequestId + - // ")"); + dueDateLoanSchedule = (ArrayList) ((HashMap) loanRepaymnetSchedule.get(2)).get("dueDate"); + dueDateCalendar.set((Integer) dueDateLoanSchedule.get(0), (Integer) dueDateLoanSchedule.get(1) - 1, + (Integer) dueDateLoanSchedule.get(2)); + assertEquals(3, dueDateCalendar.get(Calendar.DAY_OF_WEEK), + "AFTER MEETING CHANGE DATE THE NEXT REPAYMENT SHOULD BE ON TUESDAY, EVEN AFTER RESCHEDULE"); + // system.out.println("Successfully changed group meeting date (CAELNDAR + // ID: " + + // this.groupCalendarId + // + ") and rescheduled loan (RESCHEDULE ID: " + + // this.loanRescheduleRequestId + + // ")"); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, - this.responseSpecForStatusCode403); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpecForStatusCode403); + } + + @Test + public void testChangeGroupMeetingMaturedOnDate() { + // system.out + // .println("---------------------------------STARTING GROUP LOAN + // MEETING CHANGE + // DATE EXPECTED MATURED + // CHANGE------------------------------------------"); + + Calendar meetingCalendar = Calendar.getInstance(); + meetingCalendar.setFirstDayOfWeek(Calendar.MONDAY); + meetingCalendar.setTime(new java.util.Date()); + + int today = meetingCalendar.get(Calendar.DAY_OF_WEEK); + // making sure that the meeting calendar is set for the coming monday. + if (today >= Calendar.MONDAY) { + meetingCalendar.add(Calendar.DAY_OF_YEAR, +(Calendar.MONDAY - today + 7)); + } else { + meetingCalendar.add(Calendar.DAY_OF_YEAR, +(Calendar.MONDAY - today)); } - @Test - public void testChangeGroupMeetingMaturedOnDate() { - // system.out - // .println("---------------------------------STARTING GROUP LOAN MEETING CHANGE - // DATE EXPECTED MATURED CHANGE------------------------------------------"); + Calendar groupMeetingChangeCalendar = (Calendar) meetingCalendar.clone(); - Calendar meetingCalendar = Calendar.getInstance(); - meetingCalendar.setFirstDayOfWeek(Calendar.MONDAY); - meetingCalendar.setTime(new java.util.Date()); + meetingCalendar.add(Calendar.WEEK_OF_YEAR, -3); - int today = meetingCalendar.get(Calendar.DAY_OF_WEEK); - // making sure that the meeting calendar is set for the coming monday. - if (today >= Calendar.MONDAY) { - meetingCalendar.add(Calendar.DAY_OF_YEAR, +(Calendar.MONDAY - today + 7)); - } else { - meetingCalendar.add(Calendar.DAY_OF_YEAR, +(Calendar.MONDAY - today)); - } + final String groupMeetingDate = this.dateFormatterStandard.format(meetingCalendar.getTime()); - Calendar groupMeetingChangeCalendar = (Calendar) meetingCalendar.clone(); + final String disbursalDate = groupMeetingDate; // first meeting date + // after group creation - meetingCalendar.add(Calendar.WEEK_OF_YEAR, -3); + final String loanType = "jlg"; + groupMeetingChangeCalendar.add(Calendar.DAY_OF_YEAR, 1); + final String groupMeetingNewStartDate = this.dateFormatterStandard.format(groupMeetingChangeCalendar.getTime()); + // The date + // from + // which we + // start the + // new group + // meeting + // occasion, + // this is a + // tuesday. - final String groupMeetingDate = this.dateFormatterStandard.format(meetingCalendar.getTime()); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.requestSpec.header("Fineract-Platform-TenantId", "default"); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + this.generalResponseSpec = new ResponseSpecBuilder().build(); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - final String disbursalDate = groupMeetingDate; // first meeting date - // after group creation + this.loanRescheduleRequestHelper = new LoanRescheduleRequestHelper(this.requestSpec, this.responseSpec); + // system.out.println("---------------------------------CREATING + // ENTITIES AND + // JLG LOAN ------------------------------------------"); + // create all required entities + this.createRequiredEntitiesForJLGLoanSync(groupMeetingDate); - final String loanType = "jlg"; - groupMeetingChangeCalendar.add(Calendar.DAY_OF_YEAR, 1); - final String groupMeetingNewStartDate = this.dateFormatterStandard - .format(groupMeetingChangeCalendar.getTime()); - // The date - // from - // which we - // start the - // new group - // meeting - // occasion, - // this is a - // tuesday. + final String loanApplicationJSON = new LoanApplicationTestBuilder().withPrincipal(loanPrincipalAmount).withLoanTermFrequency("24") + .withLoanTermFrequencyAsWeeks().withNumberOfRepayments("12").withRepaymentEveryAfter("2") + .withRepaymentFrequencyTypeAsMonths().withAmortizationTypeAsEqualInstallments().withInterestCalculationPeriodTypeAsDays() + .withInterestRatePerPeriod(interestRatePerPeriod).withRepaymentFrequencyTypeAsWeeks().withSubmittedOnDate(disbursalDate) + .withExpectedDisbursementDate(disbursalDate).withLoanType(loanType).withSyncDisbursementWithMeetin() + .withCalendarID(this.groupCalendarId.toString()) + .build(this.clientId.toString(), this.groupId.toString(), this.loanProductId.toString(), null); - this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - this.requestSpec.header("Authorization", - "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - this.requestSpec.header("Fineract-Platform-TenantId", "default"); - this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); - this.generalResponseSpec = new ResponseSpecBuilder().build(); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + this.loanId = this.loanTransactionHelper.getLoanId(loanApplicationJSON); - this.loanRescheduleRequestHelper = new LoanRescheduleRequestHelper(this.requestSpec, this.responseSpec); - // system.out.println("---------------------------------CREATING ENTITIES AND - // JLG LOAN ------------------------------------------"); - // create all required entities - this.createRequiredEntitiesForJLGLoanSync(groupMeetingDate); + // Test for loan account is created + Assertions.assertNotNull(this.loanId); + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, this.loanId); - final String loanApplicationJSON = new LoanApplicationTestBuilder().withPrincipal(loanPrincipalAmount) - .withLoanTermFrequency("24").withLoanTermFrequencyAsWeeks().withNumberOfRepayments("12") - .withRepaymentEveryAfter("2").withRepaymentFrequencyTypeAsMonths() - .withAmortizationTypeAsEqualInstallments().withInterestCalculationPeriodTypeAsDays() - .withInterestRatePerPeriod(interestRatePerPeriod).withRepaymentFrequencyTypeAsWeeks() - .withSubmittedOnDate(disbursalDate).withExpectedDisbursementDate(disbursalDate) - .withLoanType(loanType).withSyncDisbursementWithMeetin() - .withCalendarID(this.groupCalendarId.toString()).build(this.clientId.toString(), - this.groupId.toString(), this.loanProductId.toString(), null); + LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - this.loanId = this.loanTransactionHelper.getLoanId(loanApplicationJSON); + // Test for loan account is created, can be approved + this.loanTransactionHelper.approveLoan(disbursalDate, this.loanId); + loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, this.loanId); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - // Test for loan account is created - Assertions.assertNotNull(this.loanId); - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, - this.loanId); + // Test for loan account approved can be disbursed + this.loanTransactionHelper.disburseLoan(disbursalDate, this.loanId); + loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, this.loanId); + LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); + // system.out.println("---------------------------------CHANGING GROUP + // MEETING + // DATE ------------------------------------------"); + CalendarHelper.updateMeetingCalendarForGroup(this.requestSpec, this.responseSpec, this.groupId, this.groupCalendarId.toString(), + groupMeetingNewStartDate, "2", "2", "2"); // New + // meeting + // dates + // will be + // the + // tuesday + // after the + // coming + // monday - // Test for loan account is created, can be approved - this.loanTransactionHelper.approveLoan(disbursalDate, this.loanId); - loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, this.loanId); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + Calendar expectedMaturityCalendar = Calendar.getInstance(); + expectedMaturityCalendar.setFirstDayOfWeek(Calendar.MONDAY); + ArrayList expectedMaturityDate = ((ArrayList) ((HashMap) this.loanTransactionHelper.getLoanDetail(requestSpec, generalResponseSpec, + this.loanId, "timeline")).get("expectedMaturityDate")); - // Test for loan account approved can be disbursed - this.loanTransactionHelper.disburseLoan(disbursalDate, this.loanId); - loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, this.loanId); - LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); + expectedMaturityCalendar.set((Integer) expectedMaturityDate.get(0), (Integer) expectedMaturityDate.get(1) - 1, + (Integer) expectedMaturityDate.get(2)); - // system.out.println("---------------------------------CHANGING GROUP MEETING - // DATE ------------------------------------------"); - CalendarHelper.updateMeetingCalendarForGroup(this.requestSpec, this.responseSpec, this.groupId, - this.groupCalendarId.toString(), groupMeetingNewStartDate, "2", "2", "2"); // New - // meeting - // dates - // will be - // the - // tuesday - // after the - // coming - // monday + assertEquals(3, expectedMaturityCalendar.get(Calendar.DAY_OF_WEEK), + "AFTER MEETING CHANGE DATE THE EXPECTED MATURITY SHOULD BE ON TUESDAY"); - Calendar expectedMaturityCalendar = Calendar.getInstance(); - expectedMaturityCalendar.setFirstDayOfWeek(Calendar.MONDAY); - ArrayList expectedMaturityDate = ((ArrayList) ((HashMap) this.loanTransactionHelper - .getLoanDetail(requestSpec, generalResponseSpec, this.loanId, "timeline")) - .get("expectedMaturityDate")); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpecForStatusCode403); + } - expectedMaturityCalendar.set((Integer) expectedMaturityDate.get(0), - (Integer) expectedMaturityDate.get(1) - 1, (Integer) expectedMaturityDate.get(2)); + /** + * entities for jlg loan + **/ + private void createRequiredEntitiesForJLGLoanSync(final String groupActivationDate) { + this.createGroupEntityWithCalendar("2", "2", "1", groupActivationDate);// frequency=2:Weekly + // , interval=2: + // Every two weeks , + // repeatsOnDay=1:Monday + // groupActivationDate is decided by the current date + this.createClientEntity(); + this.associateClientToGroup(this.groupId, this.clientId); + this.createLoanProductEntity(); - assertEquals(3, expectedMaturityCalendar.get(Calendar.DAY_OF_WEEK), - "AFTER MEETING CHANGE DATE THE EXPECTED MATURITY SHOULD BE ON TUESDAY"); + } - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, - this.responseSpecForStatusCode403); - } + /* + * Associate client to the group + */ - /** - * entities for jlg loan - **/ - private void createRequiredEntitiesForJLGLoanSync(final String groupActivationDate) { - this.createGroupEntityWithCalendar("2", "2", "1", groupActivationDate);// frequency=2:Weekly - // , interval=2: - // Every two weeks , - // repeatsOnDay=1:Monday - // groupActivationDate is decided by the current date - this.createClientEntity(); - this.associateClientToGroup(this.groupId, this.clientId); - this.createLoanProductEntity(); + private void associateClientToGroup(final Integer groupId, final Integer clientId) { + GroupHelper.associateClient(this.requestSpec, this.responseSpec, groupId.toString(), clientId.toString()); + GroupHelper.verifyGroupMembers(this.requestSpec, this.responseSpec, groupId, clientId); + } - } + private void createGroupEntityWithCalendar(final String frequency, final String interval, final String repeatsOnDay, + final String groupActivationDate) { + this.groupId = GroupHelper.createGroup(this.requestSpec, this.responseSpec, groupActivationDate); + GroupHelper.verifyGroupCreatedOnServer(this.requestSpec, this.responseSpec, this.groupId); - /* - * Associate client to the group - */ + final String startDate = groupActivationDate; - private void associateClientToGroup(final Integer groupId, final Integer clientId) { - GroupHelper.associateClient(this.requestSpec, this.responseSpec, groupId.toString(), - clientId.toString()); - GroupHelper.verifyGroupMembers(this.requestSpec, this.responseSpec, groupId, clientId); - } + this.setGroupCalendarId(CalendarHelper.createMeetingCalendarForGroup(this.requestSpec, this.responseSpec, this.groupId, startDate, + frequency, interval, repeatsOnDay)); + } - private void createGroupEntityWithCalendar(final String frequency, final String interval, - final String repeatsOnDay, final String groupActivationDate) { - this.groupId = GroupHelper.createGroup(this.requestSpec, this.responseSpec, groupActivationDate); - GroupHelper.verifyGroupCreatedOnServer(this.requestSpec, this.responseSpec, this.groupId); + /** + * create a new client + **/ + private void createClientEntity() { + this.clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec); + ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, this.clientId); + } - final String startDate = groupActivationDate; + /** + * create a new loan product + **/ + private void createLoanProductEntity() { + final String loanProductJSON = new LoanProductTestBuilder().withPrincipal(loanPrincipalAmount) + .withNumberOfRepayments(numberOfRepayments).withinterestRatePerPeriod(interestRatePerPeriod) + .withInterestRateFrequencyTypeAsYear().build(null); + this.loanProductId = this.loanTransactionHelper.getLoanProductId(loanProductJSON); + } - this.setGroupCalendarId(CalendarHelper.createMeetingCalendarForGroup(this.requestSpec, - this.responseSpec, this.groupId, startDate, frequency, interval, repeatsOnDay)); - } - - /** - * create a new client - **/ - private void createClientEntity() { - this.clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec); - ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, this.clientId); - } - - /** - * create a new loan product - **/ - private void createLoanProductEntity() { - final String loanProductJSON = new LoanProductTestBuilder().withPrincipal(loanPrincipalAmount) - .withNumberOfRepayments(numberOfRepayments) - .withinterestRatePerPeriod(interestRatePerPeriod).withInterestRateFrequencyTypeAsYear() - .build(null); - this.loanProductId = this.loanTransactionHelper.getLoanProductId(loanProductJSON); - } - - public void setGroupCalendarId(Integer groupCalendarId) { - this.groupCalendarId = groupCalendarId; - } -} \ No newline at end of file + public void setGroupCalendarId(Integer groupCalendarId) { + this.groupCalendarId = groupCalendarId; + } +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ExternalServicesConfigurationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ExternalServicesConfigurationTest.java index 732240023..14c58c505 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ExternalServicesConfigurationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/ExternalServicesConfigurationTest.java @@ -35,6 +35,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "rawtypes", "unchecked", "static-access" }) public class ExternalServicesConfigurationTest { + private final static Logger LOG = LoggerFactory.getLogger(ExternalServicesConfigurationTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -65,11 +66,11 @@ public class ExternalServicesConfigurationTest { String value = null; if (name.equals(configName)) { value = (String) externalServicesConfig.get(configIndex).get("value"); - if(value == null){ + if (value == null) { value = "testnull"; } String newValue = "test"; - LOG.info( "{} : {}",name, value); + LOG.info("{} : {}", name, value); HashMap arrayListValue = this.externalServicesConfigurationHelper.updateValueForExternaServicesConfiguration(requestSpec, responseSpec, "S3", name, newValue); Assertions.assertNotNull(arrayListValue.get("value")); @@ -93,11 +94,11 @@ public class ExternalServicesConfigurationTest { String value = null; if (name.equals(configName)) { value = (String) externalServicesConfig.get(configIndex).get("value"); - if(value == null){ + if (value == null) { value = "testnull"; } String newValue = "test"; - LOG.info("{} : {}",name,value); + LOG.info("{} : {}", name, value); HashMap arrayListValue = this.externalServicesConfigurationHelper.updateValueForExternaServicesConfiguration(requestSpec, responseSpec, "SMTP", name, newValue); Assertions.assertNotNull(arrayListValue.get("value")); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FinancialActivityAccountsTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FinancialActivityAccountsTest.java old mode 100755 new mode 100644 index bd71de52b..453601f80 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FinancialActivityAccountsTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FinancialActivityAccountsTest.java @@ -86,7 +86,8 @@ public class FinancialActivityAccountsTest { * Fetch Created Financial Activity to Account Mapping and validate * created values **/ - assertFinancialActivityAccountCreation(financialActivityAccountId, LIABILITY_TRANSFER_FINANCIAL_ACTIVITY_ID, liabilityTransferAccount); + assertFinancialActivityAccountCreation(financialActivityAccountId, LIABILITY_TRANSFER_FINANCIAL_ACTIVITY_ID, + liabilityTransferAccount); /** * Update Existing Financial Activity to Account Mapping and assert @@ -129,8 +130,8 @@ public class FinancialActivityAccountsTest { invalidFinancialActivityAccountError.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); /** Should be able to delete a Financial Activity to Account Mapping **/ - Integer deletedFinancialActivityAccountId = financialActivityAccountHelper.deleteFinancialActivityAccount( - financialActivityAccountId, responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); + Integer deletedFinancialActivityAccountId = financialActivityAccountHelper + .deleteFinancialActivityAccount(financialActivityAccountId, responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); Assertions.assertNotNull(deletedFinancialActivityAccountId); Assertions.assertEquals(financialActivityAccountId, deletedFinancialActivityAccountId); @@ -138,7 +139,8 @@ public class FinancialActivityAccountsTest { financialActivityAccountHelper.getFinancialActivityAccount(deletedFinancialActivityAccountId, responseSpecForResourceNotFoundError); } - private void assertFinancialActivityAccountCreation(Integer financialActivityAccountId, Integer financialActivityId, Account glAccount) { + private void assertFinancialActivityAccountCreation(Integer financialActivityAccountId, Integer financialActivityId, + Account glAccount) { HashMap mappingDetails = financialActivityAccountHelper.getFinancialActivityAccount(financialActivityAccountId, responseSpec); Assertions.assertEquals(financialActivityId, ((HashMap) mappingDetails.get("financialActivityData")).get("id")); Assertions.assertEquals(glAccount.getAccountID(), ((HashMap) mappingDetails.get("glAccountData")).get("id")); @@ -152,8 +154,8 @@ public class FinancialActivityAccountsTest { List financialActivities = this.financialActivityAccountHelper.getAllFinancialActivityAccounts(this.responseSpec); for (HashMap financialActivity : financialActivities) { Integer financialActivityAccountId = (Integer) financialActivity.get("id"); - Integer deletedFinancialActivityAccountId = this.financialActivityAccountHelper.deleteFinancialActivityAccount( - financialActivityAccountId, this.responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); + Integer deletedFinancialActivityAccountId = this.financialActivityAccountHelper + .deleteFinancialActivityAccount(financialActivityAccountId, this.responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); Assertions.assertNotNull(deletedFinancialActivityAccountId); Assertions.assertEquals(financialActivityAccountId, deletedFinancialActivityAccountId); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FixedDepositTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FixedDepositTest.java index 3cf612aaf..f6b640b5b 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FixedDepositTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FixedDepositTest.java @@ -65,6 +65,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "unused", "unchecked", "rawtypes", "static-access" }) public class FixedDepositTest { + private final static Logger LOG = LoggerFactory.getLogger(FixedDepositTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -100,9 +101,12 @@ public class FixedDepositTest { public static final Integer BIANNULLY_INTERVAL = 6; public static final Integer ANNUL_INTERVAL = 12; - // TODO Given the difference in calculation methods in test vs application, the exact values - // returned may differ enough to cause differences in rounding. Given this, we only compare the full - // digits. A proper solution would be to implement the exact interest calculation in this test, + // TODO Given the difference in calculation methods in test vs application, + // the exact values + // returned may differ enough to cause differences in rounding. Given this, + // we only compare the full + // digits. A proper solution would be to implement the exact interest + // calculation in this test, // and then to compare the exact results @BeforeEach @@ -173,8 +177,8 @@ public class FixedDepositTest { /*** * Apply for FD account with created product and verify status */ - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -229,8 +233,7 @@ public class FixedDepositTest { this.journalEntryHelper.checkJournalEntryForAssetAccount(expenseAccount, INTEREST_POSTED_DATE, expenseAccountEntry); this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, INTEREST_POSTED_DATE, liablilityAccountEntry); - this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, - CLOSED_ON_DATE); + this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, CLOSED_ON_DATE); Integer prematureClosureTransactionId = (Integer) this.fixedDepositAccountHelper.prematureCloseForFixedDeposit( fixedDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_WITHDRAW_DEPOSIT, null, CommonConstants.RESPONSE_RESOURCE_ID); @@ -240,21 +243,19 @@ public class FixedDepositTest { this.responseSpec, fixedDepositAccountId.toString()); FixedDepositAccountStatusChecker.verifyFixedDepositAccountIsPrematureClosed(fixedDepositAccountStatusHashMap); - /*** * Verify journal entry transactions for preclosure transaction */ HashMap accountDetails = this.fixedDepositAccountHelper.getFixedDepositAccountById(this.requestSpec, this.responseSpec, fixedDepositAccountId); Float maturityAmount = Float.valueOf(accountDetails.get("maturityAmount").toString()); - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, CLOSED_ON_DATE, new JournalEntry(maturityAmount, - JournalEntry.TransactionType.CREDIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, new JournalEntry(maturityAmount, - JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, CLOSED_ON_DATE, + new JournalEntry(maturityAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, + new JournalEntry(maturityAmount, JournalEntry.TransactionType.DEBIT)); } - @Test public void testFixedDepositAccountWithPrematureClosureTypeWithdrawal_WITH_HOLD_TAX() { this.fixedDepositProductHelper = new FixedDepositProductHelper(this.requestSpec, this.responseSpec); @@ -367,8 +368,7 @@ public class FixedDepositTest { this.journalEntryHelper.checkJournalEntryForAssetAccount(expenseAccount, INTEREST_POSTED_DATE, expenseAccountEntry); this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, INTEREST_POSTED_DATE, liablilityAccountEntry); - this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, - CLOSED_ON_DATE); + this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, CLOSED_ON_DATE); Integer prematureClosureTransactionId = (Integer) this.fixedDepositAccountHelper.prematureCloseForFixedDeposit( fixedDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_WITHDRAW_DEPOSIT, null, CommonConstants.RESPONSE_RESOURCE_ID); @@ -389,16 +389,15 @@ public class FixedDepositTest { Assertions.assertNotNull(summary.get("totalWithholdTax")); Float withHoldTax = (Float) summary.get("totalWithholdTax"); - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, CLOSED_ON_DATE, new JournalEntry(maturityAmount, - JournalEntry.TransactionType.CREDIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, new JournalEntry(maturityAmount, - JournalEntry.TransactionType.DEBIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccountForTax, CLOSED_ON_DATE, new JournalEntry(withHoldTax, - JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, CLOSED_ON_DATE, + new JournalEntry(maturityAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, + new JournalEntry(maturityAmount, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccountForTax, CLOSED_ON_DATE, + new JournalEntry(withHoldTax, JournalEntry.TransactionType.CREDIT)); } - @Test public void testFixedDepositAccountClosureTypeWithdrawal_WITH_HOLD_TAX() throws InterruptedException { this.fixedDepositProductHelper = new FixedDepositProductHelper(this.requestSpec, this.responseSpec); @@ -508,7 +507,7 @@ public class FixedDepositTest { * FD account verify whether account is matured */ - SchedulerJobHelper schedulerJobHelper = new SchedulerJobHelper(requestSpec); + SchedulerJobHelper schedulerJobHelper = new SchedulerJobHelper(requestSpec); String JobName = "Update Deposit Accounts Maturity details"; schedulerJobHelper.executeAndAwaitJob(JobName); @@ -518,9 +517,8 @@ public class FixedDepositTest { HashMap summary = (HashMap) accountDetails.get("summary"); Assertions.assertNotNull(summary.get("totalWithholdTax")); Float withHoldTax = (Float) summary.get("totalWithholdTax"); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccountForTax, CLOSED_ON_DATE, new JournalEntry(withHoldTax, - JournalEntry.TransactionType.CREDIT)); - + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccountForTax, CLOSED_ON_DATE, + new JournalEntry(withHoldTax, JournalEntry.TransactionType.CREDIT)); fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -528,13 +526,12 @@ public class FixedDepositTest { } - @Test public void testFixedDepositAccountWithPeriodInterestRateChart() { final String chartToUse = "period"; final String depositAmount = "10000"; final String depositPeriod = "12"; - final Float interestRate = (float)6.0; + final Float interestRate = (float) 6.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -543,7 +540,7 @@ public class FixedDepositTest { final String chartToUse = "period"; final String depositAmount = "2000"; final String depositPeriod = "12"; - final Float interestRate = (float)6.0; + final Float interestRate = (float) 6.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -552,7 +549,7 @@ public class FixedDepositTest { final String chartToUse = "period"; final String depositAmount = "10000"; final String depositPeriod = "18"; - final Float interestRate = (float)7.0; + final Float interestRate = (float) 7.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -561,7 +558,7 @@ public class FixedDepositTest { final String chartToUse = "amount"; final String depositAmount = "10000"; final String depositPeriod = "12"; - final Float interestRate = (float)7.0; + final Float interestRate = (float) 7.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -570,7 +567,7 @@ public class FixedDepositTest { final String chartToUse = "amount"; final String depositAmount = "5000"; final String depositPeriod = "12"; - final Float interestRate = (float)5.0; + final Float interestRate = (float) 5.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -579,7 +576,7 @@ public class FixedDepositTest { final String chartToUse = "amount"; final String depositAmount = "10000"; final String depositPeriod = "26"; - final Float interestRate = (float)7.0; + final Float interestRate = (float) 7.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -588,7 +585,7 @@ public class FixedDepositTest { final String chartToUse = "period_amount"; final String depositAmount = "10000"; final String depositPeriod = "12"; - final Float interestRate = (float)7.0; + final Float interestRate = (float) 7.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -597,7 +594,7 @@ public class FixedDepositTest { final String chartToUse = "period_amount"; final String depositAmount = "5000"; final String depositPeriod = "12"; - final Float interestRate = (float)6.0; + final Float interestRate = (float) 6.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -606,7 +603,7 @@ public class FixedDepositTest { final String chartToUse = "period_amount"; final String depositAmount = "10000"; final String depositPeriod = "20"; - final Float interestRate = (float)9.0; + final Float interestRate = (float) 9.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -615,7 +612,7 @@ public class FixedDepositTest { final String chartToUse = "amount_period"; final String depositAmount = "10000"; final String depositPeriod = "12"; - final Float interestRate = (float)8.0; + final Float interestRate = (float) 8.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -624,7 +621,7 @@ public class FixedDepositTest { final String chartToUse = "amount_period"; final String depositAmount = "5000"; final String depositPeriod = "12"; - final Float interestRate = (float)6.0; + final Float interestRate = (float) 6.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -633,7 +630,7 @@ public class FixedDepositTest { final String chartToUse = "amount_period"; final String depositAmount = "10000"; final String depositPeriod = "6"; - final Float interestRate = (float)7.0; + final Float interestRate = (float) 7.0; testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -663,8 +660,8 @@ public class FixedDepositTest { /*** * Apply for FD account with created product and verify status */ - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM, depositAmount, depositPeriod); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM, depositAmount, depositPeriod); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -761,8 +758,8 @@ public class FixedDepositTest { incomeAccount, expenseAccount); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -819,8 +816,7 @@ public class FixedDepositTest { */ Account financialAccount = getMappedLiabilityFinancialAccount(); - this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, - CLOSED_ON_DATE); + this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, CLOSED_ON_DATE); /*** * Preclose the account and verify journal entries @@ -842,11 +838,13 @@ public class FixedDepositTest { * transaction is an account transfer you should get financial account * mapping details and verify amounts */ - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, new JournalEntry(prematurityAmount, - JournalEntry.TransactionType.CREDIT), new JournalEntry(prematurityAmount, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, + new JournalEntry(prematurityAmount, JournalEntry.TransactionType.CREDIT), + new JournalEntry(prematurityAmount, JournalEntry.TransactionType.DEBIT)); - this.journalEntryHelper.checkJournalEntryForAssetAccount(financialAccount, CLOSED_ON_DATE, new JournalEntry(prematurityAmount, - JournalEntry.TransactionType.DEBIT), new JournalEntry(prematurityAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(financialAccount, CLOSED_ON_DATE, + new JournalEntry(prematurityAmount, JournalEntry.TransactionType.DEBIT), + new JournalEntry(prematurityAmount, JournalEntry.TransactionType.CREDIT)); HashMap savingsSummaryAfter = this.savingsAccountHelper.getSavingsSummary(savingsId); Float balanceAfter = (Float) savingsSummaryAfter.get("accountBalance"); @@ -913,8 +911,8 @@ public class FixedDepositTest { incomeAccount, expenseAccount); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -957,8 +955,7 @@ public class FixedDepositTest { this.journalEntryHelper.checkJournalEntryForAssetAccount(expenseAccount, INTEREST_POSTED_DATE, expenseAccountEntry); this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, INTEREST_POSTED_DATE, liablilityAccountEntry); - this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, - CLOSED_ON_DATE); + this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, CLOSED_ON_DATE); ArrayList errorResponse = (ArrayList) fixedDepositAccountHelperValidationError.prematureCloseForFixedDeposit( fixedDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_REINVEST, null, CommonConstants.RESPONSE_ERROR); @@ -994,13 +991,12 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - this.fixedDepositProductHelper.retrieveAllFixedDepositProducts(this.requestSpec, - this.responseSpec); - this.fixedDepositProductHelper.retrieveFixedDepositProductById(this.requestSpec, - this.responseSpec, fixedDepositProductId.toString()); + this.fixedDepositProductHelper.retrieveAllFixedDepositProducts(this.requestSpec, this.responseSpec); + this.fixedDepositProductHelper.retrieveFixedDepositProductById(this.requestSpec, this.responseSpec, + fixedDepositProductId.toString()); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); todaysDate.add(Calendar.DATE, -1); @@ -1038,8 +1034,8 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -1081,8 +1077,8 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -1122,8 +1118,8 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -1161,8 +1157,8 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -1204,8 +1200,8 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -1222,12 +1218,12 @@ public class FixedDepositTest { Integer depositPeriod = (Integer) fixedDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; todaysDate.getActualMaximum(Calendar.DATE); @@ -1237,7 +1233,7 @@ public class FixedDepositTest { principal = (float) Math.floor(principal); maturityAmount = (float) Math.floor(maturityAmount); - LOG.info("{}",principal.toString()); + LOG.info("{}", principal.toString()); Assertions.assertEquals(principal, maturityAmount, "Verifying Maturity amount for Fixed Deposit Account"); } @@ -1272,13 +1268,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, - WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, MONTHLY, MONTHLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, + INTEREST_CALCULATION_USING_DAILY_BALANCE, MONTHLY, MONTHLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -1294,12 +1290,12 @@ public class FixedDepositTest { Integer depositPeriod = (Integer) fixedDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; todaysDate.getActualMaximum(Calendar.DATE); @@ -1309,7 +1305,7 @@ public class FixedDepositTest { principal = (float) Math.floor(principal); maturityAmount = (float) Math.floor(maturityAmount); - LOG.info("{}",principal.toString()); + LOG.info("{}", principal.toString()); Assertions.assertEquals(principal, maturityAmount, "Verifying Maturity amount for Fixed Deposit Account"); } @@ -1348,8 +1344,8 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -1369,14 +1365,14 @@ public class FixedDepositTest { HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Float preClosurePenalInterestRate = (Float) fixedDepositAccountData.get("preClosurePenalInterest"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); interestRate -= preClosurePenalInterestRate; double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; todaysDate.add(Calendar.MONTH, -1); @@ -1387,15 +1383,14 @@ public class FixedDepositTest { Float interestPerMonth = (float) (interestPerDay * principal * daysInMonth); principal += interestPerMonth; todaysDate.add(Calendar.DATE, daysInMonth); - LOG.info("{}",monthDayFormat.format(todaysDate.getTime())); + LOG.info("{}", monthDayFormat.format(todaysDate.getTime())); interestPerMonth = (float) (interestPerDay * principal * currentDate); - LOG.info("IPM = {}" , interestPerMonth); + LOG.info("IPM = {}", interestPerMonth); principal += interestPerMonth; - LOG.info("principal = {}" , principal); + LOG.info("principal = {}", principal); - this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, - CLOSED_ON_DATE); + this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, CLOSED_ON_DATE); Integer prematureClosureTransactionId = (Integer) this.fixedDepositAccountHelper.prematureCloseForFixedDeposit( fixedDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_WITHDRAW_DEPOSIT, null, CommonConstants.RESPONSE_RESOURCE_ID); @@ -1450,13 +1445,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, - WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, MONTHLY, MONTHLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, + INTEREST_CALCULATION_USING_DAILY_BALANCE, MONTHLY, MONTHLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -1475,8 +1470,8 @@ public class FixedDepositTest { HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Float preClosurePenalInterestRate = (Float) fixedDepositAccountData.get("preClosurePenalInterest"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); interestRate -= preClosurePenalInterestRate; @@ -1493,15 +1488,14 @@ public class FixedDepositTest { Float interestPerMonth = (float) (interestPerDay * principal * daysInMonth); principal += interestPerMonth; todaysDate.add(Calendar.DATE, daysInMonth); - LOG.info("{}",monthDayFormat.format(todaysDate.getTime())); + LOG.info("{}", monthDayFormat.format(todaysDate.getTime())); interestPerMonth = (float) (interestPerDay * principal * currentDate); - LOG.info("IPM = {}" , interestPerMonth); + LOG.info("IPM = {}", interestPerMonth); principal += interestPerMonth; - LOG.info("principal = {}" , principal); + LOG.info("principal = {}", principal); - this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, - CLOSED_ON_DATE); + this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, CLOSED_ON_DATE); Integer prematureClosureTransactionId = (Integer) this.fixedDepositAccountHelper.prematureCloseForFixedDeposit( fixedDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_WITHDRAW_DEPOSIT, null, CommonConstants.RESPONSE_RESOURCE_ID); @@ -1556,8 +1550,8 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - TILL_PREMATURE_WITHDRAWAL); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, TILL_PREMATURE_WITHDRAWAL); Assertions.assertNotNull(fixedDepositAccountId); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, @@ -1576,8 +1570,8 @@ public class FixedDepositTest { HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Float preClosurePenalInterestRate = (Float) fixedDepositAccountData.get("preClosurePenalInterest"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Calendar activationDate = Calendar.getInstance(); activationDate.add(Calendar.MONTH, -1); @@ -1593,7 +1587,7 @@ public class FixedDepositTest { interestRate -= preClosurePenalInterestRate; double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; todaysDate.add(Calendar.MONTH, -1); @@ -1604,15 +1598,14 @@ public class FixedDepositTest { Float interestPerMonth = (float) (interestPerDay * principal * daysInMonth); principal += interestPerMonth; todaysDate.add(Calendar.DATE, daysInMonth); - LOG.info("{}",monthDayFormat.format(todaysDate.getTime())); + LOG.info("{}", monthDayFormat.format(todaysDate.getTime())); interestPerMonth = (float) (interestPerDay * principal * currentDate); - LOG.info("IPM = {}" , interestPerMonth); + LOG.info("IPM = {}", interestPerMonth); principal += interestPerMonth; - LOG.info("principal = {}" , principal); + LOG.info("principal = {}", principal); - this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, - CLOSED_ON_DATE); + this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, CLOSED_ON_DATE); Integer prematureClosureTransactionId = (Integer) this.fixedDepositAccountHelper.prematureCloseForFixedDeposit( fixedDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_WITHDRAW_DEPOSIT, null, CommonConstants.RESPONSE_RESOURCE_ID); @@ -1667,13 +1660,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - TILL_PREMATURE_WITHDRAWAL); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, TILL_PREMATURE_WITHDRAWAL); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, - TILL_PREMATURE_WITHDRAWAL, INTEREST_CALCULATION_USING_DAILY_BALANCE, MONTHLY, MONTHLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, TILL_PREMATURE_WITHDRAWAL, + INTEREST_CALCULATION_USING_DAILY_BALANCE, MONTHLY, MONTHLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -1691,8 +1684,8 @@ public class FixedDepositTest { HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Float preClosurePenalInterestRate = (Float) fixedDepositAccountData.get("preClosurePenalInterest"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Calendar activationDate = Calendar.getInstance(); activationDate.add(Calendar.MONTH, -1); @@ -1708,7 +1701,7 @@ public class FixedDepositTest { interestRate -= preClosurePenalInterestRate; double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; todaysDate.add(Calendar.MONTH, -1); @@ -1719,15 +1712,14 @@ public class FixedDepositTest { Float interestPerMonth = (float) (interestPerDay * principal * daysInMonth); principal += interestPerMonth; todaysDate.add(Calendar.DATE, daysInMonth); - LOG.info("{}",monthDayFormat.format(todaysDate.getTime())); + LOG.info("{}", monthDayFormat.format(todaysDate.getTime())); interestPerMonth = (float) (interestPerDay * principal * currentDate); - LOG.info("IPM = {}" , interestPerMonth); + LOG.info("IPM = {}", interestPerMonth); principal += interestPerMonth; - LOG.info("principal = {}" , principal); + LOG.info("principal = {}", principal); - this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, - CLOSED_ON_DATE); + this.fixedDepositAccountHelper.calculatePrematureAmountForFixedDeposit(fixedDepositAccountId, CLOSED_ON_DATE); Integer prematureClosureTransactionId = (Integer) this.fixedDepositAccountHelper.prematureCloseForFixedDeposit( fixedDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_WITHDRAW_DEPOSIT, null, CommonConstants.RESPONSE_RESOURCE_ID); @@ -1778,13 +1770,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_365, - WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, MONTHLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_365, WHOLE_TERM, + INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, MONTHLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -1800,13 +1792,13 @@ public class FixedDepositTest { Integer depositPeriod = (Integer) fixedDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; todaysDate.getActualMaximum(Calendar.DATE); @@ -1816,7 +1808,7 @@ public class FixedDepositTest { principal = (float) Math.floor(principal); maturityAmount = (float) Math.floor(maturityAmount); - LOG.info("{}",principal.toString()); + LOG.info("{}", principal.toString()); Assertions.assertEquals(principal, maturityAmount, "Verifying Maturity amount for Fixed Deposit Account"); } @@ -1837,7 +1829,7 @@ public class FixedDepositTest { final String VALID_TO = dateFormat.format(todaysDate.getTime()); todaysDate = Calendar.getInstance(); - //todaysDate.add(Calendar.MONTH, -1); + // todaysDate.add(Calendar.MONTH, -1); Integer currentDate = Integer.valueOf(currentDateFormat.format(todaysDate.getTime())); todaysDate.add(Calendar.DATE, -(currentDate - 1)); final String SUBMITTED_ON_DATE = dateFormat.format(todaysDate.getTime()); @@ -1845,7 +1837,7 @@ public class FixedDepositTest { dateFormat.format(todaysDate.getTime()); monthDayFormat.format(todaysDate.getTime()); - LOG.info("Submitted Date: {}" , SUBMITTED_ON_DATE); + LOG.info("Submitted Date: {}", SUBMITTED_ON_DATE); Integer clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec); Assertions.assertNotNull(clientId); @@ -1853,13 +1845,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, - WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, MONTHLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, + INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, MONTHLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -1875,13 +1867,13 @@ public class FixedDepositTest { Integer depositPeriod = (Integer) fixedDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; todaysDate.getActualMaximum(Calendar.DATE); @@ -1891,7 +1883,7 @@ public class FixedDepositTest { principal = new BigDecimal(principal).setScale(0, RoundingMode.FLOOR).floatValue(); maturityAmount = new BigDecimal(maturityAmount).setScale(0, RoundingMode.FLOOR).floatValue(); - LOG.info("{}",principal.toString()); + LOG.info("{}", principal.toString()); Assertions.assertEquals(principal, maturityAmount, "Verifying Maturity amount for Fixed Deposit Account"); } @@ -1917,7 +1909,7 @@ public class FixedDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -1933,13 +1925,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_365, - WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, ANNUALLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_365, WHOLE_TERM, + INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, ANNUALLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -1957,13 +1949,13 @@ public class FixedDepositTest { Integer depositPeriod = (Integer) fixedDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.fixedDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, depositPeriod, @@ -2000,7 +1992,7 @@ public class FixedDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2016,13 +2008,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, - WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, ANNUALLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, + INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, ANNUALLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -2040,13 +2032,13 @@ public class FixedDepositTest { Integer depositPeriod = (Integer) fixedDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.fixedDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, depositPeriod, @@ -2084,7 +2076,7 @@ public class FixedDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2100,13 +2092,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_365, - WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, BI_ANNUALLY, BI_ANNUALLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_365, WHOLE_TERM, + INTEREST_CALCULATION_USING_DAILY_BALANCE, BI_ANNUALLY, BI_ANNUALLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -2121,13 +2113,13 @@ public class FixedDepositTest { Integer depositPeriod = (Integer) fixedDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.fixedDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, depositPeriod, @@ -2165,7 +2157,7 @@ public class FixedDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2181,13 +2173,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, - WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, BI_ANNUALLY, BI_ANNUALLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, + INTEREST_CALCULATION_USING_DAILY_BALANCE, BI_ANNUALLY, BI_ANNUALLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -2202,13 +2194,13 @@ public class FixedDepositTest { Integer depositPeriod = (Integer) fixedDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" ,perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.fixedDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, depositPeriod, @@ -2246,7 +2238,7 @@ public class FixedDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2262,13 +2254,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_365, - WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, QUARTERLY, QUARTERLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_365, WHOLE_TERM, + INTEREST_CALCULATION_USING_DAILY_BALANCE, QUARTERLY, QUARTERLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -2283,13 +2275,13 @@ public class FixedDepositTest { Integer depositPeriod = (Integer) fixedDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.fixedDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, depositPeriod, @@ -2326,7 +2318,7 @@ public class FixedDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2342,13 +2334,13 @@ public class FixedDepositTest { Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO, accountingRule); Assertions.assertNotNull(fixedDepositProductId); - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM); Assertions.assertNotNull(fixedDepositAccountId); - this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), - fixedDepositProductId.toString(), fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, - WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, QUARTERLY, QUARTERLY); + this.fixedDepositAccountHelper.updateInterestCalculationConfigForFixedDeposit(clientId.toString(), fixedDepositProductId.toString(), + fixedDepositAccountId.toString(), SUBMITTED_ON_DATE, VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, + INTEREST_CALCULATION_USING_DAILY_BALANCE, QUARTERLY, QUARTERLY); HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, fixedDepositAccountId.toString()); @@ -2363,13 +2355,13 @@ public class FixedDepositTest { Integer depositPeriod = (Integer) fixedDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) fixedDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.fixedDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, fixedDepositProductId); + ArrayList> interestRateChartData = this.fixedDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, fixedDepositProductId); Float interestRate = this.fixedDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.fixedDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, depositPeriod, @@ -2385,8 +2377,8 @@ public class FixedDepositTest { } /*** - * Test case for Fixed Deposit Account rollover with maturity - * instruction as re invest maturity amount(principal+interest) + * Test case for Fixed Deposit Account rollover with maturity instruction as + * re invest maturity amount(principal+interest) */ @Test public void testFixedDepositAccountWithRolloverMaturityAmount() { @@ -2436,15 +2428,15 @@ public class FixedDepositTest { Assertions.assertNotNull(fixedDepositProductId); /*** - * Set maturityInstructionId as re-invest principal+interest - * */ + * Set maturityInstructionId as re-invest principal+interest + */ final Integer maturityInstructionId = 300; /*** * Apply for FD account with created product and verify status */ - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM, maturityInstructionId); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM, maturityInstructionId); Assertions.assertNotNull(fixedDepositAccountId); @@ -2465,10 +2457,9 @@ public class FixedDepositTest { FixedDepositAccountStatusChecker.verifyFixedDepositIsActive(fixedDepositAccountStatusHashMap); } - /*** - * Test case for Fixed Deposit Account rollover with maturity - * instruction as re invest principal only + * Test case for Fixed Deposit Account rollover with maturity instruction as + * re invest principal only */ @Test public void testFixedDepositAccountWithRolloverPrincipal() { @@ -2518,15 +2509,15 @@ public class FixedDepositTest { Assertions.assertNotNull(fixedDepositProductId); /*** - * Set maturityInstructionId as re-invest principal - * */ + * Set maturityInstructionId as re-invest principal + */ final Integer maturityInstructionId = 400; /*** * Apply for FD account with created product and verify status */ - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), SUBMITTED_ON_DATE, - WHOLE_TERM, maturityInstructionId); + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), + SUBMITTED_ON_DATE, WHOLE_TERM, maturityInstructionId); Assertions.assertNotNull(fixedDepositAccountId); @@ -2561,7 +2552,6 @@ public class FixedDepositTest { return FixedDepositProductHelper.createFixedDepositProduct(fixedDepositProductJSON, requestSpec, responseSpec); } - private Integer createFixedDepositProductWithWithHoldTax(final String validFrom, final String validTo, final String taxGroupId, final String accountingRule, Account... accounts) { LOG.info("------------------------------CREATING NEW FIXED DEPOSIT PRODUCT ---------------------------------------"); @@ -2589,18 +2579,18 @@ public class FixedDepositTest { switch (chartToBePicked) { case "period": fixedDepositProductHelper = fixedDepositProductHelper.withPeriodRangeChart(); - break; + break; case "amount": fixedDepositProductHelper = fixedDepositProductHelper.withAmountRangeChart(); - break; + break; case "period_amount": fixedDepositProductHelper = fixedDepositProductHelper.withPeriodAndAmountRangeChart(); - break; + break; case "amount_period": fixedDepositProductHelper = fixedDepositProductHelper.withAmountAndPeriodRangeChart(); - break; + break; default: - break; + break; } final String fixedDepositProductJSON = fixedDepositProductHelper // @@ -2613,19 +2603,18 @@ public class FixedDepositTest { LOG.info("--------------------------------APPLYING FOR FIXED DEPOSIT ACCOUNT --------------------------------"); final String fixedDepositApplicationJSON = new FixedDepositAccountHelper(this.requestSpec, this.responseSpec) // .withSubmittedOnDate(submittedOnDate).build(clientID, productID, penalInterestType); - return this.fixedDepositAccountHelper - .applyFixedDepositApplication(fixedDepositApplicationJSON, this.requestSpec, this.responseSpec); + return this.fixedDepositAccountHelper.applyFixedDepositApplication(fixedDepositApplicationJSON, this.requestSpec, + this.responseSpec); } private Integer applyForFixedDepositApplication(final String clientID, final String productID, final String submittedOnDate, final String penalInterestType, final Integer maturityInstructionId) { LOG.info("--------------------------------APPLYING FOR FIXED DEPOSIT ACCOUNT --------------------------------"); final String fixedDepositApplicationJSON = new FixedDepositAccountHelper(this.requestSpec, this.responseSpec) // - .withSubmittedOnDate(submittedOnDate) - .withMaturityInstructionId(maturityInstructionId) + .withSubmittedOnDate(submittedOnDate).withMaturityInstructionId(maturityInstructionId) .build(clientID, productID, penalInterestType); - return this.fixedDepositAccountHelper - .applyFixedDepositApplication(fixedDepositApplicationJSON, this.requestSpec, this.responseSpec); + return this.fixedDepositAccountHelper.applyFixedDepositApplication(fixedDepositApplicationJSON, this.requestSpec, + this.responseSpec); } private Integer applyForFixedDepositApplication(final String clientID, final String productID, final String submittedOnDate, @@ -2635,8 +2624,8 @@ public class FixedDepositTest { // .withSubmittedOnDate(submittedOnDate).withDepositPeriod(depositPeriod).withDepositAmount(depositAmount) .build(clientID, productID, penalInterestType); - return this.fixedDepositAccountHelper - .applyFixedDepositApplication(fixedDepositApplicationJSON, this.requestSpec, this.responseSpec); + return this.fixedDepositAccountHelper.applyFixedDepositApplication(fixedDepositApplicationJSON, this.requestSpec, + this.responseSpec); } private Integer createSavingsProduct(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, @@ -2701,20 +2690,23 @@ public class FixedDepositTest { LIABILITY_TRANSFER_FINANCIAL_ACTIVITY_ID, liabilityAccountForMapping.getAccountID(), this.responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); Assertions.assertNotNull(financialActivityAccountId); - assertFinancialActivityAccountCreation(financialActivityAccountId, LIABILITY_TRANSFER_FINANCIAL_ACTIVITY_ID, liabilityAccountForMapping); + assertFinancialActivityAccountCreation(financialActivityAccountId, LIABILITY_TRANSFER_FINANCIAL_ACTIVITY_ID, + liabilityAccountForMapping); return liabilityAccountForMapping; } - private void assertFinancialActivityAccountCreation(Integer financialActivityAccountId, Integer financialActivityId, Account glAccount) { + private void assertFinancialActivityAccountCreation(Integer financialActivityAccountId, Integer financialActivityId, + Account glAccount) { HashMap mappingDetails = this.financialActivityAccountHelper.getFinancialActivityAccount(financialActivityAccountId, this.responseSpec); Assertions.assertEquals(financialActivityId, ((HashMap) mappingDetails.get("financialActivityData")).get("id")); Assertions.assertEquals(glAccount.getAccountID(), ((HashMap) mappingDetails.get("glAccountData")).get("id")); } - private Integer createTaxGroup(final String percentage, final Account liabilityAccountForTax){ + private Integer createTaxGroup(final String percentage, final Account liabilityAccountForTax) { final Integer liabilityAccountId = liabilityAccountForTax.getAccountID(); - final Integer taxComponentId = TaxComponentHelper.createTaxComponent(this.requestSpec, this.responseSpec, percentage, liabilityAccountId); + final Integer taxComponentId = TaxComponentHelper.createTaxComponent(this.requestSpec, this.responseSpec, percentage, + liabilityAccountId); return TaxGroupHelper.createTaxGroup(this.requestSpec, this.responseSpec, Arrays.asList(taxComponentId)); } @@ -2726,8 +2718,8 @@ public class FixedDepositTest { List financialActivities = this.financialActivityAccountHelper.getAllFinancialActivityAccounts(this.responseSpec); for (HashMap financialActivity : financialActivities) { Integer financialActivityAccountId = (Integer) financialActivity.get("id"); - Integer deletedFinancialActivityAccountId = this.financialActivityAccountHelper.deleteFinancialActivityAccount( - financialActivityAccountId, this.responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); + Integer deletedFinancialActivityAccountId = this.financialActivityAccountHelper + .deleteFinancialActivityAccount(financialActivityAccountId, this.responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); Assertions.assertNotNull(deletedFinancialActivityAccountId); Assertions.assertEquals(financialActivityAccountId, deletedFinancialActivityAccountId); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FlexibleSavingsInterestPostingIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FlexibleSavingsInterestPostingIntegrationTest.java index 8053ccf16..7d6b03532 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FlexibleSavingsInterestPostingIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FlexibleSavingsInterestPostingIntegrationTest.java @@ -44,6 +44,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "rawtypes", "unused", "unchecked" }) public class FlexibleSavingsInterestPostingIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(FlexibleSavingsInterestPostingIntegrationTest.class); public static final String ACCOUNT_TYPE_INDIVIDUAL = "INDIVIDUAL"; @@ -74,8 +75,7 @@ public class FlexibleSavingsInterestPostingIntegrationTest { final Integer savingsId = createSavingsAccount(clientID, startDate); - this.savingsAccountHelper.depositToSavingsAccount(savingsId, "1000", startDate, - CommonConstants.RESPONSE_RESOURCE_ID); + this.savingsAccountHelper.depositToSavingsAccount(savingsId, "1000", startDate, CommonConstants.RESPONSE_RESOURCE_ID); /*** * Perform Post interest transaction and verify the posted transaction @@ -85,8 +85,9 @@ public class FlexibleSavingsInterestPostingIntegrationTest { HashMap accountDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); ArrayList> transactions = (ArrayList>) accountDetails.get("transactions"); HashMap interestPostingTransaction = transactions.get(transactions.size() - 2); - for (Entry entry : interestPostingTransaction.entrySet()) - {LOG.info("{} - {}",entry.getKey(), entry.getValue().toString());} + for (Entry entry : interestPostingTransaction.entrySet()) { + LOG.info("{} - {}", entry.getKey(), entry.getValue().toString()); + } // 1st Dec 13 to 31st March 14 - 365 days, daily compounding using daily // balance // 33.7016 obtained from formula in excel provided by Subramanya @@ -123,16 +124,16 @@ public class FlexibleSavingsInterestPostingIntegrationTest { Boolean enabled = (Boolean) globalConfig.get(10).get("enabled"); if (!enabled.equals(periodEndEnable)) { - periodEndConfigId = GlobalConfigurationHelper.updateEnabledFlagForGlobalConfiguration(this.requestSpec, - this.responseSpec, periodEndConfigId.toString(), periodEndEnable); + periodEndConfigId = GlobalConfigurationHelper.updateEnabledFlagForGlobalConfiguration(this.requestSpec, this.responseSpec, + periodEndConfigId.toString(), periodEndEnable); } // Updating value for financial year beginning month Integer financialYearBeginningConfigId = (Integer) globalConfig.get(11).get("id"); Assertions.assertNotNull(financialYearBeginningConfigId); - HashMap financialYearBeginningConfigData = GlobalConfigurationHelper.getGlobalConfigurationById(this.requestSpec, - this.responseSpec, financialYearBeginningConfigId.toString()); + HashMap financialYearBeginningConfigData = GlobalConfigurationHelper.getGlobalConfigurationById(this.requestSpec, this.responseSpec, + financialYearBeginningConfigId.toString()); Assertions.assertNotNull(financialYearBeginningConfigData); financialYearBeginningConfigId = GlobalConfigurationHelper.updateValueForGlobalConfiguration(this.requestSpec, this.responseSpec, diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FundsIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FundsIntegrationTest.java index c59039c58..57a75a0d7 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FundsIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/FundsIntegrationTest.java @@ -57,10 +57,7 @@ public class FundsIntegrationTest { @Test public void testCreateFund() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); @@ -69,10 +66,7 @@ public class FundsIntegrationTest { @Test public void testCreateFundWithEmptyName() { - FundsHelper fh = FundsHelper - .create(null) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(null).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(400).build(); @@ -82,10 +76,7 @@ public class FundsIntegrationTest { @Test public void testCreateFundWithEmptyExternalId() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(null) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(null).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); @@ -94,19 +85,13 @@ public class FundsIntegrationTest { @Test public void testCreateFundWithDuplicateName() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); Assertions.assertNotNull(fundID); - FundsHelper fh2 = FundsHelper - .create(fh.getName()) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh2 = FundsHelper.create(fh.getName()).externalId(Utils.randomNameGenerator("fund-", 5)).build(); jsonData = fh2.toJSON(); ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(403).build(); @@ -116,19 +101,13 @@ public class FundsIntegrationTest { @Test public void testCreateFundWithDuplicateExternalId() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); Assertions.assertNotNull(fundID); - FundsHelper fh2 = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(fh.getExternalId()) - .build(); + FundsHelper fh2 = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(fh.getExternalId()).build(); jsonData = fh2.toJSON(); ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(403).build(); @@ -138,10 +117,7 @@ public class FundsIntegrationTest { @Test public void testCreateFundWithInvalidName() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 120)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 120)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(400).build(); @@ -151,10 +127,7 @@ public class FundsIntegrationTest { @Test public void testCreateFundWithInvalidExternalId() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 120)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 120)).build(); String jsonData = fh.toJSON(); ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(400).build(); @@ -164,10 +137,7 @@ public class FundsIntegrationTest { @Test public void testRetrieveFund() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); @@ -181,10 +151,7 @@ public class FundsIntegrationTest { @Test public void testRetrieveAllFunds() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); @@ -201,16 +168,13 @@ public class FundsIntegrationTest { public void testRetrieveUnknownFund() { ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(404).build(); String jsonData = FundsResourceHandler.retrieveFund(Long.MAX_VALUE, this.requestSpec, responseSpec); - HashMap map = new Gson().fromJson(jsonData, new TypeToken>(){}.getType()); + HashMap map = new Gson().fromJson(jsonData, new TypeToken>() {}.getType()); assertEquals("error.msg.resource.not.found", map.get("userMessageGlobalisationCode")); } @Test public void testUpdateFund() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); @@ -229,17 +193,13 @@ public class FundsIntegrationTest { String newName = Utils.randomNameGenerator("", 10); String newExternalId = Utils.randomNameGenerator("fund-", 5); ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(404).build(); - FundsHelper fh = FundsResourceHandler.updateFund(Long.MAX_VALUE, newName, newExternalId, this.requestSpec, - responseSpec); + FundsHelper fh = FundsResourceHandler.updateFund(Long.MAX_VALUE, newName, newExternalId, this.requestSpec, responseSpec); Assertions.assertNull(fh); } @Test public void testUpdateFundWithInvalidNewName() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); @@ -248,18 +208,14 @@ public class FundsIntegrationTest { String newName = Utils.randomNameGenerator("", 120); String newExternalId = Utils.randomNameGenerator("fund-", 5); ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(400).build(); - FundsHelper fh2 = FundsResourceHandler.updateFund(fundID, newName, newExternalId, this.requestSpec, - responseSpec); + FundsHelper fh2 = FundsResourceHandler.updateFund(fundID, newName, newExternalId, this.requestSpec, responseSpec); Assertions.assertNull(fh2); } @Test public void testUpdateFundWithNewExternalId() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); @@ -273,10 +229,7 @@ public class FundsIntegrationTest { @Test public void testUpdateFundWithInvalidNewExternalId() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); @@ -285,18 +238,14 @@ public class FundsIntegrationTest { String newName = Utils.randomNameGenerator("", 10); String newExternalId = Utils.randomNameGenerator("fund-", 120); ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(400).build(); - FundsHelper fh2 = FundsResourceHandler.updateFund(fundID, newName, newExternalId, this.requestSpec, - responseSpec); + FundsHelper fh2 = FundsResourceHandler.updateFund(fundID, newName, newExternalId, this.requestSpec, responseSpec); Assertions.assertNull(fh2); } @Test public void testUpdateFundWithNewName() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); @@ -310,10 +259,7 @@ public class FundsIntegrationTest { @Test public void testUpdateFundWithEmptyParams() { - FundsHelper fh = FundsHelper - .create(Utils.randomNameGenerator("", 10)) - .externalId(Utils.randomNameGenerator("fund-", 5)) - .build(); + FundsHelper fh = FundsHelper.create(Utils.randomNameGenerator("", 10)).externalId(Utils.randomNameGenerator("fund-", 5)).build(); String jsonData = fh.toJSON(); final Long fundID = createFund(jsonData, this.requestSpec, this.statusOkResponseSpec); @@ -333,9 +279,7 @@ public class FundsIntegrationTest { Assertions.assertEquals(fh.getExternalId(), fh3.getExternalId()); } - private Long createFund(final String fundJSON, - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + private Long createFund(final String fundJSON, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { String fundId = String.valueOf(FundsResourceHandler.createFund(fundJSON, requestSpec, responseSpec)); if (fundId.equals("null")) { // Invalid JSON data parameters diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GlobalConfigInterestChargedFromDateSameAsDisbursalDateTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GlobalConfigInterestChargedFromDateSameAsDisbursalDateTest.java index 94827ecd5..b35683210 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GlobalConfigInterestChargedFromDateSameAsDisbursalDateTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GlobalConfigInterestChargedFromDateSameAsDisbursalDateTest.java @@ -32,7 +32,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - public class GlobalConfigInterestChargedFromDateSameAsDisbursalDateTest { private ResponseSpecification responseSpec; @@ -53,30 +52,27 @@ public class GlobalConfigInterestChargedFromDateSameAsDisbursalDateTest { GlobalConfigurationHelper.verifyAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec); } - @SuppressWarnings( {"static-access", "rawtypes", "unchecked"}) + @SuppressWarnings({ "static-access", "rawtypes", "unchecked" }) @Test - public void testInterestChargedFromDateSameAsDisbursalDate(){ + public void testInterestChargedFromDateSameAsDisbursalDate() { this.globalConfigurationHelper = new GlobalConfigurationHelper(this.requestSpec, this.responseSpec); - // Retrieving All Global Configuration details - final ArrayList globalConfig = this.globalConfigurationHelper - .getAllGlobalConfigurations(this.requestSpec, this.responseSpec); + // Retrieving All Global Configuration details + final ArrayList globalConfig = this.globalConfigurationHelper.getAllGlobalConfigurations(this.requestSpec, + this.responseSpec); Assertions.assertNotNull(globalConfig); String configName = "interest-charged-from-date-same-as-disbursal-date"; boolean newBooleanValue = true; for (Integer configIndex = 0; configIndex < globalConfig.size(); configIndex++) { - if (globalConfig.get(configIndex).get("name") - .equals(configName)) { - String configId = globalConfig.get(configIndex).get("id") - .toString(); - Integer updateConfigId = this.globalConfigurationHelper - .updateEnabledFlagForGlobalConfiguration(this.requestSpec, this.responseSpec, - configId.toString(), newBooleanValue); - Assertions.assertNotNull(updateConfigId); - break; - } + if (globalConfig.get(configIndex).get("name").equals(configName)) { + String configId = globalConfig.get(configIndex).get("id").toString(); + Integer updateConfigId = this.globalConfigurationHelper.updateEnabledFlagForGlobalConfiguration(this.requestSpec, + this.responseSpec, configId.toString(), newBooleanValue); + Assertions.assertNotNull(updateConfigId); + break; + } } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GlobalConfigurationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GlobalConfigurationTest.java index c0dee4b5a..03cec050c 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GlobalConfigurationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GlobalConfigurationTest.java @@ -137,8 +137,8 @@ public class GlobalConfigurationTest { cacheTypeId -= 1; } - HashMap changes = this.globalConfigurationHelper.updateIsCacheEnabledForGlobalConfiguration(this.requestSpec, - this.responseSpec, cacheTypeId.toString()); + HashMap changes = this.globalConfigurationHelper.updateIsCacheEnabledForGlobalConfiguration(this.requestSpec, this.responseSpec, + cacheTypeId.toString()); Assertions.assertEquals(cacheTypeId, changes.get("cacheType"), "Verifying Is Cache Enabled Global Config after Updation"); } } @@ -147,8 +147,8 @@ public class GlobalConfigurationTest { public void testGlobalConfigForcePasswordResetDays() { // Retrieving All Global Configuration details - final ArrayList globalConfig = this.globalConfigurationHelper - .getAllGlobalConfigurations(this.requestSpec, this.responseSpec); + final ArrayList globalConfig = this.globalConfigurationHelper.getAllGlobalConfigurations(this.requestSpec, + this.responseSpec); Assertions.assertNotNull(globalConfig); String configName = "force-password-reset-days"; @@ -157,23 +157,18 @@ public class GlobalConfigurationTest { for (Integer configIndex = 0; configIndex < globalConfig.size() - 1; configIndex++) { if (globalConfig.get(configIndex).get("name").equals(configName)) { - Integer configId = (Integer) globalConfig.get(configIndex).get( - "id"); + Integer configId = (Integer) globalConfig.get(configIndex).get("id"); Assertions.assertNotNull(configId); /* * Update force-password-reset-days with value as 0 and Enable * as true - failure case */ - ArrayList error = (ArrayList) this.globalConfigurationHelper - .updatePasswordResetDaysForGlobalConfiguration( - this.requestSpec, this.httpStatusForidden, - configId, newValue, newBooleanValue, - CommonConstants.RESPONSE_ERROR); + ArrayList error = (ArrayList) this.globalConfigurationHelper.updatePasswordResetDaysForGlobalConfiguration(this.requestSpec, + this.httpStatusForidden, configId, newValue, newBooleanValue, CommonConstants.RESPONSE_ERROR); HashMap hash = (HashMap) error.get(0); - Assertions.assertEquals( - "error.msg.password.reset.days.value.must.be.greater.than.zero", + Assertions.assertEquals("error.msg.password.reset.days.value.must.be.greater.than.zero", hash.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE), "Force Password Reset days value must be greater than zero."); @@ -181,27 +176,23 @@ public class GlobalConfigurationTest { * Update force-password-reset-days with value as 50 and Enable * as true - success case */ - final HashMap updateSuccess = (HashMap) this.globalConfigurationHelper - .updatePasswordResetDaysForGlobalConfiguration( - this.requestSpec, this.responseSpec, configId, - "50", newBooleanValue, "changes"); + final HashMap updateSuccess = (HashMap) this.globalConfigurationHelper.updatePasswordResetDaysForGlobalConfiguration( + this.requestSpec, this.responseSpec, configId, "50", newBooleanValue, "changes"); Assertions.assertNotNull(updateSuccess); /* Update with value as 0 and Enable as false - success case */ - final HashMap updateSuccess1 = (HashMap) this.globalConfigurationHelper - .updatePasswordResetDaysForGlobalConfiguration( - this.requestSpec, this.responseSpec, configId, - newValue, "false", "changes"); + final HashMap updateSuccess1 = (HashMap) this.globalConfigurationHelper.updatePasswordResetDaysForGlobalConfiguration( + this.requestSpec, this.responseSpec, configId, newValue, "false", "changes"); Assertions.assertNotNull(updateSuccess1); - /* Update without sending value and Enable as true - failure case*/ - ArrayList failure = (ArrayList) this.globalConfigurationHelper - .updatePasswordResetDaysForGlobalConfiguration( - this.requestSpec, this.httpStatusForidden, configId, - null, newBooleanValue, CommonConstants.RESPONSE_ERROR); + /* + * Update without sending value and Enable as true - failure + * case + */ + ArrayList failure = (ArrayList) this.globalConfigurationHelper.updatePasswordResetDaysForGlobalConfiguration( + this.requestSpec, this.httpStatusForidden, configId, null, newBooleanValue, CommonConstants.RESPONSE_ERROR); HashMap failureHash = (HashMap) failure.get(0); - Assertions.assertEquals( - "error.msg.password.reset.days.value.must.be.greater.than.zero", + Assertions.assertEquals("error.msg.password.reset.days.value.must.be.greater.than.zero", failureHash.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE), "Force Password Reset days value must be greater than zero."); @@ -211,13 +202,10 @@ public class GlobalConfigurationTest { /* Update other global configuration property */ String otherConfigName = "maker-checker"; for (Integer configIndex = 0; configIndex < globalConfig.size() - 1; configIndex++) { - if (globalConfig.get(configIndex).get("name") - .equals(otherConfigName)) { - String configId = globalConfig.get(configIndex).get("id") - .toString(); - Integer updateConfigId = this.globalConfigurationHelper - .updateValueForGlobalConfiguration(this.requestSpec, - this.responseSpec, configId, newValue); + if (globalConfig.get(configIndex).get("name").equals(otherConfigName)) { + String configId = globalConfig.get(configIndex).get("id").toString(); + Integer updateConfigId = this.globalConfigurationHelper.updateValueForGlobalConfiguration(this.requestSpec, + this.responseSpec, configId, newValue); Assertions.assertNotNull(updateConfigId); break; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupLoanIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupLoanIntegrationTest.java index 057a93f6a..df19c30ac 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupLoanIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupLoanIntegrationTest.java @@ -74,7 +74,7 @@ public class GroupLoanIntegrationTest { final Integer loanProductID = createLoanProduct(); final Integer loanID = applyForLoanApplication(groupID, loanProductID); final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, - loanID); + loanID); verifyLoanRepaymentSchedule(loanSchedule); } @@ -86,20 +86,20 @@ public class GroupLoanIntegrationTest { groupID = GroupHelper.associateClient(this.requestSpec, this.responseSpec, groupID.toString(), clientID.toString()); final Integer loanProductID = createLoanProduct(); - HashMap glim = applyForGlimApplication(clientID, groupID, loanProductID); + HashMap glim = applyForGlimApplication(clientID, groupID, loanProductID); LOG.info("Glim Loan Application: {} ", glim); - final Integer glimId=glim.get("glimId"); + final Integer glimId = glim.get("glimId"); LOG.info("GlimId : {} ", glimId); - final Integer loanId=glim.get("loanId"); + final Integer loanId = glim.get("loanId"); LOG.info("LoanId : {} ", loanId); List> approvalFormData = new ArrayList<>(); - approvalFormData.add(approvalFormData(loanId,"22 September 2011")); + approvalFormData.add(approvalFormData(loanId, "22 September 2011")); - HashMap loanStatusHashMap = this.loanTransactionHelper.approveGlimAccount(this.requestSpec, this.responseSpec, - approvalFormData, glimId); + HashMap loanStatusHashMap = this.loanTransactionHelper.approveGlimAccount(this.requestSpec, this.responseSpec, approvalFormData, + glimId); LOG.info("glim approval loanSchedule: {} ", loanStatusHashMap); LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); @@ -115,7 +115,7 @@ public class GroupLoanIntegrationTest { LOG.info("glim undoApproval loanSchedule: {} ", loanStatusHashMap); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - loanStatusHashMap = this.loanTransactionHelper.rejectGlimAccount("22 September 2011",glimId); + loanStatusHashMap = this.loanTransactionHelper.rejectGlimAccount("22 September 2011", glimId); LOG.info("glim reject loanSchedule: {} ", loanStatusHashMap); LoanStatusChecker.verifyLoanAccountRejected(loanStatusHashMap); } @@ -136,16 +136,16 @@ public class GroupLoanIntegrationTest { final Integer loanProductID = createLoanProduct(); Assertions.assertNotNull(loanProductID); - HashMap glim = applyForGlimApplication(clientID, groupID, loanProductID); + HashMap glim = applyForGlimApplication(clientID, groupID, loanProductID); LOG.info("Glim Loan Application: {} ", glim); - final Integer glimId=glim.get("glimId"); + final Integer glimId = glim.get("glimId"); LOG.info("GlimId: {} ", glimId); - final Integer loanId=glim.get("loanId"); + final Integer loanId = glim.get("loanId"); LOG.info("LoanId: {} ", loanId); - final List retrievedGlimId=GroupHelper.verifyRetrieveGlimAccountsByGroupId(this.requestSpec, this.responseSpec, groupID); + final List retrievedGlimId = GroupHelper.verifyRetrieveGlimAccountsByGroupId(this.requestSpec, this.responseSpec, groupID); Assertions.assertNotNull(retrievedGlimId.toString()); } @@ -165,16 +165,17 @@ public class GroupLoanIntegrationTest { final Integer loanProductID = createLoanProduct(); Assertions.assertNotNull(loanProductID); - HashMap glim = applyForGlimApplication(clientID, groupID, loanProductID); + HashMap glim = applyForGlimApplication(clientID, groupID, loanProductID); LOG.info("Glim Loan Application: {} ", glim); - final Integer glimId=glim.get("glimId"); + final Integer glimId = glim.get("glimId"); LOG.info("GlimId: {} ", glimId); - final Integer loanId=glim.get("loanId"); + final Integer loanId = glim.get("loanId"); LOG.info("LoanId: {} ", loanId); - final List retrievedGlimAccountId=GroupHelper.verifyRetrieveGlimAccountsByGlimId(this.requestSpec, this.responseSpec, glimId); + final List retrievedGlimAccountId = GroupHelper.verifyRetrieveGlimAccountsByGlimId(this.requestSpec, this.responseSpec, + glimId); Assertions.assertNotNull(retrievedGlimAccountId); } @@ -222,7 +223,7 @@ public class GroupLoanIntegrationTest { return this.loanTransactionHelper.getLoanId(loanApplicationJSON); } - private HashMap applyForGlimApplication(final Integer clientID, final Integer groupID, final Integer loanProductID) { + private HashMap applyForGlimApplication(final Integer clientID, final Integer groupID, final Integer loanProductID) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String GlimApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal("12,000.00") // @@ -236,10 +237,8 @@ public class GroupLoanIntegrationTest { .withInterestTypeAsDecliningBalance() // .withInterestCalculationPeriodTypeSameAsRepaymentPeriod() // .withExpectedDisbursementDate("20 September 2011") // - .withSubmittedOnDate("20 September 2011") - .withLoanType("glim") - .withtotalLoan("10000") - .withParentAccount("1").build(clientID.toString(), groupID.toString(), loanProductID.toString(), null); + .withSubmittedOnDate("20 September 2011").withLoanType("glim").withtotalLoan("10000").withParentAccount("1") + .build(clientID.toString(), groupID.toString(), loanProductID.toString(), null); LOG.info(GlimApplicationJSON); return this.loanTransactionHelper.getGlimId(GlimApplicationJSON); } @@ -249,10 +248,8 @@ public class GroupLoanIntegrationTest { assertEquals(new ArrayList<>(Arrays.asList(2011, 10, 20)), loanSchedule.get(1).get("dueDate"), "Checking for Due Date for 1st Month"); - assertEquals(Float.valueOf("2911.49"), loanSchedule.get(1).get("principalOriginalDue"), - "Checking for Principal Due for 1st Month"); - assertEquals(Float.valueOf("240.00"), loanSchedule.get(1).get("interestOriginalDue"), - "Checking for Interest Due for 1st Month"); + assertEquals(Float.valueOf("2911.49"), loanSchedule.get(1).get("principalOriginalDue"), "Checking for Principal Due for 1st Month"); + assertEquals(Float.valueOf("240.00"), loanSchedule.get(1).get("interestOriginalDue"), "Checking for Interest Due for 1st Month"); assertEquals(new ArrayList<>(Arrays.asList(2011, 11, 20)), loanSchedule.get(2).get("dueDate"), "Checking for Due Date for 2nd Month"); @@ -265,7 +262,7 @@ public class GroupLoanIntegrationTest { assertEquals(Float.valueOf("122.38"), loanSchedule.get(3).get("interestOriginalDue"), "Checking for Interest Due for 3rd Month"); assertEquals(new ArrayList<>(Arrays.asList(2012, 1, 20)), loanSchedule.get(4).get("dueDate"), - "Checking for Due Date for 4th Month"); + "Checking for Due Date for 4th Month"); assertEquals(Float.valueOf("3089.68"), loanSchedule.get(4).get("principalDue"), "Checking for Principal Due for 4th Month"); assertEquals(Float.valueOf("61.79"), loanSchedule.get(4).get("interestOriginalDue"), "Checking for Interest Due for 4th Month"); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupSavingsIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupSavingsIntegrationTest.java index 09c1dc89b..cd984e813 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupSavingsIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupSavingsIntegrationTest.java @@ -162,13 +162,13 @@ public class GroupSavingsIntegrationTest { Calendar todaysDate = Calendar.getInstance(); final String CLOSEDON_DATE = dateFormat.format(todaysDate.getTime()); String withdrawBalance = "false"; - ArrayList savingsAccountErrorData = (ArrayList) validationErrorHelper.closeSavingsAccountAndGetBackRequiredField( - savingsId, withdrawBalance, CommonConstants.RESPONSE_ERROR, CLOSEDON_DATE); + ArrayList savingsAccountErrorData = (ArrayList) validationErrorHelper + .closeSavingsAccountAndGetBackRequiredField(savingsId, withdrawBalance, CommonConstants.RESPONSE_ERROR, CLOSEDON_DATE); assertEquals("validation.msg.savingsaccount.close.results.in.balance.not.zero", savingsAccountErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); withdrawBalance = "true"; - savingsStatusHashMap = this.savingsAccountHelper.closeSavingsAccount(savingsId, withdrawBalance); + savingsStatusHashMap = this.savingsAccountHelper.closeSavingsAccount(savingsId, withdrawBalance); SavingsStatusChecker.verifySavingsAccountIsClosed(savingsStatusHashMap); } @@ -221,7 +221,7 @@ public class GroupSavingsIntegrationTest { } - //gsimcommands testing + // gsimcommands testing @SuppressWarnings("unchecked") @Test public void testGsimSavingsAccount_REJECT_APPLICATION() { @@ -248,7 +248,7 @@ public class GroupSavingsIntegrationTest { Assertions.assertNotNull(savingsProductID); List> clientArray = new ArrayList<>(); - clientArray.add(clientArray(clientID, groupID, savingsProductID,"08 January 2013")); + clientArray.add(clientArray(clientID, groupID, savingsProductID, "08 January 2013")); final Integer gsimID = this.savingsAccountHelper.applyForGsimApplication(clientArray); @@ -267,7 +267,8 @@ public class GroupSavingsIntegrationTest { assertEquals("validation.msg.savingsaccount.reject.cannot.be.a.future.date", error1.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); - error1 = savingsAccountHelperValidationError.rejectGsimApplicationWithErrorCode(gsimID, SavingsAccountHelper.CREATED_DATE_MINUS_ONE); + error1 = savingsAccountHelperValidationError.rejectGsimApplicationWithErrorCode(gsimID, + SavingsAccountHelper.CREATED_DATE_MINUS_ONE); assertEquals("validation.msg.savingsaccount.reject.cannot.be.before.submittal.date", error1.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); @@ -276,7 +277,7 @@ public class GroupSavingsIntegrationTest { } - @Test + @Test public void testGsimSavingsAccount_DEPOSIT_APPLICATION() { this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); @@ -298,7 +299,7 @@ public class GroupSavingsIntegrationTest { Assertions.assertNotNull(savingsProductID); List> clientArray = new ArrayList<>(); - clientArray.add(clientArray(clientID, groupID, savingsProductID,"08 January 2013")); + clientArray.add(clientArray(clientID, groupID, savingsProductID, "08 January 2013")); LOG.info("client Array : {} ", clientArray); final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(groupID, savingsProductID, ACCOUNT_TYPE_GROUP); @@ -313,7 +314,7 @@ public class GroupSavingsIntegrationTest { Assertions.assertNotNull(paymentTypeId); List> savingsArray = new ArrayList<>(); - final Integer transactionAmount=2500; + final Integer transactionAmount = 2500; savingsArray.add(savingsArray(paymentTypeId, savingsId, transactionAmount, "10 March 2013")); HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsId); @@ -328,7 +329,7 @@ public class GroupSavingsIntegrationTest { final Integer depositId = this.savingsAccountHelper.depositGsimApplication(savingsId, savingsArray); Assertions.assertNotNull(depositId); - } + } @SuppressWarnings("unchecked") @Test @@ -354,7 +355,7 @@ public class GroupSavingsIntegrationTest { Assertions.assertNotNull(savingsProductID); List> clientArray = new ArrayList<>(); - clientArray.add(clientArray(clientID, groupID, savingsProductID,"08 January 2013")); + clientArray.add(clientArray(clientID, groupID, savingsProductID, "08 January 2013")); final Integer gsimID = this.savingsAccountHelper.applyForGsimApplication(clientArray); @@ -368,12 +369,13 @@ public class GroupSavingsIntegrationTest { Calendar todaysDate = Calendar.getInstance(); final String CLOSEDON_DATE = dateFormat.format(todaysDate.getTime()); String withdrawBalance = "false"; - ArrayList savingsAccountErrorData = (ArrayList) validationErrorHelper.closeGsimSavingsAccountAndGetBackRequiredField(gsimID, withdrawBalance, CommonConstants.RESPONSE_ERROR, CLOSEDON_DATE); + ArrayList savingsAccountErrorData = (ArrayList) validationErrorHelper + .closeGsimSavingsAccountAndGetBackRequiredField(gsimID, withdrawBalance, CommonConstants.RESPONSE_ERROR, CLOSEDON_DATE); assertEquals("validation.msg.savingsaccount.close.results.in.balance.not.zero", savingsAccountErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); withdrawBalance = "true"; - savingsStatusHashMap = this.savingsAccountHelper.closeGsimSavingsAccount(gsimID, withdrawBalance); + savingsStatusHashMap = this.savingsAccountHelper.closeGsimSavingsAccount(gsimID, withdrawBalance); SavingsStatusChecker.verifySavingsAccountIsClosed(savingsStatusHashMap); } @@ -401,12 +403,12 @@ public class GroupSavingsIntegrationTest { Assertions.assertNotNull(savingsProductID); List> clientArray = new ArrayList<>(); - clientArray.add(clientArray(clientID, groupID, savingsProductID,"08 January 2013")); + clientArray.add(clientArray(clientID, groupID, savingsProductID, "08 January 2013")); final Integer gsimID = this.savingsAccountHelper.applyForGsimApplication(clientArray); HashMap savingsStatusHashMap = this.savingsAccountHelper.updateGsimApplication(gsimID, clientID, groupID, savingsProductID); - LOG.info("savingsStatusHashMap: {} ",savingsStatusHashMap); + LOG.info("savingsStatusHashMap: {} ", savingsStatusHashMap); Assertions.assertTrue(savingsStatusHashMap.containsKey("savingsId")); } @@ -434,12 +436,12 @@ public class GroupSavingsIntegrationTest { Assertions.assertNotNull(savingsProductID); List> clientArray = new ArrayList<>(); - clientArray.add(clientArray(clientID, groupID, savingsProductID,"08 January 2013")); + clientArray.add(clientArray(clientID, groupID, savingsProductID, "08 January 2013")); final Integer gsimID = this.savingsAccountHelper.applyForGsimApplication(clientArray); - final List retrievedGsimId=GroupHelper.verifyRetrieveGsimAccounts(this.requestSpec, this.responseSpec, groupID); + final List retrievedGsimId = GroupHelper.verifyRetrieveGsimAccounts(this.requestSpec, this.responseSpec, groupID); Assertions.assertNotNull(retrievedGsimId.toString()); - } + } @SuppressWarnings("unchecked") @Test @@ -727,7 +729,8 @@ public class GroupSavingsIntegrationTest { totalWaiveAmount = totalWaiveAmount.add(totalWaiveAmount); assertEquals(totalWaiveAmount.floatValue(), waiveCharge.get("amountWaived")); - final Integer weeklyFeeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, ChargesHelper.getSavingsWeeklyFeeJSON()); + final Integer weeklyFeeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, + ChargesHelper.getSavingsWeeklyFeeJSON()); Assertions.assertNotNull(weeklyFeeId); this.savingsAccountHelper.addChargesForSavings(savingsId, weeklyFeeId, true); @@ -777,7 +780,8 @@ public class GroupSavingsIntegrationTest { return SavingsProductHelper.createSavingsProduct(savingsProductJSON, requestSpec, responseSpec); } - private Map clientArray(final Integer clientId, final Integer groupId, final Integer productId, final String submittedOnDate) { + private Map clientArray(final Integer clientId, final Integer groupId, final Integer productId, + final String submittedOnDate) { Map map = new HashMap<>(); map.put("clientId", clientId); map.put("groupId", groupId); @@ -790,12 +794,13 @@ public class GroupSavingsIntegrationTest { return map; } - private Map savingsArray(final Integer paymentId, final Integer savingsId, final Integer transactionAmount, final String transactionDate) { + private Map savingsArray(final Integer paymentId, final Integer savingsId, final Integer transactionAmount, + final String transactionDate) { Map map = new HashMap<>(); map.put("transactionDate", transactionDate); map.put("dateFormat", CommonConstants.DATE_FORMAT); map.put("locale", "en"); - map.put("transactionAmount",transactionAmount); + map.put("transactionAmount", transactionAmount); map.put("paymentTypeId", paymentId); map.put("childAccountId", savingsId); return map; diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupTest.java old mode 100755 new mode 100644 index 6cc413d04..b38142608 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/GroupTest.java @@ -45,6 +45,7 @@ import org.slf4j.LoggerFactory; * Updating & Deletion */ public class GroupTest { + private final static Logger LOG = LoggerFactory.getLogger(GroupTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -109,11 +110,11 @@ public class GroupTest { // create staff Integer createStaffId1 = StaffHelper.createStaff(this.requestSpec, this.responseSpec); - LOG.info("--------------creating first staff with id------------- {}" , createStaffId1); + LOG.info("--------------creating first staff with id------------- {}", createStaffId1); Assertions.assertNotNull(createStaffId1); Integer createStaffId2 = StaffHelper.createStaff(this.requestSpec, this.responseSpec); - LOG.info("--------------creating second staff with id------------- {}" , createStaffId2); + LOG.info("--------------creating second staff with id------------- {}", createStaffId2); Assertions.assertNotNull(createStaffId2); // assign staff "createStaffId1" to group diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/HookIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/HookIntegrationTest.java index b5582f628..3f70aa75e 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/HookIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/HookIntegrationTest.java @@ -40,6 +40,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HookIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(HookIntegrationTest.class); private RequestSpecification requestSpec; private ResponseSpecification responseSpec; @@ -78,8 +79,8 @@ public class HookIntegrationTest { final String json = RestAssured.get(payloadURL.replace("?", "")).asString(); final Integer notificationOfficeId = JsonPath.with(json).get("officeId"); Assertions.assertEquals(createdOfficeID, notificationOfficeId, - "Equality check for created officeId and hook received payload officeId"); - LOG.info("Notification Office Id - {}" , notificationOfficeId); + "Equality check for created officeId and hook received payload officeId"); + LOG.info("Notification Office Id - {}", notificationOfficeId); i = 6; } catch (Exception e) { TimeUnit.SECONDS.sleep(3); @@ -97,20 +98,20 @@ public class HookIntegrationTest { } @Test - public void createUpdateAndDeleteHook(){ + public void createUpdateAndDeleteHook() { final String payloadURL = "http://echo-webhook.herokuapp.com:80/Z7RXoCBdLSFMDrpn?"; final String updateURL = "http://localhost"; Long hookId = this.hookHelper.createHook(payloadURL).longValue(); Assertions.assertNotNull(hookId); this.hookHelper.verifyHookCreatedOnServer(hookId); - LOG.info("---------------------SUCCESSFULLY CREATED AND VERIFIED HOOK------------------------- {}",hookId); + LOG.info("---------------------SUCCESSFULLY CREATED AND VERIFIED HOOK------------------------- {}", hookId); this.hookHelper.updateHook(updateURL, hookId); this.hookHelper.verifyUpdateHook(updateURL, hookId); - LOG.info("---------------------SUCCESSFULLY UPDATED AND VERIFIED HOOK------------------------- {}",hookId); + LOG.info("---------------------SUCCESSFULLY UPDATED AND VERIFIED HOOK------------------------- {}", hookId); this.hookHelper.deleteHook(hookId); this.hookHelper.verifyDeleteHook(hookId); - LOG.info("---------------------SUCCESSFULLY DELETED AND VERIFIED HOOK------------------------- {}",hookId); + LOG.info("---------------------SUCCESSFULLY DELETED AND VERIFIED HOOK------------------------- {}", hookId); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanApplicationApprovalTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanApplicationApprovalTest.java index 6a314e539..e52094954 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanApplicationApprovalTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanApplicationApprovalTest.java @@ -42,6 +42,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings("rawtypes") public class LoanApplicationApprovalTest { + private final static Logger LOG = LoggerFactory.getLogger(LoanApplicationApprovalTest.class); private ResponseSpecification responseSpec; private ResponseSpecification responseSpecForStatusCode403; @@ -130,14 +131,13 @@ public class LoanApplicationApprovalTest { createTranches.add(createTrancheDetail("23 March 2014", "4000")); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014"); - LOG.info("---------------------------------CLIENT CREATED WITH ID--------------------------------------------------- {}" - , clientID); + LOG.info("---------------------------------CLIENT CREATED WITH ID--------------------------------------------------- {}", clientID); - final Integer loanProductID = this.loanTransactionHelper.getLoanProductId(new LoanProductTestBuilder() - .withInterestTypeAsDecliningBalance().withTranches(true).withInterestCalculationPeriodTypeAsRepaymentPeriod(true) - .build(null)); - LOG.info("----------------------------------LOAN PRODUCT CREATED WITH ID------------------------------------------- {}" - , loanProductID); + final Integer loanProductID = this.loanTransactionHelper + .getLoanProductId(new LoanProductTestBuilder().withInterestTypeAsDecliningBalance().withTranches(true) + .withInterestCalculationPeriodTypeAsRepaymentPeriod(true).build(null)); + LOG.info("----------------------------------LOAN PRODUCT CREATED WITH ID------------------------------------------- {}", + loanProductID); this.trancheLoansApprovedAmountLesserThanProposedAmount(clientID, loanProductID, createTranches); this.trancheLoansApprovalValidation(clientID, loanProductID, createTranches); @@ -155,8 +155,7 @@ public class LoanApplicationApprovalTest { approveTranches.add(createTrancheDetail("23 March 2014", "1000")); final Integer loanID = applyForLoanApplicationWithTranches(clientID, loanProductID, proposedAmount, createTranches); - LOG.info("-----------------------------------LOAN CREATED WITH LOANID------------------------------------------------- {}" - , loanID); + LOG.info("-----------------------------------LOAN CREATED WITH LOANID------------------------------------------------- {}", loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); @@ -201,8 +200,7 @@ public class LoanApplicationApprovalTest { approveTranche4.add(createTrancheDetail("24 March 2014", "100")); final Integer loanID = applyForLoanApplicationWithTranches(clientID, loanProductID, proposedAmount, createTranches); - LOG.info("-----------------------------------LOAN CREATED WITH LOANID------------------------------------------------- {}" - , loanID); + LOG.info("-----------------------------------LOAN CREATED WITH LOANID------------------------------------------------- {}", loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); @@ -233,8 +231,8 @@ public class LoanApplicationApprovalTest { /* No. of tranches exceeds the max tranche count at product level */ error = this.loanTransactionHelper.approveLoanForTranches(approveDate, expectedDisbursementDate, approvalAmount3, loanID, approveTranche3, CommonConstants.RESPONSE_ERROR); - assertEquals("error.msg.disbursementData.exceeding.max.tranche.count", error.get(0) - .get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); + assertEquals("error.msg.disbursementData.exceeding.max.tranche.count", + error.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE)); /* If tranches are not specified for a multi-disburse loan */ /** @@ -259,7 +257,7 @@ public class LoanApplicationApprovalTest { List tranches) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() - // + // .withPrincipal(principal) // .withLoanTermFrequency("5") diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanApplicationUndoLastTrancheTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanApplicationUndoLastTrancheTest.java index b8a0cc297..4544dc2ec 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanApplicationUndoLastTrancheTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanApplicationUndoLastTrancheTest.java @@ -40,6 +40,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings("rawtypes") public class LoanApplicationUndoLastTrancheTest { + private final static Logger LOG = LoggerFactory.getLogger(LoanApplicationUndoLastTrancheTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -67,15 +68,14 @@ public class LoanApplicationUndoLastTrancheTest { // CREATE CLIENT final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014"); - LOG.info("---------------------------------CLIENT CREATED WITH ID--------------------------------------------------- {}" - , clientID); + LOG.info("---------------------------------CLIENT CREATED WITH ID--------------------------------------------------- {}", clientID); // CREATE LOAN MULTIDISBURSAL PRODUCT - final Integer loanProductID = this.loanTransactionHelper.getLoanProductId(new LoanProductTestBuilder() - .withInterestTypeAsDecliningBalance().withTranches(true).withInterestCalculationPeriodTypeAsRepaymentPeriod(true) - .build(null)); - LOG.info("----------------------------------LOAN PRODUCT CREATED WITH ID------------------------------------------- {}" - , loanProductID); + final Integer loanProductID = this.loanTransactionHelper + .getLoanProductId(new LoanProductTestBuilder().withInterestTypeAsDecliningBalance().withTranches(true) + .withInterestCalculationPeriodTypeAsRepaymentPeriod(true).build(null)); + LOG.info("----------------------------------LOAN PRODUCT CREATED WITH ID------------------------------------------- {}", + loanProductID); // CREATE TRANCHES List createTranches = new ArrayList<>(); @@ -89,8 +89,7 @@ public class LoanApplicationUndoLastTrancheTest { // APPLY FOR LOAN WITH TRANCHES final Integer loanID = applyForLoanApplicationWithTranches(clientID, loanProductID, proposedAmount, createTranches); - LOG.info("-----------------------------------LOAN CREATED WITH LOANID------------------------------------------------- {}" - , loanID); + LOG.info("-----------------------------------LOAN CREATED WITH LOANID------------------------------------------------- {}", loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); // VALIDATE THE LOAN STATUS @@ -133,7 +132,7 @@ public class LoanApplicationUndoLastTrancheTest { List tranches) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() - // + // .withPrincipal(principal) // .withLoanTermFrequency("5") diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanDisbursalDateValidationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanDisbursalDateValidationTest.java index 639fc1f08..139233a85 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanDisbursalDateValidationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanDisbursalDateValidationTest.java @@ -40,6 +40,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings("rawtypes") public class LoanDisbursalDateValidationTest { + private final static Logger LOG = LoggerFactory.getLogger(LoanDisbursalDateValidationTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -65,19 +66,17 @@ public class LoanDisbursalDateValidationTest { // CREATE CLIENT final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014"); - LOG.info("---------------------------------CLIENT CREATED WITH ID--------------------------------------------------- {}" - , clientID); + LOG.info("---------------------------------CLIENT CREATED WITH ID--------------------------------------------------- {}", clientID); - // CREATE LOAN PRODUCT - final Integer loanProductID = this.loanTransactionHelper.getLoanProductId(new LoanProductTestBuilder() - .withSyncExpectedWithDisbursementDate(true).build(null)); - LOG.info("----------------------------------LOAN PRODUCT CREATED WITH ID------------------------------------------- {}" - , loanProductID); + // CREATE LOAN PRODUCT + final Integer loanProductID = this.loanTransactionHelper + .getLoanProductId(new LoanProductTestBuilder().withSyncExpectedWithDisbursementDate(true).build(null)); + LOG.info("----------------------------------LOAN PRODUCT CREATED WITH ID------------------------------------------- {}", + loanProductID); // APPLY FOR LOAN final Integer loanID = applyForLoanApplication(clientID, loanProductID, proposedAmount); - LOG.info("-----------------------------------LOAN CREATED WITH LOANID------------------------------------------------- {}" - , loanID); + LOG.info("-----------------------------------LOAN CREATED WITH LOANID------------------------------------------------- {}", loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); // VALIDATE THE LOAN STATUS @@ -92,7 +91,8 @@ public class LoanDisbursalDateValidationTest { // DISBURSE A LOAN @SuppressWarnings("unchecked") - List disbursalError = (List) this.loanTransactionHelper.disburseLoan(disbursalDate, loanID, this.responseForbiddenError); + List disbursalError = (List) this.loanTransactionHelper.disburseLoan(disbursalDate, loanID, + this.responseForbiddenError); Assertions.assertEquals(disbursalError.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE), "error.msg.actual.disbursement.date.does.not.match.with.expected.disbursal.date"); @@ -100,18 +100,11 @@ public class LoanDisbursalDateValidationTest { } private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID, final String proposedAmount) { - final String loanApplication = new LoanApplicationTestBuilder() - .withPrincipal(proposedAmount).withLoanTermFrequency("5") - .withLoanTermFrequencyAsMonths().withNumberOfRepayments("5") - .withRepaymentEveryAfter("1") - .withRepaymentFrequencyTypeAsMonths() - .withInterestRatePerPeriod("2") - .withExpectedDisbursementDate("1 March 2014") - .withSubmittedOnDate("26 February 2014"). - build(clientID.toString(), loanProductID.toString(), null); + final String loanApplication = new LoanApplicationTestBuilder().withPrincipal(proposedAmount).withLoanTermFrequency("5") + .withLoanTermFrequencyAsMonths().withNumberOfRepayments("5").withRepaymentEveryAfter("1") + .withRepaymentFrequencyTypeAsMonths().withInterestRatePerPeriod("2").withExpectedDisbursementDate("1 March 2014") + .withSubmittedOnDate("26 February 2014").build(clientID.toString(), loanProductID.toString(), null); return this.loanTransactionHelper.getLoanId(loanApplication); } - - } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanDisbursementDetailsIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanDisbursementDetailsIntegrationTest.java index 68124c9d5..1bf251be8 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanDisbursementDetailsIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanDisbursementDetailsIntegrationTest.java @@ -44,6 +44,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "rawtypes", "unchecked" }) public class LoanDisbursementDetailsIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(LoanDisbursementDetailsIntegrationTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -75,20 +76,19 @@ public class LoanDisbursementDetailsIntegrationTest { createTranches.add(this.loanTransactionHelper.createTrancheDetail(id, "01 Sep 2015", "5000")); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014"); - LOG.info("---------------------------------CLIENT CREATED WITH ID---------------------------------------------------{}" - , clientID); + LOG.info("---------------------------------CLIENT CREATED WITH ID---------------------------------------------------{}", clientID); final Integer loanProductID = this.loanTransactionHelper.getLoanProductId(new LoanProductTestBuilder() .withInterestTypeAsDecliningBalance().withMoratorium("", "").withAmortizationTypeAsEqualInstallments().withTranches(true) .withInterestCalculationPeriodTypeAsRepaymentPeriod(true).build(null)); - LOG.info("----------------------------------LOAN PRODUCT CREATED WITH ID------------------------------------------- {}" - , loanProductID); + LOG.info("----------------------------------LOAN PRODUCT CREATED WITH ID------------------------------------------- {}", + loanProductID); final Integer loanIDWithEmi = applyForLoanApplicationWithEmiAmount(clientID, loanProductID, proposedAmount, createTranches, installmentAmount); - LOG.info("-----------------------------------LOAN CREATED WITH EMI LOANID------------------------------------------------- {}" - , loanIDWithEmi); + LOG.info("-----------------------------------LOAN CREATED WITH EMI LOANID------------------------------------------------- {}", + loanIDWithEmi); HashMap repaymentScheduleWithEmi = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, loanIDWithEmi, "repaymentSchedule"); @@ -106,7 +106,8 @@ public class LoanDisbursementDetailsIntegrationTest { createTranches); LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); - LOG.info("-----------------------------------MULTI DISBURSAL LOAN WITH EMI APPROVED SUCCESSFULLY---------------------------------------"); + LOG.info( + "-----------------------------------MULTI DISBURSAL LOAN WITH EMI APPROVED SUCCESSFULLY---------------------------------------"); final Integer loanIDWithoutEmi = applyForLoanApplicationWithEmiAmount(clientID, loanProductID, proposedAmount, createTranches, withoutInstallmentAmount); @@ -117,8 +118,8 @@ public class LoanDisbursementDetailsIntegrationTest { ArrayList periods1 = (ArrayList) repaymentScheduleWithEmi.get("periods"); assertEquals(15, periods1.size()); - LOG.info("-----------------------------------LOAN CREATED WITHOUT EMI LOANID------------------------------------------------- {}" - , loanIDWithoutEmi); + LOG.info("-----------------------------------LOAN CREATED WITHOUT EMI LOANID------------------------------------------------- {}", + loanIDWithoutEmi); /* To be uncommented once issue MIFOSX-2006 is closed. */ // this.validateRepaymentScheduleWithoutEMI(periods1); @@ -131,7 +132,8 @@ public class LoanDisbursementDetailsIntegrationTest { loanIDWithoutEmi, createTranches); LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); - LOG.info("-----------------------------------MULTI DISBURSAL LOAN WITHOUT EMI APPROVED SUCCESSFULLY---------------------------------------"); + LOG.info( + "-----------------------------------MULTI DISBURSAL LOAN WITHOUT EMI APPROVED SUCCESSFULLY---------------------------------------"); } @@ -207,9 +209,9 @@ public class LoanDisbursementDetailsIntegrationTest { assertEquals(period.get("dueDate").toString(), expectedRepaymentSchedule.getDueDate()); assertEquals(period.get("principalLoanBalanceOutstanding"), expectedRepaymentSchedule.getPrincipalLoanBalanceOutstanding()); - LOG.info("{}",period.get("totalOriginalDueForPeriod").toString()); - assertEquals(Float.valueOf(period.get("totalOriginalDueForPeriod").toString()), expectedRepaymentSchedule - .getTotalOriginalDueForPeriod().floatValue(), 0.0f); + LOG.info("{}", period.get("totalOriginalDueForPeriod").toString()); + assertEquals(Float.valueOf(period.get("totalOriginalDueForPeriod").toString()), + expectedRepaymentSchedule.getTotalOriginalDueForPeriod().floatValue(), 0.0f); assertEquals(Float.valueOf(period.get("totalOutstandingForPeriod").toString()).floatValue(), expectedRepaymentSchedule.getTotalOutstandingForPeriod(), 0.0f); @@ -220,7 +222,8 @@ public class LoanDisbursementDetailsIntegrationTest { expectedRepaymentSchedule.getInterestOutstanding(), 0.0f); assertEquals(Float.valueOf(period.get("principalOutstanding").toString()).floatValue(), expectedRepaymentSchedule.getPrincipalOutstanding(), 0.0f); - assertEquals(Float.valueOf(period.get("principalDue").toString()).floatValue(), expectedRepaymentSchedule.getPrincipalDue(), 0.0f); + assertEquals(Float.valueOf(period.get("principalDue").toString()).floatValue(), expectedRepaymentSchedule.getPrincipalDue(), + 0.0f); assertEquals(Float.valueOf(period.get("principalOriginalDue").toString()).floatValue(), expectedRepaymentSchedule.getPrincipalOriginalDue(), 0.0f); assertEquals(period.get("fromDate").toString(), expectedRepaymentSchedule.getFromDate()); @@ -342,7 +345,7 @@ public class LoanDisbursementDetailsIntegrationTest { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() - // + // .withPrincipal(proposedAmount) // .withLoanTermFrequency("12") @@ -364,25 +367,23 @@ public class LoanDisbursementDetailsIntegrationTest { } @Test - public void createApproveAndValidateMultiDisburseLoan() throws ParseException{ + public void createApproveAndValidateMultiDisburseLoan() throws ParseException { List createTranches = new ArrayList<>(); String id = null; createTranches.add(this.loanTransactionHelper.createTrancheDetail(id, "01 March 2014", "1000")); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014"); - LOG.info("---------------------------------CLIENT CREATED WITH ID--------------------------------------------------- {}" - , clientID); + LOG.info("---------------------------------CLIENT CREATED WITH ID--------------------------------------------------- {}", clientID); - final Integer loanProductID = this.loanTransactionHelper.getLoanProductId(new LoanProductTestBuilder() - .withInterestTypeAsDecliningBalance().withTranches(true).withInterestCalculationPeriodTypeAsRepaymentPeriod(true) - .build(null)); - LOG.info("----------------------------------LOAN PRODUCT CREATED WITH ID------------------------------------------- {}" - , loanProductID); + final Integer loanProductID = this.loanTransactionHelper + .getLoanProductId(new LoanProductTestBuilder().withInterestTypeAsDecliningBalance().withTranches(true) + .withInterestCalculationPeriodTypeAsRepaymentPeriod(true).build(null)); + LOG.info("----------------------------------LOAN PRODUCT CREATED WITH ID------------------------------------------- {}", + loanProductID); this.loanID = applyForLoanApplicationWithTranches(clientID, loanProductID, proposedAmount, createTranches); - LOG.info("-----------------------------------LOAN CREATED WITH LOANID------------------------------------------------- {}" - , loanID); + LOG.info("-----------------------------------LOAN CREATED WITH LOANID------------------------------------------------- {}", loanID); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); @@ -423,7 +424,7 @@ public class LoanDisbursementDetailsIntegrationTest { addTranches, ""); } - private void deleteDisbursmentDetails() throws ParseException{ + private void deleteDisbursmentDetails() throws ParseException { List deleteTranches = new ArrayList<>(); ArrayList disbursementDetails = (ArrayList) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec, this.loanID, "disbursementDetails"); @@ -440,7 +441,7 @@ public class LoanDisbursementDetailsIntegrationTest { deleteTranches, ""); } - private void editDateAndPrincipalOfExistingTranche() throws ParseException{ + private void editDateAndPrincipalOfExistingTranche() throws ParseException { String updatedExpectedDisbursementDate = "01 March 2014"; String updatedPrincipal = "900"; /* Update */ @@ -469,7 +470,7 @@ public class LoanDisbursementDetailsIntegrationTest { List tranches) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() - // + // .withPrincipal(principal) // .withLoanTermFrequency("5") diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanRepaymentRescheduleAtDisbursementTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanRepaymentRescheduleAtDisbursementTest.java index 803c01356..d71668c5a 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanRepaymentRescheduleAtDisbursementTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanRepaymentRescheduleAtDisbursementTest.java @@ -45,6 +45,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings("rawtypes") public class LoanRepaymentRescheduleAtDisbursementTest { + private final static Logger LOG = LoggerFactory.getLogger(LoanRepaymentRescheduleAtDisbursementTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -65,7 +66,7 @@ public class LoanRepaymentRescheduleAtDisbursementTest { @SuppressWarnings("unchecked") @Test - public void testLoanRepaymentRescheduleAtDisbursement(){ + public void testLoanRepaymentRescheduleAtDisbursement() { final String approvalAmount = "10000"; final String approveDate = "01 March 2015"; @@ -75,8 +76,7 @@ public class LoanRepaymentRescheduleAtDisbursementTest { // CREATE CLIENT final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014"); - LOG.info("---------------------------------CLIENT CREATED WITH ID--------------------------------------------------- {}" - , clientID); + LOG.info("---------------------------------CLIENT CREATED WITH ID--------------------------------------------------- {}", clientID); // CREATE LOAN MULTIDISBURSAL PRODUCT WITH INTEREST RECALCULATION final Integer loanProductID = createLoanProductWithInterestRecalculation(LoanProductTestBuilder.RBI_INDIA_STRATEGY, @@ -116,8 +116,9 @@ public class LoanRepaymentRescheduleAtDisbursementTest { this.loanTransactionHelper.disburseLoanWithRepaymentReschedule(disbursementDate, loanID, adjustRepaymentDate); loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); - ArrayList loanRepaymnetSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(requestSpec, generalResponseSpec, loanID); - HashMap firstInstallement = loanRepaymnetSchedule.get(1); + ArrayList loanRepaymnetSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(requestSpec, generalResponseSpec, + loanID); + HashMap firstInstallement = loanRepaymnetSchedule.get(1); Map expectedvalues = new HashMap<>(3); Calendar date = Calendar.getInstance(Utils.getTimeZoneOfTenant()); date.set(2015, Calendar.MARCH, 16); @@ -170,17 +171,10 @@ public class LoanRepaymentRescheduleAtDisbursementTest { final Integer recalculationCompoundingFrequencyDayOfWeekType, final Integer recalculationRestFrequencyOnDayType, final Integer recalculationRestFrequencyDayOfWeekType) { LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); - LoanProductTestBuilder builder = new LoanProductTestBuilder() - .withPrincipal("10000.00") - .withNumberOfRepayments("12") - .withRepaymentAfterEvery("2") - .withRepaymentTypeAsWeek() - .withinterestRatePerPeriod("2") - .withInterestRateFrequencyTypeAsMonths() - .withTranches(true) - .withInterestCalculationPeriodTypeAsRepaymentPeriod(true) - .withRepaymentStrategy(repaymentStrategy) - .withInterestTypeAsDecliningBalance() + LoanProductTestBuilder builder = new LoanProductTestBuilder().withPrincipal("10000.00").withNumberOfRepayments("12") + .withRepaymentAfterEvery("2").withRepaymentTypeAsWeek().withinterestRatePerPeriod("2") + .withInterestRateFrequencyTypeAsMonths().withTranches(true).withInterestCalculationPeriodTypeAsRepaymentPeriod(true) + .withRepaymentStrategy(repaymentStrategy).withInterestTypeAsDecliningBalance() .withInterestRecalculationDetails(interestRecalculationCompoundingMethod, rescheduleStrategyMethod, preCloseInterestCalculationStrategy) .withInterestRecalculationRestFrequencyDetails(recalculationRestFrequencyType, recalculationRestFrequencyInterval, @@ -193,7 +187,7 @@ public class LoanRepaymentRescheduleAtDisbursementTest { } if (isArrearsBasedOnOriginalSchedule) { - builder = builder.withArrearsConfiguration(); + builder = builder.withArrearsConfiguration(); } final String loanProductJSON = builder.build(chargeId); @@ -221,8 +215,7 @@ public class LoanRepaymentRescheduleAtDisbursementTest { .withRepaymentFrequencyTypeAsWeeks() // .withInterestRatePerPeriod("2") // .withAmortizationTypeAsEqualInstallments() // - .withTranches(tranches) - .withFixedEmiAmount("") // + .withTranches(tranches).withFixedEmiAmount("") // .withInterestTypeAsDecliningBalance() // .withInterestCalculationPeriodTypeAsDays() // .withInterestCalculationPeriodTypeAsDays() // @@ -240,7 +233,6 @@ public class LoanRepaymentRescheduleAtDisbursementTest { private List getDateAsArray(Calendar date, int addvalue, int type) { date.add(type, addvalue); - return new ArrayList<>(Arrays.asList(date.get(Calendar.YEAR), date.get(Calendar.MONTH) + 1, - date.get(Calendar.DAY_OF_MONTH))); + return new ArrayList<>(Arrays.asList(date.get(Calendar.YEAR), date.get(Calendar.MONTH) + 1, date.get(Calendar.DAY_OF_MONTH))); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanRescheduleRequestTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanRescheduleRequestTest.java index 4a81bc326..b33833589 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanRescheduleRequestTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanRescheduleRequestTest.java @@ -44,6 +44,7 @@ import org.slf4j.LoggerFactory; **/ @SuppressWarnings({ "rawtypes" }) public class LoanRescheduleRequestTest { + private final static Logger LOG = LoggerFactory.getLogger(LoanRescheduleRequestTest.class); private ResponseSpecification responseSpec; private ResponseSpecification generalResponseSpec; @@ -98,15 +99,12 @@ public class LoanRescheduleRequestTest { private void createLoanProductEntity() { LOG.info("---------------------------------CREATING LOAN PRODUCT------------------------------------------"); - final String loanProductJSON = new LoanProductTestBuilder() - .withPrincipal(loanPrincipalAmount) - .withNumberOfRepayments(numberOfRepayments) - .withinterestRatePerPeriod(interestRatePerPeriod) - .withInterestRateFrequencyTypeAsYear() - .build(null); + final String loanProductJSON = new LoanProductTestBuilder().withPrincipal(loanPrincipalAmount) + .withNumberOfRepayments(numberOfRepayments).withinterestRatePerPeriod(interestRatePerPeriod) + .withInterestRateFrequencyTypeAsYear().build(null); this.loanProductId = this.loanTransactionHelper.getLoanProductId(loanProductJSON); - LOG.info("Successfully created loan product (ID:{}) " , this.loanProductId); + LOG.info("Successfully created loan product (ID:{}) ", this.loanProductId); } /** @@ -115,26 +113,16 @@ public class LoanRescheduleRequestTest { private void createLoanEntity() { LOG.info("---------------------------------NEW LOAN APPLICATION------------------------------------------"); - final String loanApplicationJSON = new LoanApplicationTestBuilder() - .withPrincipal(loanPrincipalAmount) - .withLoanTermFrequency(numberOfRepayments) - .withLoanTermFrequencyAsMonths() - .withNumberOfRepayments(numberOfRepayments) - .withRepaymentEveryAfter("1") - .withRepaymentFrequencyTypeAsMonths() - .withAmortizationTypeAsEqualInstallments() - .withInterestCalculationPeriodTypeAsDays() - .withInterestRatePerPeriod(interestRatePerPeriod) - .withLoanTermFrequencyAsMonths() - .withSubmittedOnDate(dateString) - .withExpectedDisbursementDate(dateString) - .withPrincipalGrace("2") - .withInterestGrace("2") + final String loanApplicationJSON = new LoanApplicationTestBuilder().withPrincipal(loanPrincipalAmount) + .withLoanTermFrequency(numberOfRepayments).withLoanTermFrequencyAsMonths().withNumberOfRepayments(numberOfRepayments) + .withRepaymentEveryAfter("1").withRepaymentFrequencyTypeAsMonths().withAmortizationTypeAsEqualInstallments() + .withInterestCalculationPeriodTypeAsDays().withInterestRatePerPeriod(interestRatePerPeriod).withLoanTermFrequencyAsMonths() + .withSubmittedOnDate(dateString).withExpectedDisbursementDate(dateString).withPrincipalGrace("2").withInterestGrace("2") .build(this.clientId.toString(), this.loanProductId.toString(), null); this.loanId = this.loanTransactionHelper.getLoanId(loanApplicationJSON); - LOG.info("Sucessfully created loan (ID: {} )" , this.loanId); + LOG.info("Sucessfully created loan (ID: {} )", this.loanId); this.approveLoanApplication(); this.disburseLoan(); @@ -145,9 +133,9 @@ public class LoanRescheduleRequestTest { **/ private void approveLoanApplication() { - if(this.loanId != null) { + if (this.loanId != null) { this.loanTransactionHelper.approveLoan(this.dateString, this.loanId); - LOG.info("Successfully approved loan (ID: {} )" , this.loanId); + LOG.info("Successfully approved loan (ID: {} )", this.loanId); } } @@ -156,9 +144,9 @@ public class LoanRescheduleRequestTest { **/ private void disburseLoan() { - if(this.loanId != null) { + if (this.loanId != null) { this.loanTransactionHelper.disburseLoan(this.dateString, this.loanId); - LOG.info("Successfully disbursed loan (ID: {} )" , this.loanId); + LOG.info("Successfully disbursed loan (ID: {} )", this.loanId); } } @@ -173,7 +161,7 @@ public class LoanRescheduleRequestTest { this.loanRescheduleRequestId = this.loanRescheduleRequestHelper.createLoanRescheduleRequest(requestJSON); this.loanRescheduleRequestHelper.verifyCreationOfLoanRescheduleRequest(this.loanRescheduleRequestId); - LOG.info("Successfully created loan reschedule request (ID: {} )" , this.loanRescheduleRequestId); + LOG.info("Successfully created loan reschedule request (ID: {} )", this.loanRescheduleRequestId); } @Test @@ -191,9 +179,9 @@ public class LoanRescheduleRequestTest { this.loanRescheduleRequestHelper.rejectLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON); final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum"); - assertTrue((Boolean)response.get("rejected")); + assertTrue((Boolean) response.get("rejected")); - LOG.info("Successfully rejected loan reschedule request (ID: {} )" , this.loanRescheduleRequestId); + LOG.info("Successfully rejected loan reschedule request (ID: {} )", this.loanRescheduleRequestId); } @Test @@ -206,15 +194,16 @@ public class LoanRescheduleRequestTest { this.loanRescheduleRequestHelper.approveLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON); final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum"); - assertTrue((Boolean)response.get("approved")); + assertTrue((Boolean) response.get("approved")); - final Integer numberOfRepayments = (Integer) this.loanTransactionHelper.getLoanDetail(requestSpec, generalResponseSpec, loanId, "numberOfRepayments"); + final Integer numberOfRepayments = (Integer) this.loanTransactionHelper.getLoanDetail(requestSpec, generalResponseSpec, loanId, + "numberOfRepayments"); final HashMap loanSummary = this.loanTransactionHelper.getLoanSummary(requestSpec, generalResponseSpec, loanId); final Float totalExpectedRepayment = (Float) loanSummary.get("totalExpectedRepayment"); assertEquals(12, numberOfRepayments, "NUMBER OF REPAYMENTS is NOK"); assertEquals(118000, totalExpectedRepayment, "TOTAL EXPECTED REPAYMENT is NOK"); - LOG.info("Successfully approved loan reschedule request (ID: {})" , this.loanRescheduleRequestId); + LOG.info("Successfully approved loan reschedule request (ID: {})", this.loanRescheduleRequestId); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanReschedulingWithinCenterTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanReschedulingWithinCenterTest.java index 80e1b2e6e..59bc15b93 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanReschedulingWithinCenterTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanReschedulingWithinCenterTest.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.integrationtests; - import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.gson.Gson; @@ -56,6 +55,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoanReschedulingWithinCenterTest { + private final static Logger LOG = LoggerFactory.getLogger(LoanReschedulingWithinCenterTest.class); private RequestSpecification requestSpec; private ResponseSpecification responseSpec; @@ -114,8 +114,7 @@ public class LoanReschedulingWithinCenterTest { LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, LoanProductTestBuilder.RECALCULATION_STRATEGY_REDUCE_NUMBER_OF_INSTALLMENTS, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_DAILY, "0", recalculationRestFrequencyDate, - LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, isMultiTrancheLoan, - null, null); + LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, isMultiTrancheLoan, null, null); // APPLY FOR TRANCHE LOAN WITH INTEREST RECALCULATION final Integer loanId = applyForLoanApplicationForInterestRecalculation(clientId, groupId, calendarId, loanProductID, disbursalDate, @@ -177,13 +176,13 @@ public class LoanReschedulingWithinCenterTest { final String interval = "2"; // Every one week Integer repeatsOnDay = today.get(Calendar.DAY_OF_WEEK) - 1; - if (repeatsOnDay.intValue() == 0){ + if (repeatsOnDay.intValue() == 0) { repeatsOnDay = 7; } Integer calendarId = CalendarHelper.createMeetingForGroup(this.requestSpec, this.responseSpec, centerId, startDate, frequency, interval, repeatsOnDay.toString()); - LOG.info("calendarId {}" , calendarId); + LOG.info("calendarId {}", calendarId); return calendarId; } @@ -229,12 +228,11 @@ public class LoanReschedulingWithinCenterTest { LoanProductTestBuilder.RECALCULATION_COMPOUNDING_METHOD_NONE, LoanProductTestBuilder.RECALCULATION_STRATEGY_REDUCE_NUMBER_OF_INSTALLMENTS, LoanProductTestBuilder.RECALCULATION_FREQUENCY_TYPE_DAILY, "0", recalculationRestFrequencyDate, - LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, isMultiTrancheLoan, - null, null); + LoanProductTestBuilder.INTEREST_APPLICABLE_STRATEGY_ON_PRE_CLOSE_DATE, null, isMultiTrancheLoan, null, null); Calendar seondTrancheDate = Calendar.getInstance(Utils.getTimeZoneOfTenant()); seondTrancheDate.add(Calendar.MONTH, 1); - String secondDisbursement = dateFormat.format(seondTrancheDate.getTime()) ; + String secondDisbursement = dateFormat.format(seondTrancheDate.getTime()); // CREATE TRANCHES List createTranches = new ArrayList<>(); @@ -290,7 +288,8 @@ public class LoanReschedulingWithinCenterTest { final String interestRecalculationCompoundingMethod, final String rescheduleStrategyMethod, final String recalculationRestFrequencyType, final String recalculationRestFrequencyInterval, final String recalculationRestFrequencyDate, final String preCloseInterestCalculationStrategy, final Account[] accounts, - final boolean isMultiTrancheLoan, final Integer recalculationRestFrequencyOnDayType, final Integer recalculationRestFrequencyDayOfWeekType) { + final boolean isMultiTrancheLoan, final Integer recalculationRestFrequencyOnDayType, + final Integer recalculationRestFrequencyDayOfWeekType) { final String recalculationCompoundingFrequencyType = null; final String recalculationCompoundingFrequencyInterval = null; final String recalculationCompoundingFrequencyDate = null; @@ -300,8 +299,8 @@ public class LoanReschedulingWithinCenterTest { rescheduleStrategyMethod, recalculationRestFrequencyType, recalculationRestFrequencyInterval, recalculationRestFrequencyDate, recalculationCompoundingFrequencyType, recalculationCompoundingFrequencyInterval, recalculationCompoundingFrequencyDate, preCloseInterestCalculationStrategy, accounts, null, false, isMultiTrancheLoan, - recalculationCompoundingFrequencyOnDayType, recalculationCompoundingFrequencyDayOfWeekType, recalculationRestFrequencyOnDayType, - recalculationRestFrequencyDayOfWeekType); + recalculationCompoundingFrequencyOnDayType, recalculationCompoundingFrequencyDayOfWeekType, + recalculationRestFrequencyOnDayType, recalculationRestFrequencyDayOfWeekType); } private Integer createLoanProductWithInterestRecalculation(final String repaymentStrategy, @@ -311,20 +310,13 @@ public class LoanReschedulingWithinCenterTest { final String recalculationCompoundingFrequencyInterval, final String recalculationCompoundingFrequencyDate, final String preCloseInterestCalculationStrategy, final Account[] accounts, final String chargeId, boolean isArrearsBasedOnOriginalSchedule, final boolean isMultiTrancheLoan, - final Integer recalculationCompoundingFrequencyOnDayType, - final Integer recalculationCompoundingFrequencyDayOfWeekType, final Integer recalculationRestFrequencyOnDayType, - final Integer recalculationRestFrequencyDayOfWeekType) { + final Integer recalculationCompoundingFrequencyOnDayType, final Integer recalculationCompoundingFrequencyDayOfWeekType, + final Integer recalculationRestFrequencyOnDayType, final Integer recalculationRestFrequencyDayOfWeekType) { LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); - LoanProductTestBuilder builder = new LoanProductTestBuilder() - .withPrincipal("10000.00") - .withNumberOfRepayments("12") - .withRepaymentAfterEvery("2") - .withRepaymentTypeAsWeek() - .withinterestRatePerPeriod("2") - .withInterestRateFrequencyTypeAsMonths() - .withTranches(isMultiTrancheLoan) - .withInterestCalculationPeriodTypeAsRepaymentPeriod(true) - .withRepaymentStrategy(repaymentStrategy) + LoanProductTestBuilder builder = new LoanProductTestBuilder().withPrincipal("10000.00").withNumberOfRepayments("12") + .withRepaymentAfterEvery("2").withRepaymentTypeAsWeek().withinterestRatePerPeriod("2") + .withInterestRateFrequencyTypeAsMonths().withTranches(isMultiTrancheLoan) + .withInterestCalculationPeriodTypeAsRepaymentPeriod(true).withRepaymentStrategy(repaymentStrategy) .withInterestTypeAsDecliningBalance() .withInterestRecalculationDetails(interestRecalculationCompoundingMethod, rescheduleStrategyMethod, preCloseInterestCalculationStrategy) @@ -395,8 +387,8 @@ public class LoanReschedulingWithinCenterTest { map.put("active", "true"); map.put("activationDate", "04 March 2011"); - groupMembers[i] = Utils.performServerPost(requestSpec, responseSpec, "/fineract-provider/api/v1/groups?" - + Utils.TENANT_IDENTIFIER, new Gson().toJson(map), "groupId"); + groupMembers[i] = Utils.performServerPost(requestSpec, responseSpec, + "/fineract-provider/api/v1/groups?" + Utils.TENANT_IDENTIFIER, new Gson().toJson(map), "groupId"); } return groupMembers; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanWithWaiveInterestAndWriteOffIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanWithWaiveInterestAndWriteOffIntegrationTest.java index eccb78c44..0e9173e33 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanWithWaiveInterestAndWriteOffIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/LoanWithWaiveInterestAndWriteOffIntegrationTest.java @@ -42,6 +42,7 @@ import org.slf4j.LoggerFactory; */ @SuppressWarnings({ "rawtypes" }) public class LoanWithWaiveInterestAndWriteOffIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(LoanWithWaiveInterestAndWriteOffIntegrationTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -101,7 +102,7 @@ public class LoanWithWaiveInterestAndWriteOffIntegrationTest { // DISBURSE loanStatusHashMap = this.loanTransactionHelper.disburseLoan(this.DISBURSEMENT_DATE, loanID); - LOG.info("DISBURSE {}" , loanStatusHashMap.toString()); + LOG.info("DISBURSE {}", loanStatusHashMap.toString()); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); // PERFORM REPAYMENTS AND CHECK LOAN STATUS @@ -114,7 +115,7 @@ public class LoanWithWaiveInterestAndWriteOffIntegrationTest { // DIBURSE AGAIN loanStatusHashMap = this.loanTransactionHelper.disburseLoan(this.DISBURSEMENT_DATE, loanID); - LOG.info("DISBURSE {}" , loanStatusHashMap); + LOG.info("DISBURSE {}", loanStatusHashMap); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); // MAKE REPAYMENTS @@ -160,7 +161,7 @@ public class LoanWithWaiveInterestAndWriteOffIntegrationTest { // DISBURSE loanStatusHashMap = this.loanTransactionHelper.disburseLoan(this.DISBURSEMENT_DATE, loanID); - LOG.info("DISBURSE {}" , loanStatusHashMap); + LOG.info("DISBURSE {}", loanStatusHashMap); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); // MAKE REPAYMENTS @@ -174,17 +175,21 @@ public class LoanWithWaiveInterestAndWriteOffIntegrationTest { "Checking for Principal paid "); Assertions.assertTrue(Float.valueOf("180.0").compareTo(Float.valueOf(String.valueOf(toLoanSummaryAfter.get("interestPaid")))) == 0, "Checking for interestPaid paid "); - Assertions.assertTrue(Float.valueOf("680.0").compareTo(Float.valueOf(String.valueOf(toLoanSummaryAfter.get("totalRepayment")))) == 0, + Assertions.assertTrue( + Float.valueOf("680.0").compareTo(Float.valueOf(String.valueOf(toLoanSummaryAfter.get("totalRepayment")))) == 0, "Checking for total paid "); // WRITE OFF LOAN AND CHECK ACCOUNT IS CLOSED LoanStatusChecker.verifyLoanAccountIsClosed(this.loanTransactionHelper.writeOffLoan("1 January 2011", loanID)); toLoanSummaryAfter = this.loanTransactionHelper.getLoanSummary(requestSpec, responseSpec, loanID); - Assertions.assertTrue(Float.valueOf("4000.0").compareTo(Float.valueOf(String.valueOf(toLoanSummaryAfter.get("principalWrittenOff")))) == 0, + Assertions.assertTrue( + Float.valueOf("4000.0").compareTo(Float.valueOf(String.valueOf(toLoanSummaryAfter.get("principalWrittenOff")))) == 0, "Checking for Principal written off "); - Assertions.assertTrue(Float.valueOf("1440.0").compareTo(Float.valueOf(String.valueOf(toLoanSummaryAfter.get("interestWrittenOff")))) == 0, + Assertions.assertTrue( + Float.valueOf("1440.0").compareTo(Float.valueOf(String.valueOf(toLoanSummaryAfter.get("interestWrittenOff")))) == 0, "Checking for interestPaid written off "); - Assertions.assertTrue(Float.valueOf("5440.0").compareTo(Float.valueOf(String.valueOf(toLoanSummaryAfter.get("totalWrittenOff")))) == 0, + Assertions.assertTrue( + Float.valueOf("5440.0").compareTo(Float.valueOf(String.valueOf(toLoanSummaryAfter.get("totalWrittenOff")))) == 0, "Checking for total written off "); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/MinimumDaysBetweenDisbursalAndFirstRepaymentTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/MinimumDaysBetweenDisbursalAndFirstRepaymentTest.java index 7a9ae199d..3de38288f 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/MinimumDaysBetweenDisbursalAndFirstRepaymentTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/MinimumDaysBetweenDisbursalAndFirstRepaymentTest.java @@ -215,4 +215,4 @@ public class MinimumDaysBetweenDisbursalAndFirstRepaymentTest { public void setGroupCalendarId(Integer groupCalendarId) { this.groupCalendarId = groupCalendarId; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/NotificationApiTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/NotificationApiTest.java index e1f8bb3f8..48de87210 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/NotificationApiTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/NotificationApiTest.java @@ -33,6 +33,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NotificationApiTest { + private final static Logger LOG = LoggerFactory.getLogger(NotificationApiTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -50,7 +51,7 @@ public class NotificationApiTest { public void testNotificationRetrieval() { HashMap response = (HashMap) NotificationHelper.getNotifications(this.requestSpec, this.responseSpec, ""); - LOG.info("Response : {}" , response.toString()); + LOG.info("Response : {}", response.toString()); Assertions.assertNotNull(response); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/OfficeIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/OfficeIntegrationTest.java index 7138f83b0..ec2216456 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/OfficeIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/OfficeIntegrationTest.java @@ -38,14 +38,9 @@ public class OfficeIntegrationTest { @BeforeEach public void setup() { Utils.initializeRESTAssured(); - this.requestSpec = new RequestSpecBuilder().setContentType( - ContentType.JSON).build(); - this.requestSpec - .header("Authorization", - "Basic " - + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200) - .build(); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } @Test diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/PasswordPreferencesIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/PasswordPreferencesIntegrationTest.java index 693cc0db5..c4f7905fb 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/PasswordPreferencesIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/PasswordPreferencesIntegrationTest.java @@ -37,6 +37,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "rawtypes", "unchecked" }) public class PasswordPreferencesIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(PasswordPreferencesIntegrationTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -59,7 +60,7 @@ public class PasswordPreferencesIntegrationTest { this.validateIfThePasswordIsUpdated(validationPolicyId); } - private void validateIfThePasswordIsUpdated(String validationPolicyId){ + private void validateIfThePasswordIsUpdated(String validationPolicyId) { Integer id = PasswordPreferencesHelper.getActivePasswordPreference(requestSpec, responseSpec); assertEquals(validationPolicyId, id.toString()); LOG.info("---------------------------------PASSWORD PREFERENCE VALIDATED SUCCESSFULLY-----------------------------------------"); @@ -69,8 +70,8 @@ public class PasswordPreferencesIntegrationTest { @Test public void updateWithInvalidPolicyId() { String invalidValidationPolicyId = "2000"; - final List error = (List) PasswordPreferencesHelper.updateWithInvalidValidationPolicyId(requestSpec, generalResponseSpec, invalidValidationPolicyId, - CommonConstants.RESPONSE_ERROR); + final List error = (List) PasswordPreferencesHelper.updateWithInvalidValidationPolicyId(requestSpec, generalResponseSpec, + invalidValidationPolicyId, CommonConstants.RESPONSE_ERROR); assertEquals("error.msg.password.validation.policy.id.invalid", error.get(0).get("userMessageGlobalisationCode"), "Password Validation Policy with identifier 2000 does not exist"); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RatesTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RatesTest.java index c18705272..dc05094db 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RatesTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RatesTest.java @@ -31,43 +31,37 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -@SuppressWarnings({"rawtypes"}) +@SuppressWarnings({ "rawtypes" }) public class RatesTest { - private ResponseSpecification responseSpec; - private RequestSpecification requestSpec; + private ResponseSpecification responseSpec; + private RequestSpecification requestSpec; - @BeforeEach - public void setup() { - Utils.initializeRESTAssured(); - this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - this.requestSpec.header("Authorization", - "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); - } + @BeforeEach + public void setup() { + Utils.initializeRESTAssured(); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + } - @Test - public void testRatesForLoans() { + @Test + public void testRatesForLoans() { - // Retrieving all Rates - ArrayList allRatesData = RatesHelper.getRates(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(allRatesData); + // Retrieving all Rates + ArrayList allRatesData = RatesHelper.getRates(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(allRatesData); - // Testing Creation and Update of Loan Rate - final Integer loanRateId = RatesHelper.createRates(this.requestSpec, this.responseSpec, - RatesHelper.getLoanRateJSON()); - Assertions.assertNotNull(loanRateId); + // Testing Creation and Update of Loan Rate + final Integer loanRateId = RatesHelper.createRates(this.requestSpec, this.responseSpec, RatesHelper.getLoanRateJSON()); + Assertions.assertNotNull(loanRateId); - //Update Rate percentage - HashMap changes = RatesHelper.updateRates(this.requestSpec, this.responseSpec, loanRateId, - RatesHelper.getModifyRateJSON()); + // Update Rate percentage + HashMap changes = RatesHelper.updateRates(this.requestSpec, this.responseSpec, loanRateId, RatesHelper.getModifyRateJSON()); - HashMap rateDataAfterChanges = RatesHelper - .getRateById(this.requestSpec, this.responseSpec, loanRateId); - Assertions.assertEquals(rateDataAfterChanges.get("percentage"), - changes.get("percentage"), "Verifying Rate after modification"); - - } + HashMap rateDataAfterChanges = RatesHelper.getRateById(this.requestSpec, this.responseSpec, loanRateId); + Assertions.assertEquals(rateDataAfterChanges.get("percentage"), changes.get("percentage"), "Verifying Rate after modification"); + } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RecurringDepositTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RecurringDepositTest.java index b86ba2d47..099e1f0f0 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RecurringDepositTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RecurringDepositTest.java @@ -64,6 +64,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "unused", "rawtypes", "unchecked", "static-access" }) public class RecurringDepositTest { + private final static Logger LOG = LoggerFactory.getLogger(RecurringDepositTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -101,9 +102,12 @@ public class RecurringDepositTest { public static final Float DEPOSIT_AMOUNT = 2000.0f; - // TODO Given the difference in calculation methods in test vs application, the exact values - // returned may differ enough to cause differences in rounding. Given this, we only compare the full - // digits. A proper solution would be to implement the exact interest calculation in this test, + // TODO Given the difference in calculation methods in test vs application, + // the exact values + // returned may differ enough to cause differences in rounding. Given this, + // we only compare the full + // digits. A proper solution would be to implement the exact interest + // calculation in this test, // and then to compare the exact results @BeforeEach @@ -181,8 +185,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); /*** @@ -211,10 +215,10 @@ public class RecurringDepositTest { depositAmount, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(depositTransactionId); - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, new JournalEntry( - depositAmount, JournalEntry.TransactionType.DEBIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, new JournalEntry( - depositAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, + new JournalEntry(depositAmount, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, + new JournalEntry(depositAmount, JournalEntry.TransactionType.CREDIT)); /*** * Update interest earned field for RD account @@ -240,8 +244,8 @@ public class RecurringDepositTest { /*** * Calculate expected premature closure amount */ - HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper.calculatePrematureAmountForRecurringDeposit( - recurringDepositAccountId, CLOSED_ON_DATE); + HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper + .calculatePrematureAmountForRecurringDeposit(recurringDepositAccountId, CLOSED_ON_DATE); /*** * Preclose the RD account verify whether account is preClosed @@ -257,13 +261,13 @@ public class RecurringDepositTest { /*** * Verify journal entry transactions for preclosure transaction */ - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); Float maturityAmount = Float.valueOf(recurringDepositAccountData.get("maturityAmount").toString()); - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, CLOSED_ON_DATE, new JournalEntry(maturityAmount, - JournalEntry.TransactionType.CREDIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, new JournalEntry(maturityAmount, - JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, CLOSED_ON_DATE, + new JournalEntry(maturityAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, + new JournalEntry(maturityAmount, JournalEntry.TransactionType.DEBIT)); } @@ -361,8 +365,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); /*** @@ -391,10 +395,10 @@ public class RecurringDepositTest { depositAmount, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(depositTransactionId); - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, new JournalEntry( - depositAmount, JournalEntry.TransactionType.DEBIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, new JournalEntry( - depositAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, + new JournalEntry(depositAmount, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, + new JournalEntry(depositAmount, JournalEntry.TransactionType.CREDIT)); /*** * Update interest earned field for RD account @@ -423,8 +427,8 @@ public class RecurringDepositTest { HashMap savingsSummaryBefore = this.savingsAccountHelper.getSavingsSummary(savingsId); Float balanceBefore = (Float) savingsSummaryBefore.get("accountBalance"); - HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper.calculatePrematureAmountForRecurringDeposit( - recurringDepositAccountId, CLOSED_ON_DATE); + HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper + .calculatePrematureAmountForRecurringDeposit(recurringDepositAccountId, CLOSED_ON_DATE); /*** * Retrieve mapped financial account for liability transfer @@ -443,19 +447,21 @@ public class RecurringDepositTest { this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositAccountIsPrematureClosed(recurringDepositAccountStatusHashMap); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); Float maturityAmount = Float.valueOf(recurringDepositAccountData.get("maturityAmount").toString()); /*** * Verify journal entry transactions for preclosure transaction As this * transaction is an account transfer you should get financial account * mapping details and verify amounts */ - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, new JournalEntry(maturityAmount, - JournalEntry.TransactionType.CREDIT), new JournalEntry(maturityAmount, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, + new JournalEntry(maturityAmount, JournalEntry.TransactionType.CREDIT), + new JournalEntry(maturityAmount, JournalEntry.TransactionType.DEBIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(financialAccount, CLOSED_ON_DATE, new JournalEntry(maturityAmount, - JournalEntry.TransactionType.DEBIT), new JournalEntry(maturityAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(financialAccount, CLOSED_ON_DATE, + new JournalEntry(maturityAmount, JournalEntry.TransactionType.DEBIT), + new JournalEntry(maturityAmount, JournalEntry.TransactionType.CREDIT)); /*** * Verify rd account maturity amount and savings account balance */ @@ -468,8 +474,7 @@ public class RecurringDepositTest { Double balanceAfter = Math.floor((Float) savingsSummaryAfter.get("accountBalance")); Double expectedSavingsBalance = Math.floor(balanceBefore + prematurityAmount); - Assertions.assertEquals(expectedSavingsBalance, balanceAfter, - "Verifying Savings Account Balance after Premature Closure"); + Assertions.assertEquals(expectedSavingsBalance, balanceAfter, "Verifying Savings Account Balance after Premature Closure"); } @@ -480,7 +485,6 @@ public class RecurringDepositTest { this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); this.recurringDepositAccountHelper = new RecurringDepositAccountHelper(this.requestSpec, this.responseSpec); - /*** * Create GL Accounts for product account mapping */ @@ -554,8 +558,8 @@ public class RecurringDepositTest { * Create RD product with CashBased accounting enabled */ final Integer taxGroupId = createTaxGroup("10", liabilityAccountForTax); - Integer recurringDepositProductId = createRecurringDepositProductWithWithHoldTax(VALID_FROM, VALID_TO,String.valueOf(taxGroupId), accountingRule, assetAccount, - liabilityAccount, incomeAccount, expenseAccount); + Integer recurringDepositProductId = createRecurringDepositProductWithWithHoldTax(VALID_FROM, VALID_TO, String.valueOf(taxGroupId), + accountingRule, assetAccount, liabilityAccount, incomeAccount, expenseAccount); Assertions.assertNotNull(recurringDepositProductId); /*** @@ -565,8 +569,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); /*** @@ -595,10 +599,10 @@ public class RecurringDepositTest { depositAmount, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(depositTransactionId); - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, new JournalEntry( - depositAmount, JournalEntry.TransactionType.DEBIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, new JournalEntry( - depositAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, + new JournalEntry(depositAmount, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, + new JournalEntry(depositAmount, JournalEntry.TransactionType.CREDIT)); /*** * Update interest earned field for RD account @@ -613,12 +617,10 @@ public class RecurringDepositTest { .postInterestForRecurringDeposit(recurringDepositAccountId); Assertions.assertNotNull(transactionIdForPostInterest); - HashMap accountSummary = this.recurringDepositAccountHelper.getRecurringDepositSummary(recurringDepositAccountId); Float totalInterestPosted = (Float) accountSummary.get("totalInterestPosted"); Assertions.assertNull(accountSummary.get("totalWithholdTax")); - final JournalEntry[] expenseAccountEntry = { new JournalEntry(totalInterestPosted, JournalEntry.TransactionType.DEBIT) }; final JournalEntry[] liablilityAccountEntry = { new JournalEntry(totalInterestPosted, JournalEntry.TransactionType.CREDIT) }; this.journalEntryHelper.checkJournalEntryForAssetAccount(expenseAccount, INTEREST_POSTED_DATE, expenseAccountEntry); @@ -630,8 +632,8 @@ public class RecurringDepositTest { HashMap savingsSummaryBefore = this.savingsAccountHelper.getSavingsSummary(savingsId); Float balanceBefore = (Float) savingsSummaryBefore.get("accountBalance"); - HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper.calculatePrematureAmountForRecurringDeposit( - recurringDepositAccountId, CLOSED_ON_DATE); + HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper + .calculatePrematureAmountForRecurringDeposit(recurringDepositAccountId, CLOSED_ON_DATE); /*** * Retrieve mapped financial account for liability transfer @@ -650,19 +652,21 @@ public class RecurringDepositTest { this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositAccountIsPrematureClosed(recurringDepositAccountStatusHashMap); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); Float maturityAmount = Float.valueOf(recurringDepositAccountData.get("maturityAmount").toString()); /*** * Verify journal entry transactions for preclosure transaction As this * transaction is an account transfer you should get financial account * mapping details and verify amounts */ - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, new JournalEntry(maturityAmount, - JournalEntry.TransactionType.CREDIT), new JournalEntry(maturityAmount, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, CLOSED_ON_DATE, + new JournalEntry(maturityAmount, JournalEntry.TransactionType.CREDIT), + new JournalEntry(maturityAmount, JournalEntry.TransactionType.DEBIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(financialAccount, CLOSED_ON_DATE, new JournalEntry(maturityAmount, - JournalEntry.TransactionType.DEBIT), new JournalEntry(maturityAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(financialAccount, CLOSED_ON_DATE, + new JournalEntry(maturityAmount, JournalEntry.TransactionType.DEBIT), + new JournalEntry(maturityAmount, JournalEntry.TransactionType.CREDIT)); /*** * Verify rd account maturity amount and savings account balance */ @@ -672,21 +676,18 @@ public class RecurringDepositTest { HashMap summary = (HashMap) recurringDepositData.get("summary"); Assertions.assertNotNull(summary.get("totalWithholdTax")); Float withHoldTax = (Float) summary.get("totalWithholdTax"); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccountForTax, CLOSED_ON_DATE, new JournalEntry(withHoldTax, - JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccountForTax, CLOSED_ON_DATE, + new JournalEntry(withHoldTax, JournalEntry.TransactionType.CREDIT)); HashMap savingsSummaryAfter = this.savingsAccountHelper.getSavingsSummary(savingsId); Double balanceAfter = Math.floor((Float) savingsSummaryAfter.get("accountBalance")); Double expectedSavingsBalance = Math.floor(balanceBefore + prematurityAmount); - Assertions.assertEquals(expectedSavingsBalance, balanceAfter, - "Verifying Savings Account Balance after Premature Closure"); + Assertions.assertEquals(expectedSavingsBalance, balanceAfter, "Verifying Savings Account Balance after Premature Closure"); } - - @Test public void testRecurringDepositAccountWithClosureTypeTransferToSavings_WITH_HOLD_TAX() throws InterruptedException { this.recurringDepositProductHelper = new RecurringDepositProductHelper(this.requestSpec, this.responseSpec); @@ -694,7 +695,6 @@ public class RecurringDepositTest { this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); this.recurringDepositAccountHelper = new RecurringDepositAccountHelper(this.requestSpec, this.responseSpec); - /*** * Create GL Accounts for product account mapping */ @@ -770,8 +770,8 @@ public class RecurringDepositTest { * Create RD product with CashBased accounting enabled */ final Integer taxGroupId = createTaxGroup("10", liabilityAccountForTax); - Integer recurringDepositProductId = createRecurringDepositProductWithWithHoldTax(VALID_FROM, VALID_TO,String.valueOf(taxGroupId), accountingRule, assetAccount, - liabilityAccount, incomeAccount, expenseAccount); + Integer recurringDepositProductId = createRecurringDepositProductWithWithHoldTax(VALID_FROM, VALID_TO, String.valueOf(taxGroupId), + accountingRule, assetAccount, liabilityAccount, incomeAccount, expenseAccount); Assertions.assertNotNull(recurringDepositProductId); /*** @@ -781,8 +781,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); /*** @@ -815,8 +815,8 @@ public class RecurringDepositTest { depositAmount, dateFormat.format(todaysDate.getTime())); Assertions.assertNotNull(depositTransactionId); - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, dateFormat.format(todaysDate.getTime()), new JournalEntry( - depositAmount, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, dateFormat.format(todaysDate.getTime()), + new JournalEntry(depositAmount, JournalEntry.TransactionType.DEBIT)); this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, dateFormat.format(todaysDate.getTime()), new JournalEntry(depositAmount, JournalEntry.TransactionType.CREDIT)); todaysDate.add(Calendar.MONTH, 1); @@ -826,7 +826,7 @@ public class RecurringDepositTest { * FD account verify whether account is matured */ - SchedulerJobHelper schedulerJobHelper = new SchedulerJobHelper(requestSpec); + SchedulerJobHelper schedulerJobHelper = new SchedulerJobHelper(requestSpec); String JobName = "Update Deposit Accounts Maturity details"; schedulerJobHelper.executeAndAwaitJob(JobName); @@ -836,19 +836,15 @@ public class RecurringDepositTest { HashMap summary = (HashMap) accountDetails.get("summary"); Assertions.assertNotNull(summary.get("totalWithholdTax")); Float withHoldTax = (Float) summary.get("totalWithholdTax"); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccountForTax, CLOSED_ON_DATE, new JournalEntry(withHoldTax, - JournalEntry.TransactionType.CREDIT)); - + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccountForTax, CLOSED_ON_DATE, + new JournalEntry(withHoldTax, JournalEntry.TransactionType.CREDIT)); recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositAccountIsMatured(recurringDepositAccountStatusHashMap); - } - - /*** * Test case for Recurring Deposit Account premature closure with * transaction type ReInvest and Cash Based accounting enabled @@ -910,8 +906,8 @@ public class RecurringDepositTest { liabilityAccount, incomeAccount, expenseAccount); Assertions.assertNotNull(recurringDepositProductId); - ArrayList allRecurringDepositProductsData = this.recurringDepositProductHelper.retrieveAllRecurringDepositProducts( - this.requestSpec, this.responseSpec); + ArrayList allRecurringDepositProductsData = this.recurringDepositProductHelper + .retrieveAllRecurringDepositProducts(this.requestSpec, this.responseSpec); HashMap recurringDepositProductData = this.recurringDepositProductHelper.retrieveRecurringDepositProductById(this.requestSpec, this.responseSpec, recurringDepositProductId.toString()); @@ -922,8 +918,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); /*** @@ -952,10 +948,10 @@ public class RecurringDepositTest { DEPOSIT_AMOUNT, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(depositTransactionId); - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, new JournalEntry( - depositAmount, JournalEntry.TransactionType.DEBIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, new JournalEntry( - depositAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, + new JournalEntry(depositAmount, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, EXPECTED_FIRST_DEPOSIT_ON_DATE, + new JournalEntry(depositAmount, JournalEntry.TransactionType.CREDIT)); /*** * Update interest earned field for RD account @@ -981,8 +977,8 @@ public class RecurringDepositTest { /*** * Calculate expected premature closure amount */ - HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper.calculatePrematureAmountForRecurringDeposit( - recurringDepositAccountId, CLOSED_ON_DATE); + HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper + .calculatePrematureAmountForRecurringDeposit(recurringDepositAccountId, CLOSED_ON_DATE); /*** * Expected to get an error response from api because re-invest option @@ -1075,8 +1071,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -1123,8 +1119,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.rejectApplication(recurringDepositAccountId, @@ -1170,8 +1166,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.withdrawApplication(recurringDepositAccountId, @@ -1214,12 +1210,12 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); - recurringDepositAccountId = (Integer) this.recurringDepositAccountHelper.deleteRecurringDepositApplication( - recurringDepositAccountId, "resourceId"); + recurringDepositAccountId = (Integer) this.recurringDepositAccountHelper + .deleteRecurringDepositApplication(recurringDepositAccountId, "resourceId"); Assertions.assertNotNull(recurringDepositAccountId); } @@ -1280,8 +1276,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); /*** @@ -1309,10 +1305,10 @@ public class RecurringDepositTest { DEPOSIT_AMOUNT, DEPOSIT_DATE); Assertions.assertNotNull(transactionIdForDeposit); - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, DEPOSIT_DATE, new JournalEntry(DEPOSIT_AMOUNT, - JournalEntry.TransactionType.DEBIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, DEPOSIT_DATE, new JournalEntry(DEPOSIT_AMOUNT, - JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, DEPOSIT_DATE, + new JournalEntry(DEPOSIT_AMOUNT, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, DEPOSIT_DATE, + new JournalEntry(DEPOSIT_AMOUNT, JournalEntry.TransactionType.CREDIT)); /*** * verify account balances after transactions @@ -1331,10 +1327,10 @@ public class RecurringDepositTest { transactionIdForDeposit, DEPOSIT_DATE, updatedTransactionAmount); Assertions.assertNotNull(updateTransactionId); - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, DEPOSIT_DATE, new JournalEntry(updatedTransactionAmount, - JournalEntry.TransactionType.DEBIT)); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, DEPOSIT_DATE, new JournalEntry( - updatedTransactionAmount, JournalEntry.TransactionType.CREDIT)); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, DEPOSIT_DATE, + new JournalEntry(updatedTransactionAmount, JournalEntry.TransactionType.DEBIT)); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, DEPOSIT_DATE, + new JournalEntry(updatedTransactionAmount, JournalEntry.TransactionType.CREDIT)); expectedBalanceAfter = DEPOSIT_AMOUNT - updatedTransactionAmount; recurringDepositSummaryAfter = this.recurringDepositAccountHelper.getRecurringDepositSummary(recurringDepositAccountId); @@ -1394,8 +1390,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -1409,8 +1405,8 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); HashMap recurringDepositSummary = this.recurringDepositAccountHelper.getRecurringDepositSummary(recurringDepositAccountId); Float principal = (Float) recurringDepositSummary.get("accountBalance"); @@ -1418,7 +1414,7 @@ public class RecurringDepositTest { Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; Integer daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); @@ -1428,7 +1424,7 @@ public class RecurringDepositTest { principal = (float) Math.floor(principal); maturityAmount = (float) Math.floor(maturityAmount); - LOG.info("{}",principal.toString()); + LOG.info("{}", principal.toString()); Assertions.assertEquals(principal, maturityAmount, "Verifying Maturity amount for Recurring Deposit Account"); } @@ -1477,8 +1473,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, MONTHLY, MONTHLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -1492,8 +1488,8 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); HashMap recurringDepositSummary = this.recurringDepositAccountHelper.getRecurringDepositSummary(recurringDepositAccountId); Float principal = (Float) recurringDepositSummary.get("accountBalance"); @@ -1501,7 +1497,7 @@ public class RecurringDepositTest { Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; Integer daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); @@ -1511,7 +1507,7 @@ public class RecurringDepositTest { principal = (float) Math.floor(principal); maturityAmount = (float) Math.floor(maturityAmount); - LOG.info("{}",principal.toString()); + LOG.info("{}", principal.toString()); Assertions.assertEquals(principal, maturityAmount, "Verifying Maturity amount for Recurring Deposit Account"); } @@ -1552,8 +1548,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -1569,8 +1565,8 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Integer depositTransactionId = this.recurringDepositAccountHelper.depositToRecurringDepositAccount(recurringDepositAccountId, DEPOSIT_AMOUNT, EXPECTED_FIRST_DEPOSIT_ON_DATE); @@ -1582,7 +1578,7 @@ public class RecurringDepositTest { Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; Integer currentDate = Integer.valueOf(currentDateFormat.format(todaysDate.getTime())); @@ -1592,7 +1588,7 @@ public class RecurringDepositTest { principal += interestToBePosted; Float expectedBalanceAfter = (float) Math.floor(principal); - LOG.info("{}",expectedBalanceAfter.toString()); + LOG.info("{}", expectedBalanceAfter.toString()); Integer transactionIdForPostInterest = this.recurringDepositAccountHelper .postInterestForRecurringDeposit(recurringDepositAccountId); @@ -1603,7 +1599,8 @@ public class RecurringDepositTest { Float principalAfter = (float) Math.floor((Float) recurringDepositAccountSummary.get("accountBalance")); interestToBePosted = (float) Math.floor(interestToBePosted); - Assertions.assertEquals(interestToBePosted, interestAmountPosted, "Verifying Amount of Interest Posted to Recurring Deposit Account"); + Assertions.assertEquals(interestToBePosted, interestAmountPosted, + "Verifying Amount of Interest Posted to Recurring Deposit Account"); Assertions.assertEquals(expectedBalanceAfter, principalAfter, "Verifying Principal Amount after Interest Posting"); } @@ -1655,8 +1652,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -1674,8 +1671,8 @@ public class RecurringDepositTest { HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Float preClosurePenalInterestRate = (Float) recurringDepositAccountData.get("preClosurePenalInterest"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Integer depositTransactionId = this.recurringDepositAccountHelper.depositToRecurringDepositAccount(recurringDepositAccountId, DEPOSIT_AMOUNT, EXPECTED_FIRST_DEPOSIT_ON_DATE); @@ -1688,7 +1685,7 @@ public class RecurringDepositTest { interestRate -= preClosurePenalInterestRate; double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; Calendar calendar = Calendar.getInstance(); @@ -1699,7 +1696,7 @@ public class RecurringDepositTest { Float interestPerMonth = (float) (interestPerDay * principal * daysInMonth); principal += interestPerMonth + depositAmount; calendar.add(Calendar.DATE, daysInMonth); - LOG.info("{}",monthDayFormat.format(calendar.getTime())); + LOG.info("{}", monthDayFormat.format(calendar.getTime())); EXPECTED_FIRST_DEPOSIT_ON_DATE = dateFormat.format(calendar.getTime()); Integer transactionIdForDeposit = this.recurringDepositAccountHelper.depositToRecurringDepositAccount(recurringDepositAccountId, @@ -1708,12 +1705,12 @@ public class RecurringDepositTest { currentDate = currentDate - 1; interestPerMonth = (float) (interestPerDay * principal * currentDate); - LOG.info("IPM = {}" , interestPerMonth); + LOG.info("IPM = {}", interestPerMonth); principal += interestPerMonth; - LOG.info("principal = {}" , principal); + LOG.info("principal = {}", principal); - HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper.calculatePrematureAmountForRecurringDeposit( - recurringDepositAccountId, CLOSED_ON_DATE); + HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper + .calculatePrematureAmountForRecurringDeposit(recurringDepositAccountId, CLOSED_ON_DATE); Integer prematureClosureTransactionId = (Integer) this.recurringDepositAccountHelper.prematureCloseForRecurringDeposit( recurringDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_WITHDRAW_DEPOSIT, null, CommonConstants.RESPONSE_RESOURCE_ID); @@ -1723,8 +1720,8 @@ public class RecurringDepositTest { this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositAccountIsPrematureClosed(recurringDepositAccountStatusHashMap); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); principal = (float) Math.floor(principal); Float maturityAmount = (float) Math.floor((Float) recurringDepositAccountData.get("maturityAmount")); @@ -1785,8 +1782,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, MONTHLY, MONTHLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -1804,8 +1801,8 @@ public class RecurringDepositTest { HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Float preClosurePenalInterestRate = (Float) recurringDepositAccountData.get("preClosurePenalInterest"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Integer depositTransactionId = this.recurringDepositAccountHelper.depositToRecurringDepositAccount(recurringDepositAccountId, DEPOSIT_AMOUNT, EXPECTED_FIRST_DEPOSIT_ON_DATE); @@ -1818,7 +1815,7 @@ public class RecurringDepositTest { interestRate -= preClosurePenalInterestRate; double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; Calendar calendar = Calendar.getInstance(); @@ -1829,7 +1826,7 @@ public class RecurringDepositTest { Float interestPerMonth = (float) (interestPerDay * principal * daysInMonth); principal += interestPerMonth + depositAmount; calendar.add(Calendar.DATE, daysInMonth); - LOG.info("{}",monthDayFormat.format(calendar.getTime())); + LOG.info("{}", monthDayFormat.format(calendar.getTime())); EXPECTED_FIRST_DEPOSIT_ON_DATE = dateFormat.format(calendar.getTime()); Integer transactionIdForDeposit = this.recurringDepositAccountHelper.depositToRecurringDepositAccount(recurringDepositAccountId, @@ -1838,12 +1835,12 @@ public class RecurringDepositTest { currentDate = currentDate - 1; interestPerMonth = (float) (interestPerDay * principal * currentDate); - LOG.info("IPM = {}" , interestPerMonth); + LOG.info("IPM = {}", interestPerMonth); principal += interestPerMonth; - LOG.info("principal = {}" , principal); + LOG.info("principal = {}", principal); - HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper.calculatePrematureAmountForRecurringDeposit( - recurringDepositAccountId, CLOSED_ON_DATE); + HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper + .calculatePrematureAmountForRecurringDeposit(recurringDepositAccountId, CLOSED_ON_DATE); Integer prematureClosureTransactionId = (Integer) this.recurringDepositAccountHelper.prematureCloseForRecurringDeposit( recurringDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_WITHDRAW_DEPOSIT, null, CommonConstants.RESPONSE_RESOURCE_ID); @@ -1853,8 +1850,8 @@ public class RecurringDepositTest { this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositAccountIsPrematureClosed(recurringDepositAccountStatusHashMap); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); principal = (float) Math.floor(principal); Float maturityAmount = (float) Math.floor((Float) recurringDepositAccountData.get("maturityAmount")); @@ -1913,8 +1910,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, TILL_PREMATURE_WITHDRAWAL, EXPECTED_FIRST_DEPOSIT_ON_DATE); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -1931,8 +1928,8 @@ public class RecurringDepositTest { HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Float preClosurePenalInterestRate = (Float) recurringDepositAccountData.get("preClosurePenalInterest"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Calendar activationDate = Calendar.getInstance(); activationDate.add(Calendar.MONTH, -1); @@ -1955,7 +1952,7 @@ public class RecurringDepositTest { interestRate -= preClosurePenalInterestRate; double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; Calendar calendar = Calendar.getInstance(); @@ -1967,7 +1964,7 @@ public class RecurringDepositTest { Float interestPerMonth = (float) (interestPerDay * principal * daysInMonth); principal += interestPerMonth + depositAmount; calendar.add(Calendar.DATE, daysInMonth); - LOG.info("{}",monthDayFormat.format(calendar.getTime())); + LOG.info("{}", monthDayFormat.format(calendar.getTime())); EXPECTED_FIRST_DEPOSIT_ON_DATE = dateFormat.format(calendar.getTime()); Integer transactionIdForDeposit = this.recurringDepositAccountHelper.depositToRecurringDepositAccount(recurringDepositAccountId, @@ -1976,12 +1973,12 @@ public class RecurringDepositTest { currentDate = currentDate - 1; interestPerMonth = (float) (interestPerDay * principal * currentDate); - LOG.info("IPM = {}" , interestPerMonth); + LOG.info("IPM = {}", interestPerMonth); principal += interestPerMonth; - LOG.info("principal = {}" , principal); + LOG.info("principal = {}", principal); - HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper.calculatePrematureAmountForRecurringDeposit( - recurringDepositAccountId, CLOSED_ON_DATE); + HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper + .calculatePrematureAmountForRecurringDeposit(recurringDepositAccountId, CLOSED_ON_DATE); Integer prematureClosureTransactionId = (Integer) this.recurringDepositAccountHelper.prematureCloseForRecurringDeposit( recurringDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_WITHDRAW_DEPOSIT, null, CommonConstants.RESPONSE_RESOURCE_ID); @@ -1991,8 +1988,8 @@ public class RecurringDepositTest { this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositAccountIsPrematureClosed(recurringDepositAccountStatusHashMap); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); principal = (float) Math.floor(principal); Float maturityAmount = (float) Math.floor((Float) recurringDepositAccountData.get("maturityAmount")); @@ -2056,8 +2053,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_360, TILL_PREMATURE_WITHDRAWAL, INTEREST_CALCULATION_USING_DAILY_BALANCE, MONTHLY, MONTHLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -2074,8 +2071,8 @@ public class RecurringDepositTest { HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Float preClosurePenalInterestRate = (Float) recurringDepositAccountData.get("preClosurePenalInterest"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Calendar activationDate = Calendar.getInstance(); activationDate.add(Calendar.MONTH, -1); @@ -2098,7 +2095,7 @@ public class RecurringDepositTest { interestRate -= preClosurePenalInterestRate; double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; Calendar calendar = Calendar.getInstance(); @@ -2110,7 +2107,7 @@ public class RecurringDepositTest { Float interestPerMonth = (float) (interestPerDay * principal * daysInMonth); principal += interestPerMonth + depositAmount; calendar.add(Calendar.DATE, daysInMonth); - LOG.info("{}",monthDayFormat.format(calendar.getTime())); + LOG.info("{}", monthDayFormat.format(calendar.getTime())); EXPECTED_FIRST_DEPOSIT_ON_DATE = dateFormat.format(calendar.getTime()); Integer newTransactionIdForDeposit = this.recurringDepositAccountHelper.depositToRecurringDepositAccount(recurringDepositAccountId, @@ -2119,12 +2116,12 @@ public class RecurringDepositTest { currentDate = currentDate - 1; interestPerMonth = (float) (interestPerDay * principal * currentDate); - LOG.info("IPM = {}" , interestPerMonth); + LOG.info("IPM = {}", interestPerMonth); principal += interestPerMonth; - LOG.info("principal = {}" , principal); + LOG.info("principal = {}", principal); - HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper.calculatePrematureAmountForRecurringDeposit( - recurringDepositAccountId, CLOSED_ON_DATE); + HashMap recurringDepositPrematureData = this.recurringDepositAccountHelper + .calculatePrematureAmountForRecurringDeposit(recurringDepositAccountId, CLOSED_ON_DATE); Integer prematureClosureTransactionId = (Integer) this.recurringDepositAccountHelper.prematureCloseForRecurringDeposit( recurringDepositAccountId, CLOSED_ON_DATE, CLOSURE_TYPE_WITHDRAW_DEPOSIT, null, CommonConstants.RESPONSE_RESOURCE_ID); @@ -2134,8 +2131,8 @@ public class RecurringDepositTest { this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositAccountIsPrematureClosed(recurringDepositAccountStatusHashMap); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); principal = (float) Math.floor(principal); Float maturityAmount = (float) Math.floor((Float) recurringDepositAccountData.get("maturityAmount")); @@ -2188,8 +2185,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_365, WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, MONTHLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -2205,13 +2202,13 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; Integer daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); @@ -2221,7 +2218,7 @@ public class RecurringDepositTest { principal = (float) Math.floor(principal); maturityAmount = (float) Math.floor(maturityAmount); - LOG.info("{}",principal.toString()); + LOG.info("{}", principal.toString()); Assertions.assertEquals(principal, maturityAmount, "Verifying Maturity amount for Recurring Deposit Account"); } @@ -2271,8 +2268,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, MONTHLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -2288,13 +2285,13 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; Integer daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); @@ -2304,7 +2301,7 @@ public class RecurringDepositTest { principal = (float) Math.floor(principal); maturityAmount = (float) Math.floor(maturityAmount); - LOG.info("{}",principal.toString()); + LOG.info("{}", principal.toString()); Assertions.assertEquals(principal, maturityAmount, "Verifying Maturity amount for Recurring Deposit Account"); } @@ -2335,7 +2332,7 @@ public class RecurringDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2361,8 +2358,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_365, WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, BI_ANNUALLY, BI_ANNUALLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -2377,20 +2374,20 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {}" , perDay); + LOG.info("per day = {}", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.recurringDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, recurringDepositAmount, depositPeriod, interestPerDay, BIANNULLY_INTERVAL, BIANNULLY_INTERVAL); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); Double expectedPrematureAmount = Math.floor(principal); Double maturityAmount = Math.floor((Float) recurringDepositAccountData.get("maturityAmount")); @@ -2425,7 +2422,7 @@ public class RecurringDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2451,8 +2448,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, BI_ANNUALLY, BI_ANNUALLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -2467,20 +2464,20 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {} " , perDay); + LOG.info("per day = {} ", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.recurringDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, recurringDepositAmount, depositPeriod, interestPerDay, BIANNULLY_INTERVAL, BIANNULLY_INTERVAL); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); Double expectedPrematureAmount = Math.floor(principal); Double maturityAmount = Math.floor((Float) recurringDepositAccountData.get("maturityAmount")); @@ -2514,7 +2511,7 @@ public class RecurringDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2540,8 +2537,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_365, WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, ANNUALLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -2557,20 +2554,20 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {} " , perDay); + LOG.info("per day = {} ", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.recurringDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, recurringDepositAmount, depositPeriod, interestPerDay, DAILY_COMPOUNDING_INTERVAL, ANNUL_INTERVAL); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); Double expectedPrematureAmount = Math.floor(principal); Double maturityAmount = Math.floor((Float) recurringDepositAccountData.get("maturityAmount")); @@ -2604,7 +2601,7 @@ public class RecurringDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2630,8 +2627,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, DAILY, ANNUALLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -2647,20 +2644,20 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {} " , perDay); + LOG.info("per day = {} ", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.recurringDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, recurringDepositAmount, depositPeriod, interestPerDay, DAILY_COMPOUNDING_INTERVAL, ANNUL_INTERVAL); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); Double expectedPrematureAmount = Math.floor(principal); Double maturityAmount = Math.floor((Float) recurringDepositAccountData.get("maturityAmount")); @@ -2695,7 +2692,7 @@ public class RecurringDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2721,8 +2718,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_365, WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, QUARTERLY, QUARTERLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -2737,20 +2734,20 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {} " , perDay); + LOG.info("per day = {} ", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.recurringDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, recurringDepositAmount, depositPeriod, interestPerDay, QUARTERLY_INTERVAL, QUARTERLY_INTERVAL); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); Double expectedPrematureAmount = Math.floor(principal); Double maturityAmount = Math.floor((Float) recurringDepositAccountData.get("maturityAmount")); @@ -2785,7 +2782,7 @@ public class RecurringDepositTest { Integer daysLeft = daysInMonth - currentDate; todaysDate.add(Calendar.DATE, daysLeft + 1); daysInMonth = todaysDate.getActualMaximum(Calendar.DATE); - LOG.info("{}",dateFormat.format(todaysDate.getTime())); + LOG.info("{}", dateFormat.format(todaysDate.getTime())); final String VALID_FROM = dateFormat.format(todaysDate.getTime()); final String VALID_TO = null; @@ -2811,8 +2808,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, DAYS_360, WHOLE_TERM, INTEREST_CALCULATION_USING_DAILY_BALANCE, QUARTERLY, QUARTERLY, EXPECTED_FIRST_DEPOSIT_ON_DATE); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); recurringDepositAccountStatusHashMap = this.recurringDepositAccountHelper.approveRecurringDeposit(recurringDepositAccountId, @@ -2827,20 +2824,20 @@ public class RecurringDepositTest { Integer depositPeriod = (Integer) recurringDepositAccountData.get("depositPeriod"); HashMap daysInYearMap = (HashMap) recurringDepositAccountData.get("interestCalculationDaysInYearType"); Integer daysInYear = (Integer) daysInYearMap.get("id"); - ArrayList> interestRateChartData = this.recurringDepositProductHelper.getInterestRateChartSlabsByProductId( - this.requestSpec, this.responseSpec, recurringDepositProductId); + ArrayList> interestRateChartData = this.recurringDepositProductHelper + .getInterestRateChartSlabsByProductId(this.requestSpec, this.responseSpec, recurringDepositProductId); Float interestRate = this.recurringDepositAccountHelper.getInterestRate(interestRateChartData, depositPeriod); double interestRateInFraction = interestRate / 100; double perDay = (double) 1 / daysInYear; - LOG.info("per day = {} " , perDay); + LOG.info("per day = {} ", perDay); double interestPerDay = interestRateInFraction * perDay; principal = this.recurringDepositAccountHelper.getPrincipalAfterCompoundingInterest(todaysDate, principal, recurringDepositAmount, depositPeriod, interestPerDay, QUARTERLY_INTERVAL, QUARTERLY_INTERVAL); - recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, - this.responseSpec, recurringDepositAccountId); + recurringDepositAccountData = this.recurringDepositAccountHelper.getRecurringDepositAccountById(this.requestSpec, this.responseSpec, + recurringDepositAccountId); Double expectedPrematureAmount = Math.floor(principal); Double maturityAmount = Math.floor((Float) recurringDepositAccountData.get("maturityAmount")); @@ -2854,7 +2851,7 @@ public class RecurringDepositTest { final String chartToUse = "period"; final String depositAmount = "1000"; final String depositPeriod = "12"; - final Float interestRate = Float.valueOf((float)6.0); + final Float interestRate = Float.valueOf((float) 6.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2863,7 +2860,7 @@ public class RecurringDepositTest { final String chartToUse = "period"; final String depositAmount = "10000"; final String depositPeriod = "12"; - final Float interestRate = Float.valueOf((float)6.0); + final Float interestRate = Float.valueOf((float) 6.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2872,7 +2869,7 @@ public class RecurringDepositTest { final String chartToUse = "period"; final String depositAmount = "1000"; final String depositPeriod = "18"; - final Float interestRate = Float.valueOf((float)7.0); + final Float interestRate = Float.valueOf((float) 7.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2881,7 +2878,7 @@ public class RecurringDepositTest { final String chartToUse = "amount"; final String depositAmount = "1000"; final String depositPeriod = "12"; - final Float interestRate = Float.valueOf((float)8.0); + final Float interestRate = Float.valueOf((float) 8.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2890,7 +2887,7 @@ public class RecurringDepositTest { final String chartToUse = "amount"; final String depositAmount = "500"; final String depositPeriod = "12"; - final Float interestRate = Float.valueOf((float)7.0); + final Float interestRate = Float.valueOf((float) 7.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2899,7 +2896,7 @@ public class RecurringDepositTest { final String chartToUse = "amount"; final String depositAmount = "500"; final String depositPeriod = "10"; - final Float interestRate = Float.valueOf((float)5.0); + final Float interestRate = Float.valueOf((float) 5.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2908,7 +2905,7 @@ public class RecurringDepositTest { final String chartToUse = "period_amount"; final String depositAmount = "1000"; final String depositPeriod = "12"; - final Float interestRate = Float.valueOf((float)7.0); + final Float interestRate = Float.valueOf((float) 7.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2917,7 +2914,7 @@ public class RecurringDepositTest { final String chartToUse = "period_amount"; final String depositAmount = "400"; final String depositPeriod = "12"; - final Float interestRate = Float.valueOf((float)6.0); + final Float interestRate = Float.valueOf((float) 6.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2926,7 +2923,7 @@ public class RecurringDepositTest { final String chartToUse = "period_amount"; final String depositAmount = "1000"; final String depositPeriod = "14"; - final Float interestRate = Float.valueOf((float)8.0); + final Float interestRate = Float.valueOf((float) 8.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2935,7 +2932,7 @@ public class RecurringDepositTest { final String chartToUse = "amount_period"; final String depositAmount = "1000"; final String depositPeriod = "12"; - final Float interestRate = Float.valueOf((float)8.0); + final Float interestRate = Float.valueOf((float) 8.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2944,7 +2941,7 @@ public class RecurringDepositTest { final String chartToUse = "amount_period"; final String depositAmount = "100"; final String depositPeriod = "12"; - final Float interestRate = Float.valueOf((float)6.0); + final Float interestRate = Float.valueOf((float) 6.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2953,7 +2950,7 @@ public class RecurringDepositTest { final String chartToUse = "amount_period"; final String depositAmount = "1000"; final String depositPeriod = "6"; - final Float interestRate = Float.valueOf((float)7.0); + final Float interestRate = Float.valueOf((float) 7.0); testFixedDepositAccountForInterestRate(chartToUse, depositAmount, depositPeriod, interestRate); } @@ -2988,8 +2985,8 @@ public class RecurringDepositTest { VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, SUBMITTED_ON_DATE, depositAmount, depositPeriod); Assertions.assertNotNull(recurringDepositAccountId); - HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker.getStatusOfRecurringDepositAccount( - this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); + HashMap recurringDepositAccountStatusHashMap = RecurringDepositAccountStatusChecker + .getStatusOfRecurringDepositAccount(this.requestSpec, this.responseSpec, recurringDepositAccountId.toString()); RecurringDepositAccountStatusChecker.verifyRecurringDepositIsPending(recurringDepositAccountStatusHashMap); /*** @@ -3015,7 +3012,8 @@ public class RecurringDepositTest { private Integer createRecurringDepositProduct(final String validFrom, final String validTo, final String accountingRule, Account... accounts) { LOG.info("------------------------------CREATING NEW RECURRING DEPOSIT PRODUCT ---------------------------------------"); - RecurringDepositProductHelper recurringDepositProductHelper = new RecurringDepositProductHelper(this.requestSpec, this.responseSpec); + RecurringDepositProductHelper recurringDepositProductHelper = new RecurringDepositProductHelper(this.requestSpec, + this.responseSpec); if (accountingRule.equals(CASH_BASED)) { recurringDepositProductHelper = recurringDepositProductHelper.withAccountingRuleAsCashBased(accounts); } else if (accountingRule.equals(NONE)) { @@ -3025,17 +3023,17 @@ public class RecurringDepositTest { return RecurringDepositProductHelper.createRecurringDepositProduct(recurringDepositProductJSON, requestSpec, responseSpec); } - private Integer createRecurringDepositProductWithWithHoldTax(final String validFrom, final String validTo,final String taxGroupId, final String accountingRule, - Account... accounts) { + private Integer createRecurringDepositProductWithWithHoldTax(final String validFrom, final String validTo, final String taxGroupId, + final String accountingRule, Account... accounts) { LOG.info("------------------------------CREATING NEW RECURRING DEPOSIT PRODUCT ---------------------------------------"); - RecurringDepositProductHelper recurringDepositProductHelper = new RecurringDepositProductHelper(this.requestSpec, this.responseSpec); + RecurringDepositProductHelper recurringDepositProductHelper = new RecurringDepositProductHelper(this.requestSpec, + this.responseSpec); if (accountingRule.equals(CASH_BASED)) { recurringDepositProductHelper = recurringDepositProductHelper.withAccountingRuleAsCashBased(accounts); } else if (accountingRule.equals(NONE)) { recurringDepositProductHelper = recurringDepositProductHelper.withAccountingRuleAsNone(); } - final String recurringDepositProductJSON = recurringDepositProductHelper.withPeriodRangeChart() - .withWithHoldTax(taxGroupId)// + final String recurringDepositProductJSON = recurringDepositProductHelper.withPeriodRangeChart().withWithHoldTax(taxGroupId)// .build(validFrom, validTo); return RecurringDepositProductHelper.createRecurringDepositProduct(recurringDepositProductJSON, requestSpec, responseSpec); } @@ -3043,7 +3041,8 @@ public class RecurringDepositTest { private Integer createRecurringDepositProduct(final String validFrom, final String validTo, final String accountingRule, final String chartToBePicked, Account... accounts) { LOG.info("------------------------------CREATING NEW RECURRING DEPOSIT PRODUCT ---------------------------------------"); - RecurringDepositProductHelper recurringDepositProductHelper = new RecurringDepositProductHelper(this.requestSpec, this.responseSpec); + RecurringDepositProductHelper recurringDepositProductHelper = new RecurringDepositProductHelper(this.requestSpec, + this.responseSpec); if (accountingRule.equals(CASH_BASED)) { recurringDepositProductHelper = recurringDepositProductHelper.withAccountingRuleAsCashBased(accounts); } else if (accountingRule.equals(NONE)) { @@ -3151,24 +3150,26 @@ public class RecurringDepositTest { LIABILITY_TRANSFER_FINANCIAL_ACTIVITY_ID, liabilityAccountForMapping.getAccountID(), this.responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); Assertions.assertNotNull(financialActivityAccountId); - assertFinancialActivityAccountCreation(financialActivityAccountId, LIABILITY_TRANSFER_FINANCIAL_ACTIVITY_ID, liabilityAccountForMapping); + assertFinancialActivityAccountCreation(financialActivityAccountId, LIABILITY_TRANSFER_FINANCIAL_ACTIVITY_ID, + liabilityAccountForMapping); return liabilityAccountForMapping; } - private void assertFinancialActivityAccountCreation(Integer financialActivityAccountId, Integer financialActivityId, Account glAccount) { + private void assertFinancialActivityAccountCreation(Integer financialActivityAccountId, Integer financialActivityId, + Account glAccount) { HashMap mappingDetails = this.financialActivityAccountHelper.getFinancialActivityAccount(financialActivityAccountId, this.responseSpec); Assertions.assertEquals(financialActivityId, ((HashMap) mappingDetails.get("financialActivityData")).get("id")); Assertions.assertEquals(glAccount.getAccountID(), ((HashMap) mappingDetails.get("glAccountData")).get("id")); } - private Integer createTaxGroup(final String percentage, final Account liabilityAccountForTax){ + private Integer createTaxGroup(final String percentage, final Account liabilityAccountForTax) { final Integer liabilityAccountId = liabilityAccountForTax.getAccountID(); - final Integer taxComponentId = TaxComponentHelper.createTaxComponent(this.requestSpec, this.responseSpec, percentage, liabilityAccountId); + final Integer taxComponentId = TaxComponentHelper.createTaxComponent(this.requestSpec, this.responseSpec, percentage, + liabilityAccountId); return TaxGroupHelper.createTaxGroup(this.requestSpec, this.responseSpec, Arrays.asList(taxComponentId)); } - /** * Delete the Liability transfer account */ @@ -3177,8 +3178,8 @@ public class RecurringDepositTest { List financialActivities = this.financialActivityAccountHelper.getAllFinancialActivityAccounts(this.responseSpec); for (HashMap financialActivity : financialActivities) { Integer financialActivityAccountId = (Integer) financialActivity.get("id"); - Integer deletedFinancialActivityAccountId = this.financialActivityAccountHelper.deleteFinancialActivityAccount( - financialActivityAccountId, this.responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); + Integer deletedFinancialActivityAccountId = this.financialActivityAccountHelper + .deleteFinancialActivityAccount(financialActivityAccountId, this.responseSpec, CommonConstants.RESPONSE_RESOURCE_ID); Assertions.assertNotNull(deletedFinancialActivityAccountId); Assertions.assertEquals(financialActivityAccountId, deletedFinancialActivityAccountId); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RolesTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RolesTest.java index a0dcd5775..d23f20c48 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RolesTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/RolesTest.java @@ -38,6 +38,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RolesTest { + private final static Logger LOG = LoggerFactory.getLogger(RolesTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -109,7 +110,7 @@ public class RolesTest { assertEquals(enableRoleId, roleId); role = RolesHelper.getRoleDetails(requestSpec, responseSpec, roleId); assertEquals((Integer) role.get("id"), roleId); - assertEquals(false,(Boolean) role.get("disabled")); + assertEquals(false, (Boolean) role.get("disabled")); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SchedulerJobsTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SchedulerJobsTest.java index adda06585..65fa9e747 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SchedulerJobsTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SchedulerJobsTest.java @@ -67,12 +67,12 @@ public class SchedulerJobsTest { @Test // FINERACT-926 public void testDateFormat() { - // must start scheduler and make job active to have nextRunTime (which is a + // must start scheduler and make job active to have nextRunTime (which + // is a // java.util.Date) schedulerJobHelper.updateSchedulerStatus(true); schedulerJobHelper.updateSchedulerJob(1, true); - String nextRunTimeText = await().until( - () -> (String) schedulerJobHelper.getSchedulerJobById(1).get("nextRunTime"), + String nextRunTimeText = await().until(() -> (String) schedulerJobHelper.getSchedulerJobById(1).get("nextRunTime"), nextRunTime -> nextRunTime != null); DateTimeFormatter.ISO_INSTANT.parse(nextRunTimeText); } @@ -102,7 +102,8 @@ public class SchedulerJobsTest { @Test public void testFlippingJobsActiveStatus() throws InterruptedException { - // Stop the Scheduler while we test flapping jobs' active on/off, to avoid side + // Stop the Scheduler while we test flapping jobs' active on/off, to + // avoid side // effects schedulerJobHelper.updateSchedulerStatus(false); @@ -131,4 +132,4 @@ public class SchedulerJobsTest { schedulerJobHelper.executeAndAwaitJob(jobName); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SchedulerJobsTestResults.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SchedulerJobsTestResults.java index c193fd32f..908726a69 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SchedulerJobsTestResults.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SchedulerJobsTestResults.java @@ -69,1007 +69,936 @@ import org.junit.jupiter.api.Test; @SuppressWarnings({ "unused", "unchecked", "rawtypes", "static-access", "cast" }) public class SchedulerJobsTestResults { - private static final String FROM_ACCOUNT_TYPE_LOAN = "1"; - private static final String FROM_ACCOUNT_TYPE_SAVINGS = "2"; - private static final String TO_ACCOUNT_TYPE_LOAN = "1"; - private static final String TO_ACCOUNT_TYPE_SAVINGS = "2"; - private final String DATE_OF_JOINING = "01 January 2011"; + private static final String FROM_ACCOUNT_TYPE_LOAN = "1"; + private static final String FROM_ACCOUNT_TYPE_SAVINGS = "2"; + private static final String TO_ACCOUNT_TYPE_LOAN = "1"; + private static final String TO_ACCOUNT_TYPE_SAVINGS = "2"; + private final String DATE_OF_JOINING = "01 January 2011"; - private final String TRANSACTION_DATE = "01 March 2013"; - public static final String ACCOUNT_TYPE_INDIVIDUAL = "INDIVIDUAL"; - public static final String MINIMUM_OPENING_BALANCE = "1000"; + private final String TRANSACTION_DATE = "01 March 2013"; + public static final String ACCOUNT_TYPE_INDIVIDUAL = "INDIVIDUAL"; + public static final String MINIMUM_OPENING_BALANCE = "1000"; - Float SP_BALANCE = Float.valueOf(MINIMUM_OPENING_BALANCE); + Float SP_BALANCE = Float.valueOf(MINIMUM_OPENING_BALANCE); - private static ResponseSpecification responseSpec; - private static RequestSpecification requestSpec; - private ResponseSpecification responseSpecForSchedulerJob; - private SchedulerJobHelper schedulerJobHelper; - private SavingsAccountHelper savingsAccountHelper; - private LoanTransactionHelper loanTransactionHelper; - private HolidayHelper holidayHelper; - private GlobalConfigurationHelper globalConfigurationHelper; - private AccountHelper accountHelper; - private JournalEntryHelper journalEntryHelper; - private StandingInstructionsHelper standingInstructionsHelper; + private static ResponseSpecification responseSpec; + private static RequestSpecification requestSpec; + private ResponseSpecification responseSpecForSchedulerJob; + private SchedulerJobHelper schedulerJobHelper; + private SavingsAccountHelper savingsAccountHelper; + private LoanTransactionHelper loanTransactionHelper; + private HolidayHelper holidayHelper; + private GlobalConfigurationHelper globalConfigurationHelper; + private AccountHelper accountHelper; + private JournalEntryHelper journalEntryHelper; + private StandingInstructionsHelper standingInstructionsHelper; - @BeforeEach - public void setup() { - Utils.initializeRESTAssured(); - this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - this.requestSpec.header("Authorization", - "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - this.requestSpec.header("Fineract-Platform-TenantId", "default"); - this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); - this.responseSpecForSchedulerJob = new ResponseSpecBuilder().expectStatusCode(202).build(); - this.accountHelper = new AccountHelper(this.requestSpec, this.responseSpec); - this.journalEntryHelper = new JournalEntryHelper(this.requestSpec, this.responseSpec); + @BeforeEach + public void setup() { + Utils.initializeRESTAssured(); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.requestSpec.header("Fineract-Platform-TenantId", "default"); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + this.responseSpecForSchedulerJob = new ResponseSpecBuilder().expectStatusCode(202).build(); + this.accountHelper = new AccountHelper(this.requestSpec, this.responseSpec); + this.journalEntryHelper = new JournalEntryHelper(this.requestSpec, this.responseSpec); + } + + @AfterEach + public void tearDown() { + GlobalConfigurationHelper.resetAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec); + GlobalConfigurationHelper.verifyAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec); + } + + @Test + public void testApplyAnnualFeeForSavingsJobOutcome() throws InterruptedException { + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, + ClientSavingsIntegrationTest.MINIMUM_OPENING_BALANCE); + Assertions.assertNotNull(savingsProductID); + + final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, + ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); + Assertions.assertNotNull(savingsProductID); + + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsId); + SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); + + final Integer annualFeeChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, + ChargesHelper.getSavingsAnnualFeeJSON()); + Assertions.assertNotNull(annualFeeChargeId); + + this.savingsAccountHelper.addChargesForSavings(savingsId, annualFeeChargeId, true); + ArrayList chargesPendingState = this.savingsAccountHelper.getSavingsCharges(savingsId); + Assertions.assertEquals(1, chargesPendingState.size()); + + savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); + SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); + + savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); + SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); + + String JobName = "Apply Annual Fee For Savings"; + + this.schedulerJobHelper.executeAndAwaitJob(JobName); + final HashMap chargeData = ChargesHelper.getChargeById(this.requestSpec, this.responseSpec, annualFeeChargeId); + + Float chargeAmount = (Float) chargeData.get("amount"); + + final HashMap savingsDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); + final HashMap annualFeeDetails = (HashMap) savingsDetails.get("annualFee"); + ArrayList annualFeeDueDateAsArrayList = (ArrayList) annualFeeDetails.get("dueDate"); + LocalDate nextDueDateForAnnualFee = LocalDate.of(annualFeeDueDateAsArrayList.get(0), annualFeeDueDateAsArrayList.get(1), + annualFeeDueDateAsArrayList.get(2)); + LocalDate todaysDate = LocalDate.now(ZoneId.of("Asia/Kolkata")); + + Assertions.assertTrue(nextDueDateForAnnualFee.isAfter(todaysDate), "Verifying that all due Annual Fees have been paid "); + + } + + @Test + public void testInterestPostingForSavingsJobOutcome() throws InterruptedException { + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, + ClientSavingsIntegrationTest.MINIMUM_OPENING_BALANCE); + Assertions.assertNotNull(savingsProductID); + + final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, + ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); + Assertions.assertNotNull(savingsProductID); + + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsId); + SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); + + savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); + SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); + + savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); + SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); + + final HashMap summaryBefore = this.savingsAccountHelper.getSavingsSummary(savingsId); + + String JobName = "Post Interest For Savings"; + + this.schedulerJobHelper.executeAndAwaitJob(JobName); + final HashMap summaryAfter = this.savingsAccountHelper.getSavingsSummary(savingsId); + + Assertions.assertNotSame(summaryBefore.get("accountBalance"), summaryAfter.get("accountBalance"), + "Verifying the Balance after running Post Interest for Savings Job"); + + } + + @Test + public void testTransferFeeForLoansFromSavingsJobOutcome() throws InterruptedException { + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, + ClientSavingsIntegrationTest.MINIMUM_OPENING_BALANCE); + Assertions.assertNotNull(savingsProductID); + + final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, + ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); + Assertions.assertNotNull(savingsProductID); + + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsId); + SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); + + savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); + SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); + + savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); + SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); + + final Integer loanProductID = createLoanProduct(null); + Assertions.assertNotNull(loanProductID); + + final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), savingsId.toString()); + Assertions.assertNotNull(loanID); + + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); + LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + + Integer specifiedDueDateChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, + ChargesHelper.getLoanSpecifiedDueDateWithAccountTransferJSON()); + Assertions.assertNotNull(specifiedDueDateChargeId); + + this.loanTransactionHelper.addChargesForLoan(loanID, + LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON(specifiedDueDateChargeId.toString(), "12 March 2013", "100")); + ArrayList chargesPendingState = this.loanTransactionHelper.getLoanCharges(loanID); + Assertions.assertEquals(1, chargesPendingState.size()); + + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(AccountTransferTest.LOAN_DISBURSAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); + final HashMap summaryBefore = this.savingsAccountHelper.getSavingsSummary(savingsId); + + String JobName = "Transfer Fee For Loans From Savings"; + this.schedulerJobHelper.executeAndAwaitJob(JobName); + final HashMap summaryAfter = this.savingsAccountHelper.getSavingsSummary(savingsId); + + final HashMap chargeData = ChargesHelper.getChargeById(this.requestSpec, this.responseSpec, specifiedDueDateChargeId); + + Float chargeAmount = (Float) chargeData.get("amount"); + + final Float balance = (Float) summaryBefore.get("accountBalance") - chargeAmount; + + Assertions.assertEquals(balance, (Float) summaryAfter.get("accountBalance"), + "Verifying the Balance after running Transfer Fee for Loans from Savings"); + + } + + @Test + public void testApplyHolidaysToLoansJobOutcome() throws InterruptedException { + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + this.holidayHelper = new HolidayHelper(this.requestSpec, this.responseSpec); + this.globalConfigurationHelper = new GlobalConfigurationHelper(this.requestSpec, this.responseSpec); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + Integer holidayId = this.holidayHelper.createHolidays(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(holidayId); + + final Integer loanProductID = createLoanProduct(null); + Assertions.assertNotNull(loanProductID); + + final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); + Assertions.assertNotNull(loanID); + + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); + LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(AccountTransferTest.LOAN_DISBURSAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); + + // Retrieving All Global Configuration details + final ArrayList globalConfig = this.globalConfigurationHelper.getAllGlobalConfigurations(this.requestSpec, + this.responseSpec); + Assertions.assertNotNull(globalConfig); + + // Updating Value for reschedule-repayments-on-holidays Global + // Configuration + Integer configId = (Integer) globalConfig.get(3).get("id"); + Assertions.assertNotNull(configId); + + HashMap configData = this.globalConfigurationHelper.getGlobalConfigurationById(this.requestSpec, this.responseSpec, + configId.toString()); + Assertions.assertNotNull(configData); + + Boolean enabled = (Boolean) globalConfig.get(3).get("enabled"); + + if (enabled == false) { + enabled = true; + configId = this.globalConfigurationHelper.updateEnabledFlagForGlobalConfiguration(this.requestSpec, this.responseSpec, + configId.toString(), enabled); + } + final ArrayList repaymentScheduleDataBeforeJob = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, + this.responseSpec, loanID); + + holidayId = this.holidayHelper.activateHolidays(this.requestSpec, this.responseSpec, holidayId.toString()); + Assertions.assertNotNull(holidayId); + + String JobName = "Apply Holidays To Loans"; + + this.schedulerJobHelper.executeAndAwaitJob(JobName); + final ArrayList repaymentScheduleDataAfterJob = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, + this.responseSpec, loanID); + + HashMap holidayData = this.holidayHelper.getHolidayById(this.requestSpec, this.responseSpec, holidayId.toString()); + ArrayList repaymentsRescheduledDate = (ArrayList) holidayData.get("repaymentsRescheduledTo"); + + ArrayList rescheduleDateAfter = (ArrayList) repaymentScheduleDataAfterJob.get(2).get("fromDate"); + + Assertions.assertEquals(repaymentsRescheduledDate, repaymentsRescheduledDate, + "Verifying Repayment Rescheduled Date after Running Apply Holidays to Loans Scheduler Job"); + + } + + @Test + public void testApplyDueFeeChargesForSavingsJobOutcome() throws InterruptedException { + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, + ClientSavingsIntegrationTest.MINIMUM_OPENING_BALANCE); + Assertions.assertNotNull(savingsProductID); + + final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, + ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); + Assertions.assertNotNull(savingsProductID); + + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsId); + SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); + + final Integer specifiedDueDateChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, + ChargesHelper.getSavingsSpecifiedDueDateJSON()); + Assertions.assertNotNull(specifiedDueDateChargeId); + + this.savingsAccountHelper.addChargesForSavings(savingsId, specifiedDueDateChargeId, true); + ArrayList chargesPendingState = this.savingsAccountHelper.getSavingsCharges(savingsId); + Assertions.assertEquals(1, chargesPendingState.size()); + + savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); + SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); + + savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); + SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); + + HashMap summaryBefore = this.savingsAccountHelper.getSavingsSummary(savingsId); + + String JobName = "Pay Due Savings Charges"; + + this.schedulerJobHelper.executeAndAwaitJob(JobName); + HashMap summaryAfter = this.savingsAccountHelper.getSavingsSummary(savingsId); + + final HashMap chargeData = ChargesHelper.getChargeById(this.requestSpec, this.responseSpec, specifiedDueDateChargeId); + + Float chargeAmount = (Float) chargeData.get("amount"); + + final Float balance = (Float) summaryBefore.get("accountBalance") - chargeAmount; + + Assertions.assertEquals(balance, (Float) summaryAfter.get("accountBalance"), + "Verifying the Balance after running Pay due Savings Charges"); + } + + @Test + public void testUpdateAccountingRunningBalancesJobOutcome() throws InterruptedException { + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + + final Account assetAccount = this.accountHelper.createAssetAccount(); + final Account incomeAccount = this.accountHelper.createIncomeAccount(); + final Account expenseAccount = this.accountHelper.createExpenseAccount(); + final Account liabilityAccount = this.accountHelper.createLiabilityAccount(); + + final Integer accountID = assetAccount.getAccountID(); + + final Integer savingsProductID = createSavingsProduct(MINIMUM_OPENING_BALANCE, assetAccount, incomeAccount, expenseAccount, + liabilityAccount); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, this.DATE_OF_JOINING); + final Integer savingsID = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, ACCOUNT_TYPE_INDIVIDUAL); + + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsID); + SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); + + savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsID); + SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); + + savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsID); + SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); + + // Checking initial Account entries. + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(this.SP_BALANCE, JournalEntry.TransactionType.DEBIT) }; + final JournalEntry[] liablilityAccountInitialEntry = { new JournalEntry(this.SP_BALANCE, JournalEntry.TransactionType.CREDIT) }; + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.TRANSACTION_DATE, assetAccountInitialEntry); + this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, this.TRANSACTION_DATE, + liablilityAccountInitialEntry); + + String JobName = "Update Accounting Running Balances"; + + this.schedulerJobHelper.executeAndAwaitJob(JobName); + final HashMap runningBalanceAfter = this.accountHelper.getAccountingWithRunningBalanceById(accountID.toString()); + + final Integer INT_BALANCE = Integer.valueOf(MINIMUM_OPENING_BALANCE); + + Assertions.assertEquals(INT_BALANCE, runningBalanceAfter.get("organizationRunningBalance"), + "Verifying Account Running Balance after running Update Accounting Running Balances Scheduler Job"); + + } + + @Test + public void testUpdateLoanArrearsAgingJobOutcome() throws InterruptedException { + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + final Integer loanProductID = createLoanProduct(null); + Assertions.assertNotNull(loanProductID); + + final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); + Assertions.assertNotNull(loanID); + + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); + LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(AccountTransferTest.LOAN_DISBURSAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); + + String JobName = "Update Loan Arrears Ageing"; + + this.schedulerJobHelper.executeAndAwaitJob(JobName); + HashMap loanSummaryData = this.loanTransactionHelper.getLoanSummary(this.requestSpec, this.responseSpec, loanID); + + Float totalLoanArrearsAging = (Float) loanSummaryData.get("principalOverdue") + (Float) loanSummaryData.get("interestOverdue"); + + Assertions.assertEquals(totalLoanArrearsAging, loanSummaryData.get("totalOverdue"), + "Verifying Arrears Aging after Running Update Loan Arrears Aging Scheduler Job"); + + } + + @Test + public void testUpdateLoanPaidInAdvanceJobOutcome() throws InterruptedException { + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + + DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + + Calendar todayDate = Calendar.getInstance(); + final String currentDate = dateFormat.format(todayDate.getTime()); + + todayDate.add(Calendar.MONTH, -1); + final String LOAN_DISBURSEMENT_DATE = dateFormat.format(todayDate.getTime()); + + todayDate = Calendar.getInstance(); + todayDate.add(Calendar.DATE, -5); + final String LOAN_FIRST_REPAYMENT_DATE = dateFormat.format(todayDate.getTime()); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + final Integer loanProductID = createLoanProduct(null); + Assertions.assertNotNull(loanProductID); + + final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); + Assertions.assertNotNull(loanID); + + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); + LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(LOAN_DISBURSEMENT_DATE, loanID); + LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); + + ArrayList loanScheduleBefore = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, + loanID); + + Float totalDueForCurrentPeriod = (Float) loanScheduleBefore.get(1).get("totalDueForPeriod"); + + this.loanTransactionHelper.makeRepayment(LOAN_FIRST_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); + + HashMap loanSummary = this.loanTransactionHelper.getLoanSummary(this.requestSpec, this.responseSpec, loanID); + + String JobName = "Update Loan Paid In Advance"; + this.schedulerJobHelper.executeAndAwaitJob(JobName); + // Retrieving Loan Repayment Schedule after the successful + // completion of + // Update Loan Paid in Advance Scheduler Job + ArrayList loanScheduleAfter = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, + loanID); + + loanSummary = this.loanTransactionHelper.getLoanSummary(this.requestSpec, this.responseSpec, loanID); + + Float totalPaidInAdvance = (Float) loanScheduleAfter.get(1).get("totalPaidInAdvanceForPeriod"); + + Assertions.assertEquals(totalDueForCurrentPeriod, totalPaidInAdvance, + "Verifying Loan Repayment in Advance after Running Update Loan Paid in Advance Scheduler Job"); + + } + + // Invalid test case as it won't affect summary (Loan summary is properly + // updated before running this job) + @Disabled + @Test + public void testUpdateLoanSummaryJobOutcome() throws InterruptedException { + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + + DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + + Calendar todaysDate = Calendar.getInstance(); + final String currentDate = dateFormat.format(todaysDate.getTime()); + + todaysDate.add(Calendar.MONTH, -1); + final String LOAN_DISBURSEMENT_DATE = dateFormat.format(todaysDate.getTime()); + + todaysDate = Calendar.getInstance(); + todaysDate.add(Calendar.DATE, -5); + final String LOAN_FIRST_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + final Integer loanProductID = createLoanProduct(null); + Assertions.assertNotNull(loanProductID); + + final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); + Assertions.assertNotNull(loanID); + + Integer disburseChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, + ChargesHelper.getLoanDisbursementJSON()); + Assertions.assertNotNull(disburseChargeId); + + this.loanTransactionHelper.addChargesForLoan(loanID, + LoanTransactionHelper.getDisbursementChargesForLoanAsJSON(disburseChargeId.toString())); + ArrayList chargesPendingState = this.loanTransactionHelper.getLoanCharges(loanID); + Assertions.assertEquals(1, chargesPendingState.size()); + + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); + LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(LOAN_DISBURSEMENT_DATE, loanID); + LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); + + HashMap loanSummaryBefore = this.loanTransactionHelper.getLoanSummary(this.requestSpec, this.responseSpec, loanID); + + String JobName = "Update loan Summary"; + this.schedulerJobHelper.executeAndAwaitJob(JobName); + Float expectedSummaryAfterJob = (Float) loanSummaryBefore.get("totalExpectedRepayment") + /* - (Float) loanSummaryBefore.get("feeChargesPaid") */; + HashMap loanSummaryAfter = this.loanTransactionHelper.getLoanSummary(this.requestSpec, this.responseSpec, loanID); + Assertions.assertEquals(expectedSummaryAfterJob, (Float) loanSummaryAfter.get("totalExpectedRepayment"), + "Verifying Loan Summary after Running Update Loan Summary Scheduler Job"); + + } + + @Test + public void testExecuteStandingInstructionsJobOutcome() throws InterruptedException { + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); + this.standingInstructionsHelper = new StandingInstructionsHelper(this.requestSpec, this.responseSpec); + + DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + DateFormat monthDayFormat = new SimpleDateFormat("dd MMMM", Locale.US); + + Calendar todaysDate = Calendar.getInstance(); + todaysDate.add(Calendar.WEEK_OF_YEAR, -1); + final String VALID_FROM = dateFormat.format(todaysDate.getTime()); + + final String MONTH_DAY = monthDayFormat.format(todaysDate.getTime()); + + todaysDate.add(Calendar.YEAR, 1); + final String VALID_TO = dateFormat.format(todaysDate.getTime()); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, + ClientSavingsIntegrationTest.MINIMUM_OPENING_BALANCE); + Assertions.assertNotNull(savingsProductID); + + final Integer fromSavingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, + ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); + Assertions.assertNotNull(savingsProductID); + + HashMap fromSavingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, fromSavingsId); + SavingsStatusChecker.verifySavingsIsPending(fromSavingsStatusHashMap); + + fromSavingsStatusHashMap = this.savingsAccountHelper.approveSavings(fromSavingsId); + SavingsStatusChecker.verifySavingsIsApproved(fromSavingsStatusHashMap); + + fromSavingsStatusHashMap = this.savingsAccountHelper.activateSavings(fromSavingsId); + SavingsStatusChecker.verifySavingsIsActive(fromSavingsStatusHashMap); + + final Integer toSavingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, savingsProductID, + ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); + Assertions.assertNotNull(savingsProductID); + + HashMap toSavingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, toSavingsId); + SavingsStatusChecker.verifySavingsIsPending(toSavingsStatusHashMap); + + toSavingsStatusHashMap = this.savingsAccountHelper.approveSavings(toSavingsId); + SavingsStatusChecker.verifySavingsIsApproved(toSavingsStatusHashMap); + + toSavingsStatusHashMap = this.savingsAccountHelper.activateSavings(toSavingsId); + SavingsStatusChecker.verifySavingsIsActive(toSavingsStatusHashMap); + + HashMap fromSavingsSummaryBefore = this.savingsAccountHelper.getSavingsSummary(fromSavingsId); + Float fromSavingsBalanceBefore = (Float) fromSavingsSummaryBefore.get("accountBalance"); + + HashMap toSavingsSummaryBefore = this.savingsAccountHelper.getSavingsSummary(toSavingsId); + Float toSavingsBalanceBefore = (Float) toSavingsSummaryBefore.get("accountBalance"); + + Integer standingInstructionId = this.standingInstructionsHelper.createStandingInstruction(clientID.toString(), + fromSavingsId.toString(), toSavingsId.toString(), FROM_ACCOUNT_TYPE_SAVINGS, TO_ACCOUNT_TYPE_SAVINGS, VALID_FROM, VALID_TO, + MONTH_DAY); + Assertions.assertNotNull(standingInstructionId); + + String JobName = "Execute Standing Instruction"; + this.schedulerJobHelper.executeAndAwaitJob(JobName); + HashMap fromSavingsSummaryAfter = this.savingsAccountHelper.getSavingsSummary(fromSavingsId); + Float fromSavingsBalanceAfter = (Float) fromSavingsSummaryAfter.get("accountBalance"); + + HashMap toSavingsSummaryAfter = this.savingsAccountHelper.getSavingsSummary(toSavingsId); + Float toSavingsBalanceAfter = (Float) toSavingsSummaryAfter.get("accountBalance"); + + final HashMap standingInstructionData = this.standingInstructionsHelper + .getStandingInstructionById(standingInstructionId.toString()); + Float expectedFromSavingsBalance = fromSavingsBalanceBefore - (Float) standingInstructionData.get("amount"); + Float expectedToSavingsBalance = toSavingsBalanceBefore + (Float) standingInstructionData.get("amount"); + + Assertions.assertEquals(expectedFromSavingsBalance, fromSavingsBalanceAfter, + "Verifying From Savings Balance after Successful completion of Scheduler Job"); + Assertions.assertEquals(expectedToSavingsBalance, toSavingsBalanceAfter, + "Verifying To Savings Balance after Successful completion of Scheduler Job"); + Integer fromAccountType = PortfolioAccountType.SAVINGS.getValue(); + Integer transferType = AccountTransferType.ACCOUNT_TRANSFER.getValue(); + List standinInstructionHistoryData = this.standingInstructionsHelper.getStandingInstructionHistory(fromSavingsId, + fromAccountType, clientID, transferType); + Assertions.assertEquals(1, standinInstructionHistoryData.size(), + "Verifying the no of stainding instruction transactions logged for the client"); + HashMap loggedTransaction = standinInstructionHistoryData.get(0); + + Assertions.assertEquals((Float) standingInstructionData.get("amount"), (Float) loggedTransaction.get("amount"), + "Verifying transferred amount and logged transaction amounts"); + + } + + @Test + public void testApplyPenaltyForOverdueLoansJobOutcome() throws InterruptedException { + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + Integer overdueFeeChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, + ChargesHelper.getLoanOverdueFeeJSON()); + Assertions.assertNotNull(overdueFeeChargeId); + + final Integer loanProductID = createLoanProduct(overdueFeeChargeId.toString()); + Assertions.assertNotNull(loanProductID); + + final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); + Assertions.assertNotNull(loanID); + + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); + LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(AccountTransferTest.LOAN_APPROVAL_DATE_PLUS_ONE, loanID); + LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); + + ArrayList repaymentScheduleDataBefore = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, + this.responseSpec, loanID); + + String JobName = "Apply penalty to overdue loans"; + this.schedulerJobHelper.executeAndAwaitJob(JobName); + + final HashMap chargeData = ChargesHelper.getChargeById(this.requestSpec, this.responseSpec, overdueFeeChargeId); + + Float chargeAmount = (Float) chargeData.get("amount"); + + ArrayList repaymentScheduleDataAfter = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, + this.responseSpec, loanID); + + Assertions.assertEquals(chargeAmount, (Float) repaymentScheduleDataAfter.get(1).get("penaltyChargesDue"), + "Verifying From Penalty Charges due fot first Repayment after Successful completion of Scheduler Job"); + + loanStatusHashMap = this.loanTransactionHelper.undoDisbursal(loanID); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); + + } + + @Test + public void testAvoidUnncessaryPenaltyWhenAmountZeroForOverdueLoansJobOutcome() throws InterruptedException { + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); + + Integer overdueFeeChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, + ChargesHelper.getLoanOverdueFeeJSONWithCalculattionTypePercentage("0.000001")); + Assertions.assertNotNull(overdueFeeChargeId); + + final Integer loanProductID = createLoanProduct(overdueFeeChargeId.toString()); + Assertions.assertNotNull(loanProductID); + + final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); + Assertions.assertNotNull(loanID); + + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); + LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(AccountTransferTest.LOAN_APPROVAL_DATE_PLUS_ONE, loanID); + LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); + + ArrayList repaymentScheduleDataBefore = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, + this.responseSpec, loanID); + + String JobName = "Apply penalty to overdue loans"; + Integer jobId = 12; + + this.schedulerJobHelper.executeAndAwaitJob(JobName); + + Map schedulerJob = this.schedulerJobHelper.getSchedulerJobById(jobId); + + Assertions.assertNotNull(schedulerJob); + while ((Boolean) schedulerJob.get("currentlyRunning") == true) { + Thread.sleep(15000); + schedulerJob = this.schedulerJobHelper.getSchedulerJobById(jobId); + Assertions.assertNotNull(schedulerJob); } - @AfterEach - public void tearDown() { - GlobalConfigurationHelper.resetAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec); - GlobalConfigurationHelper.verifyAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec); - } + final HashMap chargeData = ChargesHelper.getChargeById(this.requestSpec, this.responseSpec, overdueFeeChargeId); - @Test - public void testApplyAnnualFeeForSavingsJobOutcome() throws InterruptedException { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + ArrayList repaymentScheduleDataAfter = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, + this.responseSpec, loanID); + + Assertions.assertEquals(0, repaymentScheduleDataAfter.get(1).get("penaltyChargesDue"), + "Verifying From Penalty Charges due fot first Repayment after Successful completion of Scheduler Job"); + + final ArrayList loanCharges = this.loanTransactionHelper.getLoanCharges(this.requestSpec, this.responseSpec, loanID); - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); + Assertions.assertNull(loanCharges, "Verifying that charge isn't created when the amount is 0"); + + loanStatusHashMap = this.loanTransactionHelper.undoDisbursal(loanID); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); + + } + + @Test + public void testUpdateOverdueDaysForNPA() throws InterruptedException { + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, - ClientSavingsIntegrationTest.MINIMUM_OPENING_BALANCE); - Assertions.assertNotNull(savingsProductID); + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientID); - final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, - savingsProductID, ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); - Assertions.assertNotNull(savingsProductID); + final Integer loanProductID = createLoanProduct(null); + Assertions.assertNotNull(loanProductID); + + final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); + Assertions.assertNotNull(loanID); + + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); + LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, - this.responseSpec, savingsId); - SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); - - final Integer annualFeeChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, - ChargesHelper.getSavingsAnnualFeeJSON()); - Assertions.assertNotNull(annualFeeChargeId); - - this.savingsAccountHelper.addChargesForSavings(savingsId, annualFeeChargeId, true); - ArrayList chargesPendingState = this.savingsAccountHelper.getSavingsCharges(savingsId); - Assertions.assertEquals(1, chargesPendingState.size()); - - savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); - SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); - - savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); - SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); - - String JobName = "Apply Annual Fee For Savings"; - - this.schedulerJobHelper.executeAndAwaitJob(JobName); - final HashMap chargeData = ChargesHelper.getChargeById(this.requestSpec, this.responseSpec, - annualFeeChargeId); - - Float chargeAmount = (Float) chargeData.get("amount"); - - final HashMap savingsDetails = this.savingsAccountHelper.getSavingsDetails(savingsId); - final HashMap annualFeeDetails = (HashMap) savingsDetails.get("annualFee"); - ArrayList annualFeeDueDateAsArrayList = (ArrayList) annualFeeDetails.get("dueDate"); - LocalDate nextDueDateForAnnualFee = LocalDate.of(annualFeeDueDateAsArrayList.get(0), - annualFeeDueDateAsArrayList.get(1), annualFeeDueDateAsArrayList.get(2)); - LocalDate todaysDate = LocalDate.now(ZoneId.of("Asia/Kolkata")); - - Assertions.assertTrue(nextDueDateForAnnualFee.isAfter(todaysDate), - "Verifying that all due Annual Fees have been paid "); - - } - - @Test - public void testInterestPostingForSavingsJobOutcome() throws InterruptedException { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, - ClientSavingsIntegrationTest.MINIMUM_OPENING_BALANCE); - Assertions.assertNotNull(savingsProductID); - - final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, - savingsProductID, ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); - Assertions.assertNotNull(savingsProductID); - - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, - this.responseSpec, savingsId); - SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); - - savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); - SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); - - savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); - SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); - - final HashMap summaryBefore = this.savingsAccountHelper.getSavingsSummary(savingsId); - - String JobName = "Post Interest For Savings"; - - this.schedulerJobHelper.executeAndAwaitJob(JobName); - final HashMap summaryAfter = this.savingsAccountHelper.getSavingsSummary(savingsId); - - Assertions.assertNotSame(summaryBefore.get("accountBalance"), summaryAfter.get("accountBalance"), - "Verifying the Balance after running Post Interest for Savings Job"); - - } - - @Test - public void testTransferFeeForLoansFromSavingsJobOutcome() throws InterruptedException { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, - ClientSavingsIntegrationTest.MINIMUM_OPENING_BALANCE); - Assertions.assertNotNull(savingsProductID); - - final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, - savingsProductID, ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); - Assertions.assertNotNull(savingsProductID); - - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, - this.responseSpec, savingsId); - SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); - - savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); - SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); - - savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); - SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); - - final Integer loanProductID = createLoanProduct(null); - Assertions.assertNotNull(loanProductID); - - final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), - savingsId.toString()); - Assertions.assertNotNull(loanID); - - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, - loanID); - LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - - Integer specifiedDueDateChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, - ChargesHelper.getLoanSpecifiedDueDateWithAccountTransferJSON()); - Assertions.assertNotNull(specifiedDueDateChargeId); - - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getSpecifiedDueDateChargesForLoanAsJSON( - specifiedDueDateChargeId.toString(), "12 March 2013", "100")); - ArrayList chargesPendingState = this.loanTransactionHelper.getLoanCharges(loanID); - Assertions.assertEquals(1, chargesPendingState.size()); - - loanStatusHashMap = this.loanTransactionHelper.disburseLoan(AccountTransferTest.LOAN_DISBURSAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - final HashMap summaryBefore = this.savingsAccountHelper.getSavingsSummary(savingsId); - - String JobName = "Transfer Fee For Loans From Savings"; - this.schedulerJobHelper.executeAndAwaitJob(JobName); - final HashMap summaryAfter = this.savingsAccountHelper.getSavingsSummary(savingsId); - - final HashMap chargeData = ChargesHelper.getChargeById(this.requestSpec, this.responseSpec, - specifiedDueDateChargeId); - - Float chargeAmount = (Float) chargeData.get("amount"); - - final Float balance = (Float) summaryBefore.get("accountBalance") - chargeAmount; - - Assertions.assertEquals(balance, (Float) summaryAfter.get("accountBalance"), - "Verifying the Balance after running Transfer Fee for Loans from Savings"); - - } - - @Test - public void testApplyHolidaysToLoansJobOutcome() throws InterruptedException { - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - this.holidayHelper = new HolidayHelper(this.requestSpec, this.responseSpec); - this.globalConfigurationHelper = new GlobalConfigurationHelper(this.requestSpec, this.responseSpec); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - Integer holidayId = this.holidayHelper.createHolidays(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(holidayId); - - final Integer loanProductID = createLoanProduct(null); - Assertions.assertNotNull(loanProductID); - - final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); - Assertions.assertNotNull(loanID); - - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, - loanID); - LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.disburseLoan(AccountTransferTest.LOAN_DISBURSAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - - // Retrieving All Global Configuration details - final ArrayList globalConfig = this.globalConfigurationHelper - .getAllGlobalConfigurations(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(globalConfig); - - // Updating Value for reschedule-repayments-on-holidays Global - // Configuration - Integer configId = (Integer) globalConfig.get(3).get("id"); - Assertions.assertNotNull(configId); - - HashMap configData = this.globalConfigurationHelper.getGlobalConfigurationById(this.requestSpec, - this.responseSpec, configId.toString()); - Assertions.assertNotNull(configData); - - Boolean enabled = (Boolean) globalConfig.get(3).get("enabled"); - - if (enabled == false) { - enabled = true; - configId = this.globalConfigurationHelper.updateEnabledFlagForGlobalConfiguration( - this.requestSpec, this.responseSpec, configId.toString(), enabled); - } - final ArrayList repaymentScheduleDataBeforeJob = this.loanTransactionHelper - .getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); - - holidayId = this.holidayHelper.activateHolidays(this.requestSpec, this.responseSpec, - holidayId.toString()); - Assertions.assertNotNull(holidayId); - - String JobName = "Apply Holidays To Loans"; - - this.schedulerJobHelper.executeAndAwaitJob(JobName); - final ArrayList repaymentScheduleDataAfterJob = this.loanTransactionHelper - .getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); - - HashMap holidayData = this.holidayHelper.getHolidayById(this.requestSpec, this.responseSpec, - holidayId.toString()); - ArrayList repaymentsRescheduledDate = (ArrayList) holidayData - .get("repaymentsRescheduledTo"); - - ArrayList rescheduleDateAfter = (ArrayList) repaymentScheduleDataAfterJob.get(2) - .get("fromDate"); - - Assertions.assertEquals(repaymentsRescheduledDate, repaymentsRescheduledDate, - "Verifying Repayment Rescheduled Date after Running Apply Holidays to Loans Scheduler Job"); - - } - - @Test - public void testApplyDueFeeChargesForSavingsJobOutcome() throws InterruptedException { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, - ClientSavingsIntegrationTest.MINIMUM_OPENING_BALANCE); - Assertions.assertNotNull(savingsProductID); - - final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, - savingsProductID, ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); - Assertions.assertNotNull(savingsProductID); - - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, - this.responseSpec, savingsId); - SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); - - final Integer specifiedDueDateChargeId = ChargesHelper.createCharges(this.requestSpec, - this.responseSpec, ChargesHelper.getSavingsSpecifiedDueDateJSON()); - Assertions.assertNotNull(specifiedDueDateChargeId); - - this.savingsAccountHelper.addChargesForSavings(savingsId, specifiedDueDateChargeId, true); - ArrayList chargesPendingState = this.savingsAccountHelper.getSavingsCharges(savingsId); - Assertions.assertEquals(1, chargesPendingState.size()); - - savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); - SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); - - savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); - SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); - - HashMap summaryBefore = this.savingsAccountHelper.getSavingsSummary(savingsId); - - String JobName = "Pay Due Savings Charges"; - - this.schedulerJobHelper.executeAndAwaitJob(JobName); - HashMap summaryAfter = this.savingsAccountHelper.getSavingsSummary(savingsId); - - final HashMap chargeData = ChargesHelper.getChargeById(this.requestSpec, this.responseSpec, - specifiedDueDateChargeId); - - Float chargeAmount = (Float) chargeData.get("amount"); - - final Float balance = (Float) summaryBefore.get("accountBalance") - chargeAmount; - - Assertions.assertEquals(balance, (Float) summaryAfter.get("accountBalance"), - "Verifying the Balance after running Pay due Savings Charges"); - } - - @Test - public void testUpdateAccountingRunningBalancesJobOutcome() throws InterruptedException { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - - final Account assetAccount = this.accountHelper.createAssetAccount(); - final Account incomeAccount = this.accountHelper.createIncomeAccount(); - final Account expenseAccount = this.accountHelper.createExpenseAccount(); - final Account liabilityAccount = this.accountHelper.createLiabilityAccount(); - - final Integer accountID = assetAccount.getAccountID(); - - final Integer savingsProductID = createSavingsProduct(MINIMUM_OPENING_BALANCE, assetAccount, - incomeAccount, expenseAccount, liabilityAccount); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, - this.DATE_OF_JOINING); - final Integer savingsID = this.savingsAccountHelper.applyForSavingsApplication(clientID, - savingsProductID, ACCOUNT_TYPE_INDIVIDUAL); - - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, - this.responseSpec, savingsID); - SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); - - savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsID); - SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); - - savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsID); - SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); - - // Checking initial Account entries. - final JournalEntry[] assetAccountInitialEntry = { - new JournalEntry(this.SP_BALANCE, JournalEntry.TransactionType.DEBIT) }; - final JournalEntry[] liablilityAccountInitialEntry = { - new JournalEntry(this.SP_BALANCE, JournalEntry.TransactionType.CREDIT) }; - this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.TRANSACTION_DATE, - assetAccountInitialEntry); - this.journalEntryHelper.checkJournalEntryForLiabilityAccount(liabilityAccount, this.TRANSACTION_DATE, - liablilityAccountInitialEntry); - - String JobName = "Update Accounting Running Balances"; - - this.schedulerJobHelper.executeAndAwaitJob(JobName); - final HashMap runningBalanceAfter = this.accountHelper - .getAccountingWithRunningBalanceById(accountID.toString()); - - final Integer INT_BALANCE = Integer.valueOf(MINIMUM_OPENING_BALANCE); - - Assertions.assertEquals(INT_BALANCE, runningBalanceAfter.get("organizationRunningBalance"), - "Verifying Account Running Balance after running Update Accounting Running Balances Scheduler Job"); - - } - - @Test - public void testUpdateLoanArrearsAgingJobOutcome() throws InterruptedException { - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - final Integer loanProductID = createLoanProduct(null); - Assertions.assertNotNull(loanProductID); - - final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); - Assertions.assertNotNull(loanID); - - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, - loanID); - LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.disburseLoan(AccountTransferTest.LOAN_DISBURSAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - - String JobName = "Update Loan Arrears Ageing"; - - this.schedulerJobHelper.executeAndAwaitJob(JobName); - HashMap loanSummaryData = this.loanTransactionHelper.getLoanSummary(this.requestSpec, this.responseSpec, - loanID); - - Float totalLoanArrearsAging = (Float) loanSummaryData.get("principalOverdue") - + (Float) loanSummaryData.get("interestOverdue"); - - Assertions.assertEquals(totalLoanArrearsAging, loanSummaryData.get("totalOverdue"), - "Verifying Arrears Aging after Running Update Loan Arrears Aging Scheduler Job"); - - } - - @Test - public void testUpdateLoanPaidInAdvanceJobOutcome() throws InterruptedException { - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - - DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); - - Calendar todayDate = Calendar.getInstance(); - final String currentDate = dateFormat.format(todayDate.getTime()); - - todayDate.add(Calendar.MONTH, -1); - final String LOAN_DISBURSEMENT_DATE = dateFormat.format(todayDate.getTime()); - - todayDate = Calendar.getInstance(); - todayDate.add(Calendar.DATE, -5); - final String LOAN_FIRST_REPAYMENT_DATE = dateFormat.format(todayDate.getTime()); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - final Integer loanProductID = createLoanProduct(null); - Assertions.assertNotNull(loanProductID); - - final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); - Assertions.assertNotNull(loanID); - - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, - loanID); - LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.disburseLoan(LOAN_DISBURSEMENT_DATE, loanID); - LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - - ArrayList loanScheduleBefore = this.loanTransactionHelper - .getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); - - Float totalDueForCurrentPeriod = (Float) loanScheduleBefore.get(1).get("totalDueForPeriod"); - - this.loanTransactionHelper.makeRepayment(LOAN_FIRST_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); - - HashMap loanSummary = this.loanTransactionHelper.getLoanSummary(this.requestSpec, this.responseSpec, - loanID); - - String JobName = "Update Loan Paid In Advance"; - this.schedulerJobHelper.executeAndAwaitJob(JobName); - // Retrieving Loan Repayment Schedule after the successful - // completion of - // Update Loan Paid in Advance Scheduler Job - ArrayList loanScheduleAfter = this.loanTransactionHelper - .getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); - - loanSummary = this.loanTransactionHelper.getLoanSummary(this.requestSpec, this.responseSpec, loanID); - - Float totalPaidInAdvance = (Float) loanScheduleAfter.get(1).get("totalPaidInAdvanceForPeriod"); - - Assertions.assertEquals(totalDueForCurrentPeriod, totalPaidInAdvance, - "Verifying Loan Repayment in Advance after Running Update Loan Paid in Advance Scheduler Job"); - - } - - // Invalid test case as it won't affect summary (Loan summary is properly - // updated before running this job) - @Disabled - @Test - public void testUpdateLoanSummaryJobOutcome() throws InterruptedException { - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - - DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); - - Calendar todaysDate = Calendar.getInstance(); - final String currentDate = dateFormat.format(todaysDate.getTime()); - - todaysDate.add(Calendar.MONTH, -1); - final String LOAN_DISBURSEMENT_DATE = dateFormat.format(todaysDate.getTime()); - - todaysDate = Calendar.getInstance(); - todaysDate.add(Calendar.DATE, -5); - final String LOAN_FIRST_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - final Integer loanProductID = createLoanProduct(null); - Assertions.assertNotNull(loanProductID); - - final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); - Assertions.assertNotNull(loanID); - - Integer disburseChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, - ChargesHelper.getLoanDisbursementJSON()); - Assertions.assertNotNull(disburseChargeId); - - this.loanTransactionHelper.addChargesForLoan(loanID, - LoanTransactionHelper.getDisbursementChargesForLoanAsJSON(disburseChargeId.toString())); - ArrayList chargesPendingState = this.loanTransactionHelper.getLoanCharges(loanID); - Assertions.assertEquals(1, chargesPendingState.size()); - - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, - loanID); - LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.disburseLoan(LOAN_DISBURSEMENT_DATE, loanID); - LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - - HashMap loanSummaryBefore = this.loanTransactionHelper.getLoanSummary(this.requestSpec, - this.responseSpec, loanID); - - String JobName = "Update loan Summary"; - this.schedulerJobHelper.executeAndAwaitJob(JobName); - Float expectedSummaryAfterJob = (Float) loanSummaryBefore.get("totalExpectedRepayment") - /* - (Float) loanSummaryBefore.get("feeChargesPaid") */; - HashMap loanSummaryAfter = this.loanTransactionHelper.getLoanSummary(this.requestSpec, - this.responseSpec, loanID); - Assertions.assertEquals(expectedSummaryAfterJob, (Float) loanSummaryAfter.get("totalExpectedRepayment"), - "Verifying Loan Summary after Running Update Loan Summary Scheduler Job"); - - } - - @Test - public void testExecuteStandingInstructionsJobOutcome() throws InterruptedException { - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - this.standingInstructionsHelper = new StandingInstructionsHelper(this.requestSpec, this.responseSpec); - - DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); - DateFormat monthDayFormat = new SimpleDateFormat("dd MMMM", Locale.US); - - Calendar todaysDate = Calendar.getInstance(); - todaysDate.add(Calendar.WEEK_OF_YEAR, -1); - final String VALID_FROM = dateFormat.format(todaysDate.getTime()); - - final String MONTH_DAY = monthDayFormat.format(todaysDate.getTime()); - - todaysDate.add(Calendar.YEAR, 1); - final String VALID_TO = dateFormat.format(todaysDate.getTime()); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, - ClientSavingsIntegrationTest.MINIMUM_OPENING_BALANCE); - Assertions.assertNotNull(savingsProductID); - - final Integer fromSavingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, - savingsProductID, ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); - Assertions.assertNotNull(savingsProductID); - - HashMap fromSavingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, - this.responseSpec, fromSavingsId); - SavingsStatusChecker.verifySavingsIsPending(fromSavingsStatusHashMap); - - fromSavingsStatusHashMap = this.savingsAccountHelper.approveSavings(fromSavingsId); - SavingsStatusChecker.verifySavingsIsApproved(fromSavingsStatusHashMap); - - fromSavingsStatusHashMap = this.savingsAccountHelper.activateSavings(fromSavingsId); - SavingsStatusChecker.verifySavingsIsActive(fromSavingsStatusHashMap); - - final Integer toSavingsId = this.savingsAccountHelper.applyForSavingsApplication(clientID, - savingsProductID, ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); - Assertions.assertNotNull(savingsProductID); - - HashMap toSavingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, - this.responseSpec, toSavingsId); - SavingsStatusChecker.verifySavingsIsPending(toSavingsStatusHashMap); - - toSavingsStatusHashMap = this.savingsAccountHelper.approveSavings(toSavingsId); - SavingsStatusChecker.verifySavingsIsApproved(toSavingsStatusHashMap); - - toSavingsStatusHashMap = this.savingsAccountHelper.activateSavings(toSavingsId); - SavingsStatusChecker.verifySavingsIsActive(toSavingsStatusHashMap); - - HashMap fromSavingsSummaryBefore = this.savingsAccountHelper.getSavingsSummary(fromSavingsId); - Float fromSavingsBalanceBefore = (Float) fromSavingsSummaryBefore.get("accountBalance"); - - HashMap toSavingsSummaryBefore = this.savingsAccountHelper.getSavingsSummary(toSavingsId); - Float toSavingsBalanceBefore = (Float) toSavingsSummaryBefore.get("accountBalance"); - - Integer standingInstructionId = this.standingInstructionsHelper.createStandingInstruction( - clientID.toString(), fromSavingsId.toString(), toSavingsId.toString(), - FROM_ACCOUNT_TYPE_SAVINGS, TO_ACCOUNT_TYPE_SAVINGS, VALID_FROM, VALID_TO, MONTH_DAY); - Assertions.assertNotNull(standingInstructionId); - - String JobName = "Execute Standing Instruction"; - this.schedulerJobHelper.executeAndAwaitJob(JobName); - HashMap fromSavingsSummaryAfter = this.savingsAccountHelper.getSavingsSummary(fromSavingsId); - Float fromSavingsBalanceAfter = (Float) fromSavingsSummaryAfter.get("accountBalance"); - - HashMap toSavingsSummaryAfter = this.savingsAccountHelper.getSavingsSummary(toSavingsId); - Float toSavingsBalanceAfter = (Float) toSavingsSummaryAfter.get("accountBalance"); - - final HashMap standingInstructionData = this.standingInstructionsHelper - .getStandingInstructionById(standingInstructionId.toString()); - Float expectedFromSavingsBalance = fromSavingsBalanceBefore - - (Float) standingInstructionData.get("amount"); - Float expectedToSavingsBalance = toSavingsBalanceBefore + (Float) standingInstructionData.get("amount"); - - Assertions.assertEquals(expectedFromSavingsBalance, fromSavingsBalanceAfter, - "Verifying From Savings Balance after Successful completion of Scheduler Job"); - Assertions.assertEquals(expectedToSavingsBalance, toSavingsBalanceAfter, - "Verifying To Savings Balance after Successful completion of Scheduler Job"); - Integer fromAccountType = PortfolioAccountType.SAVINGS.getValue(); - Integer transferType = AccountTransferType.ACCOUNT_TRANSFER.getValue(); - List standinInstructionHistoryData = this.standingInstructionsHelper - .getStandingInstructionHistory(fromSavingsId, fromAccountType, clientID, transferType); - Assertions.assertEquals(1, standinInstructionHistoryData.size(), - "Verifying the no of stainding instruction transactions logged for the client"); - HashMap loggedTransaction = standinInstructionHistoryData.get(0); - - Assertions.assertEquals((Float) standingInstructionData.get("amount"), (Float) loggedTransaction.get("amount"), - "Verifying transferred amount and logged transaction amounts"); - - } - - @Test - public void testApplyPenaltyForOverdueLoansJobOutcome() throws InterruptedException { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - Integer overdueFeeChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, - ChargesHelper.getLoanOverdueFeeJSON()); - Assertions.assertNotNull(overdueFeeChargeId); - - final Integer loanProductID = createLoanProduct(overdueFeeChargeId.toString()); - Assertions.assertNotNull(loanProductID); - - final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); - Assertions.assertNotNull(loanID); - - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, - loanID); - LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper - .disburseLoan(AccountTransferTest.LOAN_APPROVAL_DATE_PLUS_ONE, loanID); - LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - - ArrayList repaymentScheduleDataBefore = this.loanTransactionHelper - .getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); - - String JobName = "Apply penalty to overdue loans"; - this.schedulerJobHelper.executeAndAwaitJob(JobName); - - final HashMap chargeData = ChargesHelper.getChargeById(this.requestSpec, this.responseSpec, - overdueFeeChargeId); - - Float chargeAmount = (Float) chargeData.get("amount"); - - ArrayList repaymentScheduleDataAfter = this.loanTransactionHelper - .getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); - - Assertions.assertEquals(chargeAmount, (Float) repaymentScheduleDataAfter.get(1).get("penaltyChargesDue"), - "Verifying From Penalty Charges due fot first Repayment after Successful completion of Scheduler Job"); - - loanStatusHashMap = this.loanTransactionHelper.undoDisbursal(loanID); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); - - } - - @Test - public void testAvoidUnncessaryPenaltyWhenAmountZeroForOverdueLoansJobOutcome() throws InterruptedException { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - Integer overdueFeeChargeId = ChargesHelper.createCharges(this.requestSpec, this.responseSpec, - ChargesHelper.getLoanOverdueFeeJSONWithCalculattionTypePercentage("0.000001")); - Assertions.assertNotNull(overdueFeeChargeId); - - final Integer loanProductID = createLoanProduct(overdueFeeChargeId.toString()); - Assertions.assertNotNull(loanProductID); - - final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); - Assertions.assertNotNull(loanID); - - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, - loanID); - LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper - .disburseLoan(AccountTransferTest.LOAN_APPROVAL_DATE_PLUS_ONE, loanID); - LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - - ArrayList repaymentScheduleDataBefore = this.loanTransactionHelper - .getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); - - String JobName = "Apply penalty to overdue loans"; - Integer jobId = 12; - - this.schedulerJobHelper.executeAndAwaitJob(JobName); - - Map schedulerJob = this.schedulerJobHelper.getSchedulerJobById(jobId); - - Assertions.assertNotNull(schedulerJob); - while ((Boolean) schedulerJob.get("currentlyRunning") == true) { - Thread.sleep(15000); - schedulerJob = this.schedulerJobHelper.getSchedulerJobById(jobId); - Assertions.assertNotNull(schedulerJob); - } - - final HashMap chargeData = ChargesHelper.getChargeById(this.requestSpec, this.responseSpec, - overdueFeeChargeId); - - ArrayList repaymentScheduleDataAfter = this.loanTransactionHelper - .getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); - - Assertions.assertEquals(0, repaymentScheduleDataAfter.get(1).get("penaltyChargesDue"), - "Verifying From Penalty Charges due fot first Repayment after Successful completion of Scheduler Job"); - - final ArrayList loanCharges = this.loanTransactionHelper.getLoanCharges(this.requestSpec, - this.responseSpec, loanID); - - Assertions.assertNull(loanCharges, "Verifying that charge isn't created when the amount is 0"); - - loanStatusHashMap = this.loanTransactionHelper.undoDisbursal(loanID); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); - - } - - @Test - public void testUpdateOverdueDaysForNPA() throws InterruptedException { - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - - final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientID); - - final Integer loanProductID = createLoanProduct(null); - Assertions.assertNotNull(loanProductID); - - final Integer loanID = applyForLoanApplication(clientID.toString(), loanProductID.toString(), null); - Assertions.assertNotNull(loanID); - - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, - loanID); - LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); - - loanStatusHashMap = this.loanTransactionHelper.disburseLoan(AccountTransferTest.LOAN_DISBURSAL_DATE, - loanID); - LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - - final Boolean isNPABefore = (Boolean) this.loanTransactionHelper.getLoanDetail(requestSpec, - responseSpec, loanID, "isNPA"); - Assertions.assertFalse(isNPABefore); - // Integer jobId = (Integer) allSchedulerJobsData.get(1).get("jobId"); - String JobName = "Update Non Performing Assets"; - this.schedulerJobHelper.executeAndAwaitJob(JobName); - final Boolean isNPAAfter = (Boolean) this.loanTransactionHelper.getLoanDetail(requestSpec, responseSpec, - loanID, "isNPA"); - Assertions.assertTrue(isNPAAfter); - } - - @Test - public void testInterestTransferForSavings() throws InterruptedException { - this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); - this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); - // FixedDepositProductHelper fixedDepositProductHelper = new - // FixedDepositProductHelper(this.requestSpec,this.responseSpec); - // AccountHelper accountHelper = new AccountHelper(this.requestSpec, - // this.responseSpec); - FixedDepositAccountHelper fixedDepositAccountHelper = new FixedDepositAccountHelper(this.requestSpec, - this.responseSpec); - - DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); - // DateFormat monthDayFormat = new SimpleDateFormat("dd MMM", Locale.US); - - Calendar todaysDate = Calendar.getInstance(); - todaysDate.add(Calendar.MONTH, -3); - final String VALID_FROM = dateFormat.format(todaysDate.getTime()); - todaysDate.add(Calendar.YEAR, 10); - final String VALID_TO = dateFormat.format(todaysDate.getTime()); - - todaysDate = Calendar.getInstance(); - todaysDate.add(Calendar.MONTH, -2); - final String SUBMITTED_ON_DATE = dateFormat.format(todaysDate.getTime()); - final String APPROVED_ON_DATE = dateFormat.format(todaysDate.getTime()); - final String ACTIVATION_DATE = dateFormat.format(todaysDate.getTime()); - todaysDate.add(Calendar.MONTH, 1); - final String WHOLE_TERM = "1"; - - Integer clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec); - Assertions.assertNotNull(clientId); - Float balance = Float.valueOf(MINIMUM_OPENING_BALANCE) - + Float.valueOf(FixedDepositAccountHelper.DEPOSIT_AMOUNT); - final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, - String.valueOf(balance)); - Assertions.assertNotNull(savingsProductID); - - final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientId, - savingsProductID, ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); - Assertions.assertNotNull(savingsId); - - HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, - this.responseSpec, savingsId); - SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); - - savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); - SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); - - savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); - SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); - HashMap summary = savingsAccountHelper.getSavingsSummary(savingsId); - assertEquals(balance, summary.get("accountBalance"), "Verifying opening Balance"); - - Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO); - Assertions.assertNotNull(fixedDepositProductId); - - Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), - fixedDepositProductId.toString(), VALID_FROM, VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, - savingsId.toString(), true, fixedDepositAccountHelper); - Assertions.assertNotNull(fixedDepositAccountId); - - HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker - .getStatusOfFixedDepositAccount(this.requestSpec, this.responseSpec, - fixedDepositAccountId.toString()); - FixedDepositAccountStatusChecker.verifyFixedDepositIsPending(fixedDepositAccountStatusHashMap); - - fixedDepositAccountStatusHashMap = fixedDepositAccountHelper.approveFixedDeposit(fixedDepositAccountId, - APPROVED_ON_DATE); - FixedDepositAccountStatusChecker.verifyFixedDepositIsApproved(fixedDepositAccountStatusHashMap); - - fixedDepositAccountStatusHashMap = fixedDepositAccountHelper.activateFixedDeposit(fixedDepositAccountId, - ACTIVATION_DATE); - FixedDepositAccountStatusChecker.verifyFixedDepositIsActive(fixedDepositAccountStatusHashMap); - summary = savingsAccountHelper.getSavingsSummary(savingsId); - balance = Float.valueOf(MINIMUM_OPENING_BALANCE); - assertEquals(balance, summary.get("accountBalance"), "Verifying Balance"); - - fixedDepositAccountHelper.postInterestForFixedDeposit(fixedDepositAccountId); - - HashMap fixedDepositSummary = savingsAccountHelper.getSavingsSummary(fixedDepositAccountId); - Float interestPosted = (Float) fixedDepositSummary.get("accountBalance") - - Float.valueOf(FixedDepositAccountHelper.DEPOSIT_AMOUNT); - - String JobName = "Transfer Interest To Savings"; - this.schedulerJobHelper.executeAndAwaitJob(JobName); - fixedDepositSummary = savingsAccountHelper.getSavingsSummary(fixedDepositAccountId); - assertEquals(Float.valueOf(FixedDepositAccountHelper.DEPOSIT_AMOUNT), - fixedDepositSummary.get("accountBalance"), - "Verifying opening Balance"); - - summary = savingsAccountHelper.getSavingsSummary(savingsId); - balance = Float.valueOf(MINIMUM_OPENING_BALANCE) + interestPosted; - validateNumberForEqualExcludePrecission(String.valueOf(balance), - String.valueOf(summary.get("accountBalance"))); - } - - private Integer createSavingsProduct(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String minOpenningBalance) { - // system.out.println("------------------------------CREATING NEW SAVINGS - // PRODUCT ---------------------------------------"); - SavingsProductHelper savingsProductHelper = new SavingsProductHelper(); - final String savingsProductJSON = savingsProductHelper // - .withInterestCompoundingPeriodTypeAsDaily() // - .withInterestPostingPeriodTypeAsMonthly() // - .withInterestCalculationPeriodTypeAsDailyBalance() // - .withMinimumOpenningBalance(minOpenningBalance).build(); - return SavingsProductHelper.createSavingsProduct(savingsProductJSON, requestSpec, responseSpec); - } - - private static Integer createSavingsProduct(final String minOpenningBalance, final Account... accounts) { - // system.out.println("------------------------------CREATING NEW SAVINGS - // PRODUCT ---------------------------------------"); - final String savingsProductJSON = new SavingsProductHelper().withInterestCompoundingPeriodTypeAsDaily() // - .withInterestPostingPeriodTypeAsQuarterly() // - .withInterestCalculationPeriodTypeAsDailyBalance() // - .withMinimumOpenningBalance(minOpenningBalance).withAccountingRuleAsCashBased(accounts) - .build(); - return SavingsProductHelper.createSavingsProduct(savingsProductJSON, requestSpec, responseSpec); - } - - private Integer createLoanProduct(final String chargeId) { - // system.out.println("------------------------------CREATING NEW LOAN PRODUCT - // ---------------------------------------"); - final String loanProductJSON = new LoanProductTestBuilder() // - .withPrincipal("15,000.00") // - .withNumberOfRepayments("4") // - .withRepaymentAfterEvery("1") // - .withRepaymentTypeAsMonth() // - .withinterestRatePerPeriod("1") // - .withInterestRateFrequencyTypeAsMonths() // - .withAmortizationTypeAsEqualInstallments() // - .withInterestTypeAsDecliningBalance() // - .build(chargeId); - return this.loanTransactionHelper.getLoanProductId(loanProductJSON); - } - - private Integer applyForLoanApplication(final String clientID, final String loanProductID, - final String savingsID) { - // system.out.println("--------------------------------APPLYING FOR LOAN - // APPLICATION--------------------------------"); - final String loanApplicationJSON = new LoanApplicationTestBuilder() // - .withPrincipal("15,000.00") // - .withLoanTermFrequency("4") // - .withLoanTermFrequencyAsMonths() // - .withNumberOfRepayments("4") // - .withRepaymentEveryAfter("1") // - .withRepaymentFrequencyTypeAsMonths() // - .withInterestRatePerPeriod("2") // - .withAmortizationTypeAsEqualInstallments() // - .withInterestTypeAsDecliningBalance() // - .withInterestCalculationPeriodTypeSameAsRepaymentPeriod() // - .withExpectedDisbursementDate("10 January 2013") // - .withSubmittedOnDate("10 January 2013") // - .build(clientID, loanProductID, savingsID); - return this.loanTransactionHelper.getLoanId(loanApplicationJSON); - } - - private Integer createFixedDepositProduct(final String validFrom, final String validTo, Account... accounts) { - // system.out.println("------------------------------CREATING NEW FIXED DEPOSIT - // PRODUCT ---------------------------------------"); - FixedDepositProductHelper fixedDepositProductHelper = new FixedDepositProductHelper(this.requestSpec, - this.responseSpec); - final String fixedDepositProductJSON = fixedDepositProductHelper // - // .withAccountingRuleAsCashBased(accounts) - .withPeriodRangeChart()// - .build(validFrom, validTo); - return FixedDepositProductHelper.createFixedDepositProduct(fixedDepositProductJSON, requestSpec, - responseSpec); - } - - private Integer applyForFixedDepositApplication(final String clientID, final String productID, - final String validFrom, final String validTo, final String submittedOnDate, - final String penalInterestType, String savingsId, final boolean transferInterest, - final FixedDepositAccountHelper fixedDepositAccountHelper) { - // system.out.println("--------------------------------APPLYING FOR FIXED - // DEPOSIT ACCOUNT --------------------------------"); - final String fixedDepositApplicationJSON = new FixedDepositAccountHelper(this.requestSpec, - this.responseSpec) - // - .withSubmittedOnDate(submittedOnDate).withSavings(savingsId) - .transferInterest(true) - .withLockinPeriodFrequency("1", FixedDepositAccountHelper.DAYS) - .build(clientID, productID, penalInterestType); - return fixedDepositAccountHelper.applyFixedDepositApplication(fixedDepositApplicationJSON, - this.requestSpec, this.responseSpec); - } - - private void validateNumberForEqualExcludePrecission(String val, String val2) { - DecimalFormat twoDForm = new DecimalFormat("#", new DecimalFormatSymbols(Locale.US)); - Assertions.assertTrue(Float.valueOf(twoDForm.format(Float.valueOf(val))) - .compareTo(Float.valueOf(twoDForm.format(Float.valueOf(val2)))) == 0); - } + loanStatusHashMap = this.loanTransactionHelper.approveLoan(AccountTransferTest.LOAN_APPROVAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); + + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(AccountTransferTest.LOAN_DISBURSAL_DATE, loanID); + LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); + + final Boolean isNPABefore = (Boolean) this.loanTransactionHelper.getLoanDetail(requestSpec, responseSpec, loanID, "isNPA"); + Assertions.assertFalse(isNPABefore); + // Integer jobId = (Integer) allSchedulerJobsData.get(1).get("jobId"); + String JobName = "Update Non Performing Assets"; + this.schedulerJobHelper.executeAndAwaitJob(JobName); + final Boolean isNPAAfter = (Boolean) this.loanTransactionHelper.getLoanDetail(requestSpec, responseSpec, loanID, "isNPA"); + Assertions.assertTrue(isNPAAfter); + } + + @Test + public void testInterestTransferForSavings() throws InterruptedException { + this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); + this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec); + // FixedDepositProductHelper fixedDepositProductHelper = new + // FixedDepositProductHelper(this.requestSpec,this.responseSpec); + // AccountHelper accountHelper = new AccountHelper(this.requestSpec, + // this.responseSpec); + FixedDepositAccountHelper fixedDepositAccountHelper = new FixedDepositAccountHelper(this.requestSpec, this.responseSpec); + + DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); + // DateFormat monthDayFormat = new SimpleDateFormat("dd MMM", + // Locale.US); + + Calendar todaysDate = Calendar.getInstance(); + todaysDate.add(Calendar.MONTH, -3); + final String VALID_FROM = dateFormat.format(todaysDate.getTime()); + todaysDate.add(Calendar.YEAR, 10); + final String VALID_TO = dateFormat.format(todaysDate.getTime()); + + todaysDate = Calendar.getInstance(); + todaysDate.add(Calendar.MONTH, -2); + final String SUBMITTED_ON_DATE = dateFormat.format(todaysDate.getTime()); + final String APPROVED_ON_DATE = dateFormat.format(todaysDate.getTime()); + final String ACTIVATION_DATE = dateFormat.format(todaysDate.getTime()); + todaysDate.add(Calendar.MONTH, 1); + final String WHOLE_TERM = "1"; + + Integer clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Assertions.assertNotNull(clientId); + Float balance = Float.valueOf(MINIMUM_OPENING_BALANCE) + Float.valueOf(FixedDepositAccountHelper.DEPOSIT_AMOUNT); + final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, String.valueOf(balance)); + Assertions.assertNotNull(savingsProductID); + + final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplication(clientId, savingsProductID, + ClientSavingsIntegrationTest.ACCOUNT_TYPE_INDIVIDUAL); + Assertions.assertNotNull(savingsId); + + HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(this.requestSpec, this.responseSpec, savingsId); + SavingsStatusChecker.verifySavingsIsPending(savingsStatusHashMap); + + savingsStatusHashMap = this.savingsAccountHelper.approveSavings(savingsId); + SavingsStatusChecker.verifySavingsIsApproved(savingsStatusHashMap); + + savingsStatusHashMap = this.savingsAccountHelper.activateSavings(savingsId); + SavingsStatusChecker.verifySavingsIsActive(savingsStatusHashMap); + HashMap summary = savingsAccountHelper.getSavingsSummary(savingsId); + assertEquals(balance, summary.get("accountBalance"), "Verifying opening Balance"); + + Integer fixedDepositProductId = createFixedDepositProduct(VALID_FROM, VALID_TO); + Assertions.assertNotNull(fixedDepositProductId); + + Integer fixedDepositAccountId = applyForFixedDepositApplication(clientId.toString(), fixedDepositProductId.toString(), VALID_FROM, + VALID_TO, SUBMITTED_ON_DATE, WHOLE_TERM, savingsId.toString(), true, fixedDepositAccountHelper); + Assertions.assertNotNull(fixedDepositAccountId); + + HashMap fixedDepositAccountStatusHashMap = FixedDepositAccountStatusChecker.getStatusOfFixedDepositAccount(this.requestSpec, + this.responseSpec, fixedDepositAccountId.toString()); + FixedDepositAccountStatusChecker.verifyFixedDepositIsPending(fixedDepositAccountStatusHashMap); + + fixedDepositAccountStatusHashMap = fixedDepositAccountHelper.approveFixedDeposit(fixedDepositAccountId, APPROVED_ON_DATE); + FixedDepositAccountStatusChecker.verifyFixedDepositIsApproved(fixedDepositAccountStatusHashMap); + + fixedDepositAccountStatusHashMap = fixedDepositAccountHelper.activateFixedDeposit(fixedDepositAccountId, ACTIVATION_DATE); + FixedDepositAccountStatusChecker.verifyFixedDepositIsActive(fixedDepositAccountStatusHashMap); + summary = savingsAccountHelper.getSavingsSummary(savingsId); + balance = Float.valueOf(MINIMUM_OPENING_BALANCE); + assertEquals(balance, summary.get("accountBalance"), "Verifying Balance"); + + fixedDepositAccountHelper.postInterestForFixedDeposit(fixedDepositAccountId); + + HashMap fixedDepositSummary = savingsAccountHelper.getSavingsSummary(fixedDepositAccountId); + Float interestPosted = (Float) fixedDepositSummary.get("accountBalance") - Float.valueOf(FixedDepositAccountHelper.DEPOSIT_AMOUNT); + + String JobName = "Transfer Interest To Savings"; + this.schedulerJobHelper.executeAndAwaitJob(JobName); + fixedDepositSummary = savingsAccountHelper.getSavingsSummary(fixedDepositAccountId); + assertEquals(Float.valueOf(FixedDepositAccountHelper.DEPOSIT_AMOUNT), fixedDepositSummary.get("accountBalance"), + "Verifying opening Balance"); + + summary = savingsAccountHelper.getSavingsSummary(savingsId); + balance = Float.valueOf(MINIMUM_OPENING_BALANCE) + interestPosted; + validateNumberForEqualExcludePrecission(String.valueOf(balance), String.valueOf(summary.get("accountBalance"))); + } + + private Integer createSavingsProduct(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String minOpenningBalance) { + // system.out.println("------------------------------CREATING NEW + // SAVINGS + // PRODUCT ---------------------------------------"); + SavingsProductHelper savingsProductHelper = new SavingsProductHelper(); + final String savingsProductJSON = savingsProductHelper // + .withInterestCompoundingPeriodTypeAsDaily() // + .withInterestPostingPeriodTypeAsMonthly() // + .withInterestCalculationPeriodTypeAsDailyBalance() // + .withMinimumOpenningBalance(minOpenningBalance).build(); + return SavingsProductHelper.createSavingsProduct(savingsProductJSON, requestSpec, responseSpec); + } + + private static Integer createSavingsProduct(final String minOpenningBalance, final Account... accounts) { + // system.out.println("------------------------------CREATING NEW + // SAVINGS + // PRODUCT ---------------------------------------"); + final String savingsProductJSON = new SavingsProductHelper().withInterestCompoundingPeriodTypeAsDaily() // + .withInterestPostingPeriodTypeAsQuarterly() // + .withInterestCalculationPeriodTypeAsDailyBalance() // + .withMinimumOpenningBalance(minOpenningBalance).withAccountingRuleAsCashBased(accounts).build(); + return SavingsProductHelper.createSavingsProduct(savingsProductJSON, requestSpec, responseSpec); + } + + private Integer createLoanProduct(final String chargeId) { + // system.out.println("------------------------------CREATING NEW LOAN + // PRODUCT + // ---------------------------------------"); + final String loanProductJSON = new LoanProductTestBuilder() // + .withPrincipal("15,000.00") // + .withNumberOfRepayments("4") // + .withRepaymentAfterEvery("1") // + .withRepaymentTypeAsMonth() // + .withinterestRatePerPeriod("1") // + .withInterestRateFrequencyTypeAsMonths() // + .withAmortizationTypeAsEqualInstallments() // + .withInterestTypeAsDecliningBalance() // + .build(chargeId); + return this.loanTransactionHelper.getLoanProductId(loanProductJSON); + } + + private Integer applyForLoanApplication(final String clientID, final String loanProductID, final String savingsID) { + // system.out.println("--------------------------------APPLYING FOR LOAN + // APPLICATION--------------------------------"); + final String loanApplicationJSON = new LoanApplicationTestBuilder() // + .withPrincipal("15,000.00") // + .withLoanTermFrequency("4") // + .withLoanTermFrequencyAsMonths() // + .withNumberOfRepayments("4") // + .withRepaymentEveryAfter("1") // + .withRepaymentFrequencyTypeAsMonths() // + .withInterestRatePerPeriod("2") // + .withAmortizationTypeAsEqualInstallments() // + .withInterestTypeAsDecliningBalance() // + .withInterestCalculationPeriodTypeSameAsRepaymentPeriod() // + .withExpectedDisbursementDate("10 January 2013") // + .withSubmittedOnDate("10 January 2013") // + .build(clientID, loanProductID, savingsID); + return this.loanTransactionHelper.getLoanId(loanApplicationJSON); + } + + private Integer createFixedDepositProduct(final String validFrom, final String validTo, Account... accounts) { + // system.out.println("------------------------------CREATING NEW FIXED + // DEPOSIT + // PRODUCT ---------------------------------------"); + FixedDepositProductHelper fixedDepositProductHelper = new FixedDepositProductHelper(this.requestSpec, this.responseSpec); + final String fixedDepositProductJSON = fixedDepositProductHelper // + // .withAccountingRuleAsCashBased(accounts) + .withPeriodRangeChart()// + .build(validFrom, validTo); + return FixedDepositProductHelper.createFixedDepositProduct(fixedDepositProductJSON, requestSpec, responseSpec); + } + + private Integer applyForFixedDepositApplication(final String clientID, final String productID, final String validFrom, + final String validTo, final String submittedOnDate, final String penalInterestType, String savingsId, + final boolean transferInterest, final FixedDepositAccountHelper fixedDepositAccountHelper) { + // system.out.println("--------------------------------APPLYING FOR + // FIXED + // DEPOSIT ACCOUNT --------------------------------"); + final String fixedDepositApplicationJSON = new FixedDepositAccountHelper(this.requestSpec, this.responseSpec) + // + .withSubmittedOnDate(submittedOnDate).withSavings(savingsId).transferInterest(true) + .withLockinPeriodFrequency("1", FixedDepositAccountHelper.DAYS).build(clientID, productID, penalInterestType); + return fixedDepositAccountHelper.applyFixedDepositApplication(fixedDepositApplicationJSON, this.requestSpec, this.responseSpec); + } + + private void validateNumberForEqualExcludePrecission(String val, String val2) { + DecimalFormat twoDForm = new DecimalFormat("#", new DecimalFormatSymbols(Locale.US)); + Assertions.assertTrue( + Float.valueOf(twoDForm.format(Float.valueOf(val))).compareTo(Float.valueOf(twoDForm.format(Float.valueOf(val2)))) == 0); + } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SkipRepaymentOnMonthFirstTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SkipRepaymentOnMonthFirstTest.java index 76e1a304f..e052d7b1c 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SkipRepaymentOnMonthFirstTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SkipRepaymentOnMonthFirstTest.java @@ -45,6 +45,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "static-access", "rawtypes", "unchecked", "deprecation" }) public class SkipRepaymentOnMonthFirstTest { + private final static Logger LOG = LoggerFactory.getLogger(SkipRepaymentOnMonthFirstTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -56,8 +57,7 @@ public class SkipRepaymentOnMonthFirstTest { public void setup() { Utils.initializeRESTAssured(); this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - this.requestSpec.header("Authorization", - "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } @@ -72,8 +72,8 @@ public class SkipRepaymentOnMonthFirstTest { this.globalConfigurationHelper = new GlobalConfigurationHelper(this.requestSpec, this.responseSpec); // Retrieving All Global Configuration details - final ArrayList globalConfig = this.globalConfigurationHelper - .getAllGlobalConfigurations(this.requestSpec, this.responseSpec); + final ArrayList globalConfig = this.globalConfigurationHelper.getAllGlobalConfigurations(this.requestSpec, + this.responseSpec); Assertions.assertNotNull(globalConfig); String configName = "skip-repayment-on-first-day-of-month"; @@ -82,8 +82,8 @@ public class SkipRepaymentOnMonthFirstTest { for (Integer configIndex = 0; configIndex < globalConfig.size(); configIndex++) { if (globalConfig.get(configIndex).get("name").equals(configName)) { String configId = globalConfig.get(configIndex).get("id").toString(); - Integer updateConfigId = this.globalConfigurationHelper.updateEnabledFlagForGlobalConfiguration( - this.requestSpec, this.responseSpec, configId.toString(), newBooleanValue); + Integer updateConfigId = this.globalConfigurationHelper.updateEnabledFlagForGlobalConfiguration(this.requestSpec, + this.responseSpec, configId.toString(), newBooleanValue); Assertions.assertNotNull(updateConfigId); break; } @@ -97,26 +97,23 @@ public class SkipRepaymentOnMonthFirstTest { final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); Integer groupID = GroupHelper.createGroup(this.requestSpec, this.responseSpec, true); - groupID = GroupHelper.associateClient(this.requestSpec, this.responseSpec, groupID.toString(), - clientID.toString()); + groupID = GroupHelper.associateClient(this.requestSpec, this.responseSpec, groupID.toString(), clientID.toString()); final String startDate = "15 September 2011"; final String frequency = "3"; // Monthly - final String interval = "1"; //Every One Moth - Integer calendarID = calendarHelper.createMeetingForGroup(requestSpec, responseSpec, groupID, startDate, frequency, - interval, null); - LOG.info("caladerId -------------------- {}" , calendarID); + final String interval = "1"; // Every One Moth + Integer calendarID = calendarHelper.createMeetingForGroup(requestSpec, responseSpec, groupID, startDate, frequency, interval, null); + LOG.info("caladerId -------------------- {}", calendarID); final Integer loanProductID = createLoanProduct(); final Integer loanID = applyForLoanApplication(groupID, loanProductID, calendarID, clientID); - LOG.info("loanID---- {}" , loanID); - final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, - this.responseSpec, loanID); + LOG.info("loanID---- {}", loanID); + final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, + loanID); verifyLoanRepaymentSchedule(loanSchedule); } private Integer createLoanProduct() { - LOG.info( - "------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); + LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); final String loanProductJSON = new LoanProductTestBuilder() // .withPrincipal("12,000.00") // .withNumberOfRepayments("4") // @@ -130,10 +127,8 @@ public class SkipRepaymentOnMonthFirstTest { return this.loanTransactionHelper.getLoanProductId(loanProductJSON); } - private Integer applyForLoanApplication(final Integer groupID, final Integer loanProductID, Integer calendarID, - Integer clientID) { - LOG.info( - "--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); + private Integer applyForLoanApplication(final Integer groupID, final Integer loanProductID, Integer calendarID, Integer clientID) { + LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal("12,000.00") // .withLoanTermFrequency("4") // @@ -157,19 +152,19 @@ public class SkipRepaymentOnMonthFirstTest { LOG.info("--------------------VERIFYING THE REPAYMENT DATE--------------------------"); assertEquals(new ArrayList<>(Arrays.asList(2011, 10, 15)), loanSchedule.get(1).get("dueDate"), "Checking for Repayment Date for 1st Month"); - LOG.info("Repayment Date for 1st Month-- {}" , loanSchedule.get(1).get("dueDate")); + LOG.info("Repayment Date for 1st Month-- {}", loanSchedule.get(1).get("dueDate")); assertEquals(new ArrayList<>(Arrays.asList(2011, 11, 15)), loanSchedule.get(2).get("dueDate"), "Checking for Repayment Date for 2nd Month"); - LOG.info("Repayment Date for 2nd Month-- {}" , loanSchedule.get(2).get("dueDate")); + LOG.info("Repayment Date for 2nd Month-- {}", loanSchedule.get(2).get("dueDate")); assertEquals(new ArrayList<>(Arrays.asList(2011, 12, 15)), loanSchedule.get(3).get("dueDate"), "Checking for Repayment Date for 3rd Month"); - LOG.info("Repayment Date for 3rd Month-- {}" , loanSchedule.get(3).get("dueDate")); + LOG.info("Repayment Date for 3rd Month-- {}", loanSchedule.get(3).get("dueDate")); assertEquals(new ArrayList<>(Arrays.asList(2012, 1, 15)), loanSchedule.get(4).get("dueDate"), "Checking for Repayment Date for 4th Month"); - LOG.info("Repayment Date for 4th Month-- {}" , loanSchedule.get(4).get("dueDate")); + LOG.info("Repayment Date for 4th Month-- {}", loanSchedule.get(4).get("dueDate")); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/StaffImageApiTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/StaffImageApiTest.java index b2eeedd92..d54ee26ae 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/StaffImageApiTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/StaffImageApiTest.java @@ -53,7 +53,7 @@ public class StaffImageApiTest { } @Test - public void getStaffImage(){ + public void getStaffImage() { Integer staffId = StaffHelper.createStaff(this.requestSpec, this.responseSpec); Integer imageId = ImageHelper.createImageForStaff(this.requestSpec, this.responseSpec, staffId); assertNotNull(imageId, "Image id should not be null"); @@ -63,7 +63,7 @@ public class StaffImageApiTest { } @Test - public void getStaffImageAsBinary(){ + public void getStaffImageAsBinary() { Integer staffId = StaffHelper.createStaff(this.requestSpec, this.responseSpec); Integer imageId = ImageHelper.createImageForStaff(this.requestSpec, this.responseSpec, staffId); assertNotNull(imageId, "Image id should not be null"); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/StaffTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/StaffTest.java index 2a9d5aff7..c18ee3fce 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/StaffTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/StaffTest.java @@ -84,7 +84,7 @@ public class StaffTest { /** Long lastname test */ map.put("lastname", Utils.randomNameGenerator("Doe_", 47)); StaffHelper.createStaffWithJson(requestSpec, responseSpecForValidationError, new Gson().toJson(map)); - map.put("lastname", Utils.randomNameGenerator("Doe_",4)); + map.put("lastname", Utils.randomNameGenerator("Doe_", 4)); /** Long mobileNo test */ map.put("mobileNo", Utils.randomNameGenerator("num_", 47)); @@ -136,7 +136,7 @@ public class StaffTest { @Test public void testStaffListStatusActive() { List> responseActive = StaffHelper.getStaffListWithState(requestSpec, responseSpec, "active"); - for(final Map staff : responseActive) { + for (final Map staff : responseActive) { Assertions.assertNotNull(staff.get("id")); Assertions.assertEquals(true, staff.get("isActive")); } @@ -145,7 +145,7 @@ public class StaffTest { @Test public void testStaffListStatusInactive() { List> responseInactive = StaffHelper.getStaffListWithState(requestSpec, responseSpec, "inactive"); - for(final Map staff : responseInactive) { + for (final Map staff : responseInactive) { Assertions.assertNotNull(staff.get("id")); Assertions.assertEquals(false, staff.get("isActive")); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SurveyIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SurveyIntegrationTest.java index ac65e561f..0ae3d3864 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SurveyIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SurveyIntegrationTest.java @@ -46,4 +46,4 @@ public class SurveyIntegrationTest { this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SystemCodeTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SystemCodeTest.java index d89c7dcab..a5bb290c1 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SystemCodeTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/SystemCodeTest.java @@ -90,8 +90,8 @@ public class SystemCodeTest { assertEquals(createResponseId, deleteResponseId, "Verify code deleted"); // verify code deleted - final HashMap deletedCodeValues = (HashMap) CodeHelper - .getCodeById(this.requestSpec, this.generalResponseSpec, deleteResponseId, ""); + final HashMap deletedCodeValues = (HashMap) CodeHelper.getCodeById(this.requestSpec, this.generalResponseSpec, deleteResponseId, + ""); Assertions.assertNotNull(deletedCodeValues); assertNull(deletedCodeValues.get(CodeHelper.CODE_ID_ATTRIBUTE_NAME), "Verify value of codeId"); @@ -132,8 +132,8 @@ public class SystemCodeTest { assertEquals(createResponseId, deleteResponseId, "Verify code deleted"); // verify code deleted - final HashMap deletedCodeAttributes = (HashMap) CodeHelper.getCodeById(this.requestSpec, this.generalResponseSpec, - deleteResponseId, ""); + final HashMap deletedCodeAttributes = (HashMap) CodeHelper.getCodeById(this.requestSpec, this.generalResponseSpec, deleteResponseId, + ""); Assertions.assertNotNull(deletedCodeAttributes); assertNull(deletedCodeAttributes.get(CodeHelper.CODE_ID_ATTRIBUTE_NAME), "Verify value of codeId"); @@ -206,11 +206,10 @@ public class SystemCodeTest { createCodeResponseId, createCodeValueResponseId1, ""); Assertions.assertNotNull(codeValuesAttributes1); - assertEquals(createCodeValueResponseId1, - codeValuesAttributes1.get(CodeHelper.CODE_VALUE_ID_ATTRIBUTE_NAME), "Verify value of codeValueId"); + assertEquals(createCodeValueResponseId1, codeValuesAttributes1.get(CodeHelper.CODE_VALUE_ID_ATTRIBUTE_NAME), + "Verify value of codeValueId"); - assertEquals(codeValue1, codeValuesAttributes1.get(CodeHelper.CODE_VALUE_NAME_ATTRIBUTE_NAME), - "Verify value of code name"); + assertEquals(codeValue1, codeValuesAttributes1.get(CodeHelper.CODE_VALUE_NAME_ATTRIBUTE_NAME), "Verify value of code name"); assertEquals(codeDescription1, codeValuesAttributes1.get(CodeHelper.CODE_VALUE_DESCRIPTION_ATTRIBUTE_NAME), "Verify value of code description"); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/TemplateIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/TemplateIntegrationTest.java index 28dfe0ac1..0e82fc0d9 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/TemplateIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/TemplateIntegrationTest.java @@ -64,11 +64,13 @@ public class TemplateIntegrationTest { ArrayList get = Utils.performServerGet(this.requestSpec, this.responseSpec, this.GET_TEMPLATES_URL, ""); final int entriesBeforeTest = get.size(); - final Integer id = Utils.performServerPost(this.requestSpec, this.responseSpec, this.GET_TEMPLATES_URL, new Gson().toJson(map), "resourceId"); + final Integer id = Utils.performServerPost(this.requestSpec, this.responseSpec, this.GET_TEMPLATES_URL, new Gson().toJson(map), + "resourceId"); final String templateUrlForId = String.format(this.GET_TEMPLATE_ID_URL, id); - final String getrequest2 = Utils.performServerGet(this.requestSpec, this.responseSpec, templateUrlForId, this.RESPONSE_ATTRIBUTE_NAME); + final String getrequest2 = Utils.performServerGet(this.requestSpec, this.responseSpec, templateUrlForId, + this.RESPONSE_ATTRIBUTE_NAME); Assertions.assertTrue(getrequest2.equals("foo")); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/UserAdministrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/UserAdministrationTest.java index 988818f6b..81936d772 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/UserAdministrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/UserAdministrationTest.java @@ -40,6 +40,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UserAdministrationTest { + private final static Logger LOG = LoggerFactory.getLogger(UserAdministrationTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @@ -59,7 +60,7 @@ public class UserAdministrationTest { @AfterEach public void tearDown() { - for(Integer userId : this.transientUsers) { + for (Integer userId : this.transientUsers) { UserHelper.deleteUser(this.requestSpec, this.responseSpec, userId); } this.transientUsers.clear(); @@ -74,14 +75,15 @@ public class UserAdministrationTest { final Integer staffId = StaffHelper.createStaff(this.requestSpec, this.responseSpec); Assertions.assertNotNull(staffId); - final Integer userId = (Integer) UserHelper.createUser(this.requestSpec, this.responseSpec, roleId, staffId, "alphabet", "resourceId"); + final Integer userId = (Integer) UserHelper.createUser(this.requestSpec, this.responseSpec, roleId, staffId, "alphabet", + "resourceId"); Assertions.assertNotNull(userId); this.transientUsers.add(userId); final List errors = (List) UserHelper.createUser(this.requestSpec, expectStatusCode(403), roleId, staffId, "alphabet", "errors"); Map reason = (Map) errors.get(0); - LOG.info("Reason: {}" , reason.get("defaultUserMessage")); - LOG.info("Code: {}" , reason.get("userMessageGlobalisationCode")); + LOG.info("Reason: {}", reason.get("defaultUserMessage")); + LOG.info("Code: {}", reason.get("userMessageGlobalisationCode")); Assertions.assertEquals("User with username alphabet already exists.", reason.get("defaultUserMessage")); Assertions.assertEquals("error.msg.user.duplicate.username", reason.get("userMessageGlobalisationCode")); } @@ -94,7 +96,8 @@ public class UserAdministrationTest { final Integer staffId = StaffHelper.createStaff(this.requestSpec, this.responseSpec); Assertions.assertNotNull(staffId); - final Integer userId = (Integer) UserHelper.createUser(this.requestSpec, this.responseSpec, roleId, staffId, "alphabet", "resourceId"); + final Integer userId = (Integer) UserHelper.createUser(this.requestSpec, this.responseSpec, roleId, staffId, "alphabet", + "resourceId"); Assertions.assertNotNull(userId); this.transientUsers.add(userId); @@ -113,11 +116,13 @@ public class UserAdministrationTest { final Integer staffId = StaffHelper.createStaff(this.requestSpec, this.responseSpec); Assertions.assertNotNull(staffId); - final Integer userId = (Integer) UserHelper.createUser(this.requestSpec, this.responseSpec, roleId, staffId, "alphabet", "resourceId"); + final Integer userId = (Integer) UserHelper.createUser(this.requestSpec, this.responseSpec, roleId, staffId, "alphabet", + "resourceId"); Assertions.assertNotNull(userId); this.transientUsers.add(userId); - final Integer userId2 = (Integer) UserHelper.createUser(this.requestSpec, this.responseSpec, roleId, staffId, "bilingual", "resourceId"); + final Integer userId2 = (Integer) UserHelper.createUser(this.requestSpec, this.responseSpec, roleId, staffId, "bilingual", + "resourceId"); Assertions.assertNotNull(userId2); this.transientUsers.add(userId2); @@ -126,6 +131,7 @@ public class UserAdministrationTest { Assertions.assertEquals("User with username alphabet already exists.", reason.get("defaultUserMessage")); Assertions.assertEquals("error.msg.user.duplicate.username", reason.get("userMessageGlobalisationCode")); } + @Test public void testCreateNewUserBlocksDuplicateClientId() { final Integer roleId = RolesHelper.createRole(this.requestSpec, this.responseSpec); @@ -137,13 +143,16 @@ public class UserAdministrationTest { final Integer clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec); Assertions.assertNotNull(clientId); - final Integer userId = (Integer) UserHelper.createUserForSelfService(this.requestSpec, this.responseSpec, roleId, staffId, clientId, "resourceId"); + final Integer userId = (Integer) UserHelper.createUserForSelfService(this.requestSpec, this.responseSpec, roleId, staffId, clientId, + "resourceId"); Assertions.assertNotNull(userId); this.transientUsers.add(userId); - final List errors = (List) UserHelper.createUserForSelfService(this.requestSpec, expectStatusCode(403), roleId, staffId, clientId, "errors"); + final List errors = (List) UserHelper.createUserForSelfService(this.requestSpec, expectStatusCode(403), roleId, staffId, clientId, + "errors"); Map reason = (Map) errors.get(0); - Assertions.assertEquals("Self Service User Id is already created. Go to Admin->Users to edit or delete the self-service user.", reason.get("defaultUserMessage")); + Assertions.assertEquals("Self Service User Id is already created. Go to Admin->Users to edit or delete the self-service user.", + reason.get("defaultUserMessage")); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/XBRLIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/XBRLIntegrationTest.java index 7263481c5..bfa62f509 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/XBRLIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/XBRLIntegrationTest.java @@ -36,6 +36,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "rawtypes", "unchecked" }) public class XBRLIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(XBRLIntegrationTest.class); private RequestSpecification requestSpec; private ResponseSpecification responseSpec; diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/client/ClientEntityImportHandlerTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/client/ClientEntityImportHandlerTest.java index 0a76d3656..b555193b8 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/client/ClientEntityImportHandlerTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/client/ClientEntityImportHandlerTest.java @@ -52,6 +52,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClientEntityImportHandlerTest { + private final static Logger LOG = LoggerFactory.getLogger(ClientEntityImportHandlerTest.class); private ResponseSpecification responseSpec; @@ -68,85 +69,90 @@ public class ClientEntityImportHandlerTest { @Test public void testClientImport() throws InterruptedException, IOException, ParseException { - //in order to populate helper sheets + // in order to populate helper sheets requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - Integer outcome_staff_creation = StaffHelper.createStaff(requestSpec,responseSpec); + Integer outcome_staff_creation = StaffHelper.createStaff(requestSpec, responseSpec); Assertions.assertNotNull(outcome_staff_creation, "Could not create staff"); - //in order to populate helper sheets - OfficeHelper officeHelper = new OfficeHelper(requestSpec,responseSpec); - Integer outcome_office_creation=officeHelper.createOffice("02 May 2000"); + // in order to populate helper sheets + OfficeHelper officeHelper = new OfficeHelper(requestSpec, responseSpec); + Integer outcome_office_creation = officeHelper.createOffice("02 May 2000"); Assertions.assertNotNull(outcome_office_creation, "Could not create office"); - //in order to populate helper columns in client entity sheet - //create constitution - CodeHelper.retrieveOrCreateCodeValue(24,requestSpec,responseSpec); - //create client classification - CodeHelper.retrieveOrCreateCodeValue(17,requestSpec,responseSpec); - //create client types - CodeHelper.retrieveOrCreateCodeValue(16,requestSpec,responseSpec); - //create Address types - CodeHelper.retrieveOrCreateCodeValue(29,requestSpec,responseSpec); - //create State - CodeHelper.retrieveOrCreateCodeValue(27,requestSpec,responseSpec); - //create Country - CodeHelper.retrieveOrCreateCodeValue(28,requestSpec,responseSpec); - //create Main business line - CodeHelper.retrieveOrCreateCodeValue(25,requestSpec,responseSpec); + // in order to populate helper columns in client entity sheet + // create constitution + CodeHelper.retrieveOrCreateCodeValue(24, requestSpec, responseSpec); + // create client classification + CodeHelper.retrieveOrCreateCodeValue(17, requestSpec, responseSpec); + // create client types + CodeHelper.retrieveOrCreateCodeValue(16, requestSpec, responseSpec); + // create Address types + CodeHelper.retrieveOrCreateCodeValue(29, requestSpec, responseSpec); + // create State + CodeHelper.retrieveOrCreateCodeValue(27, requestSpec, responseSpec); + // create Country + CodeHelper.retrieveOrCreateCodeValue(28, requestSpec, responseSpec); + // create Main business line + CodeHelper.retrieveOrCreateCodeValue(25, requestSpec, responseSpec); - ClientHelper clientHelper=new ClientHelper(requestSpec,responseSpec); - Workbook workbook=clientHelper.getClientEntityWorkbook(GlobalEntityType.CLIENTS_ENTTTY,"dd MMMM yyyy"); + ClientHelper clientHelper = new ClientHelper(requestSpec, responseSpec); + Workbook workbook = clientHelper.getClientEntityWorkbook(GlobalEntityType.CLIENTS_ENTTTY, "dd MMMM yyyy"); - //insert dummy data into client entity sheet + // insert dummy data into client entity sheet Sheet clientEntitySheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME); - Row firstClientRow=clientEntitySheet.getRow(1); - firstClientRow.createCell(ClientEntityConstants.NAME_COL).setCellValue(Utils.randomNameGenerator("C_E_",6)); - Sheet staffSheet=workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME); + Row firstClientRow = clientEntitySheet.getRow(1); + firstClientRow.createCell(ClientEntityConstants.NAME_COL).setCellValue(Utils.randomNameGenerator("C_E_", 6)); + Sheet staffSheet = workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME); firstClientRow.createCell(ClientEntityConstants.OFFICE_NAME_COL).setCellValue(staffSheet.getRow(1).getCell(0).getStringCellValue()); firstClientRow.createCell(ClientEntityConstants.STAFF_NAME_COL).setCellValue(staffSheet.getRow(1).getCell(1).getStringCellValue()); - SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd MMMM yyyy"); - Date incoporationDate=simpleDateFormat.parse("14 May 2001"); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM yyyy"); + Date incoporationDate = simpleDateFormat.parse("14 May 2001"); firstClientRow.createCell(ClientEntityConstants.INCOPORATION_DATE_COL).setCellValue(incoporationDate); - Date validTill=simpleDateFormat.parse("14 May 2019"); + Date validTill = simpleDateFormat.parse("14 May 2019"); firstClientRow.createCell(ClientEntityConstants.INCOPORATION_VALID_TILL_COL).setCellValue(validTill); firstClientRow.createCell(ClientEntityConstants.MOBILE_NO_COL).setCellValue(Utils.randomNumberGenerator(7)); - firstClientRow.createCell(ClientEntityConstants.CLIENT_TYPE_COL).setCellValue(clientEntitySheet.getRow(1).getCell(ClientEntityConstants.LOOKUP_CLIENT_TYPES).getStringCellValue()); - firstClientRow.createCell(ClientEntityConstants.CLIENT_CLASSIFICATION_COL).setCellValue(clientEntitySheet.getRow(1).getCell(ClientEntityConstants.LOOKUP_CLIENT_CLASSIFICATION).getStringCellValue()); + firstClientRow.createCell(ClientEntityConstants.CLIENT_TYPE_COL) + .setCellValue(clientEntitySheet.getRow(1).getCell(ClientEntityConstants.LOOKUP_CLIENT_TYPES).getStringCellValue()); + firstClientRow.createCell(ClientEntityConstants.CLIENT_CLASSIFICATION_COL) + .setCellValue(clientEntitySheet.getRow(1).getCell(ClientEntityConstants.LOOKUP_CLIENT_CLASSIFICATION).getStringCellValue()); firstClientRow.createCell(ClientEntityConstants.INCOPORATION_NUMBER_COL).setCellValue(Utils.randomNumberGenerator(6)); - firstClientRow.createCell(ClientEntityConstants.MAIN_BUSINESS_LINE).setCellValue(clientEntitySheet.getRow(1).getCell(ClientEntityConstants.LOOKUP_MAIN_BUSINESS_LINE).getStringCellValue()); - firstClientRow.createCell(ClientEntityConstants.CONSTITUTION_COL).setCellValue(clientEntitySheet.getRow(1).getCell(ClientEntityConstants.LOOKUP_CONSTITUTION_COL).getStringCellValue()); + firstClientRow.createCell(ClientEntityConstants.MAIN_BUSINESS_LINE) + .setCellValue(clientEntitySheet.getRow(1).getCell(ClientEntityConstants.LOOKUP_MAIN_BUSINESS_LINE).getStringCellValue()); + firstClientRow.createCell(ClientEntityConstants.CONSTITUTION_COL) + .setCellValue(clientEntitySheet.getRow(1).getCell(ClientEntityConstants.LOOKUP_CONSTITUTION_COL).getStringCellValue()); firstClientRow.createCell(ClientEntityConstants.ACTIVE_COL).setCellValue("False"); - Date submittedDate=simpleDateFormat.parse("28 September 2017"); + Date submittedDate = simpleDateFormat.parse("28 September 2017"); firstClientRow.createCell(ClientEntityConstants.SUBMITTED_ON_COL).setCellValue(submittedDate); firstClientRow.createCell(ClientEntityConstants.ADDRESS_ENABLED).setCellValue("False"); - File directory=new File(System.getProperty("user.home")+File.separator+"Fineract"+File.separator+"bulkimport"+File.separator+"integration_tests"+File.separator+"importhandler"+File.separator+"client") ; + File directory = new File(System.getProperty("user.home") + File.separator + "Fineract" + File.separator + "bulkimport" + + File.separator + "integration_tests" + File.separator + "importhandler" + File.separator + "client"); if (!directory.exists()) { directory.mkdirs(); } - File file= new File(directory+File.separator+"ClientEntity.xls"); - OutputStream outputStream=new FileOutputStream(file); + File file = new File(directory + File.separator + "ClientEntity.xls"); + OutputStream outputStream = new FileOutputStream(file); workbook.write(outputStream); outputStream.close(); - String importDocumentId=clientHelper.importClientEntityTemplate(file); + String importDocumentId = clientHelper.importClientEntityTemplate(file); file.delete(); Assertions.assertNotNull(importDocumentId); - //Wait for the creation of output excel + // Wait for the creation of output excel Thread.sleep(10000); - //check status column of output excel - String location=clientHelper.getOutputTemplateLocation(importDocumentId); + // check status column of output excel + String location = clientHelper.getOutputTemplateLocation(importDocumentId); FileInputStream fileInputStream = new FileInputStream(location); - Workbook outputWorkbook=new HSSFWorkbook(fileInputStream); + Workbook outputWorkbook = new HSSFWorkbook(fileInputStream); Sheet outputClientEntitySheet = outputWorkbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME); - Row row= outputClientEntitySheet.getRow(1); + Row row = outputClientEntitySheet.getRow(1); LOG.info("Output location: {}", location); LOG.info("Failure reason column: {}", row.getCell(ClientEntityConstants.STATUS_COL).getStringCellValue()); - Assertions.assertEquals("Imported",row.getCell(ClientEntityConstants.STATUS_COL).getStringCellValue()); + Assertions.assertEquals("Imported", row.getCell(ClientEntityConstants.STATUS_COL).getStringCellValue()); outputWorkbook.close(); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/loan/LoanImportHandlerTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/loan/LoanImportHandlerTest.java index aa344d5c9..8dee9f55c 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/loan/LoanImportHandlerTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/loan/LoanImportHandlerTest.java @@ -80,9 +80,9 @@ public class LoanImportHandlerTest { public void testLoanImport() throws InterruptedException, IOException, ParseException { requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - //in order to populate helper sheets - OfficeHelper officeHelper=new OfficeHelper(requestSpec,responseSpec); - Integer outcome_office_creation=officeHelper.createOffice("02 May 2000"); + // in order to populate helper sheets + OfficeHelper officeHelper = new OfficeHelper(requestSpec, responseSpec); + Integer outcome_office_creation = officeHelper.createOffice("02 May 2000"); Assertions.assertNotNull(outcome_office_creation, "Could not create office"); OfficeDomain office = officeHelper.retrieveOfficeByID(outcome_office_creation); @@ -102,55 +102,57 @@ public class LoanImportHandlerTest { clientMap.put("active", "true"); clientMap.put("activationDate", "04 March 2011"); - Integer outcome_client_creation= Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, + Integer outcome_client_creation = Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, new Gson().toJson(clientMap), "clientId"); Assertions.assertNotNull(outcome_client_creation, "Could not create client"); - //in order to populate helper sheets - Integer outcome_group_creation = GroupHelper.createGroup(requestSpec,responseSpec,true); + // in order to populate helper sheets + Integer outcome_group_creation = GroupHelper.createGroup(requestSpec, responseSpec, true); Assertions.assertNotNull(outcome_group_creation, "Could not create group"); - //in order to populate helper sheets - Integer outcome_staff_creation = StaffHelper.createStaff(requestSpec,responseSpec); + // in order to populate helper sheets + Integer outcome_staff_creation = StaffHelper.createStaff(requestSpec, responseSpec); Assertions.assertNotNull(outcome_staff_creation, "Could not create staff"); Map staffMap = StaffHelper.getStaff(requestSpec, responseSpec, outcome_staff_creation); Assertions.assertNotNull(staffMap, "Could not retrieve created staff"); - LoanTransactionHelper ltHelper=new LoanTransactionHelper(requestSpec,responseSpec); - LoanProductTestBuilder loanProductTestBuilder=new LoanProductTestBuilder(); - String jsonLoanProduct=loanProductTestBuilder.build(null); - Integer outcome_lp_creation=ltHelper.getLoanProductId(jsonLoanProduct); + LoanTransactionHelper ltHelper = new LoanTransactionHelper(requestSpec, responseSpec); + LoanProductTestBuilder loanProductTestBuilder = new LoanProductTestBuilder(); + String jsonLoanProduct = loanProductTestBuilder.build(null); + Integer outcome_lp_creation = ltHelper.getLoanProductId(jsonLoanProduct); Assertions.assertNotNull(outcome_lp_creation, "Could not create Loan Product"); String loanProductStr = ltHelper.getLoanProductDetails(requestSpec, responseSpec, outcome_lp_creation); - Assertions.assertNotNull("Could not get created Loan Product" , loanProductStr); + Assertions.assertNotNull("Could not get created Loan Product", loanProductStr); JsonPath loanProductJson = JsonPath.from(loanProductStr); - String fundName = Utils.randomNameGenerator("",9); + String fundName = Utils.randomNameGenerator("", 9); FundsHelper fh = FundsHelper.create(fundName).externalId("fund-" + fundName).build(); - Integer outcome_fund_creation= FundsResourceHandler.createFund(new Gson().toJson(fh),requestSpec,responseSpec); + Integer outcome_fund_creation = FundsResourceHandler.createFund(new Gson().toJson(fh), requestSpec, responseSpec); Assertions.assertNotNull(outcome_fund_creation, "Could not create Fund"); String paymentTypeName = PaymentTypeHelper.randomNameGenerator("P_T", 5); String paymentTypeDescription = PaymentTypeHelper.randomNameGenerator("PT_Desc", 15); - Integer outcome_payment_creation= PaymentTypeHelper.createPaymentType(requestSpec, responseSpec, paymentTypeName, paymentTypeDescription, true,1); + Integer outcome_payment_creation = PaymentTypeHelper.createPaymentType(requestSpec, responseSpec, paymentTypeName, + paymentTypeDescription, true, 1); Assertions.assertNotNull(outcome_payment_creation, "Could not create payment type"); - LoanTransactionHelper loanTransactionHelper=new LoanTransactionHelper(requestSpec,responseSpec); - Workbook workbook=loanTransactionHelper.getLoanWorkbook("dd MMMM yyyy"); + LoanTransactionHelper loanTransactionHelper = new LoanTransactionHelper(requestSpec, responseSpec); + Workbook workbook = loanTransactionHelper.getLoanWorkbook("dd MMMM yyyy"); - //insert dummy data into loan Sheet + // insert dummy data into loan Sheet Sheet loanSheet = workbook.getSheet(TemplatePopulateImportConstants.LOANS_SHEET_NAME); - Row firstLoanRow=loanSheet.getRow(1); + Row firstLoanRow = loanSheet.getRow(1); firstLoanRow.createCell(LoanConstants.OFFICE_NAME_COL).setCellValue(office.getName()); firstLoanRow.createCell(LoanConstants.LOAN_TYPE_COL).setCellValue("Individual"); - firstLoanRow.createCell(LoanConstants.CLIENT_NAME_COL).setCellValue(firstName + " " + lastName + "(" + outcome_client_creation + ")"); + firstLoanRow.createCell(LoanConstants.CLIENT_NAME_COL) + .setCellValue(firstName + " " + lastName + "(" + outcome_client_creation + ")"); firstLoanRow.createCell(LoanConstants.CLIENT_EXTERNAL_ID).setCellValue(externalId); firstLoanRow.createCell(LoanConstants.PRODUCT_COL).setCellValue(loanProductJson.getString("name")); firstLoanRow.createCell(LoanConstants.LOAN_OFFICER_NAME_COL).setCellValue((String) staffMap.get("displayName")); - SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd MMMM yyyy"); - Date date=simpleDateFormat.parse("13 May 2017"); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM yyyy"); + Date date = simpleDateFormat.parse("13 May 2017"); firstLoanRow.createCell(LoanConstants.SUBMITTED_ON_DATE_COL).setCellValue(date); firstLoanRow.createCell(LoanConstants.APPROVED_DATE_COL).setCellValue(date); firstLoanRow.createCell(LoanConstants.DISBURSED_DATE_COL).setCellValue(date); @@ -159,16 +161,22 @@ public class LoanImportHandlerTest { firstLoanRow.createCell(LoanConstants.PRINCIPAL_COL).setCellValue(loanProductJson.getFloat("principal")); firstLoanRow.createCell(LoanConstants.NO_OF_REPAYMENTS_COL).setCellValue(loanProductJson.getInt("numberOfRepayments")); firstLoanRow.createCell(LoanConstants.REPAID_EVERY_COL).setCellValue(loanProductJson.getInt("repaymentEvery")); - firstLoanRow.createCell(LoanConstants.REPAID_EVERY_FREQUENCY_COL).setCellValue(loanProductJson.getString("repaymentFrequencyType.value")); - firstLoanRow.createCell(LoanConstants.LOAN_TERM_COL).setCellValue(loanProductJson.getInt("repaymentEvery") * loanProductJson.getInt("numberOfRepayments")); - firstLoanRow.createCell(LoanConstants.LOAN_TERM_FREQUENCY_COL).setCellValue(loanProductJson.getString("repaymentFrequencyType.value")); + firstLoanRow.createCell(LoanConstants.REPAID_EVERY_FREQUENCY_COL) + .setCellValue(loanProductJson.getString("repaymentFrequencyType.value")); + firstLoanRow.createCell(LoanConstants.LOAN_TERM_COL) + .setCellValue(loanProductJson.getInt("repaymentEvery") * loanProductJson.getInt("numberOfRepayments")); + firstLoanRow.createCell(LoanConstants.LOAN_TERM_FREQUENCY_COL) + .setCellValue(loanProductJson.getString("repaymentFrequencyType.value")); firstLoanRow.createCell(LoanConstants.NOMINAL_INTEREST_RATE_COL).setCellValue(loanProductJson.getDouble("interestRatePerPeriod")); - firstLoanRow.createCell(LoanConstants.NOMINAL_INTEREST_RATE_FREQUENCY_COL).setCellValue(loanProductJson.getString("interestRateFrequencyType.value")); + firstLoanRow.createCell(LoanConstants.NOMINAL_INTEREST_RATE_FREQUENCY_COL) + .setCellValue(loanProductJson.getString("interestRateFrequencyType.value")); firstLoanRow.createCell(LoanConstants.AMORTIZATION_COL).setCellValue(loanProductJson.getString("amortizationType.value")); firstLoanRow.createCell(LoanConstants.INTEREST_METHOD_COL).setCellValue(loanProductJson.getString("interestType.value")); - firstLoanRow.createCell(LoanConstants.INTEREST_CALCULATION_PERIOD_COL).setCellValue(loanProductJson.getString("interestCalculationPeriodType.value")); + firstLoanRow.createCell(LoanConstants.INTEREST_CALCULATION_PERIOD_COL) + .setCellValue(loanProductJson.getString("interestCalculationPeriodType.value")); firstLoanRow.createCell(LoanConstants.ARREARS_TOLERANCE_COL).setCellValue(0); - firstLoanRow.createCell(LoanConstants.REPAYMENT_STRATEGY_COL).setCellValue(loanProductJson.getString("transactionProcessingStrategyName")); + firstLoanRow.createCell(LoanConstants.REPAYMENT_STRATEGY_COL) + .setCellValue(loanProductJson.getString("transactionProcessingStrategyName")); firstLoanRow.createCell(LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL).setCellValue(0); firstLoanRow.createCell(LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL).setCellValue(0); firstLoanRow.createCell(LoanConstants.GRACE_ON_INTEREST_CHARGED_COL).setCellValue(0); @@ -178,34 +186,34 @@ public class LoanImportHandlerTest { firstLoanRow.createCell(LoanConstants.REPAYMENT_TYPE_COL).setCellValue(paymentTypeName); String currentdirectory = new File("").getAbsolutePath(); - File directory=new File(currentdirectory+File.separator+"src"+File.separator+"integrationTest"+File.separator+ - "resources"+File.separator+"bulkimport"+File.separator+"importhandler"+File.separator+"loan") ; + File directory = new File(currentdirectory + File.separator + "src" + File.separator + "integrationTest" + File.separator + + "resources" + File.separator + "bulkimport" + File.separator + "importhandler" + File.separator + "loan"); if (!directory.exists()) { directory.mkdirs(); } - File file= new File(directory+File.separator+"Loan.xls"); - OutputStream outputStream=new FileOutputStream(file); + File file = new File(directory + File.separator + "Loan.xls"); + OutputStream outputStream = new FileOutputStream(file); workbook.write(outputStream); outputStream.close(); - String importDocumentId=loanTransactionHelper.importLoanTemplate(file); + String importDocumentId = loanTransactionHelper.importLoanTemplate(file); file.delete(); Assertions.assertNotNull(importDocumentId); - //Wait for the creation of output excel + // Wait for the creation of output excel Thread.sleep(10000); - //check status column of output excel - String location=loanTransactionHelper.getOutputTemplateLocation(importDocumentId); + // check status column of output excel + String location = loanTransactionHelper.getOutputTemplateLocation(importDocumentId); FileInputStream fileInputStream = new FileInputStream(location); - Workbook outputworkbook=new HSSFWorkbook(fileInputStream); + Workbook outputworkbook = new HSSFWorkbook(fileInputStream); Sheet outputLoanSheet = outputworkbook.getSheet(TemplatePopulateImportConstants.LOANS_SHEET_NAME); - Row row= outputLoanSheet.getRow(1); + Row row = outputLoanSheet.getRow(1); LOG.info("Output location: {}", location); LOG.info("Failure reason column: {}", row.getCell(LoanConstants.FAILURE_REPORT_COL).getStringCellValue()); - Assertions.assertEquals("Imported",row.getCell(LoanConstants.STATUS_COL).getStringCellValue()); + Assertions.assertEquals("Imported", row.getCell(LoanConstants.STATUS_COL).getStringCellValue()); outputworkbook.close(); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/office/OfficeImportHandlerTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/office/OfficeImportHandlerTest.java index 310f4f852..d1f510314 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/office/OfficeImportHandlerTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/office/OfficeImportHandlerTest.java @@ -52,56 +52,54 @@ public class OfficeImportHandlerTest { private RequestSpecification requestSpec; @BeforeEach - public void setup(){ + public void setup() { Utils.initializeRESTAssured(); - this.requestSpec=new RequestSpecBuilder().build(); - this.requestSpec - .header("Authorization", - "Basic " - + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200) - .build(); + this.requestSpec = new RequestSpecBuilder().build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } @Test public void testOfficeImport() throws IOException, InterruptedException, NoSuchFieldException, ParseException { - OfficeHelper officeHelper=new OfficeHelper(requestSpec,responseSpec); - Workbook workbook=officeHelper.getOfficeWorkBook("dd MMMM yyyy"); + OfficeHelper officeHelper = new OfficeHelper(requestSpec, responseSpec); + Workbook workbook = officeHelper.getOfficeWorkBook("dd MMMM yyyy"); - //insert dummy data into excel - Sheet sheet=workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); - Row firstOfficeRow= sheet.getRow(1); - firstOfficeRow.createCell(OfficeConstants.OFFICE_NAME_COL).setCellValue(Utils.randomNameGenerator("Test_Off_",6)); - firstOfficeRow.createCell(OfficeConstants.PARENT_OFFICE_NAME_COL).setCellValue(firstOfficeRow.getCell(OfficeConstants.LOOKUP_OFFICE_COL).getStringCellValue()); - firstOfficeRow.createCell(OfficeConstants.PARENT_OFFICE_ID_COL).setCellValue(firstOfficeRow.getCell(OfficeConstants.LOOKUP_OFFICE_ID_COL).getNumericCellValue()); - SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd MMMM yyyy"); - Date date=simpleDateFormat.parse("14 May 2001"); + // insert dummy data into excel + Sheet sheet = workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); + Row firstOfficeRow = sheet.getRow(1); + firstOfficeRow.createCell(OfficeConstants.OFFICE_NAME_COL).setCellValue(Utils.randomNameGenerator("Test_Off_", 6)); + firstOfficeRow.createCell(OfficeConstants.PARENT_OFFICE_NAME_COL) + .setCellValue(firstOfficeRow.getCell(OfficeConstants.LOOKUP_OFFICE_COL).getStringCellValue()); + firstOfficeRow.createCell(OfficeConstants.PARENT_OFFICE_ID_COL) + .setCellValue(firstOfficeRow.getCell(OfficeConstants.LOOKUP_OFFICE_ID_COL).getNumericCellValue()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM yyyy"); + Date date = simpleDateFormat.parse("14 May 2001"); firstOfficeRow.createCell(OfficeConstants.OPENED_ON_COL).setCellValue(date); String currentdirectory = new File("").getAbsolutePath(); - File directory=new File(currentdirectory+File.separator+"src"+File.separator+"integrationTest"+File.separator+ - "resources"+File.separator+"bulkimport"+File.separator+"importhandler"+File.separator+"office"); + File directory = new File(currentdirectory + File.separator + "src" + File.separator + "integrationTest" + File.separator + + "resources" + File.separator + "bulkimport" + File.separator + "importhandler" + File.separator + "office"); if (!directory.exists()) { directory.mkdirs(); } - File file= new File(directory+File.separator+"Office.xls"); - OutputStream outputStream=new FileOutputStream(file); + File file = new File(directory + File.separator + "Office.xls"); + OutputStream outputStream = new FileOutputStream(file); workbook.write(outputStream); outputStream.close(); - String importDocumentId=officeHelper.importOfficeTemplate(file); + String importDocumentId = officeHelper.importOfficeTemplate(file); file.delete(); Assertions.assertNotNull(importDocumentId); // Wait for the creation of output excel Thread.sleep(10000); - //check status column of output excel - String location=officeHelper.getOutputTemplateLocation(importDocumentId); + // check status column of output excel + String location = officeHelper.getOutputTemplateLocation(importDocumentId); FileInputStream fileInputStream = new FileInputStream(location); - Workbook outputWorkbook=new HSSFWorkbook(fileInputStream); + Workbook outputWorkbook = new HSSFWorkbook(fileInputStream); Sheet officeSheet = outputWorkbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); - Row row= officeSheet.getRow(1); + Row row = officeSheet.getRow(1); LOG.info("Output location: {}", location); LOG.info("Failure reason column: {}", row.getCell(OfficeConstants.STATUS_COL).getStringCellValue()); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/savings/SavingsImportHandlerTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/savings/SavingsImportHandlerTest.java index 753426f9f..f2ad53e71 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/savings/SavingsImportHandlerTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/importhandler/savings/SavingsImportHandlerTest.java @@ -77,9 +77,9 @@ public class SavingsImportHandlerTest { public void testSavingsImport() throws InterruptedException, IOException, ParseException { requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - //in order to populate helper sheets - OfficeHelper officeHelper=new OfficeHelper(requestSpec,responseSpec); - Integer outcome_office_creation=officeHelper.createOffice("02 May 2000"); + // in order to populate helper sheets + OfficeHelper officeHelper = new OfficeHelper(requestSpec, responseSpec); + Integer outcome_office_creation = officeHelper.createOffice("02 May 2000"); Assertions.assertNotNull(outcome_office_creation, "Could not create office"); OfficeDomain office = officeHelper.retrieveOfficeByID(outcome_office_creation); @@ -99,87 +99,98 @@ public class SavingsImportHandlerTest { clientMap.put("active", "true"); clientMap.put("activationDate", "04 March 2011"); - Integer outcome_client_creation= Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, + Integer outcome_client_creation = Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, new Gson().toJson(clientMap), "clientId"); Assertions.assertNotNull(outcome_client_creation, "Could not create client"); - //in order to populate helper sheets - Integer outcome_group_creation=GroupHelper.createGroup(requestSpec,responseSpec,true); + // in order to populate helper sheets + Integer outcome_group_creation = GroupHelper.createGroup(requestSpec, responseSpec, true); Assertions.assertNotNull(outcome_group_creation, "Could not create group"); - //in order to populate helper sheets - Integer outcome_staff_creation =StaffHelper.createStaff(requestSpec,responseSpec); + // in order to populate helper sheets + Integer outcome_staff_creation = StaffHelper.createStaff(requestSpec, responseSpec); Assertions.assertNotNull(outcome_staff_creation, "Could not create staff"); Map staffMap = StaffHelper.getStaff(requestSpec, responseSpec, outcome_staff_creation); Assertions.assertNotNull(staffMap, "Could not retrieve created staff"); SavingsProductHelper savingsProductHelper = new SavingsProductHelper(); - String jsonSavingsProduct=savingsProductHelper.build(); - Integer outcome_sp_creaction=SavingsProductHelper.createSavingsProduct(jsonSavingsProduct,requestSpec,responseSpec); + String jsonSavingsProduct = savingsProductHelper.build(); + Integer outcome_sp_creaction = SavingsProductHelper.createSavingsProduct(jsonSavingsProduct, requestSpec, responseSpec); Assertions.assertNotNull(outcome_sp_creaction, "Could not create Savings product"); - SavingsAccountHelper savingsAccountHelper=new SavingsAccountHelper(requestSpec,responseSpec); - Workbook workbook=savingsAccountHelper.getSavingsWorkbook("dd MMMM yyyy"); + SavingsAccountHelper savingsAccountHelper = new SavingsAccountHelper(requestSpec, responseSpec); + Workbook workbook = savingsAccountHelper.getSavingsWorkbook("dd MMMM yyyy"); - //insert dummy data into Savings sheet + // insert dummy data into Savings sheet Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME); - Row firstSavingsRow=savingsSheet.getRow(1); + Row firstSavingsRow = savingsSheet.getRow(1); firstSavingsRow.createCell(SavingsConstants.OFFICE_NAME_COL).setCellValue(office.getName()); firstSavingsRow.createCell(SavingsConstants.SAVINGS_TYPE_COL).setCellValue("Individual"); - firstSavingsRow.createCell(SavingsConstants.CLIENT_NAME_COL).setCellValue(firstName + " " + lastName + "(" + outcome_client_creation + ")"); - Sheet savingsProductSheet=workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); - firstSavingsRow.createCell(SavingsConstants.PRODUCT_COL).setCellValue(savingsProductSheet.getRow(1).getCell(1).getStringCellValue()); + firstSavingsRow.createCell(SavingsConstants.CLIENT_NAME_COL) + .setCellValue(firstName + " " + lastName + "(" + outcome_client_creation + ")"); + Sheet savingsProductSheet = workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); + firstSavingsRow.createCell(SavingsConstants.PRODUCT_COL) + .setCellValue(savingsProductSheet.getRow(1).getCell(1).getStringCellValue()); firstSavingsRow.createCell(SavingsConstants.FIELD_OFFICER_NAME_COL).setCellValue((String) staffMap.get("displayName")); - SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd MMMM yyyy"); - Date date=simpleDateFormat.parse("13 May 2017"); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM yyyy"); + Date date = simpleDateFormat.parse("13 May 2017"); firstSavingsRow.createCell(SavingsConstants.SUBMITTED_ON_DATE_COL).setCellValue(date); firstSavingsRow.createCell(SavingsConstants.APPROVED_DATE_COL).setCellValue(date); firstSavingsRow.createCell(SavingsConstants.ACTIVATION_DATE_COL).setCellValue(date); - firstSavingsRow.createCell(SavingsConstants.CURRENCY_COL).setCellValue(savingsProductSheet.getRow(1).getCell(10).getStringCellValue()); - firstSavingsRow.createCell(SavingsConstants.DECIMAL_PLACES_COL).setCellValue(savingsProductSheet.getRow(1).getCell(11).getNumericCellValue()); - firstSavingsRow.createCell(SavingsConstants.IN_MULTIPLES_OF_COL).setCellValue(savingsProductSheet.getRow(1).getCell(12).getNumericCellValue()); - firstSavingsRow.createCell(SavingsConstants.NOMINAL_ANNUAL_INTEREST_RATE_COL).setCellValue(savingsProductSheet.getRow(1).getCell(2).getNumericCellValue()); - firstSavingsRow.createCell(SavingsConstants.INTEREST_COMPOUNDING_PERIOD_COL).setCellValue(savingsProductSheet.getRow(1).getCell(3).getStringCellValue()); - firstSavingsRow.createCell(SavingsConstants.INTEREST_POSTING_PERIOD_COL).setCellValue(savingsProductSheet.getRow(1).getCell(4).getStringCellValue()); - firstSavingsRow.createCell(SavingsConstants.INTEREST_CALCULATION_COL).setCellValue(savingsProductSheet.getRow(1).getCell(5).getStringCellValue()); - firstSavingsRow.createCell(SavingsConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL).setCellValue(savingsProductSheet.getRow(1).getCell(6).getStringCellValue()); + firstSavingsRow.createCell(SavingsConstants.CURRENCY_COL) + .setCellValue(savingsProductSheet.getRow(1).getCell(10).getStringCellValue()); + firstSavingsRow.createCell(SavingsConstants.DECIMAL_PLACES_COL) + .setCellValue(savingsProductSheet.getRow(1).getCell(11).getNumericCellValue()); + firstSavingsRow.createCell(SavingsConstants.IN_MULTIPLES_OF_COL) + .setCellValue(savingsProductSheet.getRow(1).getCell(12).getNumericCellValue()); + firstSavingsRow.createCell(SavingsConstants.NOMINAL_ANNUAL_INTEREST_RATE_COL) + .setCellValue(savingsProductSheet.getRow(1).getCell(2).getNumericCellValue()); + firstSavingsRow.createCell(SavingsConstants.INTEREST_COMPOUNDING_PERIOD_COL) + .setCellValue(savingsProductSheet.getRow(1).getCell(3).getStringCellValue()); + firstSavingsRow.createCell(SavingsConstants.INTEREST_POSTING_PERIOD_COL) + .setCellValue(savingsProductSheet.getRow(1).getCell(4).getStringCellValue()); + firstSavingsRow.createCell(SavingsConstants.INTEREST_CALCULATION_COL) + .setCellValue(savingsProductSheet.getRow(1).getCell(5).getStringCellValue()); + firstSavingsRow.createCell(SavingsConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL) + .setCellValue(savingsProductSheet.getRow(1).getCell(6).getStringCellValue()); firstSavingsRow.createCell(SavingsConstants.MIN_OPENING_BALANCE_COL).setCellValue(1000.0); firstSavingsRow.createCell(SavingsConstants.LOCKIN_PERIOD_COL).setCellValue(1); firstSavingsRow.createCell(SavingsConstants.LOCKIN_PERIOD_FREQUENCY_COL).setCellValue("Weeks"); firstSavingsRow.createCell(SavingsConstants.APPLY_WITHDRAWAL_FEE_FOR_TRANSFERS).setCellValue("False"); firstSavingsRow.createCell(SavingsConstants.ALLOW_OVER_DRAFT_COL).setCellValue("False"); - firstSavingsRow.createCell(SavingsConstants.OVER_DRAFT_LIMIT_COL).setCellValue(savingsProductSheet.getRow(1).getCell(15).getNumericCellValue()); + firstSavingsRow.createCell(SavingsConstants.OVER_DRAFT_LIMIT_COL) + .setCellValue(savingsProductSheet.getRow(1).getCell(15).getNumericCellValue()); String currentdirectory = new File("").getAbsolutePath(); - File directory=new File(currentdirectory+File.separator+"src"+File.separator+"integrationTest"+File.separator+ - "resources"+File.separator+"bulkimport"+File.separator+"importhandler"+File.separator+"savings") ; + File directory = new File(currentdirectory + File.separator + "src" + File.separator + "integrationTest" + File.separator + + "resources" + File.separator + "bulkimport" + File.separator + "importhandler" + File.separator + "savings"); if (!directory.exists()) { directory.mkdirs(); } - File file= new File(directory+File.separator+"Savings.xls"); - OutputStream outputStream=new FileOutputStream(file); + File file = new File(directory + File.separator + "Savings.xls"); + OutputStream outputStream = new FileOutputStream(file); workbook.write(outputStream); outputStream.close(); - String importDocumentId=savingsAccountHelper.importSavingsTemplate(file); + String importDocumentId = savingsAccountHelper.importSavingsTemplate(file); file.delete(); Assertions.assertNotNull(importDocumentId); - //Wait for the creation of output excel + // Wait for the creation of output excel Thread.sleep(10000); - //check status column of output excel - String location=savingsAccountHelper.getOutputTemplateLocation(importDocumentId); + // check status column of output excel + String location = savingsAccountHelper.getOutputTemplateLocation(importDocumentId); FileInputStream fileInputStream = new FileInputStream(location); - Workbook Outputworkbook=new HSSFWorkbook(fileInputStream); + Workbook Outputworkbook = new HSSFWorkbook(fileInputStream); Sheet OutputSavingsSheet = Outputworkbook.getSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME); - Row row= OutputSavingsSheet.getRow(1); + Row row = OutputSavingsSheet.getRow(1); LOG.info("Output location: {}", location); LOG.info("Failure reason column: {}", row.getCell(SavingsConstants.STATUS_COL).getStringCellValue()); - Assertions.assertEquals("Imported",row.getCell(SavingsConstants.STATUS_COL).getStringCellValue()); + Assertions.assertEquals("Imported", row.getCell(SavingsConstants.STATUS_COL).getStringCellValue()); Outputworkbook.close(); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/client/ClientEntityWorkbookPopulatorTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/client/ClientEntityWorkbookPopulatorTest.java index 24369541e..be0d8942b 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/client/ClientEntityWorkbookPopulatorTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/client/ClientEntityWorkbookPopulatorTest.java @@ -44,39 +44,34 @@ public class ClientEntityWorkbookPopulatorTest { private RequestSpecification requestSpec; @BeforeEach - public void setup(){ + public void setup() { Utils.initializeRESTAssured(); - this.requestSpec=new RequestSpecBuilder().build(); - this.requestSpec - .header("Authorization", - "Basic " - + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200) - .build(); - + this.requestSpec = new RequestSpecBuilder().build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } @Test public void testClientEntityWorkbookPopulate() throws IOException { - //in order to populate helper sheets - StaffHelper staffHelper=new StaffHelper(); + // in order to populate helper sheets + StaffHelper staffHelper = new StaffHelper(); requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - Integer outcome_staff_creation =staffHelper.createStaff(requestSpec,responseSpec); + Integer outcome_staff_creation = staffHelper.createStaff(requestSpec, responseSpec); Assertions.assertNotNull(outcome_staff_creation, "Could not create staff"); - //in order to populate helper sheets - OfficeHelper officeHelper=new OfficeHelper(requestSpec,responseSpec); - Integer outcome_office_creation=officeHelper.createOffice("02 May 2000"); + // in order to populate helper sheets + OfficeHelper officeHelper = new OfficeHelper(requestSpec, responseSpec); + Integer outcome_office_creation = officeHelper.createOffice("02 May 2000"); Assertions.assertNotNull(outcome_office_creation, "Could not create office"); - ClientHelper clientHelper=new ClientHelper(requestSpec,responseSpec); - Workbook workbook=clientHelper.getClientEntityWorkbook(GlobalEntityType.CLIENTS_ENTTTY,"dd MMMM yyyy"); - Sheet officeSheet=workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); - Row firstOfficeRow=officeSheet.getRow(1); + ClientHelper clientHelper = new ClientHelper(requestSpec, responseSpec); + Workbook workbook = clientHelper.getClientEntityWorkbook(GlobalEntityType.CLIENTS_ENTTTY, "dd MMMM yyyy"); + Sheet officeSheet = workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); + Row firstOfficeRow = officeSheet.getRow(1); Assertions.assertNotNull(firstOfficeRow.getCell(1), "No offices found for given OfficeId "); - Sheet staffSheet=workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME); - Row firstStaffRow=staffSheet.getRow(1); + Sheet staffSheet = workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME); + Row firstStaffRow = staffSheet.getRow(1); Assertions.assertNotNull(firstStaffRow.getCell(1), "No staff found for given staffId"); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/loan/LoanWorkbookPopulatorTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/loan/LoanWorkbookPopulatorTest.java index 9c67c4f2b..949e4e38d 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/loan/LoanWorkbookPopulatorTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/loan/LoanWorkbookPopulatorTest.java @@ -49,80 +49,80 @@ public class LoanWorkbookPopulatorTest { private RequestSpecification requestSpec; @BeforeEach - public void setup(){ + public void setup() { Utils.initializeRESTAssured(); this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } + @Test public void testLoanWorkbookPopulate() throws IOException { requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - //in order to populate helper sheets - OfficeHelper officeHelper=new OfficeHelper(requestSpec,responseSpec); - Integer outcome_office_creation=officeHelper.createOffice("02 May 2000"); + // in order to populate helper sheets + OfficeHelper officeHelper = new OfficeHelper(requestSpec, responseSpec); + Integer outcome_office_creation = officeHelper.createOffice("02 May 2000"); Assertions.assertNotNull(outcome_office_creation, "Could not create office"); - //in order to populate helper sheets - ClientHelper clientHelper=new ClientHelper(requestSpec,responseSpec); - Integer outcome_client_creation=clientHelper.createClient(requestSpec,responseSpec); + // in order to populate helper sheets + ClientHelper clientHelper = new ClientHelper(requestSpec, responseSpec); + Integer outcome_client_creation = clientHelper.createClient(requestSpec, responseSpec); Assertions.assertNotNull(outcome_client_creation, "Could not create client"); - //in order to populate helper sheets - GroupHelper groupHelper=new GroupHelper(requestSpec,responseSpec); - Integer outcome_group_creation=groupHelper.createGroup(requestSpec,responseSpec,true); + // in order to populate helper sheets + GroupHelper groupHelper = new GroupHelper(requestSpec, responseSpec); + Integer outcome_group_creation = groupHelper.createGroup(requestSpec, responseSpec, true); Assertions.assertNotNull(outcome_group_creation, "Could not create group"); - //in order to populate helper sheets - StaffHelper staffHelper=new StaffHelper(); - Integer outcome_staff_creation =staffHelper.createStaff(requestSpec,responseSpec); + // in order to populate helper sheets + StaffHelper staffHelper = new StaffHelper(); + Integer outcome_staff_creation = staffHelper.createStaff(requestSpec, responseSpec); Assertions.assertNotNull(outcome_staff_creation, "Could not create staff"); - LoanTransactionHelper loanTransactionHelper=new LoanTransactionHelper(requestSpec,responseSpec); - LoanProductTestBuilder loanProductTestBuilder=new LoanProductTestBuilder(); - String jsonLoanProduct=loanProductTestBuilder.build(null); - Integer outcome_lp_creaion=loanTransactionHelper.getLoanProductId(jsonLoanProduct); + LoanTransactionHelper loanTransactionHelper = new LoanTransactionHelper(requestSpec, responseSpec); + LoanProductTestBuilder loanProductTestBuilder = new LoanProductTestBuilder(); + String jsonLoanProduct = loanProductTestBuilder.build(null); + Integer outcome_lp_creaion = loanTransactionHelper.getLoanProductId(jsonLoanProduct); Assertions.assertNotNull(outcome_lp_creaion, "Could not create Loan Product"); - FundsResourceHandler fundsResourceHandler=new FundsResourceHandler(); - String jsonFund="{\n" + - "\t\"name\": \""+Utils.randomNameGenerator("Fund_Name",9)+"\"\n" + - "}"; - Integer outcome_fund_creation=fundsResourceHandler.createFund(jsonFund,requestSpec,responseSpec); + FundsResourceHandler fundsResourceHandler = new FundsResourceHandler(); + String jsonFund = "{\n" + "\t\"name\": \"" + Utils.randomNameGenerator("Fund_Name", 9) + "\"\n" + "}"; + Integer outcome_fund_creation = fundsResourceHandler.createFund(jsonFund, requestSpec, responseSpec); Assertions.assertNotNull(outcome_fund_creation, "Could not create Fund"); - PaymentTypeHelper paymentTypeHelper=new PaymentTypeHelper(); + PaymentTypeHelper paymentTypeHelper = new PaymentTypeHelper(); String name = PaymentTypeHelper.randomNameGenerator("P_T", 5); String description = PaymentTypeHelper.randomNameGenerator("PT_Desc", 15); Boolean isCashPayment = true; Integer position = 1; - Integer outcome_payment_creation= paymentTypeHelper.createPaymentType(requestSpec, responseSpec,name,description,isCashPayment,position); + Integer outcome_payment_creation = paymentTypeHelper.createPaymentType(requestSpec, responseSpec, name, description, isCashPayment, + position); Assertions.assertNotNull(outcome_payment_creation, "Could not create payment type"); - Workbook workbook=loanTransactionHelper.getLoanWorkbook("dd MMMM yyyy"); + Workbook workbook = loanTransactionHelper.getLoanWorkbook("dd MMMM yyyy"); - Sheet officeSheet=workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); - Row firstOfficeRow=officeSheet.getRow(1); + Sheet officeSheet = workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); + Row firstOfficeRow = officeSheet.getRow(1); Assertions.assertNotNull(firstOfficeRow.getCell(1), "No offices found "); - Sheet clientSheet=workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME); - Row firstClientRow=clientSheet.getRow(1); + Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME); + Row firstClientRow = clientSheet.getRow(1); Assertions.assertNotNull(firstClientRow.getCell(1), "No clients found "); - Sheet groupSheet=workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME); - Row firstGroupRow=groupSheet.getRow(1); + Sheet groupSheet = workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME); + Row firstGroupRow = groupSheet.getRow(1); Assertions.assertNotNull(firstGroupRow.getCell(1), "No groups found "); - Sheet staffSheet=workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME); - Row firstStaffRow=staffSheet.getRow(1); + Sheet staffSheet = workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME); + Row firstStaffRow = staffSheet.getRow(1); Assertions.assertNotNull(firstStaffRow.getCell(1), "No staff found "); - Sheet productSheet=workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); - Row firstProductRow=productSheet.getRow(1); + Sheet productSheet = workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); + Row firstProductRow = productSheet.getRow(1); Assertions.assertNotNull(firstProductRow.getCell(1), "No products found "); - Sheet extrasSheet=workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME); - Row firstExtrasRow=extrasSheet.getRow(1); + Sheet extrasSheet = workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME); + Row firstExtrasRow = extrasSheet.getRow(1); Assertions.assertNotNull(firstExtrasRow.getCell(1), "No Extras found "); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/office/OfficeWorkBookPopulatorTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/office/OfficeWorkBookPopulatorTest.java index 457991c5c..894ec69d7 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/office/OfficeWorkBookPopulatorTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/office/OfficeWorkBookPopulatorTest.java @@ -35,27 +35,24 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class OfficeWorkBookPopulatorTest { + private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @BeforeEach - public void setup(){ + public void setup() { Utils.initializeRESTAssured(); - this.requestSpec=new RequestSpecBuilder().build(); - this.requestSpec - .header("Authorization", - "Basic " - + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200) - .build(); + this.requestSpec = new RequestSpecBuilder().build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } @Test public void testOfficeWorkbookPopulate() throws IOException { - OfficeHelper officeHelper=new OfficeHelper(requestSpec,responseSpec); - Workbook workbook=officeHelper.getOfficeWorkBook("dd MMMM yyyy"); - Sheet sheet=workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); - Row firstRow= sheet.getRow(1); + OfficeHelper officeHelper = new OfficeHelper(requestSpec, responseSpec); + Workbook workbook = officeHelper.getOfficeWorkBook("dd MMMM yyyy"); + Sheet sheet = workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); + Row firstRow = sheet.getRow(1); Assertions.assertNotNull("No parent offices found", firstRow.getCell(OfficeConstants.LOOKUP_OFFICE_COL).getStringCellValue()); Assertions.assertEquals(1, firstRow.getCell(OfficeConstants.LOOKUP_OFFICE_ID_COL).getNumericCellValue(), 0.0); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/savings/SavingsWorkbookPopulateTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/savings/SavingsWorkbookPopulateTest.java index 4a212476e..89e7f6a3a 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/savings/SavingsWorkbookPopulateTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/bulkimport/populator/savings/SavingsWorkbookPopulateTest.java @@ -42,11 +42,12 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class SavingsWorkbookPopulateTest { + private ResponseSpecification responseSpec; private RequestSpecification requestSpec; @BeforeEach - public void setup(){ + public void setup() { Utils.initializeRESTAssured(); this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); @@ -56,52 +57,52 @@ public class SavingsWorkbookPopulateTest { @Test public void testSavingsWorkbookPopulate() throws IOException { requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - //in order to populate helper sheets - OfficeHelper officeHelper=new OfficeHelper(requestSpec,responseSpec); - Integer outcome_office_creation=officeHelper.createOffice("02 May 2000"); + // in order to populate helper sheets + OfficeHelper officeHelper = new OfficeHelper(requestSpec, responseSpec); + Integer outcome_office_creation = officeHelper.createOffice("02 May 2000"); Assertions.assertNotNull(outcome_office_creation, "Could not create office"); - //in order to populate helper sheets - ClientHelper clientHelper=new ClientHelper(requestSpec,responseSpec); - Integer outcome_client_creation=clientHelper.createClient(requestSpec,responseSpec); + // in order to populate helper sheets + ClientHelper clientHelper = new ClientHelper(requestSpec, responseSpec); + Integer outcome_client_creation = clientHelper.createClient(requestSpec, responseSpec); Assertions.assertNotNull(outcome_client_creation, "Could not create client"); - //in order to populate helper sheets - GroupHelper groupHelper=new GroupHelper(requestSpec,responseSpec); - Integer outcome_group_creation=groupHelper.createGroup(requestSpec,responseSpec,true); + // in order to populate helper sheets + GroupHelper groupHelper = new GroupHelper(requestSpec, responseSpec); + Integer outcome_group_creation = groupHelper.createGroup(requestSpec, responseSpec, true); Assertions.assertNotNull(outcome_group_creation, "Could not create group"); - //in order to populate helper sheets - StaffHelper staffHelper=new StaffHelper(); - Integer outcome_staff_creation =staffHelper.createStaff(requestSpec,responseSpec); + // in order to populate helper sheets + StaffHelper staffHelper = new StaffHelper(); + Integer outcome_staff_creation = staffHelper.createStaff(requestSpec, responseSpec); Assertions.assertNotNull(outcome_staff_creation, "Could not create staff"); - SavingsProductHelper savingsProductHelper=new SavingsProductHelper(); - String jsonSavingsProduct=savingsProductHelper.build(); - Integer outcome_sp_creaction=savingsProductHelper.createSavingsProduct(jsonSavingsProduct,requestSpec,responseSpec); + SavingsProductHelper savingsProductHelper = new SavingsProductHelper(); + String jsonSavingsProduct = savingsProductHelper.build(); + Integer outcome_sp_creaction = savingsProductHelper.createSavingsProduct(jsonSavingsProduct, requestSpec, responseSpec); Assertions.assertNotNull(outcome_sp_creaction, "Could not create Savings product"); - SavingsAccountHelper savingsAccountHelper=new SavingsAccountHelper(requestSpec,responseSpec); - Workbook workbook=savingsAccountHelper.getSavingsWorkbook("dd MMMM yyyy"); + SavingsAccountHelper savingsAccountHelper = new SavingsAccountHelper(requestSpec, responseSpec); + Workbook workbook = savingsAccountHelper.getSavingsWorkbook("dd MMMM yyyy"); - Sheet officeSheet=workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); - Row firstOfficeRow=officeSheet.getRow(1); + Sheet officeSheet = workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); + Row firstOfficeRow = officeSheet.getRow(1); Assertions.assertNotNull(firstOfficeRow.getCell(1), "No offices found "); - Sheet clientSheet=workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME); - Row firstClientRow=clientSheet.getRow(1); + Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME); + Row firstClientRow = clientSheet.getRow(1); Assertions.assertNotNull(firstClientRow.getCell(1), "No clients found "); - Sheet groupSheet=workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME); - Row firstGroupRow=groupSheet.getRow(1); + Sheet groupSheet = workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME); + Row firstGroupRow = groupSheet.getRow(1); Assertions.assertNotNull(firstGroupRow.getCell(1), "No groups found "); - Sheet staffSheet=workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME); - Row firstStaffRow=staffSheet.getRow(1); + Sheet staffSheet = workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME); + Row firstStaffRow = staffSheet.getRow(1); Assertions.assertNotNull(firstStaffRow.getCell(1), "No staff found "); - Sheet productSheet=workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); - Row firstProductRow=productSheet.getRow(1); + Sheet productSheet = workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); + Row firstProductRow = productSheet.getRow(1); Assertions.assertNotNull(firstProductRow.getCell(1), "No products found "); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/BatchHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/BatchHelper.java index 161465085..310157afb 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/BatchHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/BatchHelper.java @@ -32,15 +32,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Helper class for {@link org.apache.fineract.integrationtests.BatchApiTest}. It - * takes care of creation of {@code BatchRequest} list and posting this list to - * the server. + * Helper class for {@link org.apache.fineract.integrationtests.BatchApiTest}. + * It takes care of creation of {@code BatchRequest} list and posting this list + * to the server. * * @author Rishabh Shukla * * @see org.apache.fineract.integrationtests.BatchApiTest */ public class BatchHelper { + private final static Logger LOG = LoggerFactory.getLogger(BatchHelper.class); private static final String BATCH_API_URL = "/fineract-provider/api/v1/batches?" + Utils.TENANT_IDENTIFIER; private static final String BATCH_API_URL_EXT = BATCH_API_URL + "&enclosingTransaction=true"; @@ -190,14 +191,14 @@ public class BatchHelper { } final String body = "{ \"officeId\": 1, \"firstname\": \"Petra\", \"lastname\": \"Yton\"," + "\"externalId\": \"" + externalId - + "\", \"dateFormat\": \"dd MMMM yyyy\", \"locale\": \"en\"," + "\"active\": true, \"activationDate\": \"04 March 2010\", \"submittedOnDate\": \"04 March 2010\"}"; + + "\", \"dateFormat\": \"dd MMMM yyyy\", \"locale\": \"en\"," + + "\"active\": true, \"activationDate\": \"04 March 2010\", \"submittedOnDate\": \"04 March 2010\"}"; br.setBody(body); return br; } - /** * Creates and returns a * {@link org.apache.fineract.batch.command.internal.UpdateClientCommandStrategy} @@ -408,8 +409,8 @@ public class BatchHelper { br.setReference(reference); br.setRelativeUrl("loans/$.loanId/transactions?command=repayment"); br.setMethod("POST"); - br.setBody("{\"locale\": \"en\", \"dateFormat\": \"dd MMMM yyyy\", " + - "\"transactionDate\": \"15 September 2013\", \"transactionAmount\": 500}"); + br.setBody("{\"locale\": \"en\", \"dateFormat\": \"dd MMMM yyyy\", " + + "\"transactionDate\": \"15 September 2013\", \"transactionAmount\": 500}"); return br; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CalendarHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CalendarHelper.java index e55b1bdf4..5d7e83246 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CalendarHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CalendarHelper.java @@ -29,6 +29,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CalendarHelper { + private final static Logger LOG = LoggerFactory.getLogger(CalendarHelper.class); private static final String BASE_URL = "/fineract-provider/api/v1/"; private static final String PARENT_ENTITY_NAME = "groups/"; @@ -43,7 +44,7 @@ public class CalendarHelper { final String CALENDAR_RESOURCE_URL = BASE_URL + PARENT_ENTITY_NAME + groupId + ENITY_NAME + "?" + Utils.TENANT_IDENTIFIER; - LOG.info("{}",CALENDAR_RESOURCE_URL); + LOG.info("{}", CALENDAR_RESOURCE_URL); return Utils.performServerPost(requestSpec, responseSpec, CALENDAR_RESOURCE_URL, getTestCalendarAsJSON(frequency, interval, repeatsOnDay, startDate), "resourceId"); @@ -57,7 +58,7 @@ public class CalendarHelper { final String CALENDAR_RESOURCE_URL = BASE_URL + PARENT_ENTITY_NAME + groupId + ENITY_NAME + "/" + calendarID; - LOG.info("{}",CALENDAR_RESOURCE_URL); + LOG.info("{}", CALENDAR_RESOURCE_URL); // TODO: check that resource id indeed exists in calendar update put. return Utils.performServerPut(requestSpec, responseSpec, CALENDAR_RESOURCE_URL, getTestCalendarAsJSON(frequency, interval, repeatsOnDay, startDate), "resourceId"); @@ -76,7 +77,7 @@ public class CalendarHelper { map.put("title", Utils.randomNameGenerator("groups_CollectionMeeting", 4)); map.put("typeId", "1"); map.put("startDate", startDate); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } @@ -87,17 +88,17 @@ public class CalendarHelper { final String responseCalendarDetailsinJSON = Utils.performServerGet(requestSpec, responseSpec, CLIENT_URL, "collectionMeetingCalendar"); final Integer responseCalendarId = from(responseCalendarDetailsinJSON).get("id"); - assertEquals( generatedCalendarId, responseCalendarId, "ERROR IN CREATING THE CALENDAR"); + assertEquals(generatedCalendarId, responseCalendarId, "ERROR IN CREATING THE CALENDAR"); } public static Integer createMeetingForGroup(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final Integer groupId, final String startDate, final String frequency, final String interval, final String repeatsOnDay) { + final Integer groupId, final String startDate, final String frequency, final String interval, final String repeatsOnDay) { LOG.info("---------------------------------CREATING A MEETING CALENDAR FOR THE GROUP------------------------------"); final String CALENDAR_RESOURCE_URL = BASE_URL + CENTER_ENTITY + groupId + ENITY_NAME + "?" + Utils.TENANT_IDENTIFIER; - LOG.info("{}",CALENDAR_RESOURCE_URL); + LOG.info("{}", CALENDAR_RESOURCE_URL); return Utils.performServerPost(requestSpec, responseSpec, CALENDAR_RESOURCE_URL, getTestCalendarAsJSON(frequency, interval, repeatsOnDay, startDate), "resourceId"); @@ -111,7 +112,7 @@ public class CalendarHelper { final String CALENDAR_RESOURCE_URL = BASE_URL + CENTER_ENTITY + centerId + ENITY_NAME + "/" + calendarID + "?" + Utils.TENANT_IDENTIFIER; - LOG.info("{}",CALENDAR_RESOURCE_URL); + LOG.info("{}", CALENDAR_RESOURCE_URL); return Utils.performServerPut(requestSpec, responseSpec, CALENDAR_RESOURCE_URL, getTestCalendarMeetingAsJSON(oldDate, startDate), "resourceId"); @@ -128,4 +129,4 @@ public class CalendarHelper { LOG.info("map : {}", map); return new Gson().toJson(map); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CenterDomain.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CenterDomain.java index 46c00d04c..ce385c321 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CenterDomain.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CenterDomain.java @@ -26,7 +26,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CenterDomain implements Comparable { + private final static Logger LOG = LoggerFactory.getLogger(CenterDomain.class); + public static class Builder { private final Integer id; @@ -84,9 +86,9 @@ public class CenterDomain implements Comparable { /* super(); */ } - private CenterDomain(final Integer id, final String accountNo, final Integer statusid, final String statuscode, final String statusvalue, final boolean active, - final String name, final String externalId, final Integer staffId, final Integer officeId, final String officeName, - final String hierarchy, final ArrayList groupMembers) { + private CenterDomain(final Integer id, final String accountNo, final Integer statusid, final String statuscode, + final String statusvalue, final boolean active, final String name, final String externalId, final Integer staffId, + final Integer officeId, final String officeName, final String hierarchy, final ArrayList groupMembers) { this.id = id; this.accountNo = accountNo; this.status = new HashMap<>(); @@ -163,7 +165,7 @@ public class CenterDomain implements Comparable { if (groupMembers != null) { map.put("groupMembers", groupMembers); } - LOG.info("{}",map.toString()); + LOG.info("{}", map.toString()); return new Gson().toJson(map); } @@ -211,7 +213,7 @@ public class CenterDomain implements Comparable { return this.hierarchy; } - public String getAccountNo(){ + public String getAccountNo() { return this.accountNo; } @@ -256,15 +258,11 @@ public class CenterDomain implements Comparable { public boolean equals(Object obj) { if (obj == this) { return true; } - if (!(obj instanceof CenterDomain)) { - return false; - } + if (!(obj instanceof CenterDomain)) { return false; } CenterDomain cd = (CenterDomain) obj; - if (this.hashCode() == cd.hashCode()) { - return true; - } + if (this.hashCode() == cd.hashCode()) { return true; } return false; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CenterHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CenterHelper.java index 382d5f47d..8a8ea7526 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CenterHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CenterHelper.java @@ -32,6 +32,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "rawtypes", "unchecked" }) public class CenterHelper { + private final static Logger LOG = LoggerFactory.getLogger(CenterHelper.class); private static final String CENTERS_URL = "/fineract-provider/api/v1/centers"; @@ -40,7 +41,7 @@ public class CenterHelper { public static CenterDomain retrieveByID(int id, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { final String GET_CENTER_BY_ID_URL = CENTERS_URL + "/" + id + "?associations=groupMembers&" + Utils.TENANT_IDENTIFIER; - LOG.info("------------------------ RETRIEVING CENTER AT {}-------------------------",id); + LOG.info("------------------------ RETRIEVING CENTER AT {}-------------------------", id); Object get = Utils.performServerGet(requestSpec, responseSpec, GET_CENTER_BY_ID_URL, ""); final String jsonData = new Gson().toJson(get); return new Gson().fromJson(jsonData, new TypeToken() {}.getType()); @@ -110,7 +111,7 @@ public class CenterHelper { public static HashMap updateCenter(final int id, HashMap request, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { final String UPDATE_CENTER_URL = CENTERS_URL + "/" + id + "?" + Utils.TENANT_IDENTIFIER; - LOG.info("---------------------------------UPDATE CENTER AT {}---------------------------------------------",id); + LOG.info("---------------------------------UPDATE CENTER AT {}---------------------------------------------", id); HashMap hash = Utils.performServerPut(requestSpec, responseSpec, UPDATE_CENTER_URL, new Gson().toJson(request), "changes"); return hash; @@ -121,10 +122,10 @@ public class CenterHelper { final String ASSOCIATE_GROUP_CENTER_URL = CENTERS_URL + "/" + id + "?command=associateGroups&" + Utils.TENANT_IDENTIFIER; HashMap groupMemberHashMap = new HashMap(); groupMemberHashMap.put("groupMembers", groupMembers); - LOG.info("---------------------------------ASSOCIATING GROUPS AT {}--------------------------------------------",id); - HashMap hash = Utils.performServerPost(requestSpec, responseSpec, ASSOCIATE_GROUP_CENTER_URL, - new Gson().toJson(groupMemberHashMap), "changes"); - LOG.info("{}",hash.toString()); + LOG.info("---------------------------------ASSOCIATING GROUPS AT {}--------------------------------------------", id); + HashMap hash = Utils.performServerPost(requestSpec, responseSpec, ASSOCIATE_GROUP_CENTER_URL, new Gson().toJson(groupMemberHashMap), + "changes"); + LOG.info("{}", hash.toString()); ArrayList arr = (ArrayList) hash.get("groupMembers"); int[] ret = new int[arr.size()]; for (int i = 0; i < ret.length; i++) { @@ -135,7 +136,7 @@ public class CenterHelper { public static void deleteCenter(final int id, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { final String DELETE_CENTER_URL = CENTERS_URL + "/" + id + "?" + Utils.TENANT_IDENTIFIER; - LOG.info("---------------------------------DELETING CENTER AT {}--------------------------------------------",id); + LOG.info("---------------------------------DELETING CENTER AT {}--------------------------------------------", id); Utils.performServerDelete(requestSpec, responseSpec, DELETE_CENTER_URL, ""); } @@ -182,7 +183,8 @@ public class CenterHelper { public static Integer activateCenter(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String centerId) { - final String CENTER_ASSOCIATE_URL = "/fineract-provider/api/v1/centers/" + centerId + "?command=activate&" + Utils.TENANT_IDENTIFIER; + final String CENTER_ASSOCIATE_URL = "/fineract-provider/api/v1/centers/" + centerId + "?command=activate&" + + Utils.TENANT_IDENTIFIER; LOG.info("---------------------------------ACTIVATE A CENTER---------------------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, CENTER_ASSOCIATE_URL, activateCenterAsJSON(""), "groupId"); } @@ -201,7 +203,7 @@ public class CenterHelper { int[] groupMembers = null; String submittedDate = null; - return CenterDomain.jsonRequestToCreateCenter(id, statusid, statuscode, statusvalue, active, activationDate,submittedDate,name, + return CenterDomain.jsonRequestToCreateCenter(id, statusid, statuscode, statusvalue, active, activationDate, submittedDate, name, externalId, staffId, officeID, officeName, hierarchy, groupMembers); } @@ -220,7 +222,7 @@ public class CenterHelper { final int[] groupMembers = null; String submittedDate = null; - return CenterDomain.jsonRequestToCreateCenter(id, statusid, statuscode, statusvalue, active, activationDate,submittedDate,name, + return CenterDomain.jsonRequestToCreateCenter(id, statusid, statuscode, statusvalue, active, activationDate, submittedDate, name, externalId, staffId, officeID, officeName, hierarchy, groupMembers); } @@ -228,14 +230,14 @@ public class CenterHelper { public static String assignStaffAsJSON(final Long staffId) { final HashMap map = new HashMap<>(); map.put("staffId", staffId); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } public static String unassignStaffAsJSON(final Long staffId) { final HashMap map = new HashMap<>(); map.put("staffId", staffId); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } @@ -249,7 +251,7 @@ public class CenterHelper { map.put("activationDate", "CREATED_DATE"); LOG.info("defaulting to fixed date: CREATED_DATE"); } - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } @@ -257,8 +259,8 @@ public class CenterHelper { return Utils.randomStringGenerator(prefix, lenOfRandomSuffix); } - public static Object assignStaff(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final String groupId, final Long staffId) { + public static Object assignStaff(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId, + final Long staffId) { final String GROUP_ASSIGN_STAFF_URL = "/fineract-provider/api/v1/groups/" + groupId + "?" + Utils.TENANT_IDENTIFIER + "&command=assignStaff"; LOG.info("---------------------------------Assign Staff---------------------------------------------"); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ClientChargesTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ClientChargesTest.java index 407a2a2b0..0a0b4af6c 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ClientChargesTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ClientChargesTest.java @@ -96,8 +96,8 @@ public class ClientChargesTest { * Revert the paid client charge transaction by passing the * clientChargePaidTransactionId and ensure the same is reverted. */ - final Integer undoTrxnId = ClientHelper.revertClientChargeTransaction(this.requestSpec, this.responseSpec, - clientId.toString(), clientChargePaidTransactionId); + final Integer undoTrxnId = ClientHelper.revertClientChargeTransaction(this.requestSpec, this.responseSpec, clientId.toString(), + clientChargePaidTransactionId); Assertions.assertNotNull(undoTrxnId); isReversedTransaction(clientId.toString(), undoTrxnId.toString()); /** diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ClientHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ClientHelper.java old mode 100755 new mode 100644 index 5e61ae3ba..bd1b1994f --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ClientHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ClientHelper.java @@ -40,6 +40,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClientHelper { + private final static Logger LOG = LoggerFactory.getLogger(ClientHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; @@ -69,8 +70,7 @@ public class ClientHelper { this.responseSpec = responseSpec; } - public static Integer createClient(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public static Integer createClient(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { return createClient(requestSpec, responseSpec, "04 March 2011"); } @@ -82,79 +82,72 @@ public class ClientHelper { public static Integer createClient(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String activationDate, final String officeId) { LOG.info("---------------------------------CREATING A CLIENT---------------------------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, - getTestClientAsJSON(activationDate, officeId), "clientId"); + return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, getTestClientAsJSON(activationDate, officeId), + "clientId"); } - public static Integer createClientPending(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public static Integer createClientPending(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { return createClientPending(requestSpec, responseSpec, "04 March 2014"); } - public static Integer createClientPending(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String submittedOnDate) { + public static Integer createClientPending(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String submittedOnDate) { return createClientPending(requestSpec, responseSpec, submittedOnDate, "1"); } - public static Integer createClientPending(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String submittedOnDate, final String officeId) { - LOG.info( - "---------------------------------CREATING A CLIENT IN PENDING---------------------------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, - getTestClientAsJSONPending(submittedOnDate, officeId), "clientId"); + public static Integer createClientPending(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String submittedOnDate, final String officeId) { + LOG.info("---------------------------------CREATING A CLIENT IN PENDING---------------------------------------------"); + return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, getTestClientAsJSONPending(submittedOnDate, officeId), + "clientId"); } public Object createClientPendingWithError(final String jsonAttributeToGetBack) { - LOG.info( - "---------------------------------CREATING A CLIENT IN PENDING WITH ERROR---------------------------------------------"); + LOG.info("---------------------------------CREATING A CLIENT IN PENDING WITH ERROR---------------------------------------------"); return Utils.performServerPost(this.requestSpec, this.responseSpec, CREATE_CLIENT_URL, getTestClientAsJSONPending("04 March 2014", "1"), jsonAttributeToGetBack); } - public static Integer createClientPendingWithDatatable(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String registeredTableName) { - LOG.info( - "-------------------------- CREATING A CLIENT IN PENDING WITH DATATABLES --------------------------------"); + public static Integer createClientPendingWithDatatable(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String registeredTableName) { + LOG.info("-------------------------- CREATING A CLIENT IN PENDING WITH DATATABLES --------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, getTestPendingClientWithDatatableAsJson(registeredTableName), "clientId"); } - public static Integer createClientAsPerson(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public static Integer createClientAsPerson(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { return createClientAsPerson(requestSpec, responseSpec, "04 March 2011"); } - public static Integer createClientAsPerson(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String activationDate) { + public static Integer createClientAsPerson(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String activationDate) { return createClientAsPerson(requestSpec, responseSpec, activationDate, "1"); } - public static Integer createClientAsPerson(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String activationDate, final String officeId) { + public static Integer createClientAsPerson(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String activationDate, final String officeId) { LOG.info( "---------------------------------CREATING A CLIENT NON PERSON(ORGANISATION)---------------------------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, - getTestPersonClientAsJSON(activationDate, officeId), "clientId"); + return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, getTestPersonClientAsJSON(activationDate, officeId), + "clientId"); } - public static Integer createClientAsEntity(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public static Integer createClientAsEntity(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { return createClientAsEntity(requestSpec, responseSpec, "04 March 2011"); } - public static Integer createClientAsEntity(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String activationDate) { + public static Integer createClientAsEntity(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String activationDate) { return createClientAsEntity(requestSpec, responseSpec, activationDate, "1"); } - public static Integer createClientAsEntity(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String activationDate, final String officeId) { + public static Integer createClientAsEntity(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String activationDate, final String officeId) { - Integer constitutionCodeId = (Integer) CodeHelper.getCodeByName(requestSpec, responseSpec, "Constitution") + Integer constitutionCodeId = (Integer) CodeHelper.getCodeByName(requestSpec, responseSpec, "Constitution").get("id"); + Integer soleProprietorCodeValueId = (Integer) CodeHelper.retrieveOrCreateCodeValue(constitutionCodeId, requestSpec, responseSpec) .get("id"); - Integer soleProprietorCodeValueId = (Integer) CodeHelper - .retrieveOrCreateCodeValue(constitutionCodeId, requestSpec, responseSpec).get("id"); LOG.info( "---------------------------------CREATING A CLIENT NON PERSON(ORGANISATION)---------------------------------------------"); @@ -162,29 +155,27 @@ public class ClientHelper { getTestEntityClientAsJSON(activationDate, officeId, soleProprietorCodeValueId), "clientId"); } - public static Integer createClientForAccountPreference(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer clientType, String jsonAttributeToGetBack) { + public static Integer createClientForAccountPreference(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer clientType, String jsonAttributeToGetBack) { final String activationDate = "04 March 2011"; final String officeId = "1"; LOG.info( "---------------------------------CREATING A CLIENT BASED ON ACCOUNT PREFERENCE---------------------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, - getTestClientWithClientTypeAsJSON(activationDate, officeId, clientType.toString()), - jsonAttributeToGetBack); + getTestClientWithClientTypeAsJSON(activationDate, officeId, clientType.toString()), jsonAttributeToGetBack); } - public static Object assignStaffToClient(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String clientId, final String staffId) { - final String CLIENT_ASSIGN_STAFF_URL = "/fineract-provider/api/v1/clients/" + clientId + "?" - + Utils.TENANT_IDENTIFIER + "&command=assignStaff"; + public static Object assignStaffToClient(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String clientId, final String staffId) { + final String CLIENT_ASSIGN_STAFF_URL = "/fineract-provider/api/v1/clients/" + clientId + "?" + Utils.TENANT_IDENTIFIER + + "&command=assignStaff"; LOG.info("---------------------------------CREATING A CLIENT---------------------------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, CLIENT_ASSIGN_STAFF_URL, - assignStaffToClientAsJson(staffId), "changes"); + return Utils.performServerPost(requestSpec, responseSpec, CLIENT_ASSIGN_STAFF_URL, assignStaffToClientAsJson(staffId), "changes"); } - public static Integer getClientsStaffId(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String clientId) { + public static Integer getClientsStaffId(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String clientId) { return (Integer) getClient(requestSpec, responseSpec, clientId, "staffId"); } @@ -283,8 +274,7 @@ public class ClientHelper { return new Gson().toJson(map); } - public static String getTestClientWithClientTypeAsJSON(final String dateOfJoining, final String officeId, - final String clientType) { + public static String getTestClientWithClientTypeAsJSON(final String dateOfJoining, final String officeId, final String clientType) { final HashMap map = new HashMap<>(); map.put("officeId", officeId); map.put("firstname", Utils.randomNameGenerator("Client_FirstName_", 5)); @@ -306,17 +296,16 @@ public class ClientHelper { return new Gson().toJson(map); } - public static void verifyClientCreatedOnServer(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer generatedClientID) { + public static void verifyClientCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer generatedClientID) { LOG.info("------------------------------CHECK CLIENT DETAILS------------------------------------\n"); - final String CLIENT_URL = "/fineract-provider/api/v1/clients/" + generatedClientID + "?" - + Utils.TENANT_IDENTIFIER; + final String CLIENT_URL = "/fineract-provider/api/v1/clients/" + generatedClientID + "?" + Utils.TENANT_IDENTIFIER; final Integer responseClientID = Utils.performServerGet(requestSpec, responseSpec, CLIENT_URL, "id"); assertEquals(generatedClientID, responseClientID, "ERROR IN CREATING THE CLIENT"); } - public static Object getClient(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final String clientId, final String jsonReturn) { + public static Object getClient(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String clientId, + final String jsonReturn) { final String GET_CLIENT_URL = "/fineract-provider/api/v1/clients/" + clientId + "?" + Utils.TENANT_IDENTIFIER; LOG.info("---------------------------------GET A CLIENT---------------------------------------------"); return Utils.performServerGet(requestSpec, responseSpec, GET_CLIENT_URL, jsonReturn); @@ -325,8 +314,8 @@ public class ClientHelper { /* Client status is a map.So adding SuppressWarnings */ @SuppressWarnings("unchecked") - public static HashMap getClientStatus(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String clientId) { + public static HashMap getClientStatus(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String clientId) { return (HashMap) getClient(requestSpec, responseSpec, clientId, "status"); } @@ -343,8 +332,7 @@ public class ClientHelper { Integer clientClosureCodeId = (Integer) code.get("id"); /* Retrieve/Create Code Values for the Code "ClientClosureReason" */ - HashMap codeValue = CodeHelper.retrieveOrCreateCodeValue(clientClosureCodeId, this.requestSpec, - this.responseSpec); + HashMap codeValue = CodeHelper.retrieveOrCreateCodeValue(clientClosureCodeId, this.requestSpec, this.responseSpec); Integer closureReasonId = (Integer) codeValue.get("id"); map.put("closureReasonId", closureReasonId.toString()); @@ -399,8 +387,8 @@ public class ClientHelper { Integer clientRejectionReasonCodeId = (Integer) code.get("id"); /* Retrieve/Create Code Values for the Code "ClientRejectReason" */ - HashMap codeValue = CodeHelper.retrieveOrCreateCodeValue(clientRejectionReasonCodeId, - this.requestSpec, this.responseSpec); + HashMap codeValue = CodeHelper.retrieveOrCreateCodeValue(clientRejectionReasonCodeId, this.requestSpec, + this.responseSpec); Integer rejectionReasonId = (Integer) codeValue.get("id"); map.put("locale", CommonConstants.LOCALE); @@ -431,8 +419,8 @@ public class ClientHelper { Integer clientWithdrawReasonCodeId = (Integer) code.get("id"); /* Retrieve/Create Code Values for the Code "ClientWithdrawReason" */ - HashMap codeValue = CodeHelper.retrieveOrCreateCodeValue(clientWithdrawReasonCodeId, - this.requestSpec, this.responseSpec); + HashMap codeValue = CodeHelper.retrieveOrCreateCodeValue(clientWithdrawReasonCodeId, this.requestSpec, + this.responseSpec); Integer withdrawalReasonId = (Integer) codeValue.get("id"); map.put("locale", CommonConstants.LOCALE); @@ -479,20 +467,17 @@ public class ClientHelper { public HashMap closeClient(final Integer clientId) { LOG.info("--------------------------------- CLOSE CLIENT -------------------------------"); - return performClientActions(createClientOperationURL(CLOSE_CLIENT_COMMAND, clientId), getCloseClientAsJSON(), - clientId); + return performClientActions(createClientOperationURL(CLOSE_CLIENT_COMMAND, clientId), getCloseClientAsJSON(), clientId); } public HashMap reactivateClient(final Integer clientId) { LOG.info("--------------------------------- REACTIVATE CLIENT -------------------------------"); - return performClientActions(createClientOperationURL(REACTIVATE_CLIENT_COMMAND, clientId), - getReactivateClientAsJSON(), clientId); + return performClientActions(createClientOperationURL(REACTIVATE_CLIENT_COMMAND, clientId), getReactivateClientAsJSON(), clientId); } public HashMap rejectClient(final Integer clientId) { LOG.info("--------------------------------- REJECT CLIENT -------------------------------"); - return performClientActions(createClientOperationURL(REJECT_CLIENT_COMMAND, clientId), getRejectClientAsJSON(), - clientId); + return performClientActions(createClientOperationURL(REJECT_CLIENT_COMMAND, clientId), getRejectClientAsJSON(), clientId); } public HashMap activateClient(final Integer clientId) { @@ -503,8 +488,7 @@ public class ClientHelper { public HashMap withdrawClient(final Integer clientId) { LOG.info("--------------------------------- WITHDRAWN CLIENT -------------------------------"); - return performClientActions(createClientOperationURL(WITHDRAW_CLIENT_COMMAND, clientId), - getWithdrawClientAsJSON(), clientId); + return performClientActions(createClientOperationURL(WITHDRAW_CLIENT_COMMAND, clientId), getWithdrawClientAsJSON(), clientId); } private String createClientOperationURL(final String command, final Integer clientId) { @@ -523,113 +507,102 @@ public class ClientHelper { getUndoWithdrawnClientAsJSON(CREATED_DATE_PLUS_TWO), clientId); } - public ArrayList> undoRejectedclient(final Integer clientId, - final String jsonAttributeToGetBack, final String rejectedDate) { + public ArrayList> undoRejectedclient(final Integer clientId, final String jsonAttributeToGetBack, + final String rejectedDate) { LOG.info("----------------------------------UNDO REJECT CLIENT ----------------------------------"); return performClientActionsWithValidationErrors(createClientOperationURL(UNDOREJECT_CLIENT_COMMAND, clientId), getUndoRejectClientAsJSON(rejectedDate), jsonAttributeToGetBack); } - public ArrayList> undoWithdrawclient(final Integer clientId, - final String jsonAttributeToGetBack, final String rejectedDate) { + public ArrayList> undoWithdrawclient(final Integer clientId, final String jsonAttributeToGetBack, + final String rejectedDate) { LOG.info("----------------------------------UNDO WITHDRAW CLIENT ----------------------------------"); - return performClientActionsWithValidationErrors( - createClientOperationURL(UNDOWITHDRAWN_CLIENT_COMMAND, clientId), + return performClientActionsWithValidationErrors(createClientOperationURL(UNDOWITHDRAWN_CLIENT_COMMAND, clientId), getUndoWithdrawnClientAsJSON(rejectedDate), jsonAttributeToGetBack); } - public ArrayList> activateClient(final Integer clientId, - final String jsonAttributeToGetBack) { + public ArrayList> activateClient(final Integer clientId, final String jsonAttributeToGetBack) { LOG.info("--------------------------------- ACTIVATE CLIENT -------------------------------"); return performClientActionsWithValidationErrors(createClientOperationURL(ACTIVATE_CLIENT_COMMAND, clientId), getActivateClientAsJSON(CREATED_DATE_PLUS_ONE), jsonAttributeToGetBack); } - public HashMap activateClientWithDiffDateOption(final Integer clientId, - final String activationDate) { + public HashMap activateClientWithDiffDateOption(final Integer clientId, final String activationDate) { LOG.info("--------------------------------- ACTIVATE CLIENT -------------------------------"); - return performClientActions(createClientOperationURL(ACTIVATE_CLIENT_COMMAND, clientId), - getActivateClientAsJSON(activationDate), clientId); + return performClientActions(createClientOperationURL(ACTIVATE_CLIENT_COMMAND, clientId), getActivateClientAsJSON(activationDate), + clientId); } private ArrayList> performClientActionsWithValidationErrors(final String postURLForClient, final String jsonToBeSent, final String jsonAttributeToGetBack) { - return Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForClient, jsonToBeSent, - jsonAttributeToGetBack); + return Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForClient, jsonToBeSent, jsonAttributeToGetBack); } - private HashMap performClientActions(final String postURLForClient, final String jsonToBeSent, - final Integer clientId) { - Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForClient, jsonToBeSent, - CommonConstants.RESPONSE_STATUS); - HashMap response = ClientHelper.getClientStatus(requestSpec, responseSpec, - String.valueOf(clientId)); + private HashMap performClientActions(final String postURLForClient, final String jsonToBeSent, final Integer clientId) { + Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForClient, jsonToBeSent, CommonConstants.RESPONSE_STATUS); + HashMap response = ClientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId)); return response; } - public static Integer addChargesForClient(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer clientId, final String request) { + public static Integer addChargesForClient(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer clientId, final String request) { LOG.info("--------------------------------- ADD CHARGES FOR Client --------------------------------"); - final String ADD_CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/charges?" - + Utils.TENANT_IDENTIFIER; + final String ADD_CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/charges?" + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerPost(requestSpec, responseSpec, ADD_CHARGES_URL, request, ""); return (Integer) response.get("resourceId"); } - public static String payChargesForClients(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer clientId, final Integer clientChargeId, - final String json) { + public static String payChargesForClients(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer clientId, final Integer clientChargeId, final String json) { LOG.info("--------------------------------- PAY CHARGES FOR CLIENT --------------------------------"); - final String CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/charges/" + clientChargeId - + "?command=paycharge&" + Utils.TENANT_IDENTIFIER; + final String CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/charges/" + clientChargeId + "?command=paycharge&" + + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, json, ""); return response.get("transactionId") != null ? response.get("transactionId").toString() : null; } - public static String waiveChargesForClients(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer clientId, final Integer clientChargeId, - final String json) { + public static String waiveChargesForClients(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer clientId, final Integer clientChargeId, final String json) { LOG.info("--------------------------------- WAIVE CHARGES FOR CLIENT --------------------------------"); - final String CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/charges/" + clientChargeId - + "?command=waive&" + Utils.TENANT_IDENTIFIER; + final String CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/charges/" + clientChargeId + "?command=waive&" + + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, json, ""); return response.get("transactionId").toString(); } - public static Integer revertClientChargeTransaction(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String clientId, String clientChargeId) { + public static Integer revertClientChargeTransaction(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String clientId, String clientChargeId) { LOG.info("---------------------------------UNDO TRANSACTION---------------------------------------------"); - final String CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/transactions/" + clientChargeId - + "?command=undo&" + Utils.TENANT_IDENTIFIER; + final String CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/transactions/" + clientChargeId + "?command=undo&" + + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, "", ""); return (Integer) response.get("resourceId"); } - public static Object getClientCharge(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String clientId, final String clientChargeId) { + public static Object getClientCharge(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String clientId, final String clientChargeId) { LOG.info("---------------------------------GET CLIENT CHARGE---------------------------------------------"); final String CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/charges/" + clientChargeId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, CHARGES_URL, "amountOutstanding"); } - public static Boolean getClientTransactions(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String clientId, final String transactionId) { - LOG.info( - "---------------------------------GET CLIENT CHARGE TRANSACTIONS---------------------------------------------"); - final String CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/transactions/" + transactionId - + "?" + Utils.TENANT_IDENTIFIER; + public static Boolean getClientTransactions(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String clientId, final String transactionId) { + LOG.info("---------------------------------GET CLIENT CHARGE TRANSACTIONS---------------------------------------------"); + final String CHARGES_URL = "/fineract-provider/api/v1/clients/" + clientId + "/transactions/" + transactionId + "?" + + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, CHARGES_URL, "reversed"); } public Workbook getClientEntityWorkbook(GlobalEntityType clientsEntity, String dateFormat) throws IOException { requestSpec.header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel"); - byte[] byteArray = Utils.performGetBinaryResponse(requestSpec, responseSpec, CLIENT_URL + "/downloadtemplate" - + "?" + Utils.TENANT_IDENTIFIER + "&legalFormType=" + clientsEntity + "&dateFormat=" + dateFormat); + byte[] byteArray = Utils.performGetBinaryResponse(requestSpec, responseSpec, CLIENT_URL + "/downloadtemplate" + "?" + + Utils.TENANT_IDENTIFIER + "&legalFormType=" + clientsEntity + "&dateFormat=" + dateFormat); InputStream inputStream = new ByteArrayInputStream(byteArray); Workbook workbook = new HSSFWorkbook(inputStream); return workbook; @@ -638,8 +611,7 @@ public class ClientHelper { public String getOutputTemplateLocation(final String importDocumentId) { requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN); return Utils.performServerOutputTemplateLocationGet(requestSpec, responseSpec, - "/fineract-provider/api/v1/imports/getOutputTemplateLocation" + "?" + Utils.TENANT_IDENTIFIER, - importDocumentId); + "/fineract-provider/api/v1/imports/getOutputTemplateLocation" + "?" + Utils.TENANT_IDENTIFIER, importDocumentId); } public String importClientEntityTemplate(File file) { @@ -647,8 +619,7 @@ public class ClientHelper { String dateFormat = "dd MMMM yyyy"; String legalFormType = GlobalEntityType.CLIENTS_ENTTTY.toString(); requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA); - return Utils.performServerTemplatePost(requestSpec, responseSpec, - CLIENT_URL + "/uploadtemplate" + "?" + Utils.TENANT_IDENTIFIER, legalFormType, file, locale, - dateFormat); + return Utils.performServerTemplatePost(requestSpec, responseSpec, CLIENT_URL + "/uploadtemplate" + "?" + Utils.TENANT_IDENTIFIER, + legalFormType, file, locale, dateFormat); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CommonConstants.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CommonConstants.java old mode 100755 new mode 100644 index 94d456c03..2857caf29 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CommonConstants.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CommonConstants.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.integrationtests.common; - public interface CommonConstants { public final static String LOCALE = "en"; diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CurrenciesHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CurrenciesHelper.java index 80e483d34..2b7bd57ab 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CurrenciesHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CurrenciesHelper.java @@ -29,6 +29,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "unused", "rawtypes", "unchecked" }) public class CurrenciesHelper { + private final static Logger LOG = LoggerFactory.getLogger(CurrenciesHelper.class); private static final String CURRENCIES_URL = "/fineract-provider/api/v1/currencies"; @@ -57,9 +58,7 @@ public class CurrenciesHelper { final String code) { ArrayList currenciesList = getAllCurrencies(requestSpec, responseSpec); for (CurrencyDomain e : currenciesList) { - if (e.getCode().equals(code)) { - return e; - } + if (e.getCode().equals(code)) { return e; } } return null; } @@ -75,7 +74,7 @@ public class CurrenciesHelper { private static String currenciesToJSON(final ArrayList currencies) { HashMap map = new HashMap<>(); map.put("currencies", currencies); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CurrencyDomain.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CurrencyDomain.java index 41b7a2e10..5c1527fc1 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CurrencyDomain.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/CurrencyDomain.java @@ -57,8 +57,8 @@ public class CurrencyDomain implements Comparable { super(); } - private CurrencyDomain(final String code, final String name, final int decimalPlaces, final String displaySymbol, - final String nameCode, final String displayLabel) { + private CurrencyDomain(final String code, final String name, final int decimalPlaces, final String displaySymbol, final String nameCode, + final String displayLabel) { super(); this.code = code; this.name = name; @@ -135,9 +135,7 @@ public class CurrencyDomain implements Comparable { public boolean equals(Object obj) { if (obj == this) { return true; } - if (!(obj instanceof CurrencyDomain)) { - return false; - } + if (!(obj instanceof CurrencyDomain)) { return false; } CurrencyDomain cd = (CurrencyDomain) obj; diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ExternalServicesConfigurationHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ExternalServicesConfigurationHelper.java index 946033407..bb6a840b3 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ExternalServicesConfigurationHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ExternalServicesConfigurationHelper.java @@ -29,27 +29,27 @@ public class ExternalServicesConfigurationHelper { private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; - public ExternalServicesConfigurationHelper(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public ExternalServicesConfigurationHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { this.requestSpec = requestSpec; this.responseSpec = responseSpec; } - public static ArrayList getExternalServicesConfigurationByServiceName( - final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final String serviceName) { - final String GET_EXTERNAL_SERVICES_CONFIG_BY_SERVICE_NAME_URL = "/fineract-provider/api/v1/externalservice/" - + serviceName + "?" + Utils.TENANT_IDENTIFIER; - // system.out.println("------------------------ RETRIEVING GLOBAL CONFIGURATION + public static ArrayList getExternalServicesConfigurationByServiceName(final RequestSpecification requestSpec, + final ResponseSpecification responseSpec, final String serviceName) { + final String GET_EXTERNAL_SERVICES_CONFIG_BY_SERVICE_NAME_URL = "/fineract-provider/api/v1/externalservice/" + serviceName + "?" + + Utils.TENANT_IDENTIFIER; + // system.out.println("------------------------ RETRIEVING GLOBAL + // CONFIGURATION // BY ID -------------------------"); return Utils.performServerGet(requestSpec, responseSpec, GET_EXTERNAL_SERVICES_CONFIG_BY_SERVICE_NAME_URL, ""); } public static HashMap updateValueForExternaServicesConfiguration(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String serviceName, final String name, final String value) { - final String EXTERNAL_SERVICES_CONFIG_UPDATE_URL = "/fineract-provider/api/v1/externalservice/" + serviceName - + "?" + Utils.TENANT_IDENTIFIER; - // system.out.println("---------------------------------UPDATE VALUE FOR GLOBAL + final String EXTERNAL_SERVICES_CONFIG_UPDATE_URL = "/fineract-provider/api/v1/externalservice/" + serviceName + "?" + + Utils.TENANT_IDENTIFIER; + // system.out.println("---------------------------------UPDATE VALUE FOR + // GLOBAL // CONFIG---------------------------------------------"); HashMap map = Utils.performServerPut(requestSpec, responseSpec, EXTERNAL_SERVICES_CONFIG_UPDATE_URL, updateExternalServicesConfigUpdateValueAsJSON(name, value), ""); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/GlobalConfigurationHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/GlobalConfigurationHelper.java index a1b3b2f85..d8d185585 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/GlobalConfigurationHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/GlobalConfigurationHelper.java @@ -29,6 +29,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "unused", "rawtypes" }) public class GlobalConfigurationHelper { + private final static Logger LOG = LoggerFactory.getLogger(GlobalConfigurationHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; @@ -38,11 +39,13 @@ public class GlobalConfigurationHelper { this.responseSpec = responseSpec; } - public static ArrayList getAllGlobalConfigurations(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + public static ArrayList getAllGlobalConfigurations(final RequestSpecification requestSpec, + final ResponseSpecification responseSpec) { final String GET_ALL_GLOBAL_CONFIG_URL = "/fineract-provider/api/v1/configurations?" + Utils.TENANT_IDENTIFIER; LOG.info("------------------------ RETRIEVING ALL GLOBAL CONFIGURATIONS -------------------------"); - final HashMap> response = Utils.performServerGet(requestSpec, responseSpec, GET_ALL_GLOBAL_CONFIG_URL, ""); - return response.get("globalConfiguration"); + final HashMap> response = Utils.performServerGet(requestSpec, responseSpec, GET_ALL_GLOBAL_CONFIG_URL, + ""); + return response.get("globalConfiguration"); } public static HashMap getGlobalConfigurationById(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, @@ -52,30 +55,35 @@ public class GlobalConfigurationHelper { return Utils.performServerGet(requestSpec, responseSpec, GET_GLOBAL_CONFIG_BY_ID_URL, ""); } - public static void resetAllDefaultGlobalConfigurations(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + public static void resetAllDefaultGlobalConfigurations(final RequestSpecification requestSpec, + final ResponseSpecification responseSpec) { final ArrayList defaults = getAllDefaultGlobalConfigurations(); for (HashMap configDefault : defaults) { /** * Cannot update trapDoor global configurations because - * {@link org.apache.fineract.infrastructure.configuration.exception.GlobalConfigurationPropertyCannotBeModfied} + * {@link org.apache.fineract.infrastructure.configuration.exception.GlobalConfigurationPropertyCannotBeModfied} * will be thrown. */ - if ((Boolean)configDefault.get("trapDoor")) { + if ((Boolean) configDefault.get("trapDoor")) { continue; } - // Currently only values and enabled flags are modified by the integration test suite. - // If any other column is modified by the integration test suite in the future, it needs to be reset here. - final Integer configDefaultId = (Integer)configDefault.get("id"); - final Integer configDefaultValue = (Integer)configDefault.get("value"); + // Currently only values and enabled flags are modified by the + // integration test suite. + // If any other column is modified by the integration test suite in + // the future, it needs to be reset here. + final Integer configDefaultId = (Integer) configDefault.get("id"); + final Integer configDefaultValue = (Integer) configDefault.get("value"); updateValueForGlobalConfiguration(requestSpec, responseSpec, configDefaultId.toString(), configDefaultValue.toString()); - updateEnabledFlagForGlobalConfiguration(requestSpec, responseSpec, configDefaultId.toString(), (Boolean)configDefault.get("enabled")); + updateEnabledFlagForGlobalConfiguration(requestSpec, responseSpec, configDefaultId.toString(), + (Boolean) configDefault.get("enabled")); } } - public static void verifyAllDefaultGlobalConfigurations(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + public static void verifyAllDefaultGlobalConfigurations(final RequestSpecification requestSpec, + final ResponseSpecification responseSpec) { ArrayList expectedGlobalConfigurations = getAllDefaultGlobalConfigurations(); ArrayList actualGlobalConfigurations = getAllGlobalConfigurations(requestSpec, responseSpec); @@ -92,19 +100,26 @@ public class GlobalConfigurationHelper { Assertions.assertEquals(expectedGlobalConfiguration.get("id"), actualGlobalConfiguration.get("id")); final String assertionFailedMessage = "Assertion failed for configID:<" + expectedGlobalConfiguration.get("id") + ">"; Assertions.assertEquals(expectedGlobalConfiguration.get("name"), actualGlobalConfiguration.get("name"), assertionFailedMessage); - Assertions.assertEquals(expectedGlobalConfiguration.get("value"), actualGlobalConfiguration.get("value"), assertionFailedMessage); - Assertions.assertEquals(expectedGlobalConfiguration.get("enabled"), actualGlobalConfiguration.get("enabled"), assertionFailedMessage); - Assertions.assertEquals(expectedGlobalConfiguration.get("trapDoor"), actualGlobalConfiguration.get("trapDoor"), assertionFailedMessage); + Assertions.assertEquals(expectedGlobalConfiguration.get("value"), actualGlobalConfiguration.get("value"), + assertionFailedMessage); + Assertions.assertEquals(expectedGlobalConfiguration.get("enabled"), actualGlobalConfiguration.get("enabled"), + assertionFailedMessage); + Assertions.assertEquals(expectedGlobalConfiguration.get("trapDoor"), actualGlobalConfiguration.get("trapDoor"), + assertionFailedMessage); } } /** - * Helper method to get the current default instance data of the /configurations endpoint. - * Used to reset and verify that no global configuration affects state between integration tests. - * @see FINERACT-722 - * This is a quick, fail fast and early implementation to resolve this issue. - * TODO: A more robust future solution would be isolating all integration test state using Spring Framework's - * integration test infrastructure for transaction commits and rollbacks. + * Helper method to get the current default instance data of the + * /configurations endpoint. Used to reset and verify that no global + * configuration affects state between integration tests. + * + * @see FINERACT-722 + * This is a quick, fail fast and early implementation to resolve this + * issue. TODO: A more robust future solution would be isolating all + * integration test state using Spring Framework's integration test + * infrastructure for transaction commits and rollbacks. */ private static ArrayList getAllDefaultGlobalConfigurations() { @@ -370,41 +385,42 @@ public class GlobalConfigurationHelper { } public static Object updatePasswordResetDaysForGlobalConfiguration(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer configId, final String value, final String enabled, final String jsonAttributeToGetBack) { + final ResponseSpecification responseSpec, final Integer configId, final String value, final String enabled, + final String jsonAttributeToGetBack) { final String UPDATE_URL = "/fineract-provider/api/v1/configurations/" + configId + "?" + Utils.TENANT_IDENTIFIER; LOG.info("------------------UPDATE GLOBAL CONFIG FOR FORCE PASSWORD RESET DAYS----------------------"); - return Utils.performServerPut(requestSpec, responseSpec, UPDATE_URL, - updatePasswordResetDaysGlobalConfigAsJSON(value, enabled), jsonAttributeToGetBack); + return Utils.performServerPut(requestSpec, responseSpec, UPDATE_URL, updatePasswordResetDaysGlobalConfigAsJSON(value, enabled), + jsonAttributeToGetBack); } public static String updateGlobalConfigUpdateValueAsJSON(final String value) { final HashMap map = new HashMap<>(); map.put("value", value); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } public static String updatePasswordResetDaysGlobalConfigAsJSON(final String value, final String enabled) { final HashMap map = new HashMap<>(); - if(value != null){ + if (value != null) { map.put("value", value); } map.put("enabled", enabled); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } public static String updateGlobalConfigUpdateEnabledFlagAsJSON(final Boolean enabled) { final HashMap map = new HashMap(); map.put("enabled", enabled); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } public static String updateIsCacheEnabledGlobalConfigUpdateAsJSON(final String cacheType) { final HashMap map = new HashMap<>(); map.put("cacheType", cacheType); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/GroupHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/GroupHelper.java old mode 100755 new mode 100644 index cd97f166d..9ab1d73c8 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/GroupHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/GroupHelper.java @@ -70,25 +70,25 @@ public class GroupHelper { jsonAttributeToGetBack); } - public static Integer createGroupPendingWithDatatable(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String registeredTableName) { + public static Integer createGroupPendingWithDatatable(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String registeredTableName) { LOG.info("-------------------------- CREATING A GROUP WITH DATATABLES --------------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, CREATE_GROUP_URL, - getTestGroupWithDatatableAsJson(registeredTableName), "groupId"); + return Utils.performServerPost(requestSpec, responseSpec, CREATE_GROUP_URL, getTestGroupWithDatatableAsJson(registeredTableName), + "groupId"); } public static Integer associateClient(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId, final String clientMember) { - final String GROUP_ASSOCIATE_URL = "/fineract-provider/api/v1/groups/" + groupId - + "?command=associateClients&" + Utils.TENANT_IDENTIFIER; + final String GROUP_ASSOCIATE_URL = "/fineract-provider/api/v1/groups/" + groupId + "?command=associateClients&" + + Utils.TENANT_IDENTIFIER; LOG.info("---------------------------------Associate Client To A GROUP---------------------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, GROUP_ASSOCIATE_URL, associateClientAsJSON(clientMember), "groupId"); } public static Integer disAssociateClient(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId, final String clientMember) { - final String GROUP_ASSOCIATE_URL = "/fineract-provider/api/v1/groups/" + groupId - + "?command=disassociateClients&" + Utils.TENANT_IDENTIFIER; + final String GROUP_ASSOCIATE_URL = "/fineract-provider/api/v1/groups/" + groupId + "?command=disassociateClients&" + + Utils.TENANT_IDENTIFIER; LOG.info("---------------------------------Disassociate Client To A GROUP---------------------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, GROUP_ASSOCIATE_URL, associateClientAsJSON(clientMember), "groupId"); } @@ -107,23 +107,29 @@ public class GroupHelper { return Utils.performServerPut(requestSpec, responseSpec, GROUP_ASSOCIATE_URL, updateGroupAsJSON(name), "groupId"); } - public static Integer deleteGroup(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId) { + public static Integer deleteGroup(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String groupId) { final String GROUP_ASSOCIATE_URL = "/fineract-provider/api/v1/groups/" + groupId + "?" + Utils.TENANT_IDENTIFIER; LOG.info("---------------------------------DELETE GROUP---------------------------------------------"); return Utils.performServerDelete(requestSpec, responseSpec, GROUP_ASSOCIATE_URL, "groupId"); } - public static Object assignStaff(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId,final Long staffId){ - final String GROUP_ASSIGN_STAFF_URL = "/fineract-provider/api/v1/groups/" + groupId + "?" + Utils.TENANT_IDENTIFIER + "&command=assignStaff"; + public static Object assignStaff(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId, + final Long staffId) { + final String GROUP_ASSIGN_STAFF_URL = "/fineract-provider/api/v1/groups/" + groupId + "?" + Utils.TENANT_IDENTIFIER + + "&command=assignStaff"; LOG.info("---------------------------------DELETE GROUP---------------------------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, GROUP_ASSIGN_STAFF_URL,assignStaffAsJSON(staffId),"changes"); - } - public static Object assignStaffInheritStaffForClientAccounts(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId,final String staffId){ - final String GROUP_ASSIGN_STAFF_URL = "/fineract-provider/api/v1/groups/" + groupId + "?" + Utils.TENANT_IDENTIFIER + "&command=assignStaff"; - LOG.info("---------------------------------DELETE GROUP---------------------------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, GROUP_ASSIGN_STAFF_URL,assignStaffAndInheritStaffForClientAccountsAsJSON(staffId),"changes"); + return Utils.performServerPost(requestSpec, responseSpec, GROUP_ASSIGN_STAFF_URL, assignStaffAsJSON(staffId), "changes"); } + public static Object assignStaffInheritStaffForClientAccounts(final RequestSpecification requestSpec, + final ResponseSpecification responseSpec, final String groupId, final String staffId) { + final String GROUP_ASSIGN_STAFF_URL = "/fineract-provider/api/v1/groups/" + groupId + "?" + Utils.TENANT_IDENTIFIER + + "&command=assignStaff"; + LOG.info("---------------------------------DELETE GROUP---------------------------------------------"); + return Utils.performServerPost(requestSpec, responseSpec, GROUP_ASSIGN_STAFF_URL, + assignStaffAndInheritStaffForClientAccountsAsJSON(staffId), "changes"); + } public static String getTestGroupAsJSON(final boolean active, final String activationDate) { final HashMap map = new HashMap<>(); @@ -173,21 +179,22 @@ public class GroupHelper { LOG.debug("map : {}", map); return new Gson().toJson(map); } + public static String assignStaffAsJSON(final Long staffId) { final HashMap map = new HashMap<>(); map.put("staffId", staffId); LOG.debug("map : {}", map); return new Gson().toJson(map); } + public static String assignStaffAndInheritStaffForClientAccountsAsJSON(final String staffId) { final HashMap map = new HashMap<>(); map.put("staffId", staffId); - map.put("inheritStaffForClientAccounts","true"); + map.put("inheritStaffForClientAccounts", "true"); LOG.debug("map : {}", map); return new Gson().toJson(map); } - public static void verifyGroupCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer generatedGroupID) { LOG.info("------------------------------CHECK GROUP DETAILS------------------------------------\n"); @@ -216,8 +223,8 @@ public class GroupHelper { final Integer generatedGroupID, final Integer groupMember) { List list = new ArrayList<>(); LOG.info("------------------------------CHECK GROUP MEMBERS------------------------------------\n"); - final String GROUP_URL = "/fineract-provider/api/v1/groups/" + generatedGroupID - + "?associations=clientMembers&" + Utils.TENANT_IDENTIFIER; + final String GROUP_URL = "/fineract-provider/api/v1/groups/" + generatedGroupID + "?associations=clientMembers&" + + Utils.TENANT_IDENTIFIER; list = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "clientMembers"); LOG.debug("the list of verifyEmptyGroupMembers : {} ", list); assertTrue(list.toString().contains("id=" + groupMember.toString()), "ERROR IN GROUP MEMBER"); @@ -227,8 +234,8 @@ public class GroupHelper { final Integer generatedGroupID) { List list = new ArrayList<>(); LOG.info("------------------------------CHECK EMPTY GROUP MEMBER LIST------------------------------------\n"); - final String GROUP_URL = "/fineract-provider/api/v1/groups/" + generatedGroupID - + "?associations=clientMembers&" + Utils.TENANT_IDENTIFIER; + final String GROUP_URL = "/fineract-provider/api/v1/groups/" + generatedGroupID + "?associations=clientMembers&" + + Utils.TENANT_IDENTIFIER; list = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "clientMembers"); LOG.debug("the list of verifyEmptyGroupMembers : {} ", list); assertEquals(list, null, "GROUP MEMBER LIST NOT EMPTY"); @@ -243,22 +250,22 @@ public class GroupHelper { assertFalse(list.toString().contains("id=" + generatedGroupID.toString()), "GROUP NOT DELETED"); } - //Glim_Gsim_testing - public static List verifyRetrieveGlimAccountsByGroupId(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final Integer groupID) { + // Glim_Gsim_testing + public static List verifyRetrieveGlimAccountsByGroupId(final RequestSpecification requestSpec, + final ResponseSpecification responseSpec, final Integer groupID) { List list = new ArrayList<>(); LOG.info("------------------------------CHECK GROUP Retrieve Accounts------------------------------------\n"); - final String GROUP_URL = "/fineract-provider/api/v1/groups/"+groupID+"/glimaccounts?" + Utils.TENANT_IDENTIFIER; + final String GROUP_URL = "/fineract-provider/api/v1/groups/" + groupID + "/glimaccounts?" + Utils.TENANT_IDENTIFIER; list = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "glimId"); LOG.debug("GlimId of Retrieved Account : {} ", list); return list; } - public static List verifyRetrieveGlimAccountsByGlimId(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final Integer glimId) { + public static List verifyRetrieveGlimAccountsByGlimId(final RequestSpecification requestSpec, + final ResponseSpecification responseSpec, final Integer glimId) { List list = new ArrayList<>(); LOG.info("------------------------------CHECK GROUP Retrieve Accounts------------------------------------\n"); - final String GROUP_URL = "/fineract-provider/api/v1/loans/glimAccount/"+glimId+"?"+ Utils.TENANT_IDENTIFIER; + final String GROUP_URL = "/fineract-provider/api/v1/loans/glimAccount/" + glimId + "?" + Utils.TENANT_IDENTIFIER; list = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "glimId"); LOG.debug("GlimId of Retrieved Account: {} ", list); return list; @@ -268,7 +275,7 @@ public class GroupHelper { final Integer groupID) { List list = new ArrayList<>(); LOG.info("------------------------------CHECK GROUP Retrieve Accounts------------------------------------\n"); - final String GROUP_URL = "/fineract-provider/api/v1/groups/"+groupID+"/gsimaccounts?" + Utils.TENANT_IDENTIFIER; + final String GROUP_URL = "/fineract-provider/api/v1/groups/" + groupID + "/gsimaccounts?" + Utils.TENANT_IDENTIFIER; list = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "gsimId"); LOG.debug("GsimId Retrieved Accounts: {} ", list); return list; @@ -312,4 +319,4 @@ public class GroupHelper { map.put("datatables", datatablesListMap); return new Gson().toJson(map); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/HolidayHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/HolidayHelper.java index 65beb2bc7..8362470da 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/HolidayHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/HolidayHelper.java @@ -29,6 +29,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "unused", "rawtypes" }) public class HolidayHelper { + private final static Logger LOG = LoggerFactory.getLogger(HolidayHelper.class); private static final String HOLIDAYS_URL = "/fineract-provider/api/v1/holidays"; private static final String CREATE_HOLIDAY_URL = HOLIDAYS_URL + "?" + Utils.TENANT_IDENTIFIER; @@ -59,14 +60,14 @@ public class HolidayHelper { map.put("repaymentsRescheduledTo", "08 April 2013"); map.put("reschedulingType", 2); String HolidayCreateJson = new Gson().toJson(map); - LOG.info("{}",HolidayCreateJson); + LOG.info("{}", HolidayCreateJson); return HolidayCreateJson; } public static String getActivateHolidayDataAsJSON() { final HashMap map = new HashMap<>(); String activateHoliday = new Gson().toJson(map); - LOG.info("{}",activateHoliday); + LOG.info("{}", activateHoliday); return activateHoliday; } @@ -74,7 +75,8 @@ public class HolidayHelper { return Utils.performServerPost(requestSpec, responseSpec, CREATE_HOLIDAY_URL, getCreateHolidayDataAsJSON(), "resourceId"); } - public static Integer activateHolidays(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String holidayID) { + public static Integer activateHolidays(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String holidayID) { final String ACTIVATE_HOLIDAY_URL = HOLIDAYS_URL + "/" + holidayID + "?command=activate&" + Utils.TENANT_IDENTIFIER; return Utils.performServerPost(requestSpec, responseSpec, ACTIVATE_HOLIDAY_URL, getActivateHolidayDataAsJSON(), "resourceId"); } @@ -87,4 +89,4 @@ public class HolidayHelper { return response; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/HookHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/HookHelper.java index e5fac8970..b76ffd41c 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/HookHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/HookHelper.java @@ -30,6 +30,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HookHelper { + private final static Logger LOG = LoggerFactory.getLogger(HookHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; @@ -43,8 +44,7 @@ public class HookHelper { public Integer createHook(final String payloadURL) { LOG.info("---------------------------------CREATING A HOOK---------------------------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, CREATE_HOOK_URL, getTestHookAsJson(payloadURL), - "resourceId"); + return Utils.performServerPost(requestSpec, responseSpec, CREATE_HOOK_URL, getTestHookAsJson(payloadURL), "resourceId"); } public String getTestHookAsJson(final String payloadURL) { @@ -62,7 +62,7 @@ public class HookHelper { createOfficeEvent.put("entityName", "OFFICE"); events.add(createOfficeEvent); map.put("events", events); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } @@ -88,8 +88,9 @@ public class HookHelper { public void verifyUpdateHook(final String updateURL, final Long hookId) { LOG.info("------------------------------CHECK UPDATE HOOK DETAILS------------------------------------\n"); final String GET_URL = "/fineract-provider/api/v1/hooks/" + hookId + "?" + Utils.TENANT_IDENTIFIER; - ArrayList> map = Utils.>>performServerGet(this.requestSpec, this.responseSpec, GET_URL, "config"); - HashMap hash = map.get(1); + ArrayList> map = Utils.>> performServerGet(this.requestSpec, + this.responseSpec, GET_URL, "config"); + HashMap hash = map.get(1); assertEquals(updateURL, hash.get("fieldValue")); } @@ -97,8 +98,9 @@ public class HookHelper { LOG.info("------------------------------CHECK DELETE HOOK DETAILS------------------------------------\n"); final String GET_URL = "/fineract-provider/api/v1/hooks/" + hookId + "?" + Utils.TENANT_IDENTIFIER; ResponseSpecification responseSpec404 = new ResponseSpecBuilder().expectStatusCode(404).build(); - ArrayList> array = Utils.>>performServerGet(this.requestSpec, responseSpec404, GET_URL, "errors"); + ArrayList> array = Utils.>> performServerGet(this.requestSpec, + responseSpec404, GET_URL, "errors"); HashMap map = array.get(0); - assertEquals("error.msg.hook.identifier.not.found",map.get("userMessageGlobalisationCode")); + assertEquals("error.msg.hook.identifier.not.found", map.get("userMessageGlobalisationCode")); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ImageHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ImageHelper.java index 45f85921a..9171c81be 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ImageHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ImageHelper.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ImageHelper { + private final static Logger LOG = LoggerFactory.getLogger(ImageHelper.class); private static final String STAFF_IMAGE_URL = "/fineract-provider/api/v1/staff/"; private static final String IMAGES_URI = "/images"; @@ -59,7 +60,8 @@ public class ImageHelper { return Utils.performGetBinaryResponse(requestSpec, responseSpec, URL); } - public static Integer deleteStaffImage(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, Integer staffId) { + public static Integer deleteStaffImage(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + Integer staffId) { LOG.info("---------------------------------RETRIEVING STAFF IMAGE---------------------------------------------"); String URL = STAFF_IMAGE_URL + staffId + IMAGES_URI + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerDelete(requestSpec, responseSpec, URL, "resourceId"); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/LoanRescheduleRequestHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/LoanRescheduleRequestHelper.java index 5b9c315c2..7ba7227fe 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/LoanRescheduleRequestHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/LoanRescheduleRequestHelper.java @@ -24,6 +24,7 @@ import io.restassured.specification.RequestSpecification; import io.restassured.specification.ResponseSpecification; public class LoanRescheduleRequestHelper { + private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/NotificationHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/NotificationHelper.java index f5793304f..d0917f646 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/NotificationHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/NotificationHelper.java @@ -24,6 +24,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NotificationHelper { + private final static Logger LOG = LoggerFactory.getLogger(NotificationHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; @@ -36,7 +37,7 @@ public class NotificationHelper { } public static Object getNotifications(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final String jsonReturn) { + final String jsonReturn) { final String GET_NOTIFICATIONS_URL = NOTIFICATION_API_URL; LOG.info("-----------------------------GET NOTIFICATIONS-----------------------------------"); return Utils.performServerGet(requestSpec, responseSpec, GET_NOTIFICATIONS_URL, ""); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/OfficeDomain.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/OfficeDomain.java index 89d907b96..e5cb54ae2 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/OfficeDomain.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/OfficeDomain.java @@ -32,9 +32,8 @@ public class OfficeDomain { private String[] openingDate; private String hierarchy; - private Builder(final int id, final String name, - final String nameDecorated, final String externalId, - final String[] openingDate, final String hierarchy) { + private Builder(final int id, final String name, final String nameDecorated, final String externalId, final String[] openingDate, + final String hierarchy) { this.id = id; this.name = name; this.nameDecorated = nameDecorated; @@ -44,8 +43,7 @@ public class OfficeDomain { } public OfficeDomain build() { - return new OfficeDomain(this.id, this.name, this.nameDecorated, - this.externalId, this.openingDate, this.hierarchy); + return new OfficeDomain(this.id, this.name, this.nameDecorated, this.externalId, this.openingDate, this.hierarchy); } } @@ -60,9 +58,8 @@ public class OfficeDomain { super(); } - private OfficeDomain(final int id, final String name, - final String nameDecorated, final String externalId, - final String[] openingDate, final String hierarchy) { + private OfficeDomain(final int id, final String name, final String nameDecorated, final String externalId, final String[] openingDate, + final String hierarchy) { super(); this.id = id; this.name = name; @@ -80,11 +77,9 @@ public class OfficeDomain { return new Gson().fromJson(jsonData, OfficeDomain.class); } - public static Builder create(final int id, final String name, - final String nameDecorated, final String externalId, + public static Builder create(final int id, final String name, final String nameDecorated, final String externalId, final String[] openingDate, final String hierarchy) { - return new Builder(id, name, nameDecorated, externalId, openingDate, - hierarchy); + return new Builder(id, name, nameDecorated, externalId, openingDate, hierarchy); } public int getId() { @@ -139,20 +134,14 @@ public class OfficeDomain { @Override public boolean equals(Object obj) { - if (obj == this) { - return true; - } + if (obj == this) { return true; } - if (!(obj instanceof OfficeDomain)) { - return false; - } + if (!(obj instanceof OfficeDomain)) { return false; } OfficeDomain od = (OfficeDomain) obj; - if (this.id == od.getId() && this.name.equals(od.getName()) - && this.nameDecorated.equals(od.getName()) - && this.externalId.equals(od.getExternalId()) - && Arrays.equals(this.openingDate, od.getOpeningDate()) + if (this.id == od.getId() && this.name.equals(od.getName()) && this.nameDecorated.equals(od.getName()) + && this.externalId.equals(od.getExternalId()) && Arrays.equals(this.openingDate, od.getOpeningDate()) && this.hierarchy.equals(od.getHierarchy())) { return true; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/OfficeHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/OfficeHelper.java old mode 100755 new mode 100644 index cf25c675a..99dfafb7b --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/OfficeHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/OfficeHelper.java @@ -35,30 +35,26 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OfficeHelper { + private final static Logger LOG = LoggerFactory.getLogger(OfficeHelper.class); private static final String OFFICE_URL = "/fineract-provider/api/v1/offices"; private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; - public OfficeHelper(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public OfficeHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { this.requestSpec = requestSpec; this.responseSpec = responseSpec; } public OfficeDomain retrieveOfficeByID(int id) { - Object get = Utils.performServerGet( - requestSpec, responseSpec, OFFICE_URL + "/" + id + "?" - + Utils.TENANT_IDENTIFIER, ""); + Object get = Utils.performServerGet(requestSpec, responseSpec, OFFICE_URL + "/" + id + "?" + Utils.TENANT_IDENTIFIER, ""); final String json = new Gson().toJson(get); - return new Gson().fromJson(json, new TypeToken() { - }.getType()); + return new Gson().fromJson(json, new TypeToken() {}.getType()); } public Integer createOffice(final String openingDate) { String json = getAsJSON(openingDate); - return Utils.performServerPost(this.requestSpec, this.responseSpec, - OFFICE_URL + "?" + Utils.TENANT_IDENTIFIER, json, + return Utils.performServerPost(this.requestSpec, this.responseSpec, OFFICE_URL + "?" + Utils.TENANT_IDENTIFIER, json, CommonConstants.RESPONSE_RESOURCE_ID); } @@ -69,10 +65,9 @@ public class OfficeHelper { map.put("locale", "en"); map.put("openingDate", openingDate); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); - return Utils.performServerPut(requestSpec, responseSpec, OFFICE_URL - + "/" + id + "?" + Utils.TENANT_IDENTIFIER, + return Utils.performServerPut(requestSpec, responseSpec, OFFICE_URL + "/" + id + "?" + Utils.TENANT_IDENTIFIER, new Gson().toJson(map), "resourceId"); } @@ -83,30 +78,31 @@ public class OfficeHelper { map.put("dateFormat", "dd MMMM yyyy"); map.put("locale", "en"); map.put("openingDate", openingDate); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } - public String importOfficeTemplate(File file){ - String locale="en"; - String dateFormat="dd MMMM yyyy"; + public String importOfficeTemplate(File file) { + String locale = "en"; + String dateFormat = "dd MMMM yyyy"; requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA); - return Utils.performServerTemplatePost(requestSpec,responseSpec,OFFICE_URL+"/uploadtemplate"+"?"+Utils.TENANT_IDENTIFIER, - null,file,locale,dateFormat); + return Utils.performServerTemplatePost(requestSpec, responseSpec, OFFICE_URL + "/uploadtemplate" + "?" + Utils.TENANT_IDENTIFIER, + null, file, locale, dateFormat); } - public String getOutputTemplateLocation(final String importDocumentId){ - requestSpec.header(HttpHeaders.CONTENT_TYPE,MediaType.TEXT_PLAIN); - return Utils.performServerOutputTemplateLocationGet(requestSpec,responseSpec,"/fineract-provider/api/v1/imports/getOutputTemplateLocation"+"?" - +Utils.TENANT_IDENTIFIER,importDocumentId); + public String getOutputTemplateLocation(final String importDocumentId) { + requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN); + return Utils.performServerOutputTemplateLocationGet(requestSpec, responseSpec, + "/fineract-provider/api/v1/imports/getOutputTemplateLocation" + "?" + Utils.TENANT_IDENTIFIER, importDocumentId); } + public Workbook getOfficeWorkBook(final String dateFormat) throws IOException { - requestSpec.header(HttpHeaders.CONTENT_TYPE,"application/vnd.ms-excel"); - byte[] byteArray=Utils.performGetBinaryResponse(requestSpec,responseSpec,OFFICE_URL+"/downloadtemplate"+"?"+ - Utils.TENANT_IDENTIFIER+"&dateFormat="+dateFormat); - InputStream inputStream= new ByteArrayInputStream(byteArray); - Workbook workbook=new HSSFWorkbook(inputStream); + requestSpec.header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel"); + byte[] byteArray = Utils.performGetBinaryResponse(requestSpec, responseSpec, + OFFICE_URL + "/downloadtemplate" + "?" + Utils.TENANT_IDENTIFIER + "&dateFormat=" + dateFormat); + InputStream inputStream = new ByteArrayInputStream(byteArray); + Workbook workbook = new HSSFWorkbook(inputStream); return workbook; } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/PasswordPreferencesHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/PasswordPreferencesHelper.java index 472dac43e..46902f8cf 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/PasswordPreferencesHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/PasswordPreferencesHelper.java @@ -27,8 +27,8 @@ public class PasswordPreferencesHelper { private static final String PASSWORD_PREFERENCES_URL = "/fineract-provider/api/v1/passwordpreferences"; - public static Object updatePasswordPreferences(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, String validationPolicyId) { + public static Object updatePasswordPreferences(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + String validationPolicyId) { final String UPDATE_PASSWORD_PREFERENCES_URL = PASSWORD_PREFERENCES_URL + "?" + Utils.TENANT_IDENTIFIER; // system.out.println("---------------------------------UPDATE PASSWORD // PREFERENCE---------------------------------------------"); @@ -37,12 +37,14 @@ public class PasswordPreferencesHelper { } public static Object updateWithInvalidValidationPolicyId(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec,String invalidValidationPolicyId, String jsonAttributeToGetback) { + final ResponseSpecification responseSpec, String invalidValidationPolicyId, String jsonAttributeToGetback) { final String UPDATE_PASSWORD_PREFERENCES_URL = PASSWORD_PREFERENCES_URL + "?" + Utils.TENANT_IDENTIFIER; - //system.out - //.println("---------------------------------UPDATE PASSWORD PREFERENCES WITH INVALID ID-----------------------------------------"); - return Utils.performServerPut(requestSpec, responseSpec, UPDATE_PASSWORD_PREFERENCES_URL, updatePreferencesWithInvalidId(invalidValidationPolicyId), - jsonAttributeToGetback); + // system.out + // .println("---------------------------------UPDATE PASSWORD + // PREFERENCES WITH INVALID + // ID-----------------------------------------"); + return Utils.performServerPut(requestSpec, responseSpec, UPDATE_PASSWORD_PREFERENCES_URL, + updatePreferencesWithInvalidId(invalidValidationPolicyId), jsonAttributeToGetback); } public static String updatePreferencesAsJson(String validationPolicyId) { @@ -57,17 +59,15 @@ public class PasswordPreferencesHelper { return new Gson().toJson(map); } - public static int getActivePasswordPreference(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { - return Utils.performServerGet(requestSpec, responseSpec, - PASSWORD_PREFERENCES_URL + "?" + Utils.TENANT_IDENTIFIER, "id"); + public static int getActivePasswordPreference(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + return Utils.performServerGet(requestSpec, responseSpec, PASSWORD_PREFERENCES_URL + "?" + Utils.TENANT_IDENTIFIER, "id"); } public static HashMap getAllPreferences(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { - return Utils.performServerGet(requestSpec, responseSpec, - PASSWORD_PREFERENCES_URL + "/template" + "?" + Utils.TENANT_IDENTIFIER, ""); + return Utils.performServerGet(requestSpec, responseSpec, PASSWORD_PREFERENCES_URL + "/template" + "?" + Utils.TENANT_IDENTIFIER, + ""); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/PaymentTypeHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/PaymentTypeHelper.java index 3d7e28e79..626edfd9e 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/PaymentTypeHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/PaymentTypeHelper.java @@ -29,21 +29,20 @@ import java.util.HashMap; @SuppressWarnings({ "rawtypes", "unchecked" }) public class PaymentTypeHelper { - private static final String CREATE_PAYMENTTYPE_URL = "/fineract-provider/api/v1/paymenttypes?" - + Utils.TENANT_IDENTIFIER; + private static final String CREATE_PAYMENTTYPE_URL = "/fineract-provider/api/v1/paymenttypes?" + Utils.TENANT_IDENTIFIER; private static final String PAYMENTTYPE_URL = "/fineract-provider/api/v1/paymenttypes"; - public static Integer createPaymentType(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String name, final String description, - final Boolean isCashPayment, final Integer position) { - // system.out.println("---------------------------------CREATING A PAYMENT + public static Integer createPaymentType(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String name, final String description, final Boolean isCashPayment, final Integer position) { + // system.out.println("---------------------------------CREATING A + // PAYMENT // TYPE---------------------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, CREATE_PAYMENTTYPE_URL, getJsonToCreatePaymentType(name, description, isCashPayment, position), "resourceId"); } - public static String getJsonToCreatePaymentType(final String name, final String description, - final Boolean isCashPayment, final Integer position) { + public static String getJsonToCreatePaymentType(final String name, final String description, final Boolean isCashPayment, + final Integer position) { HashMap hm = new HashMap(); hm.put("name", name); if (description != null) { @@ -59,14 +58,12 @@ public class PaymentTypeHelper { return new Gson().toJson(hm); } - public static void verifyPaymentTypeCreatedOnServer(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer generatedPaymentTypeID) { + public static void verifyPaymentTypeCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer generatedPaymentTypeID) { // system.out.println("------------------------------CHECK PAYMENT // DETAILS------------------------------------\n"); - final String GET_PAYMENTTYPE_URL = PAYMENTTYPE_URL + "/" + generatedPaymentTypeID + "?" - + Utils.TENANT_IDENTIFIER; - final Integer responsePaymentTypeID = Utils.performServerGet(requestSpec, responseSpec, GET_PAYMENTTYPE_URL, - "id"); + final String GET_PAYMENTTYPE_URL = PAYMENTTYPE_URL + "/" + generatedPaymentTypeID + "?" + Utils.TENANT_IDENTIFIER; + final Integer responsePaymentTypeID = Utils.performServerGet(requestSpec, responseSpec, GET_PAYMENTTYPE_URL, "id"); assertEquals(generatedPaymentTypeID, responsePaymentTypeID, "ERROR IN CREATING THE PAYMENT TYPE"); } @@ -77,25 +74,26 @@ public class PaymentTypeHelper { // TYPE---------------------------------------------"); Object get = Utils.performServerGet(requestSpec, responseSpec, GET_PAYMENTTYPE_URL, ""); final String jsonData = new Gson().toJson(get); - return new Gson().fromJson(jsonData, new TypeToken() { - }.getType()); + return new Gson().fromJson(jsonData, new TypeToken() {}.getType()); } - public static HashMap updatePaymentType(final int id, HashMap request, - final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + public static HashMap updatePaymentType(final int id, HashMap request, final RequestSpecification requestSpec, + final ResponseSpecification responseSpec) { final String UPDATE_PAYMENTTYPE_URL = PAYMENTTYPE_URL + "/" + id + "?" + Utils.TENANT_IDENTIFIER; - // system.out.println("---------------------------------UPDATE PAYMENT TYPE " + + // system.out.println("---------------------------------UPDATE PAYMENT + // TYPE " + // id + "---------------------------------------------"); - HashMap hash = Utils.performServerPut(requestSpec, responseSpec, UPDATE_PAYMENTTYPE_URL, - new Gson().toJson(request), "changes"); + HashMap hash = Utils.performServerPut(requestSpec, responseSpec, UPDATE_PAYMENTTYPE_URL, new Gson().toJson(request), + "changes"); return hash; } public static Integer deletePaymentType(final int id, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { final String DELETE_PAYMENTTYPE_URL = PAYMENTTYPE_URL + "/" + id + "?" + Utils.TENANT_IDENTIFIER; - // system.out.println("---------------------------------DELETING PAYMENT TYPE " + // system.out.println("---------------------------------DELETING PAYMENT + // TYPE " // + id + "--------------------------------------------"); return Utils.performServerDelete(requestSpec, responseSpec, DELETE_PAYMENTTYPE_URL, "resourceId"); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ProvisioningIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ProvisioningIntegrationTest.java index f2cbdaa98..88269b100 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ProvisioningIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/ProvisioningIntegrationTest.java @@ -49,6 +49,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "rawtypes", "unchecked" }) public class ProvisioningIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(ProvisioningIntegrationTest.class); private static final String NONE = "1"; private final static int LOANPRODUCTS_SIZE = 10; @@ -59,7 +60,7 @@ public class ProvisioningIntegrationTest { private LoanTransactionHelper loanTransactionHelper; @BeforeEach - public void setup() throws ParseException{ + public void setup() throws ParseException { Utils.initializeRESTAssured(); this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); @@ -94,33 +95,33 @@ public class ProvisioningIntegrationTest { } ArrayList categories = transactionHelper.retrieveAllProvisioningCategories(); - Assertions.assertTrue(categories.size() > 0) ; - Account liability = accountHelper.createLiabilityAccount() ; - Account expense = accountHelper.createExpenseAccount() ; + Assertions.assertTrue(categories.size() > 0); + Account liability = accountHelper.createLiabilityAccount(); + Account expense = accountHelper.createExpenseAccount(); Map requestCriteria = ProvisioningHelper.createProvisioingCriteriaJson(loanProducts, categories, liability, expense); String provisioningCriteriaCreateJson = new Gson().toJson(requestCriteria); Integer criteriaId = transactionHelper.createProvisioningCriteria(provisioningCriteriaCreateJson); Assertions.assertNotNull(criteriaId); - Map newCriteria = transactionHelper.retrieveProvisioningCriteria(criteriaId) ; - validateProvisioningCriteria(requestCriteria, newCriteria) ; + Map newCriteria = transactionHelper.retrieveProvisioningCriteria(criteriaId); + validateProvisioningCriteria(requestCriteria, newCriteria); - ArrayList definitions = (ArrayList)newCriteria.get("definitions") ; - for(int i = 0 ; i < definitions.size(); i++) { - Map criteriadefinition = (Map) definitions.get(i) ; - criteriadefinition.put("provisioningPercentage", Float.valueOf((float)20.0)) ; + ArrayList definitions = (ArrayList) newCriteria.get("definitions"); + for (int i = 0; i < definitions.size(); i++) { + Map criteriadefinition = (Map) definitions.get(i); + criteriadefinition.put("provisioningPercentage", Float.valueOf((float) 20.0)); } newCriteria.put("locale", "en"); - String updateCriteriaString = new Gson().toJson(newCriteria) ; - Integer criteriaId1 = transactionHelper.updateProvisioningCriteria(criteriaId, updateCriteriaString) ; - Map updatedCriteria = transactionHelper.retrieveProvisioningCriteria(criteriaId1) ; - validateProvisioningCriteria(newCriteria, updatedCriteria) ; + String updateCriteriaString = new Gson().toJson(newCriteria); + Integer criteriaId1 = transactionHelper.updateProvisioningCriteria(criteriaId, updateCriteriaString); + Map updatedCriteria = transactionHelper.retrieveProvisioningCriteria(criteriaId1); + validateProvisioningCriteria(newCriteria, updatedCriteria); - transactionHelper.deleteProvisioningCriteria(criteriaId1) ; + transactionHelper.deleteProvisioningCriteria(criteriaId1); categories = transactionHelper.retrieveAllProvisioningCategories(); - liability = accountHelper.createLiabilityAccount() ; - expense = accountHelper.createExpenseAccount() ; + liability = accountHelper.createLiabilityAccount(); + expense = accountHelper.createExpenseAccount(); requestCriteria = ProvisioningHelper.createProvisioingCriteriaJson(loanProducts, categories, liability, expense); provisioningCriteriaCreateJson = new Gson().toJson(requestCriteria); criteriaId = transactionHelper.createProvisioningCriteria(provisioningCriteriaCreateJson); @@ -130,58 +131,58 @@ public class ProvisioningIntegrationTest { Integer provisioningEntryId = transactionHelper.createProvisioningEntries(provisioningEntryJson); Assertions.assertNotNull(provisioningEntryId); - transactionHelper.updateProvisioningEntry("recreateprovisioningentry", provisioningEntryId, "") ; - transactionHelper.updateProvisioningEntry("createjournalentry", provisioningEntryId, "") ; - Map entry = transactionHelper.retrieveProvisioningEntry(provisioningEntryId) ; - Assertions.assertTrue((Boolean)entry.get("journalEntry")) ; - Map provisioningEntry = transactionHelper.retrieveProvisioningEntries(provisioningEntryId) ; - Assertions.assertTrue(((ArrayList)provisioningEntry.get("pageItems")).size() > 0) ; + transactionHelper.updateProvisioningEntry("recreateprovisioningentry", provisioningEntryId, ""); + transactionHelper.updateProvisioningEntry("createjournalentry", provisioningEntryId, ""); + Map entry = transactionHelper.retrieveProvisioningEntry(provisioningEntryId); + Assertions.assertTrue((Boolean) entry.get("journalEntry")); + Map provisioningEntry = transactionHelper.retrieveProvisioningEntries(provisioningEntryId); + Assertions.assertTrue(((ArrayList) provisioningEntry.get("pageItems")).size() > 0); } private void validateProvisioningCriteria(Map requestCriteria, Map newCriteria) { - //criteria name validation - String requestCriteriaName = (String)requestCriteria.get("criteriaName") ; - String criteriaName = (String)newCriteria.get("criteriaName") ; - Assertions.assertEquals(criteriaName, requestCriteriaName) ; + // criteria name validation + String requestCriteriaName = (String) requestCriteria.get("criteriaName"); + String criteriaName = (String) newCriteria.get("criteriaName"); + Assertions.assertEquals(criteriaName, requestCriteriaName); - //loan products validation - ArrayList requestProducts = (ArrayList)requestCriteria.get("loanProducts") ; - ArrayList products = (ArrayList)newCriteria.get("loanProducts") ; - Assertions.assertEquals(products.size(), requestProducts.size()) ; + // loan products validation + ArrayList requestProducts = (ArrayList) requestCriteria.get("loanProducts"); + ArrayList products = (ArrayList) newCriteria.get("loanProducts"); + Assertions.assertEquals(products.size(), requestProducts.size()); - ArrayList requestedDefinitions = (ArrayList)requestCriteria.get("definitions") ; - ArrayList newdefintions = (ArrayList) newCriteria.get("definitions") ; - Assertions.assertEquals(newdefintions.size(), requestedDefinitions.size()) ; - for(int i = 0 ; i < newdefintions.size() ; i++) { - Map requestedMap = (Map)requestedDefinitions.get(i) ; - Object requestedCategoryId = requestedMap.get("categoryId") ; - boolean found = false ; - for(int j = 0 ; j < newdefintions.size(); j++) { - Map newMap = (Map)newdefintions.get(j) ; - Object newCategoryId = newMap.get("categoryId") ; - if(requestedCategoryId.equals(newCategoryId)) { - found = true ; - checkProperty("categoryId", requestedMap, newMap) ; - checkProperty("categoryName", requestedMap, newMap) ; - checkProperty("minAge", requestedMap, newMap) ; - checkProperty("maxAge", requestedMap, newMap) ; - checkProperty("provisioningPercentage", requestedMap, newMap) ; - checkProperty("liabilityAccount", requestedMap, newMap) ; - checkProperty("expenseAccount", requestedMap, newMap) ; - break ; //internal loop + ArrayList requestedDefinitions = (ArrayList) requestCriteria.get("definitions"); + ArrayList newdefintions = (ArrayList) newCriteria.get("definitions"); + Assertions.assertEquals(newdefintions.size(), requestedDefinitions.size()); + for (int i = 0; i < newdefintions.size(); i++) { + Map requestedMap = (Map) requestedDefinitions.get(i); + Object requestedCategoryId = requestedMap.get("categoryId"); + boolean found = false; + for (int j = 0; j < newdefintions.size(); j++) { + Map newMap = (Map) newdefintions.get(j); + Object newCategoryId = newMap.get("categoryId"); + if (requestedCategoryId.equals(newCategoryId)) { + found = true; + checkProperty("categoryId", requestedMap, newMap); + checkProperty("categoryName", requestedMap, newMap); + checkProperty("minAge", requestedMap, newMap); + checkProperty("maxAge", requestedMap, newMap); + checkProperty("provisioningPercentage", requestedMap, newMap); + checkProperty("liabilityAccount", requestedMap, newMap); + checkProperty("expenseAccount", requestedMap, newMap); + break; // internal loop } } - if(!found) { + if (!found) { Assertions.fail("No Category found with Id:" + requestedCategoryId); } } } private void checkProperty(String propertyName, Map requestMap, Map newMap) { - Object requested = requestMap.get(propertyName) ; - Object modified = newMap.get(propertyName) ; - Assertions.assertEquals(requested, modified) ; + Object requested = requestMap.get(propertyName); + Object modified = newMap.get(propertyName); + Assertions.assertEquals(requested, modified); } private Integer createLoanProduct(final boolean multiDisburseLoan, final String accountingRule, final Account... accounts) { @@ -227,19 +228,19 @@ public class ProvisioningIntegrationTest { private boolean isAlreadyProvisioningEntriesCreated() throws ParseException { ProvisioningTransactionHelper transactionHelper = new ProvisioningTransactionHelper(requestSpec, responseSpec); - Map entries = transactionHelper.retrieveAllProvisioningEntries() ; - ArrayList pageItems = (ArrayList)entries.get("pageItems") ; - boolean provisioningetryAlreadyCreated = false ; - if(pageItems != null) { - for(Map item: pageItems) { - String date = (String)item.get("createdDate") ; + Map entries = transactionHelper.retrieveAllProvisioningEntries(); + ArrayList pageItems = (ArrayList) entries.get("pageItems"); + boolean provisioningetryAlreadyCreated = false; + if (pageItems != null) { + for (Map item : pageItems) { + String date = (String) item.get("createdDate"); DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy"); - Date date1 = formatter.parse(date) ; + Date date1 = formatter.parse(date); DateFormat simple = new SimpleDateFormat("dd MMMM yyyy"); String formattedString = simple.format(Utils.getLocalDateOfTenant().toDate()); - Date currentDate = simple.parse(formattedString) ; - if(date1.getTime() == currentDate.getTime()) { - provisioningetryAlreadyCreated = true ; + Date currentDate = simple.parse(formattedString); + if (date1.getTime() == currentDate.getTime()) { + provisioningetryAlreadyCreated = true; break; } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/SchedulerJobHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/SchedulerJobHelper.java index 8d54c5c89..c0ea9e924 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/SchedulerJobHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/SchedulerJobHelper.java @@ -43,6 +43,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SchedulerJobHelper { + private final static Logger LOG = LoggerFactory.getLogger(SchedulerJobHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification response200Spec; @@ -78,7 +79,7 @@ public class SchedulerJobHelper { final String GET_SCHEDULER_JOB_BY_ID_URL = "/fineract-provider/api/v1/jobs/" + jobId + "?" + Utils.TENANT_IDENTIFIER; LOG.info("------------------------ RETRIEVING SCHEDULER JOB BY ID -------------------------"); final Map response = Utils.performServerGet(requestSpec, response200Spec, GET_SCHEDULER_JOB_BY_ID_URL, ""); - LOG.info("{}",response.toString()); + LOG.info("{}", response.toString()); assertNotNull(response); return response; } @@ -108,7 +109,7 @@ public class SchedulerJobHelper { private static String updateSchedulerJobAsJSON(final boolean active) { final Map map = new HashMap<>(); map.put("active", Boolean.toString(active)); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } @@ -133,12 +134,17 @@ public class SchedulerJobHelper { return (Integer) allSchedulerJobsData.get(jobIndex).get("jobId"); } } - throw new IllegalArgumentException("No such named Job (see org.apache.fineract.infrastructure.jobs.service.JobName enum):" + jobName); + throw new IllegalArgumentException( + "No such named Job (see org.apache.fineract.infrastructure.jobs.service.JobName enum):" + jobName); } /** * Launches a Job and awaits its completion. - * @param jobName displayName (see {@link org.apache.fineract.infrastructure.jobs.service.JobName}) of Scheduler Job + * + * @param jobName + * displayName (see + * {@link org.apache.fineract.infrastructure.jobs.service.JobName}) + * of Scheduler Job * * @author Michael Vorburger.ch */ @@ -148,53 +154,54 @@ public class SchedulerJobHelper { DateTimeFormatter df = DateTimeFormatter.ISO_INSTANT; // FINERACT-926 Instant beforeExecuteTime = now().truncatedTo(ChronoUnit.SECONDS); - // Stop the Scheduler while we manually trigger execution of job, to avoid side effects and simplify debugging when readings logs + // Stop the Scheduler while we manually trigger execution of job, to + // avoid side effects and simplify debugging when readings logs updateSchedulerStatus(false); // Executing Scheduler Job int jobId = getSchedulerJobIdByName(jobName); runSchedulerJob(jobId); - // Await JobDetailData.lastRunHistory [JobDetailHistoryData] jobRunStartTime >= beforeExecuteTime (or timeout) + // Await JobDetailData.lastRunHistory [JobDetailHistoryData] + // jobRunStartTime >= beforeExecuteTime (or timeout) await().atMost(TIMEOUT).pollInterval(PAUSE).until(jobLastRunHistorySupplier(jobId), lastRunHistory -> { String jobRunStartText = lastRunHistory.get("jobRunStartTime"); - if (jobRunStartText == null) { - return false; - } + if (jobRunStartText == null) { return false; } Instant jobRunStartTime = df.parse(jobRunStartText, Instant::from); return jobRunStartTime.equals(beforeExecuteTime) || jobRunStartTime.isAfter(beforeExecuteTime); }); - // Await JobDetailData.lastRunHistory [JobDetailHistoryData] jobRunEndTime to be both set and >= jobRunStartTime (or timeout) - Map finalLastRunHistory = await().atMost(TIMEOUT).pollInterval(PAUSE).until(jobLastRunHistorySupplier(jobId), lastRunHistory -> { - String jobRunEndText = lastRunHistory.get("jobRunEndTime"); - if (jobRunEndText == null) { - return false; - } - Instant jobRunEndTime = df.parse(jobRunEndText, Instant::from); - Instant jobRunStartTime = df.parse(lastRunHistory.get("jobRunStartTime"), Instant::from); - return jobRunEndTime.equals(jobRunStartTime) || jobRunEndTime.isAfter(jobRunStartTime); - }); + // Await JobDetailData.lastRunHistory [JobDetailHistoryData] + // jobRunEndTime to be both set and >= jobRunStartTime (or timeout) + Map finalLastRunHistory = await().atMost(TIMEOUT).pollInterval(PAUSE).until(jobLastRunHistorySupplier(jobId), + lastRunHistory -> { + String jobRunEndText = lastRunHistory.get("jobRunEndTime"); + if (jobRunEndText == null) { return false; } + Instant jobRunEndTime = df.parse(jobRunEndText, Instant::from); + Instant jobRunStartTime = df.parse(lastRunHistory.get("jobRunStartTime"), Instant::from); + return jobRunEndTime.equals(jobRunStartTime) || jobRunEndTime.isAfter(jobRunStartTime); + }); // Verify triggerType assertThat(finalLastRunHistory.get("triggerType"), is("application")); - // Verify status & propagate jobRunErrorMessage and/or jobRunErrorLog (if any) + // Verify status & propagate jobRunErrorMessage and/or jobRunErrorLog + // (if any) String status = finalLastRunHistory.get("status"); if (!status.equals("success")) { fail("Job status is not success: " + finalLastRunHistory.toString()); } - // PS: Checking getSchedulerJobHistory() [/runhistory] is pointless, because the lastRunHistory JobDetailHistoryData is already part of JobDetailData anyway. + // PS: Checking getSchedulerJobHistory() [/runhistory] is pointless, + // because the lastRunHistory JobDetailHistoryData is already part of + // JobDetailData anyway. } @SuppressWarnings("unchecked") private Callable> jobLastRunHistorySupplier(int jobId) { return () -> { Map job = getSchedulerJobById(jobId); - if (job == null) { - return null; - } + if (job == null) { return null; } return (Map) job.get("lastRunHistory"); }; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/StandingInstructionsHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/StandingInstructionsHelper.java index aea18e46b..20ceec78a 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/StandingInstructionsHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/StandingInstructionsHelper.java @@ -26,8 +26,9 @@ import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@SuppressWarnings({"unused", "rawtypes", "unchecked" }) +@SuppressWarnings({ "unused", "rawtypes", "unchecked" }) public class StandingInstructionsHelper { + private final static Logger LOG = LoggerFactory.getLogger(StandingInstructionsHelper.class); private static final String STANDING_INSTRUCTIONS_URL = "/fineract-provider/api/v1/standinginstructions"; private static final String STANDING_INSTRUCTIONS_RUNHISTORY_URL = "/fineract-provider/api/v1/standinginstructionrunhistory"; @@ -90,7 +91,7 @@ public class StandingInstructionsHelper { map.put("recurrenceFrequency", RECURRENCE_FREQUENCY_WEEKS); map.put("recurrenceOnMonthDay", monthDay); String savingsApplicationJSON = new Gson().toJson(map); - LOG.info("{}",savingsApplicationJSON); + LOG.info("{}", savingsApplicationJSON); return savingsApplicationJSON; } @@ -113,13 +114,14 @@ public class StandingInstructionsHelper { return response; } - public List getStandingInstructionHistory(Integer fromSavingsId, Integer fromAccountType, Integer fromClientId, Integer transferType) { + public List getStandingInstructionHistory(Integer fromSavingsId, Integer fromAccountType, Integer fromClientId, + Integer transferType) { final String STANDING_INSTRUCTIONS_HISTORY_URL = STANDING_INSTRUCTIONS_RUNHISTORY_URL + "?" + Utils.TENANT_IDENTIFIER - + "&fromSavingsId=" + fromSavingsId + "&fromAccountType=" + fromAccountType + "&clientId=" + fromClientId - + "&transferType=" + transferType; - LOG.info("STANDING_INSTRUCTIONS_HISTORY_URL= {}",STANDING_INSTRUCTIONS_HISTORY_URL); + + "&fromSavingsId=" + fromSavingsId + "&fromAccountType=" + fromAccountType + "&clientId=" + fromClientId + "&transferType=" + + transferType; + LOG.info("STANDING_INSTRUCTIONS_HISTORY_URL= {}", STANDING_INSTRUCTIONS_HISTORY_URL); final List response = (List) Utils.performServerGet(this.requestSpec, this.responseSpec, STANDING_INSTRUCTIONS_HISTORY_URL, "pageItems"); return response; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/SurveyHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/SurveyHelper.java index 3b2c34ce9..41250a8e5 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/SurveyHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/SurveyHelper.java @@ -28,6 +28,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SurveyHelper { + private final static Logger LOG = LoggerFactory.getLogger(SurveyHelper.class); private static final String FULFIL_SURVEY_URL = "/fineract-provider/api/v1/survey/ppi_kenya_2009/clientId?" + Utils.TENANT_IDENTIFIER; @@ -38,16 +39,16 @@ public class SurveyHelper { public static Integer fulfilSurvey(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String activationDate) { LOG.info("---------------------------------FULFIL PPI ---------------------------------------------"); - return Utils.performServerPost(requestSpec, responseSpec,FULFIL_SURVEY_URL, getTestPPIAsJSON(), "clientId"); + return Utils.performServerPost(requestSpec, responseSpec, FULFIL_SURVEY_URL, getTestPPIAsJSON(), "clientId"); } public static String getTestPPIAsJSON() { final HashMap map = new HashMap<>(); map.put("date", "2014-05-19 00:00:00"); - map.put("ppi_household_members_cd_q1_householdmembers","107"); - map.put("ppi_highestschool_cd_q2_highestschool","112"); - map.put("ppi_businessoccupation_cd_q3_businessoccupation","116"); + map.put("ppi_household_members_cd_q1_householdmembers", "107"); + map.put("ppi_highestschool_cd_q2_highestschool", "112"); + map.put("ppi_businessoccupation_cd_q3_businessoccupation", "116"); map.put("dateFormat", "dd MMMM yyyy"); map.put("locale", "en"); map.put("ppi_habitablerooms_cd_q4_habitablerooms", "120"); @@ -59,17 +60,17 @@ public class SurveyHelper { map.put("ppi_towels_cd_q9_towels", "134"); map.put("ppi_fryingpans_cd_q10_fryingpans", "138"); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } public static void verifySurveyCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer generatedClientID) { LOG.info("------------------------------CHECK CLIENT DETAILS------------------------------------\n"); - final String SURVEY_URL = "/fineract-provider/api/v1/Survey/ppi_kenya_2009/clientid/entryId" + generatedClientID + "?" + Utils.TENANT_IDENTIFIER; + final String SURVEY_URL = "/fineract-provider/api/v1/Survey/ppi_kenya_2009/clientid/entryId" + generatedClientID + "?" + + Utils.TENANT_IDENTIFIER; final Integer responseClientID = Utils.performServerGet(requestSpec, responseSpec, SURVEY_URL, "id"); assertEquals(generatedClientID, responseClientID, "ERROR IN CREATING THE CLIENT"); } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/TaxComponentHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/TaxComponentHelper.java index 5e87d522d..d24f06f1e 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/TaxComponentHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/TaxComponentHelper.java @@ -27,6 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TaxComponentHelper { + private final static Logger LOG = LoggerFactory.getLogger(TaxComponentHelper.class); private static final String CREATE_TAX_COMPONENT_URL = "/fineract-provider/api/v1/taxes/component?" + Utils.TENANT_IDENTIFIER; @@ -43,7 +44,7 @@ public class TaxComponentHelper { map.put("creditAccountType", Account.AccountType.LIABILITY.toString()); map.put("creditAcountId", String.valueOf(creditAccountId)); } - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } @@ -61,4 +62,4 @@ public class TaxComponentHelper { return Utils.randomStringGenerator(prefix, lenOfRandomSuffix); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/TaxGroupHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/TaxGroupHelper.java index 02adfbd19..cdf71f29f 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/TaxGroupHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/TaxGroupHelper.java @@ -29,13 +29,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TaxGroupHelper { + private final static Logger LOG = LoggerFactory.getLogger(TaxGroupHelper.class); private static final String CREATE_TAX_COMPONENT_URL = "/fineract-provider/api/v1/taxes/group?" + Utils.TENANT_IDENTIFIER; public static Integer createTaxGroup(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Collection taxComponentIds) { LOG.info("---------------------------------CREATING A TAX GROUP---------------------------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, CREATE_TAX_COMPONENT_URL, getTaxGroupAsJSON(taxComponentIds), "resourceId"); + return Utils.performServerPost(requestSpec, responseSpec, CREATE_TAX_COMPONENT_URL, getTaxGroupAsJSON(taxComponentIds), + "resourceId"); } public static String getTaxGroupAsJSON(final Collection taxComponentIds) { @@ -66,4 +68,4 @@ public class TaxGroupHelper { return Utils.randomStringGenerator(prefix, lenOfRandomSuffix); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java index e5f400efa..24abceb3e 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java @@ -83,13 +83,11 @@ public class Utils { LOG.info("{} return HTTP 200, application is now ready for integration testing!", HEALTH_URL); return; } else { - LOG.info("{} returned HTTP {}, going to wait and retry (attempt {})", HEALTH_URL, - healthHttpStatus, attempt++); + LOG.info("{} returned HTTP {}, going to wait and retry (attempt {})", HEALTH_URL, healthHttpStatus, attempt++); sleep(3); } } catch (Exception e) { - LOG.info("{} caused {}, going to wait and retry (attempt {})", HEALTH_URL, e.getMessage(), - attempt++); + LOG.info("{} caused {}, going to wait and retry (attempt {})", HEALTH_URL, e.getMessage(), attempt++); lastException = e; sleep(3); } @@ -99,8 +97,7 @@ public class Utils { LOG.error("{} still not reachable, giving up", HEALTH_URL, lastException); throw new AssertionError(HEALTH_URL + " not reachable", lastException); } else { - LOG.error("{} still has not returned HTTP 200, giving up (last) body: {}", HEALTH_URL, - response.prettyPrint()); + LOG.error("{} still has not returned HTTP 200, giving up (last) body: {}", HEALTH_URL, response.prettyPrint()); fail(HEALTH_URL + " returned " + response.prettyPrint()); } } @@ -119,9 +116,8 @@ public class Utils { try { LOG.info("Logging in, for integration test..."); // system.out.println("-----------------------------------LOGIN-----------------------------------------"); - String json = RestAssured.given().contentType(ContentType.JSON) - .body("{\"username\":\"mifos\", \"password\":\"password\"}").expect().log().ifError().when() - .post(LOGIN_URL).asString(); + String json = RestAssured.given().contentType(ContentType.JSON).body("{\"username\":\"mifos\", \"password\":\"password\"}") + .expect().log().ifError().when().post(LOGIN_URL).asString(); assertThat("Failed to login into fineract platform", StringUtils.isBlank(json), is(false)); String key = JsonPath.with(json).get("base64EncodedAuthenticationKey"); assertThat("Failed to obtain key: " + json, StringUtils.isBlank(key), is(false)); @@ -136,63 +132,53 @@ public class Utils { } } - public static T performServerGet(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String getURL, final String jsonAttributeToGetBack) { - final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL) + public static T performServerGet(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String getURL, final String jsonAttributeToGetBack) { + final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); + if (jsonAttributeToGetBack == null) { return (T) json; } + return (T) from(json).get(jsonAttributeToGetBack); + } + + public static String performGetTextResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String getURL) { + return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); + } + + public static byte[] performGetBinaryResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String getURL) { + return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asByteArray(); + } + + public static T performServerPost(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String postURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { + final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().post(postURL) .andReturn().asString(); - if (jsonAttributeToGetBack == null) { - return (T) json; - } + if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } - public static String performGetTextResponse(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String getURL) { - return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn() + public static T performServerPut(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String putURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { + final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().put(putURL) + .andReturn().asString(); + return (T) from(json).get(jsonAttributeToGetBack); + } + + public static T performServerDelete(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String deleteURL, final String jsonAttributeToGetBack) { + final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().delete(deleteURL).andReturn() .asString(); - } - - public static byte[] performGetBinaryResponse(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String getURL) { - return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn() - .asByteArray(); - } - - public static T performServerPost(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String postURL, final String jsonBodyToSend, - final String jsonAttributeToGetBack) { - final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError() - .when().post(postURL).andReturn().asString(); - if (jsonAttributeToGetBack == null) { - return (T) json; - } return (T) from(json).get(jsonAttributeToGetBack); } - public static T performServerPut(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String putURL, final String jsonBodyToSend, - final String jsonAttributeToGetBack) { - final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError() - .when().put(putURL).andReturn().asString(); - return (T) from(json).get(jsonAttributeToGetBack); - } - - public static T performServerDelete(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String deleteURL, final String jsonAttributeToGetBack) { - final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when() + public static T performServerDelete(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String deleteURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { + final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when() .delete(deleteURL).andReturn().asString(); - return (T) from(json).get(jsonAttributeToGetBack); - } - - public static T performServerDelete(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String deleteURL, final String jsonBodyToSend, - final String jsonAttributeToGetBack) { - final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError() - .when().delete(deleteURL).andReturn().asString(); return (T) (jsonAttributeToGetBack == null ? json : from(json).get(jsonAttributeToGetBack)); } - public static String convertDateToURLFormat(final String dateToBeConvert) throws ParseException{ + public static String convertDateToURLFormat(final String dateToBeConvert) throws ParseException { final SimpleDateFormat oldFormat = new SimpleDateFormat("dd MMMMMM yyyy", Locale.US); final SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); String reformattedStr = ""; @@ -250,20 +236,19 @@ public class Utils { return TimeZone.getTimeZone(TENANT_TIME_ZONE); } - public static String performServerTemplatePost(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String postURL, final String legalFormType, final File file, - final String locale, final String dateFormat) { + public static String performServerTemplatePost(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String postURL, final String legalFormType, final File file, final String locale, final String dateFormat) { - final String importDocumentId = given().spec(requestSpec).queryParam("legalFormType", legalFormType) - .multiPart("file", file).formParam("locale", locale).formParam("dateFormat", dateFormat).expect() - .spec(responseSpec).log().ifError().when().post(postURL).andReturn().asString(); + final String importDocumentId = given().spec(requestSpec).queryParam("legalFormType", legalFormType).multiPart("file", file) + .formParam("locale", locale).formParam("dateFormat", dateFormat).expect().spec(responseSpec).log().ifError().when() + .post(postURL).andReturn().asString(); return importDocumentId; } public static String performServerOutputTemplateLocationGet(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL, final String importDocumentId) { - final String templateLocation = given().spec(requestSpec).queryParam("importDocumentId", importDocumentId) - .expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); + final String templateLocation = given().spec(requestSpec).queryParam("importDocumentId", importDocumentId).expect() + .spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); return templateLocation.substring(1, templateLocation.length() - 1); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/WorkingDaysHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/WorkingDaysHelper.java old mode 100755 new mode 100644 index 9529a78a3..df14bb8b0 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/WorkingDaysHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/WorkingDaysHelper.java @@ -27,6 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WorkingDaysHelper { + private final static Logger LOG = LoggerFactory.getLogger(WorkingDaysHelper.class); private static final String WORKINGDAYS_URL = "/fineract-provider/api/v1/workingdays"; @@ -50,7 +51,7 @@ public class WorkingDaysHelper { map.put("locale", "en"); map.put("repaymentRescheduleType", new Random().nextInt(4) + 1); map.put("extendTermForDailyRepayments", false); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } @@ -60,7 +61,7 @@ public class WorkingDaysHelper { map.put("locale", "en"); map.put("repaymentRescheduleType", new Random().nextInt(4) + 1); map.put("extendTermForDailyRepayments", false); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } @@ -69,7 +70,8 @@ public class WorkingDaysHelper { return (int) workingDays.get("id"); } - public static HashMap getAllWorkingDays(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + public static HashMap getAllWorkingDays(final RequestSpecification requestSpec, + final ResponseSpecification responseSpec) { return Utils.performServerGet(requestSpec, responseSpec, WORKINGDAYS_URL + "?" + Utils.TENANT_IDENTIFIER, ""); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/Account.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/Account.java index 2cb9de035..936fee0a5 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/Account.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/Account.java @@ -21,6 +21,7 @@ package org.apache.fineract.integrationtests.common.accounting; public class Account { public enum AccountType { + ASSET("1"), INCOME("4"), EXPENSE("5"), LIABILITY("2"), EQUITY("3"); private final String accountValue; diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/AccountHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/AccountHelper.java index 3c61b17c7..585217352 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/AccountHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/AccountHelper.java @@ -40,22 +40,22 @@ public class AccountHelper { public Account createAssetAccount() { final String assetAccountJSON = new GLAccountBuilder().withAccountTypeAsAsset().build(); - final Integer accountID = Utils.performServerPost(this.requestSpec, this.responseSpec, this.CREATE_GL_ACCOUNT_URL, - assetAccountJSON, this.GL_ACCOUNT_ID_RESPONSE); + final Integer accountID = Utils.performServerPost(this.requestSpec, this.responseSpec, this.CREATE_GL_ACCOUNT_URL, assetAccountJSON, + this.GL_ACCOUNT_ID_RESPONSE); return new Account(accountID, Account.AccountType.ASSET); } public Account createIncomeAccount() { final String assetAccountJSON = new GLAccountBuilder().withAccountTypeAsIncome().build(); - final Integer accountID = Utils.performServerPost(this.requestSpec, this.responseSpec, this.CREATE_GL_ACCOUNT_URL, - assetAccountJSON, this.GL_ACCOUNT_ID_RESPONSE); + final Integer accountID = Utils.performServerPost(this.requestSpec, this.responseSpec, this.CREATE_GL_ACCOUNT_URL, assetAccountJSON, + this.GL_ACCOUNT_ID_RESPONSE); return new Account(accountID, Account.AccountType.INCOME); } public Account createExpenseAccount() { final String assetAccountJSON = new GLAccountBuilder().withAccountTypeAsExpense().build(); - final Integer accountID = Utils.performServerPost(this.requestSpec, this.responseSpec, this.CREATE_GL_ACCOUNT_URL, - assetAccountJSON, this.GL_ACCOUNT_ID_RESPONSE); + final Integer accountID = Utils.performServerPost(this.requestSpec, this.responseSpec, this.CREATE_GL_ACCOUNT_URL, assetAccountJSON, + this.GL_ACCOUNT_ID_RESPONSE); return new Account(accountID, Account.AccountType.EXPENSE); } @@ -68,7 +68,8 @@ public class AccountHelper { public ArrayList getAccountingWithRunningBalances() { final String GET_RUNNING_BALANCE_URL = "/fineract-provider/api/v1/glaccounts?fetchRunningBalance=true"; - final ArrayList accountRunningBalance = Utils.performServerGet(this.requestSpec, this.responseSpec, GET_RUNNING_BALANCE_URL, ""); + final ArrayList accountRunningBalance = Utils.performServerGet(this.requestSpec, this.responseSpec, + GET_RUNNING_BALANCE_URL, ""); return accountRunningBalance; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/FinancialActivityAccountHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/FinancialActivityAccountHelper.java old mode 100755 new mode 100644 index 6a481bea7..36a18dd79 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/FinancialActivityAccountHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/FinancialActivityAccountHelper.java @@ -37,18 +37,19 @@ public class FinancialActivityAccountHelper { public Object createFinancialActivityAccount(Integer financialActivityId, Integer glAccountId, final ResponseSpecification responseSpecification, String jsonBack) { String json = FinancialActivityAccountsMappingBuilder.build(financialActivityId, glAccountId); - return Utils.performServerPost(this.requestSpec, responseSpecification, FINANCIAL_ACTIVITY_ACCOUNT_MAPPING_URL + "?" - + Utils.TENANT_IDENTIFIER, json, jsonBack); + return Utils.performServerPost(this.requestSpec, responseSpecification, + FINANCIAL_ACTIVITY_ACCOUNT_MAPPING_URL + "?" + Utils.TENANT_IDENTIFIER, json, jsonBack); } public Object updateFinancialActivityAccount(Integer financialActivityAccountId, Integer financialActivityId, Integer glAccountId, final ResponseSpecification responseSpecification, String jsonBack) { String json = FinancialActivityAccountsMappingBuilder.build(financialActivityId, glAccountId); - return Utils.performServerPut(this.requestSpec, responseSpecification, FINANCIAL_ACTIVITY_ACCOUNT_MAPPING_URL + "/" - + financialActivityAccountId + "?" + Utils.TENANT_IDENTIFIER, json, jsonBack); + return Utils.performServerPut(this.requestSpec, responseSpecification, + FINANCIAL_ACTIVITY_ACCOUNT_MAPPING_URL + "/" + financialActivityAccountId + "?" + Utils.TENANT_IDENTIFIER, json, jsonBack); } - public HashMap getFinancialActivityAccount(final Integer financialActivityAccountId, final ResponseSpecification responseSpecification) { + public HashMap getFinancialActivityAccount(final Integer financialActivityAccountId, + final ResponseSpecification responseSpecification) { final String url = FINANCIAL_ACTIVITY_ACCOUNT_MAPPING_URL + "/" + financialActivityAccountId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpecification, url, ""); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/JournalEntry.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/JournalEntry.java index bbfd8fd49..6d7cd7d15 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/JournalEntry.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/accounting/JournalEntry.java @@ -21,6 +21,7 @@ package org.apache.fineract.integrationtests.common.accounting; public class JournalEntry { public enum TransactionType { + CREDIT("CREDIT"), DEBIT("DEBIT"); private TransactionType(final String type) { diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/charges/ChargesHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/charges/ChargesHelper.java old mode 100755 new mode 100644 index 352b3cdc8..bbb659278 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/charges/ChargesHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/charges/ChargesHelper.java @@ -31,6 +31,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "rawtypes", "unchecked" }) public class ChargesHelper { + private final static Logger LOG = LoggerFactory.getLogger(ChargesHelper.class); private static final String CHARGES_URL = "/fineract-provider/api/v1/charges"; private static final String CREATE_CHARGES_URL = CHARGES_URL + "?" + Utils.TENANT_IDENTIFIER; @@ -168,14 +169,11 @@ public class ChargesHelper { return getLoanDisbursementJSON(chargeCalculationType, amount, ChargesHelper.CHARGE_PAYMENT_MODE_REGULAR); } - public static String getLoanDisbursementAccountTransferJSON(final Integer chargeCalculationType, - final String amount) { - return getLoanDisbursementJSON(chargeCalculationType, amount, - ChargesHelper.CHARGE_PAYMENT_MODE_ACCOUNT_TRANSFER); + public static String getLoanDisbursementAccountTransferJSON(final Integer chargeCalculationType, final String amount) { + return getLoanDisbursementJSON(chargeCalculationType, amount, ChargesHelper.CHARGE_PAYMENT_MODE_ACCOUNT_TRANSFER); } - public static String getLoanDisbursementJSON(final Integer chargeCalculationType, final String amount, - final Integer paymentmode) { + public static String getLoanDisbursementJSON(final Integer chargeCalculationType, final String amount, final Integer paymentmode) { final HashMap map = populateDefaultsForLoan(); map.put("chargeTimeType", CHARGE_DISBURSEMENT_FEE); map.put("chargePaymentMode", paymentmode); @@ -187,18 +185,15 @@ public class ChargesHelper { } public static String getLoanSpecifiedDueDateJSON() { - return getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, ChargesHelper.AMOUNT, - ChargesHelper.PENALTY); + return getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, ChargesHelper.AMOUNT, ChargesHelper.PENALTY); } - public static String getLoanSpecifiedDueDateJSON(final Integer chargeCalculationType, final String amount, - boolean penalty) { - return getLoanSpecifiedDueDateJSON(chargeCalculationType, amount, penalty, - ChargesHelper.CHARGE_PAYMENT_MODE_REGULAR); + public static String getLoanSpecifiedDueDateJSON(final Integer chargeCalculationType, final String amount, boolean penalty) { + return getLoanSpecifiedDueDateJSON(chargeCalculationType, amount, penalty, ChargesHelper.CHARGE_PAYMENT_MODE_REGULAR); } - public static String getLoanSpecifiedDueDateJSON(final Integer chargeCalculationType, final String amount, - final boolean penalty, final Integer paymentMode) { + public static String getLoanSpecifiedDueDateJSON(final Integer chargeCalculationType, final String amount, final boolean penalty, + final Integer paymentMode) { final HashMap map = populateDefaultsForLoan(); map.put("chargeTimeType", CHARGE_SPECIFIED_DUE_DATE); map.put("chargePaymentMode", paymentMode); @@ -211,25 +206,22 @@ public class ChargesHelper { return chargesCreateJson; } - public static String getLoanSpecifiedDueDateWithAccountTransferJSON(final Integer chargeCalculationType, - final String amount, boolean penalty) { - return getLoanSpecifiedDueDateJSON(chargeCalculationType, amount, penalty, - ChargesHelper.CHARGE_PAYMENT_MODE_ACCOUNT_TRANSFER); + public static String getLoanSpecifiedDueDateWithAccountTransferJSON(final Integer chargeCalculationType, final String amount, + boolean penalty) { + return getLoanSpecifiedDueDateJSON(chargeCalculationType, amount, penalty, ChargesHelper.CHARGE_PAYMENT_MODE_ACCOUNT_TRANSFER); } public static String getLoanSpecifiedDueDateWithAccountTransferJSON() { - return getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, ChargesHelper.AMOUNT, - ChargesHelper.PENALTY, ChargesHelper.CHARGE_PAYMENT_MODE_ACCOUNT_TRANSFER); + return getLoanSpecifiedDueDateJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, ChargesHelper.AMOUNT, ChargesHelper.PENALTY, + ChargesHelper.CHARGE_PAYMENT_MODE_ACCOUNT_TRANSFER); } - public static String getLoanInstallmentJSON(final Integer chargeCalculationType, final String amount, - boolean penalty) { - return getLoanInstallmentJSON(chargeCalculationType, amount, penalty, - ChargesHelper.CHARGE_PAYMENT_MODE_REGULAR); + public static String getLoanInstallmentJSON(final Integer chargeCalculationType, final String amount, boolean penalty) { + return getLoanInstallmentJSON(chargeCalculationType, amount, penalty, ChargesHelper.CHARGE_PAYMENT_MODE_REGULAR); } - public static String getLoanInstallmentJSON(final Integer chargeCalculationType, final String amount, - final boolean penalty, final Integer paymentMode) { + public static String getLoanInstallmentJSON(final Integer chargeCalculationType, final String amount, final boolean penalty, + final Integer paymentMode) { final HashMap map = populateDefaultsForLoan(); map.put("chargeTimeType", CHARGE_INSTALLMENT_FEE); map.put("chargePaymentMode", paymentMode); @@ -242,15 +234,13 @@ public class ChargesHelper { return chargesCreateJson; } - public static String getLoanInstallmentWithAccountTransferJSON(final Integer chargeCalculationType, - final String amount, boolean penalty) { - return getLoanInstallmentJSON(chargeCalculationType, amount, penalty, - ChargesHelper.CHARGE_PAYMENT_MODE_ACCOUNT_TRANSFER); + public static String getLoanInstallmentWithAccountTransferJSON(final Integer chargeCalculationType, final String amount, + boolean penalty) { + return getLoanInstallmentJSON(chargeCalculationType, amount, penalty, ChargesHelper.CHARGE_PAYMENT_MODE_ACCOUNT_TRANSFER); } public static String getLoanInstallmentFeeJSON() { - return getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, ChargesHelper.AMOUNT, - ChargesHelper.PENALTY); + return getLoanInstallmentJSON(ChargesHelper.CHARGE_CALCULATION_TYPE_FLAT, ChargesHelper.AMOUNT, ChargesHelper.PENALTY); } public static String getShareAccountActivationChargeJson() { @@ -365,40 +355,36 @@ public class ChargesHelper { return map; } - public static Integer createCharges(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String request) { + public static Integer createCharges(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String request) { return Utils.performServerPost(requestSpec, responseSpec, CREATE_CHARGES_URL, request, "resourceId"); } - public static ArrayList getCharges(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { - return (ArrayList) Utils.performServerGet(requestSpec, responseSpec, - CHARGES_URL + "?" + Utils.TENANT_IDENTIFIER, ""); + public static ArrayList getCharges(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + return (ArrayList) Utils.performServerGet(requestSpec, responseSpec, CHARGES_URL + "?" + Utils.TENANT_IDENTIFIER, ""); } - public static HashMap getChargeById(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer chargeId) { - return Utils.performServerGet(requestSpec, responseSpec, - CHARGES_URL + "/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, ""); + public static HashMap getChargeById(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer chargeId) { + return Utils.performServerGet(requestSpec, responseSpec, CHARGES_URL + "/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, ""); } - public static HashMap getChargeChanges(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer chargeId) { - return Utils.performServerGet(requestSpec, responseSpec, - CHARGES_URL + "/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, CommonConstants.RESPONSE_CHANGES); + public static HashMap getChargeChanges(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer chargeId) { + return Utils.performServerGet(requestSpec, responseSpec, CHARGES_URL + "/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, + CommonConstants.RESPONSE_CHANGES); } - public static HashMap updateCharges(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer chargeId, final String request) { - return Utils.performServerPut(requestSpec, responseSpec, - CHARGES_URL + "/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, request, + public static HashMap updateCharges(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer chargeId, final String request) { + return Utils.performServerPut(requestSpec, responseSpec, CHARGES_URL + "/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, request, CommonConstants.RESPONSE_CHANGES); } public static Integer deleteCharge(final ResponseSpecification responseSpec, final RequestSpecification requestSpec, final Integer chargeId) { - return Utils.performServerDelete(requestSpec, responseSpec, - CHARGES_URL + "/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, CommonConstants.RESPONSE_RESOURCE_ID); + return Utils.performServerDelete(requestSpec, responseSpec, CHARGES_URL + "/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, + CommonConstants.RESPONSE_RESOURCE_ID); } public static String getModifyChargeJSON() { @@ -496,10 +482,9 @@ public class ChargesHelper { return chargesCreateJson; } - public static String applyCharge(RequestSpecification requestSpec, ResponseSpecification responseSpec, - String chargeId, String json) { - return Utils.performServerPost(requestSpec, responseSpec, - CHARGES_URL + "/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, json, "status"); + public static String applyCharge(RequestSpecification requestSpec, ResponseSpecification responseSpec, String chargeId, String json) { + return Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL + "/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, json, + "status"); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositAccountHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositAccountHelper.java index 80e3f863d..87726e1c7 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositAccountHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositAccountHelper.java @@ -31,6 +31,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "unused", "rawtypes" }) public class FixedDepositAccountHelper { + private final static Logger LOG = LoggerFactory.getLogger(FixedDepositAccountHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; @@ -41,8 +42,7 @@ public class FixedDepositAccountHelper { } private static final String FIXED_DEPOSIT_ACCOUNT_URL = "/fineract-provider/api/v1/fixeddepositaccounts"; - private static final String APPLY_FIXED_DEPOSIT_ACCOUNT_URL = FIXED_DEPOSIT_ACCOUNT_URL + "?" - + Utils.TENANT_IDENTIFIER; + private static final String APPLY_FIXED_DEPOSIT_ACCOUNT_URL = FIXED_DEPOSIT_ACCOUNT_URL + "?" + Utils.TENANT_IDENTIFIER; private static final String APPROVE_FIXED_DEPOSIT_COMMAND = "approve"; private static final String UNDO_APPROVAL_FIXED_DEPOSIT_COMMAND = "undoapproval"; private static final String REJECT_FIXED_DEPOSIT_COMMAND = "reject"; @@ -135,17 +135,16 @@ public class FixedDepositAccountHelper { return fixedDepositAccountJson; } - public static Integer applyFixedDepositApplication(final String fixedDepositAccountAsJson, - final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + public static Integer applyFixedDepositApplication(final String fixedDepositAccountAsJson, final RequestSpecification requestSpec, + final ResponseSpecification responseSpec) { LOG.info("--------------------- APPLYING FOR FIXED DEPOSIT ACCOUNT ------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, APPLY_FIXED_DEPOSIT_ACCOUNT_URL, - fixedDepositAccountAsJson, CommonConstants.RESPONSE_RESOURCE_ID); + return Utils.performServerPost(requestSpec, responseSpec, APPLY_FIXED_DEPOSIT_ACCOUNT_URL, fixedDepositAccountAsJson, + CommonConstants.RESPONSE_RESOURCE_ID); } - public static HashMap getFixedDepositAccountById(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer accountID) { - final String GET_FIXED_DEPOSIT_BY_ID_URL = FIXED_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" - + Utils.TENANT_IDENTIFIER; + public static HashMap getFixedDepositAccountById(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer accountID) { + final String GET_FIXED_DEPOSIT_BY_ID_URL = FIXED_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" + Utils.TENANT_IDENTIFIER; LOG.info("------------------------ RETRIEVING FIXED DEPOSIT ACCOUNT BY ID -------------------------"); return Utils.performServerGet(requestSpec, responseSpec, GET_FIXED_DEPOSIT_BY_ID_URL, ""); } @@ -179,8 +178,8 @@ public class FixedDepositAccountHelper { return annualInterestRate; } - public static Float getPrincipalAfterCompoundingInterest(Calendar currentDate, Float principal, - Integer depositPeriod, double interestPerDay, Integer compoundingInterval, Integer postingInterval) { + public static Float getPrincipalAfterCompoundingInterest(Calendar currentDate, Float principal, Integer depositPeriod, + double interestPerDay, Integer compoundingInterval, Integer postingInterval) { Float totalInterest = 0.0f; Float interestEarned = 0.0f; @@ -209,23 +208,22 @@ public class FixedDepositAccountHelper { return principal; } - public HashMap updateFixedDepositAccount(final String clientID, final String productID, final String accountID, - final String validFrom, final String validTo, final String penalInterestType, - final String submittedOnDate) { + public HashMap updateFixedDepositAccount(final String clientID, final String productID, final String accountID, final String validFrom, + final String validTo, final String penalInterestType, final String submittedOnDate) { final String fixedDepositApplicationJSON = new FixedDepositAccountHelper(this.requestSpec, this.responseSpec) // .withSubmittedOnDate(submittedOnDate) // .build(clientID, productID, penalInterestType); return Utils.performServerPut(this.requestSpec, this.responseSpec, - FIXED_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" + Utils.TENANT_IDENTIFIER, - fixedDepositApplicationJSON, CommonConstants.RESPONSE_CHANGES); + FIXED_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" + Utils.TENANT_IDENTIFIER, fixedDepositApplicationJSON, + CommonConstants.RESPONSE_CHANGES); } - public HashMap updateInterestCalculationConfigForFixedDeposit(final String clientID, final String productID, - final String accountID, final String submittedOnDate, final String validFrom, final String validTo, - final String numberOfDaysPerYear, final String penalInterestType, final String interestCalculationType, - final String interestCompoundingPeriodType, final String interestPostingPeriodType) { + public HashMap updateInterestCalculationConfigForFixedDeposit(final String clientID, final String productID, final String accountID, + final String submittedOnDate, final String validFrom, final String validTo, final String numberOfDaysPerYear, + final String penalInterestType, final String interestCalculationType, final String interestCompoundingPeriodType, + final String interestPostingPeriodType) { final String fixedDepositApplicationJSON = new FixedDepositAccountHelper(this.requestSpec, this.responseSpec) // .withSubmittedOnDate(submittedOnDate) // @@ -236,63 +234,51 @@ public class FixedDepositAccountHelper { .build(clientID, productID, penalInterestType); return Utils.performServerPut(this.requestSpec, this.responseSpec, - FIXED_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" + Utils.TENANT_IDENTIFIER, - fixedDepositApplicationJSON, CommonConstants.RESPONSE_CHANGES); + FIXED_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" + Utils.TENANT_IDENTIFIER, fixedDepositApplicationJSON, + CommonConstants.RESPONSE_CHANGES); } public HashMap approveFixedDeposit(final Integer fixedDepositAccountID, final String approvedOnDate) { - LOG.info( - "--------------------------------- APPROVING FIXED DEPOSIT APPLICATION ------------------------------------"); - return performFixedDepositApplicationActions( - createFixedDepositOperationURL(APPROVE_FIXED_DEPOSIT_COMMAND, fixedDepositAccountID), + LOG.info("--------------------------------- APPROVING FIXED DEPOSIT APPLICATION ------------------------------------"); + return performFixedDepositApplicationActions(createFixedDepositOperationURL(APPROVE_FIXED_DEPOSIT_COMMAND, fixedDepositAccountID), getApproveFixedDepositAccountAsJSON(approvedOnDate)); } public HashMap undoApproval(final Integer fixedDepositAccountID) { - LOG.info( - "--------------------------------- UNDO APPROVING FIXED DEPOSIT APPLICATION -------------------------------"); + LOG.info("--------------------------------- UNDO APPROVING FIXED DEPOSIT APPLICATION -------------------------------"); final String undoBodyJson = "{'note':'UNDO APPROVAL'}"; return performFixedDepositApplicationActions( - createFixedDepositOperationURL(UNDO_APPROVAL_FIXED_DEPOSIT_COMMAND, fixedDepositAccountID), - undoBodyJson); + createFixedDepositOperationURL(UNDO_APPROVAL_FIXED_DEPOSIT_COMMAND, fixedDepositAccountID), undoBodyJson); } public HashMap rejectApplication(final Integer fixedDepositAccountID, final String rejectedOnDate) { LOG.info("--------------------------------- REJECT FIXED DEPOSIT APPLICATION -------------------------------"); - return performFixedDepositApplicationActions( - createFixedDepositOperationURL(REJECT_FIXED_DEPOSIT_COMMAND, fixedDepositAccountID), + return performFixedDepositApplicationActions(createFixedDepositOperationURL(REJECT_FIXED_DEPOSIT_COMMAND, fixedDepositAccountID), getRejectedFixedDepositAsJSON(rejectedOnDate)); } public HashMap withdrawApplication(final Integer fixedDepositAccountID, final String withdrawApplicationOnDate) { - LOG.info( - "--------------------------------- Withdraw FIXED DEPOSIT APPLICATION -------------------------------"); + LOG.info("--------------------------------- Withdraw FIXED DEPOSIT APPLICATION -------------------------------"); return performFixedDepositApplicationActions( createFixedDepositOperationURL(WITHDRAWN_BY_CLIENT_FIXED_DEPOSIT_COMMAND, fixedDepositAccountID), getWithdrawnFixedDepositAccountAsJSON(withdrawApplicationOnDate)); } public HashMap activateFixedDeposit(final Integer fixedDepositAccountID, final String activationDate) { - LOG.info( - "---------------------------------- ACTIVATING FIXED DEPOSIT APPLICATION ----------------------------------"); - return performFixedDepositApplicationActions( - createFixedDepositOperationURL(ACTIVATE_FIXED_DEPOSIT_COMMAND, fixedDepositAccountID), + LOG.info("---------------------------------- ACTIVATING FIXED DEPOSIT APPLICATION ----------------------------------"); + return performFixedDepositApplicationActions(createFixedDepositOperationURL(ACTIVATE_FIXED_DEPOSIT_COMMAND, fixedDepositAccountID), getActivatedFixedDepositAccountAsJSON(activationDate)); } - public Object deleteFixedDepositApplication(final Integer fixedDepositAccountID, - final String jsonAttributeToGetBack) { - LOG.info( - "---------------------------------- DELETE FIXED DEPOSIT APPLICATION ----------------------------------"); + public Object deleteFixedDepositApplication(final Integer fixedDepositAccountID, final String jsonAttributeToGetBack) { + LOG.info("---------------------------------- DELETE FIXED DEPOSIT APPLICATION ----------------------------------"); return Utils.performServerDelete(this.requestSpec, this.responseSpec, - FIXED_DEPOSIT_ACCOUNT_URL + "/" + fixedDepositAccountID + "?" + Utils.TENANT_IDENTIFIER, - jsonAttributeToGetBack); + FIXED_DEPOSIT_ACCOUNT_URL + "/" + fixedDepositAccountID + "?" + Utils.TENANT_IDENTIFIER, jsonAttributeToGetBack); } public Integer calculateInterestForFixedDeposit(final Integer fixedDepositAccountId) { - LOG.info( - "--------------------------------- CALCULATING INTEREST FOR FIXED DEPOSIT --------------------------------"); + LOG.info("--------------------------------- CALCULATING INTEREST FOR FIXED DEPOSIT --------------------------------"); return (Integer) performFixedDepositActions( createFixedDepositCalculateInterestURL(CALCULATE_INTEREST_FIXED_DEPOSIT_COMMAND, fixedDepositAccountId), getCalculatedInterestForFixedDepositApplicationAsJSON(), CommonConstants.RESPONSE_RESOURCE_ID); @@ -305,21 +291,18 @@ public class FixedDepositAccountHelper { getCalculatedInterestForFixedDepositApplicationAsJSON(), CommonConstants.RESPONSE_RESOURCE_ID); } - public HashMap calculatePrematureAmountForFixedDeposit(final Integer fixedDepositAccountId, - final String closedOnDate) { + public HashMap calculatePrematureAmountForFixedDeposit(final Integer fixedDepositAccountId, final String closedOnDate) { LOG.info("--------------------- CALCULATING PREMATURE AMOUNT FOR FIXED DEPOSIT ----------------------------"); return (HashMap) performFixedDepositActions( createFixedDepositCalculateInterestURL(CALCULATE_PREMATURE_AMOUNT_COMMAND, fixedDepositAccountId), getCalculatedPrematureAmountForFixedDepositAccountAsJSON(closedOnDate), ""); } - public Object prematureCloseForFixedDeposit(final Integer fixedDepositAccountId, final String closedOnDate, - final String closureType, final Integer toSavingsId, final String jsonAttributeToGetBack) { + public Object prematureCloseForFixedDeposit(final Integer fixedDepositAccountId, final String closedOnDate, final String closureType, + final Integer toSavingsId, final String jsonAttributeToGetBack) { LOG.info("--------------------- PREMATURE CLOSE FOR FIXED DEPOSIT ----------------------------"); - return performFixedDepositActions( - createFixedDepositCalculateInterestURL(PREMATURE_CLOSE_COMMAND, fixedDepositAccountId), - getPrematureCloseForFixedDepositAccountAsJSON(closedOnDate, closureType, toSavingsId), - jsonAttributeToGetBack); + return performFixedDepositActions(createFixedDepositCalculateInterestURL(PREMATURE_CLOSE_COMMAND, fixedDepositAccountId), + getPrematureCloseForFixedDepositAccountAsJSON(closedOnDate, closureType, toSavingsId), jsonAttributeToGetBack); } private String getApproveFixedDepositAccountAsJSON(final String approvedOnDate) { @@ -399,21 +382,18 @@ public class FixedDepositAccountHelper { } private String createFixedDepositOperationURL(final String command, final Integer fixedDepositAccountID) { - return FIXED_DEPOSIT_ACCOUNT_URL + "/" + fixedDepositAccountID + "?command=" + command + "&" - + Utils.TENANT_IDENTIFIER; + return FIXED_DEPOSIT_ACCOUNT_URL + "/" + fixedDepositAccountID + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; } private Object performFixedDepositActions(final String postURLForFixedDeposit, final String jsonToBeSent, final String jsonAttributeToGetBack) { - return Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForFixedDeposit, jsonToBeSent, - jsonAttributeToGetBack); + return Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForFixedDeposit, jsonToBeSent, jsonAttributeToGetBack); } - private HashMap performFixedDepositApplicationActions(final String postURLForFixedDepositAction, - final String jsonToBeSent) { + private HashMap performFixedDepositApplicationActions(final String postURLForFixedDepositAction, final String jsonToBeSent) { HashMap status = null; - final HashMap response = Utils.performServerPost(this.requestSpec, this.responseSpec, - postURLForFixedDepositAction, jsonToBeSent, CommonConstants.RESPONSE_CHANGES); + final HashMap response = Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForFixedDepositAction, jsonToBeSent, + CommonConstants.RESPONSE_CHANGES); if (response != null) { status = (HashMap) response.get("status"); } @@ -421,8 +401,7 @@ public class FixedDepositAccountHelper { } private String createFixedDepositCalculateInterestURL(final String command, final Integer fixedDepositAccountID) { - return FIXED_DEPOSIT_ACCOUNT_URL + "/" + fixedDepositAccountID + "?command=" + command + "&" - + Utils.TENANT_IDENTIFIER; + return FIXED_DEPOSIT_ACCOUNT_URL + "/" + fixedDepositAccountID + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; } public static ArrayList retrieveAllFixedDepositAccounts(final RequestSpecification requestSpec, @@ -486,14 +465,12 @@ public class FixedDepositAccountHelper { } private String getDepositAmount() { - if (this.newDepositAmount == null) { - return DEPOSIT_AMOUNT; - } + if (this.newDepositAmount == null) { return DEPOSIT_AMOUNT; } return this.newDepositAmount; } - public FixedDepositAccountHelper withMaturityInstructionId(Integer maturityInstructionId){ + public FixedDepositAccountHelper withMaturityInstructionId(Integer maturityInstructionId) { this.maturityInstructionId = maturityInstructionId; return this; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositAccountStatusChecker.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositAccountStatusChecker.java index ef9637e72..68ba676d9 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositAccountStatusChecker.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositAccountStatusChecker.java @@ -30,6 +30,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings("rawtypes") public class FixedDepositAccountStatusChecker { + private final static Logger LOG = LoggerFactory.getLogger(FixedDepositAccountStatusChecker.class); private static final String FIXED_DEPOSIT_ACCOUNT_URL = "/fineract-provider/api/v1/fixeddepositaccounts"; @@ -41,8 +42,7 @@ public class FixedDepositAccountStatusChecker { public static void verifyFixedDepositIsPending(final HashMap fixedDepositStatusHashMap) { LOG.info("-------------------- VERIFYING FIXED DEPOSIT APPLICATION IS PENDING --------------------"); - assertTrue(getStatus(fixedDepositStatusHashMap, "submittedAndPendingApproval"), - "FIXED DEPOSIT ACCOUNT IS NOT IN PENDING STATE"); + assertTrue(getStatus(fixedDepositStatusHashMap, "submittedAndPendingApproval"), "FIXED DEPOSIT ACCOUNT IS NOT IN PENDING STATE"); LOG.info("{}", fixedDepositStatusHashMap.toString()); } @@ -54,15 +54,13 @@ public class FixedDepositAccountStatusChecker { public static void verifyFixedDepositIsRejected(final HashMap fixedDepositStatusHashMap) { LOG.info("-------------- VERIFYING FIXED DEPOSIT APPLICATION IS REJECTED ----------------"); - assertTrue(getStatus(fixedDepositStatusHashMap, "rejected"), - "ERROR IN REJECTING THE FIXED DEPOSIT APPLICATION"); + assertTrue(getStatus(fixedDepositStatusHashMap, "rejected"), "ERROR IN REJECTING THE FIXED DEPOSIT APPLICATION"); LOG.info("{}", fixedDepositStatusHashMap.toString()); } public static void verifyFixedDepositIsWithdrawn(final HashMap fixedDepositStatusHashMap) { LOG.info("---------------- VERIFYING FIXED DEPOSIT APPLICATION IS WITHDRAWN ----------------"); - assertTrue(getStatus(fixedDepositStatusHashMap, "withdrawnByApplicant"), - "ERROR IN WITHDRAW THE FIXED DEPOSIT APPLICATION"); + assertTrue(getStatus(fixedDepositStatusHashMap, "withdrawnByApplicant"), "ERROR IN WITHDRAW THE FIXED DEPOSIT APPLICATION"); LOG.info("{}", fixedDepositStatusHashMap.toString()); } @@ -78,28 +76,26 @@ public class FixedDepositAccountStatusChecker { LOG.info("{}", fixedDepositStatusHashMap.toString()); } - public static HashMap getStatusOfFixedDepositAccount(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String fixedDepositAccountID) { - final String GET_STATUS_OF_FIXED_DEPOSIT_ACCOUNT_URL = FIXED_DEPOSIT_ACCOUNT_URL + "/" + fixedDepositAccountID - + "?" + Utils.TENANT_IDENTIFIER; + public static HashMap getStatusOfFixedDepositAccount(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String fixedDepositAccountID) { + final String GET_STATUS_OF_FIXED_DEPOSIT_ACCOUNT_URL = FIXED_DEPOSIT_ACCOUNT_URL + "/" + fixedDepositAccountID + "?" + + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, GET_STATUS_OF_FIXED_DEPOSIT_ACCOUNT_URL, "status"); } public static void verifyFixedDepositAccountIsPrematureClosed(HashMap fixedDepositStatusHashMap) { LOG.info("--------------------- VERIFYING FIXED DEPOSIT APPLICATION IS CLOSED ---------------------"); - assertTrue(getStatus(fixedDepositStatusHashMap, "prematureClosed"), - "ERROR IN PREMATURELY CLOSING THE FIXED DEPOSIT ACCOUNT"); + assertTrue(getStatus(fixedDepositStatusHashMap, "prematureClosed"), "ERROR IN PREMATURELY CLOSING THE FIXED DEPOSIT ACCOUNT"); LOG.info("{}", fixedDepositStatusHashMap.toString()); } public static void verifyFixedDepositAccountIsMatured(HashMap fixedDepositStatusHashMap) { LOG.info("--------------------- VERIFYING FIXED DEPOSIT APPLICATION IS MATURED ---------------------"); - assertTrue(getStatus(fixedDepositStatusHashMap, "matured"), - "ERROR IN MATURITY JOB OF THE FIXED DEPOSIT ACCOUNT"); + assertTrue(getStatus(fixedDepositStatusHashMap, "matured"), "ERROR IN MATURITY JOB OF THE FIXED DEPOSIT ACCOUNT"); LOG.info("{}", fixedDepositStatusHashMap.toString()); } private static boolean getStatus(final HashMap fixedDepositStatusMap, final String fixedDepositStatusString) { return (Boolean) fixedDepositStatusMap.get(fixedDepositStatusString); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositProductHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositProductHelper.java index 61687b444..0f8c81ef6 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositProductHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/fixeddeposit/FixedDepositProductHelper.java @@ -33,6 +33,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "unused", "rawtypes" }) public class FixedDepositProductHelper { + private final static Logger LOG = LoggerFactory.getLogger(FixedDepositProductHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; @@ -70,7 +71,6 @@ public class FixedDepositProductHelper { private static final String WHOLE_TERM = "1"; private static final String TILL_PREMATURE_WITHDRAWAL = "2"; - private String name = Utils.randomNameGenerator("FIXED_DEPOSIT_PRODUCT_", 6); private String shortName = Utils.randomNameGenerator("", 4); private String description = Utils.randomNameGenerator("", 20); @@ -142,14 +142,12 @@ public class FixedDepositProductHelper { map.put("taxGroupId", taxGroupId); } - - if (this.accountingRule.equals(CASH_BASED)) { map.putAll(getAccountMappingForCashBased()); } String FixedDepositProductCreateJson = new Gson().toJson(map); - LOG.info("{}",FixedDepositProductCreateJson); + LOG.info("{}", FixedDepositProductCreateJson); return FixedDepositProductCreateJson; } @@ -393,7 +391,6 @@ public class FixedDepositProductHelper { return this; } - private Map getAccountMappingForCashBased() { final Map map = new HashMap<>(); if (accountList != null) { @@ -428,10 +425,11 @@ public class FixedDepositProductHelper { CommonConstants.RESPONSE_RESOURCE_ID); } - public static ArrayList retrieveAllFixedDepositProducts(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + public static ArrayList retrieveAllFixedDepositProducts(final RequestSpecification requestSpec, + final ResponseSpecification responseSpec) { LOG.info("-------------------- RETRIEVING ALL FIXED DEPOSIT PRODUCTS ---------------------"); - final ArrayList response = Utils.performServerGet(requestSpec, responseSpec, FIXED_DEPOSIT_PRODUCT_URL + "?" - + Utils.TENANT_IDENTIFIER, ""); + final ArrayList response = Utils.performServerGet(requestSpec, responseSpec, + FIXED_DEPOSIT_PRODUCT_URL + "?" + Utils.TENANT_IDENTIFIER, ""); return response; } @@ -451,4 +449,4 @@ public class FixedDepositProductHelper { return response; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/funds/FundsHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/funds/FundsHelper.java index eed6ae54f..a7a345705 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/funds/FundsHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/funds/FundsHelper.java @@ -50,8 +50,7 @@ public class FundsHelper { super(); } - private FundsHelper(final String name, - final String externalId) { + private FundsHelper(final String name, final String externalId) { super(); this.name = name; this.externalId = externalId; @@ -83,27 +82,19 @@ public class FundsHelper { @Override public int hashCode() { - if (this.name != null) { - return this.name.hashCode(); - } + if (this.name != null) { return this.name.hashCode(); } return super.hashCode(); } @Override public boolean equals(Object o) { - if (o == this) { - return true; - } + if (o == this) { return true; } - if (!(o instanceof FundsHelper)) { - return false; - } + if (!(o instanceof FundsHelper)) { return false; } - FundsHelper fh = (FundsHelper)o; + FundsHelper fh = (FundsHelper) o; - if (this.name.equals(fh.name)) { - return true; - } + if (this.name.equals(fh.name)) { return true; } return false; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/funds/FundsResourceHandler.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/funds/FundsResourceHandler.java index 4335e4841..b2d299d13 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/funds/FundsResourceHandler.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/funds/FundsResourceHandler.java @@ -31,33 +31,26 @@ public class FundsResourceHandler { private static final String FUNDS_URL = "/fineract-provider/api/v1/funds"; private static final String CREATE_FUNDS_URL = FUNDS_URL + "?" + Utils.TENANT_IDENTIFIER; - public static Integer createFund(final String fundJSON, - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public static Integer createFund(final String fundJSON, final RequestSpecification requestSpec, + final ResponseSpecification responseSpec) { return Utils.performServerPost(requestSpec, responseSpec, CREATE_FUNDS_URL, fundJSON, "resourceId"); } - public static List retrieveAllFunds(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public static List retrieveAllFunds(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { final String URL = FUNDS_URL + "?" + Utils.TENANT_IDENTIFIER; List> list = Utils.performServerGet(requestSpec, responseSpec, URL, ""); final String jsonData = new Gson().toJson(list); - return new Gson().fromJson(jsonData, new TypeToken>(){}.getType()); + return new Gson().fromJson(jsonData, new TypeToken>() {}.getType()); } - public static String retrieveFund(final Long fundID, - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public static String retrieveFund(final Long fundID, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { final String URL = FUNDS_URL + "/" + fundID + "?" + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerGet(requestSpec, responseSpec, URL, ""); return new Gson().toJson(response); } - public static FundsHelper updateFund(final Long fundID, - final String newName, - final String newExternalId, - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public static FundsHelper updateFund(final Long fundID, final String newName, final String newExternalId, + final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { FundsHelper fh = FundsHelper.create(newName).externalId(newExternalId).build(); String updateJSON = new Gson().toJson(fh); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanApplicationTestBuilder.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanApplicationTestBuilder.java index 3001c6109..4d9c7af4f 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanApplicationTestBuilder.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanApplicationTestBuilder.java @@ -42,7 +42,6 @@ public class LoanApplicationTestBuilder { public static final String DEFAULT_STRATEGY = "1"; public static final String RBI_INDIA_STRATEGY = "4"; - private String principal = "10,000"; private String loanTermFrequency = ""; private String loanTermFrequencyType = ""; @@ -73,8 +72,7 @@ public class LoanApplicationTestBuilder { private String calendarId; private boolean syncDisbursementWithMeeting = false; private List> datatables = null; - private List> approvalFormData =null; - + private List> approvalFormData = null; public String build(final String clientID, final String groupID, final String loanProductId, final String savingsID) { final HashMap map = new HashMap<>(); @@ -88,11 +86,11 @@ public class LoanApplicationTestBuilder { } if ("glim".equals(this.loanType)) { - if (isParentAccount!=null){ + if (isParentAccount != null) { map.put("isParentAccount", this.isParentAccount); } - if (totalLoan!=null){ + if (totalLoan != null) { map.put("totalLoan", this.totalLoan); } } @@ -111,15 +109,14 @@ public class LoanApplicationTestBuilder { return build(map, loanProductId, savingsID); } - public String build() - { - final HashMap map = new HashMap<>(); + public String build() { + final HashMap map = new HashMap<>(); - if(this.approvalFormData != null) { - map.put("approvalFormData", this.approvalFormData) ; - } + if (this.approvalFormData != null) { + map.put("approvalFormData", this.approvalFormData); + } - String approvalFormData=new Gson().toJson(map); + String approvalFormData = new Gson().toJson(map); LOG.info("approvalFormData: {} ", approvalFormData); return approvalFormData; } @@ -314,8 +311,6 @@ public class LoanApplicationTestBuilder { return this; } - - public LoanApplicationTestBuilder withFirstRepaymentDate(final String firstRepaymentDate) { this.repaymentsStartingFromDate = firstRepaymentDate; return this; @@ -327,9 +322,9 @@ public class LoanApplicationTestBuilder { } public LoanApplicationTestBuilder withApprovalFormData(final List> approvalFormData) { - this.approvalFormData = new ArrayList<>(); - this.approvalFormData.addAll(approvalFormData); - return this; + this.approvalFormData = new ArrayList<>(); + this.approvalFormData.addAll(approvalFormData); + return this; } /** diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanDisbursementTestBuilder.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanDisbursementTestBuilder.java index 6ba736279..e2b78eb5e 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanDisbursementTestBuilder.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanDisbursementTestBuilder.java @@ -30,7 +30,7 @@ public class LoanDisbursementTestBuilder { Float principalOriginalDue = null; String fromDate = null; - public LoanDisbursementTestBuilder(String dueDate,Float totalOriginalDueForPeriod,Float totalOutstandingForPeriod, + public LoanDisbursementTestBuilder(String dueDate, Float totalOriginalDueForPeriod, Float totalOutstandingForPeriod, Float interestOutstanding, Float principalOutstanding, Float principalLoanBalanceOutstanding, Float principalDue, Float principalOriginalDue, String fromDate) { this.dueDate = dueDate; @@ -80,25 +80,29 @@ public class LoanDisbursementTestBuilder { return this.fromDate; } - /*public HashMap build(String dueDate,String totalOriginalDueForPeriod,String totalOutstandingForPeriod, - String interestOutstanding, String principalOutstanding, String principalLoanBalanceOutstanding, String principalDue, - String principalOriginalDue, String fromDate) { - HashMap expectedRepaymentSchedule = new HashMap(); - expectedRepaymentSchedule.put("dueDate", dueDate); - expectedRepaymentSchedule.put("totalOriginalDueForPeriod", - totalOriginalDueForPeriod); - expectedRepaymentSchedule.put("totalOutstandingForPeriod", - totalOutstandingForPeriod); - expectedRepaymentSchedule.put("interestOutstanding", interestOutstanding); - expectedRepaymentSchedule.put("principalOutstanding", - principalOutstanding); - expectedRepaymentSchedule.put("principalLoanBalanceOutstanding", - principalLoanBalanceOutstanding); - expectedRepaymentSchedule.put("principalDue", principalDue); - expectedRepaymentSchedule.put("principalOriginalDue", - principalOriginalDue); - expectedRepaymentSchedule.put("fromDate", fromDate); - - return expectedRepaymentSchedule; - }*/ + /* + * public HashMap build(String dueDate,String + * totalOriginalDueForPeriod,String totalOutstandingForPeriod, String + * interestOutstanding, String principalOutstanding, String + * principalLoanBalanceOutstanding, String principalDue, String + * principalOriginalDue, String fromDate) { HashMap + * expectedRepaymentSchedule = new HashMap(); + * expectedRepaymentSchedule.put("dueDate", dueDate); + * expectedRepaymentSchedule.put("totalOriginalDueForPeriod", + * totalOriginalDueForPeriod); + * expectedRepaymentSchedule.put("totalOutstandingForPeriod", + * totalOutstandingForPeriod); + * expectedRepaymentSchedule.put("interestOutstanding", + * interestOutstanding); + * expectedRepaymentSchedule.put("principalOutstanding", + * principalOutstanding); + * expectedRepaymentSchedule.put("principalLoanBalanceOutstanding", + * principalLoanBalanceOutstanding); + * expectedRepaymentSchedule.put("principalDue", principalDue); + * expectedRepaymentSchedule.put("principalOriginalDue", + * principalOriginalDue); expectedRepaymentSchedule.put("fromDate", + * fromDate); + * + * return expectedRepaymentSchedule; } + */ } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanProductTestBuilder.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanProductTestBuilder.java index 9dbaa9ac2..f0cc62638 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanProductTestBuilder.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanProductTestBuilder.java @@ -205,13 +205,12 @@ public class LoanProductTestBuilder { map.put("allowAttributeOverrides", this.allowAttributeOverrides); } map.put("allowPartialPeriodInterestCalcualtion", this.allowPartialPeriodInterestCalcualtion); - map.put("allowVariableInstallments", allowVariableInstallments) ; - if(allowVariableInstallments) { - map.put("minimumGap", minimumGap) ; - map.put("maximumGap", maximumGap) ; + map.put("allowVariableInstallments", allowVariableInstallments); + if (allowVariableInstallments) { + map.put("minimumGap", minimumGap); + map.put("maximumGap", maximumGap); } - map.put("syncExpectedWithDisbursementDate", - this.syncExpectedWithDisbursementDate); + map.put("syncExpectedWithDisbursementDate", this.syncExpectedWithDisbursementDate); return new Gson().toJson(map); } @@ -463,7 +462,8 @@ public class LoanProductTestBuilder { return this; } - public LoanProductTestBuilder withMinimumDaysBetweenDisbursalAndFirstRepayment(final String minimumDaysBetweenDisbursalAndFirstRepayment) { + public LoanProductTestBuilder withMinimumDaysBetweenDisbursalAndFirstRepayment( + final String minimumDaysBetweenDisbursalAndFirstRepayment) { this.minimumDaysBetweenDisbursalAndFirstRepayment = minimumDaysBetweenDisbursalAndFirstRepayment; return this; } @@ -493,16 +493,16 @@ public class LoanProductTestBuilder { return this; } - public LoanProductTestBuilder withVariableInstallmentsConfig(Boolean allowVariableInstallments, Integer minimumGap, Integer maximumGap) { - this.allowVariableInstallments = allowVariableInstallments ; + public LoanProductTestBuilder withVariableInstallmentsConfig(Boolean allowVariableInstallments, Integer minimumGap, + Integer maximumGap) { + this.allowVariableInstallments = allowVariableInstallments; this.minimumGap = minimumGap; this.maximumGap = maximumGap; - return this ; + return this; } public LoanProductTestBuilder withSyncExpectedWithDisbursementDate(Boolean syncExpectedWithDisbursementDate) { - this.syncExpectedWithDisbursementDate = - syncExpectedWithDisbursementDate ; - return this ; + this.syncExpectedWithDisbursementDate = syncExpectedWithDisbursementDate; + return this; } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanTransactionHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanTransactionHelper.java old mode 100755 new mode 100644 index b036c379e..9654eb4a3 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanTransactionHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/loans/LoanTransactionHelper.java @@ -49,8 +49,7 @@ public class LoanTransactionHelper { private final ResponseSpecification responseSpec; private final static Logger LOG = LoggerFactory.getLogger(LoanTransactionHelper.class); - private static final String CREATE_LOAN_PRODUCT_URL = "/fineract-provider/api/v1/loanproducts?" - + Utils.TENANT_IDENTIFIER; + private static final String CREATE_LOAN_PRODUCT_URL = "/fineract-provider/api/v1/loanproducts?" + Utils.TENANT_IDENTIFIER; private static final String APPLY_LOAN_URL = "/fineract-provider/api/v1/loans?" + Utils.TENANT_IDENTIFIER; private static final String LOAN_ACCOUNT_URL = "/fineract-provider/api/v1/loans"; private static final String APPROVE_LOAN_COMMAND = "approve"; @@ -76,13 +75,11 @@ public class LoanTransactionHelper { } public Integer getLoanProductId(final String loanProductJSON) { - return Utils.performServerPost(this.requestSpec, this.responseSpec, CREATE_LOAN_PRODUCT_URL, loanProductJSON, - "resourceId"); + return Utils.performServerPost(this.requestSpec, this.responseSpec, CREATE_LOAN_PRODUCT_URL, loanProductJSON, "resourceId"); } public Integer getLoanId(final String loanApplicationJSON) { - return Utils.performServerPost(this.requestSpec, this.responseSpec, APPLY_LOAN_URL, loanApplicationJSON, - "loanId"); + return Utils.performServerPost(this.requestSpec, this.responseSpec, APPLY_LOAN_URL, loanApplicationJSON, "loanId"); } public HashMap getGlimId(final String loanApplicationJSON) { @@ -90,15 +87,13 @@ public class LoanTransactionHelper { } public Object getGlimLoanId(final String glimId) { - final String GET_LOAN_URL = "/fineract-provider/api/v1/loans/glimAccount/" + glimId + "?" - + Utils.TENANT_IDENTIFIER; + final String GET_LOAN_URL = "/fineract-provider/api/v1/loans/glimAccount/" + glimId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(this.requestSpec, this.responseSpec, GET_LOAN_URL, "childLoanId"); } public Object getLoanError(final String loanApplicationJSON, final String responseAttribute) { - return Utils.performServerPost(this.requestSpec, this.responseSpec, APPLY_LOAN_URL, loanApplicationJSON, - responseAttribute); + return Utils.performServerPost(this.requestSpec, this.responseSpec, APPLY_LOAN_URL, loanApplicationJSON, responseAttribute); } public Integer getLoanOfficerId(final String loanId) { @@ -107,8 +102,7 @@ public class LoanTransactionHelper { } public Object createLoanAccount(final String loanApplicationJSON, final String responseAttribute) { - return Utils.performServerPost(this.requestSpec, this.responseSpec, APPLY_LOAN_URL, loanApplicationJSON, - responseAttribute); + return Utils.performServerPost(this.requestSpec, this.responseSpec, APPLY_LOAN_URL, loanApplicationJSON, responseAttribute); } public Integer updateLoan(final Integer id, final String loanApplicationJSON) { @@ -116,65 +110,58 @@ public class LoanTransactionHelper { "/fineract-provider/api/v1/loans/" + id + "?" + Utils.TENANT_IDENTIFIER, loanApplicationJSON, "loanId"); } - public ArrayList getLoanRepaymentSchedule(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer loanID) { - final String URL = "/fineract-provider/api/v1/loans/" + loanID + "?associations=repaymentSchedule&" - + Utils.TENANT_IDENTIFIER; + public ArrayList getLoanRepaymentSchedule(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer loanID) { + final String URL = "/fineract-provider/api/v1/loans/" + loanID + "?associations=repaymentSchedule&" + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerGet(requestSpec, responseSpec, URL, "repaymentSchedule"); return (ArrayList) response.get("periods"); } public ArrayList getLoanCharges(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer loanID) { - final String URL = "/fineract-provider/api/v1/loans/" + loanID + "?associations=charges&" - + Utils.TENANT_IDENTIFIER; + final String URL = "/fineract-provider/api/v1/loans/" + loanID + "?associations=charges&" + Utils.TENANT_IDENTIFIER; return (ArrayList) Utils.performServerGet(requestSpec, responseSpec, URL, "charges"); } - public ArrayList getLoanFutureRepaymentSchedule(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer loanID) { - final String URL = "/fineract-provider/api/v1/loans/" + loanID - + "?associations=repaymentSchedule,futureSchedule&" + Utils.TENANT_IDENTIFIER; + public ArrayList getLoanFutureRepaymentSchedule(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer loanID) { + final String URL = "/fineract-provider/api/v1/loans/" + loanID + "?associations=repaymentSchedule,futureSchedule&" + + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerGet(requestSpec, responseSpec, URL, "repaymentSchedule"); return (ArrayList) response.get("futurePeriods"); } - public HashMap getLoanSummary(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final Integer loanID) { + public HashMap getLoanSummary(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer loanID) { final String URL = "/fineract-provider/api/v1/loans/" + loanID + "?associations=all&" + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerGet(requestSpec, responseSpec, URL, "summary"); return response; } - public Object getLoanDetail(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final Integer loanID, final String param) { + public Object getLoanDetail(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer loanID, + final String param) { final String URL = "/fineract-provider/api/v1/loans/" + loanID + "?associations=all&" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, URL, param); } - public String getLoanDetails(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final Integer loanID) { + public String getLoanDetails(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer loanID) { final String URL = "/fineract-provider/api/v1/loans/" + loanID + "?associations=all&" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, URL, null); } public Object getLoanProductDetail(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer loanProductId, final String jsonAttributeToGetBack) { - final String URL = "/fineract-provider/api/v1/loanproducts/" + loanProductId + "?associations=all&" - + Utils.TENANT_IDENTIFIER; + final String URL = "/fineract-provider/api/v1/loanproducts/" + loanProductId + "?associations=all&" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, URL, jsonAttributeToGetBack); } - public String getLoanProductDetails(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer loanProductId) { - final String URL = "/fineract-provider/api/v1/loanproducts/" + loanProductId + "?associations=all&" - + Utils.TENANT_IDENTIFIER; + public String getLoanProductDetails(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer loanProductId) { + final String URL = "/fineract-provider/api/v1/loanproducts/" + loanProductId + "?associations=all&" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, URL, null); } public ArrayList getLoanCharges(final Integer loanId) { - final String GET_LOAN_CHARGES_URL = "/fineract-provider/api/v1/loans/" + loanId + "/charges?" - + Utils.TENANT_IDENTIFIER; + final String GET_LOAN_CHARGES_URL = "/fineract-provider/api/v1/loans/" + loanId + "/charges?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, GET_LOAN_CHARGES_URL, ""); } @@ -192,13 +179,10 @@ public class LoanTransactionHelper { getApproveLoanAsJSON(approvalDate, expectedDisbursementDate, approvalAmount, tranches)); } - public List> approveLoanForTranches(final String approvalDate, - final String expectedDisbursementDate, final String approvalAmount, final Integer loanID, - List tranches, final String responseAttribute) { - return (List>) performLoanTransaction( - createLoanOperationURL(APPROVE_LOAN_COMMAND, loanID), - getApproveLoanAsJSON(approvalDate, expectedDisbursementDate, approvalAmount, tranches), - responseAttribute); + public List> approveLoanForTranches(final String approvalDate, final String expectedDisbursementDate, + final String approvalAmount, final Integer loanID, List tranches, final String responseAttribute) { + return (List>) performLoanTransaction(createLoanOperationURL(APPROVE_LOAN_COMMAND, loanID), + getApproveLoanAsJSON(approvalDate, expectedDisbursementDate, approvalAmount, tranches), responseAttribute); } public Object approveLoan(final String approvalDate, final String approvalAmount, final Integer loanID, @@ -216,29 +200,25 @@ public class LoanTransactionHelper { } public HashMap disburseLoan(final String date, final Integer loanID) { - return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), - getDisburseLoanAsJSON(date, null)); + return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), getDisburseLoanAsJSON(date, null)); } - public HashMap disburseLoanWithRepaymentReschedule(final String date, final Integer loanID, - String adjustRepaymentDate) { + public HashMap disburseLoanWithRepaymentReschedule(final String date, final Integer loanID, String adjustRepaymentDate) { return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), getDisburseLoanWithRepaymentRescheduleAsJSON(date, null, adjustRepaymentDate)); } public HashMap disburseLoan(final String date, final Integer loanID, final String disburseAmt) { - return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), - getDisburseLoanAsJSON(date, disburseAmt)); + return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), getDisburseLoanAsJSON(date, disburseAmt)); } public Object disburseLoan(final String date, final Integer loanID, ResponseSpecification responseValidationError) { - return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), - getDisburseLoanAsJSON(date, null), responseValidationError); + return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), getDisburseLoanAsJSON(date, null), + responseValidationError); } public HashMap disburseLoanToSavings(final String date, final Integer loanID) { - return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_TO_SAVINGS_COMMAND, loanID), - getDisburseLoanAsJSON(date, null)); + return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_TO_SAVINGS_COMMAND, loanID), getDisburseLoanAsJSON(date, null)); } public HashMap undoDisbursal(final Integer loanID) { @@ -253,8 +233,8 @@ public class LoanTransactionHelper { final String undoLastDisburseJson = "{'note' : 'UNDO LAST DISBURSAL'}"; final String url = createLoanOperationURL(UNDO_LAST_DISBURSE_LOAN_COMMAND, loanID); LOG.info("IN UNDO LAST DISBURSE LOAN URL : {} ", url); - return performUndoLastLoanDisbursementTransaction( - createLoanOperationURL(UNDO_LAST_DISBURSE_LOAN_COMMAND, loanID), undoLastDisburseJson); + return performUndoLastLoanDisbursementTransaction(createLoanOperationURL(UNDO_LAST_DISBURSE_LOAN_COMMAND, loanID), + undoLastDisburseJson); } // glimtesting @@ -294,20 +274,16 @@ public class LoanTransactionHelper { } public HashMap writeOffLoan(final String date, final Integer loanID) { - return performLoanTransaction(createLoanTransactionURL(WRITE_OFF_LOAN_COMMAND, loanID), - getWriteOffBodyAsJSON(date)); + return performLoanTransaction(createLoanTransactionURL(WRITE_OFF_LOAN_COMMAND, loanID), getWriteOffBodyAsJSON(date)); } public HashMap waiveInterest(final String date, final String amountToBeWaived, final Integer loanID) { - return performLoanTransaction(createLoanTransactionURL(WAIVE_INTEREST_COMMAND, loanID), - getWaiveBodyAsJSON(date, amountToBeWaived)); + return performLoanTransaction(createLoanTransactionURL(WAIVE_INTEREST_COMMAND, loanID), getWaiveBodyAsJSON(date, amountToBeWaived)); } - public Integer waiveInterestAndReturnTransactionId(final String date, final String amountToBeWaived, - final Integer loanID) { + public Integer waiveInterestAndReturnTransactionId(final String date, final String amountToBeWaived, final Integer loanID) { Integer resourceId = Utils.performServerPost(this.requestSpec, this.responseSpec, - createLoanTransactionURL(WAIVE_INTEREST_COMMAND, loanID), getWaiveBodyAsJSON(date, amountToBeWaived), - "resourceId"); + createLoanTransactionURL(WAIVE_INTEREST_COMMAND, loanID), getWaiveBodyAsJSON(date, amountToBeWaived), "resourceId"); return resourceId; } @@ -328,16 +304,14 @@ public class LoanTransactionHelper { public Integer addChargesForLoan(final Integer loanId, final String request) { LOG.info("--------------------------------- ADD CHARGES FOR LOAN --------------------------------"); - final String ADD_CHARGES_URL = "/fineract-provider/api/v1/loans/" + loanId + "/charges?" - + Utils.TENANT_IDENTIFIER; + final String ADD_CHARGES_URL = "/fineract-provider/api/v1/loans/" + loanId + "/charges?" + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerPost(requestSpec, responseSpec, ADD_CHARGES_URL, request, ""); return (Integer) response.get("resourceId"); } public Object addChargesForAllreadyDisursedLoan(final Integer loanId, final String request, final ResponseSpecification responseSpecification) { - final String ADD_CHARGES_URL = "/fineract-provider/api/v1/loans/" + loanId + "/charges?" - + Utils.TENANT_IDENTIFIER; + final String ADD_CHARGES_URL = "/fineract-provider/api/v1/loans/" + loanId + "/charges?" + Utils.TENANT_IDENTIFIER; return Utils.performServerPost(this.requestSpec, responseSpecification, ADD_CHARGES_URL, request, ""); } @@ -359,16 +333,16 @@ public class LoanTransactionHelper { public Integer waiveChargesForLoan(final Integer loanId, final Integer loanchargeId, final String json) { LOG.info("--------------------------------- WAIVE CHARGES FOR LOAN --------------------------------"); - final String CHARGES_URL = "/fineract-provider/api/v1/loans/" + loanId + "/charges/" + loanchargeId - + "?command=waive&" + Utils.TENANT_IDENTIFIER; + final String CHARGES_URL = "/fineract-provider/api/v1/loans/" + loanId + "/charges/" + loanchargeId + "?command=waive&" + + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, json, ""); return (Integer) response.get("resourceId"); } public Integer payChargesForLoan(final Integer loanId, final Integer loanchargeId, final String json) { LOG.info("--------------------------------- WAIVE CHARGES FOR LOAN --------------------------------"); - final String CHARGES_URL = "/fineract-provider/api/v1/loans/" + loanId + "/charges/" + loanchargeId - + "?command=pay&" + Utils.TENANT_IDENTIFIER; + final String CHARGES_URL = "/fineract-provider/api/v1/loans/" + loanId + "/charges/" + loanchargeId + "?command=pay&" + + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, json, ""); return (Integer) response.get("resourceId"); } @@ -386,8 +360,8 @@ public class LoanTransactionHelper { return new Gson().toJson(map); } - private String getDisburseLoanWithRepaymentRescheduleAsJSON(final String actualDisbursementDate, - final String transactionAmount, final String adjustRepaymentDate) { + private String getDisburseLoanWithRepaymentRescheduleAsJSON(final String actualDisbursementDate, final String transactionAmount, + final String adjustRepaymentDate) { final HashMap map = new HashMap<>(); map.put("locale", "en"); map.put("dateFormat", "dd MMMM yyyy"); @@ -405,8 +379,8 @@ public class LoanTransactionHelper { return getApproveLoanAsJSON(approvalDate, null, null, null); } - private String getApproveLoanAsJSON(final String approvalDate, final String expectedDisbursementDate, - final String approvalAmount, List tranches) { + private String getApproveLoanAsJSON(final String approvalDate, final String expectedDisbursementDate, final String approvalAmount, + List tranches) { final HashMap map = new HashMap<>(); map.put("locale", "en"); map.put("dateFormat", "dd MMMM yyyy"); @@ -494,8 +468,7 @@ public class LoanTransactionHelper { return getSpecifiedDueDateChargesForLoanAsJSON(chargeId, "12 January 2013", "100"); } - public static String getSpecifiedDueDateChargesForLoanAsJSON(final String chargeId, final String dueDate, - final String amount) { + public static String getSpecifiedDueDateChargesForLoanAsJSON(final String chargeId, final String dueDate, final String amount) { final HashMap map = new HashMap<>(); map.put("locale", "en_GB"); map.put("dateFormat", "dd MMMM yyyy"); @@ -591,53 +564,47 @@ public class LoanTransactionHelper { } private String createLoanTransactionURL(final String command, final Integer loanID) { - return "/fineract-provider/api/v1/loans/" + loanID + "/transactions?command=" + command + "&" - + Utils.TENANT_IDENTIFIER; + return "/fineract-provider/api/v1/loans/" + loanID + "/transactions?command=" + command + "&" + Utils.TENANT_IDENTIFIER; } private String createGlimAccountURL(final String command, final Integer glimID) { - return "/fineract-provider/api/v1/loans/glimAccount/" + glimID + "?command=" + command + "&" - + Utils.TENANT_IDENTIFIER; + return "/fineract-provider/api/v1/loans/glimAccount/" + glimID + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; } private HashMap performLoanTransaction(final String postURLForLoanTransaction, final String jsonToBeSent) { - final HashMap response = Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForLoanTransaction, - jsonToBeSent, "changes"); + final HashMap response = Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForLoanTransaction, jsonToBeSent, + "changes"); return (HashMap) response.get("status"); } - private Float performUndoLastLoanDisbursementTransaction(final String postURLForLoanTransaction, - final String jsonToBeSent) { + private Float performUndoLastLoanDisbursementTransaction(final String postURLForLoanTransaction, final String jsonToBeSent) { - final HashMap response = Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForLoanTransaction, - jsonToBeSent, "changes"); + final HashMap response = Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForLoanTransaction, jsonToBeSent, + "changes"); return (Float) response.get("disbursedAmount"); } private Object performLoanTransaction(final String postURLForLoanTransaction, final String jsonToBeSent, final String responseAttribute) { - return Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForLoanTransaction, jsonToBeSent, - responseAttribute); + return Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForLoanTransaction, jsonToBeSent, responseAttribute); } private Object performLoanTransaction(final String postURLForLoanTransaction, final String jsonToBeSent, ResponseSpecification responseValidationError) { - return Utils.performServerPost(this.requestSpec, responseValidationError, postURLForLoanTransaction, - jsonToBeSent, CommonConstants.RESPONSE_ERROR); + return Utils.performServerPost(this.requestSpec, responseValidationError, postURLForLoanTransaction, jsonToBeSent, + CommonConstants.RESPONSE_ERROR); } public Object adjustLoanTransaction(final Integer loanId, final Integer transactionId, final String date, final String transactionAmount, final String responseAttribute) { - return adjustLoanTransaction(loanId, transactionId, getAdjustTransactionJSON(date, transactionAmount), - responseAttribute); + return adjustLoanTransaction(loanId, transactionId, getAdjustTransactionJSON(date, transactionAmount), responseAttribute); } private Object adjustLoanTransaction(final Integer loanId, final Integer tansactionId, final String jsonToBeSent, final String responseAttribute) { - final String URL = "/fineract-provider/api/v1/loans/" + loanId + "/transactions/" + tansactionId + "?" - + Utils.TENANT_IDENTIFIER; + final String URL = "/fineract-provider/api/v1/loans/" + loanId + "/transactions/" + tansactionId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, jsonToBeSent, responseAttribute); } @@ -652,8 +619,7 @@ public class LoanTransactionHelper { return json; } - public HashMap getPrepayAmount(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final Integer loanID) { + public HashMap getPrepayAmount(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer loanID) { final String URL = "/fineract-provider/api/v1/loans/" + loanID + "/transactions/template?command=prepayLoan&" + Utils.TENANT_IDENTIFIER; final HashMap response = Utils.performServerGet(requestSpec, responseSpec, URL, ""); @@ -664,21 +630,17 @@ public class LoanTransactionHelper { return "/fineract-provider/api/v1/accounttransfers/refundByTransfer?tenantIdentifier=default"; } - public void verifyRepaymentScheduleEntryFor(final int repaymentNumber, final float expectedPrincipalOutstanding, - final Integer loanID) { + public void verifyRepaymentScheduleEntryFor(final int repaymentNumber, final float expectedPrincipalOutstanding, final Integer loanID) { LOG.info("---------------------------GETTING LOAN REPAYMENT SCHEDULE--------------------------------"); - final ArrayList repaymentPeriods = getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, - loanID); - assertEquals(expectedPrincipalOutstanding, - repaymentPeriods.get(repaymentNumber).get("principalLoanBalanceOutstanding"), + final ArrayList repaymentPeriods = getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); + assertEquals(expectedPrincipalOutstanding, repaymentPeriods.get(repaymentNumber).get("principalLoanBalanceOutstanding"), "Mismatch in Principal Loan Balance Outstanding "); } - public void checkAccrualTransactionForRepayment(final LocalDate transactionDate, final Float interestPortion, - final Float feePortion, final Float penaltyPortion, final Integer loanID) { + public void checkAccrualTransactionForRepayment(final LocalDate transactionDate, final Float interestPortion, final Float feePortion, + final Float penaltyPortion, final Integer loanID) { - ArrayList transactions = (ArrayList) getLoanDetail(this.requestSpec, this.responseSpec, - loanID, "transactions"); + ArrayList transactions = (ArrayList) getLoanDetail(this.requestSpec, this.responseSpec, loanID, "transactions"); boolean isTransactionFound = false; for (int i = 0; i < transactions.size(); i++) { HashMap transactionType = (HashMap) transactions.get(i).get("type"); @@ -686,19 +648,16 @@ public class LoanTransactionHelper { if (isAccrualTransaction) { ArrayList accrualEntryDateAsArray = (ArrayList) transactions.get(i).get("date"); - LocalDate accrualEntryDate = new LocalDate(accrualEntryDateAsArray.get(0), - accrualEntryDateAsArray.get(1), accrualEntryDateAsArray.get(2)); + LocalDate accrualEntryDate = new LocalDate(accrualEntryDateAsArray.get(0), accrualEntryDateAsArray.get(1), + accrualEntryDateAsArray.get(2)); if (transactionDate.equals(accrualEntryDate)) { isTransactionFound = true; - assertEquals(interestPortion, - Float.valueOf(String.valueOf(transactions.get(i).get("interestPortion"))), + assertEquals(interestPortion, Float.valueOf(String.valueOf(transactions.get(i).get("interestPortion"))), "Mismatch in transaction amounts"); - assertEquals(feePortion, - Float.valueOf(String.valueOf(transactions.get(i).get("feeChargesPortion"))), + assertEquals(feePortion, Float.valueOf(String.valueOf(transactions.get(i).get("feeChargesPortion"))), "Mismatch in transaction amounts"); - assertEquals(penaltyPortion, - Float.valueOf(String.valueOf(transactions.get(i).get("penaltyChargesPortion"))), + assertEquals(penaltyPortion, Float.valueOf(String.valueOf(transactions.get(i).get("penaltyChargesPortion"))), "Mismatch in transaction amounts"); break; } @@ -713,10 +672,10 @@ public class LoanTransactionHelper { getRefundByCashBodyAsJSON(date, amountToBeRefunded)); } - public HashMap makeRefundByTransfer(final Integer fromAccountId, final Integer toClientId, - final Integer toAccountId, final Integer fromClientId, final String date, final Float amountToBeRefunded) { - return performLoanTransaction(createLoanRefundTransferURL(), getRefundByTransferBodyAsJSON(fromAccountId, - toClientId, toAccountId, fromClientId, date, amountToBeRefunded)); + public HashMap makeRefundByTransfer(final Integer fromAccountId, final Integer toClientId, final Integer toAccountId, + final Integer fromClientId, final String date, final Float amountToBeRefunded) { + return performLoanTransaction(createLoanRefundTransferURL(), + getRefundByTransferBodyAsJSON(fromAccountId, toClientId, toAccountId, fromClientId, date, amountToBeRefunded)); } private String getRefundByCashBodyAsJSON(final String transactionDate, final Float transactionAmount) { @@ -729,9 +688,8 @@ public class LoanTransactionHelper { return new Gson().toJson(map); } - private String getRefundByTransferBodyAsJSON(final Integer fromAccountId, final Integer toClientId, - final Integer toAccountId, final Integer fromClientId, final String transactionDate, - final Float transactionAmount) { + private String getRefundByTransferBodyAsJSON(final Integer fromAccountId, final Integer toClientId, final Integer toAccountId, + final Integer fromClientId, final String transactionDate, final Float transactionAmount) { final HashMap map = new HashMap<>(); map.put("fromAccountId", fromAccountId.toString()); map.put("fromAccountType", "1"); @@ -760,34 +718,28 @@ public class LoanTransactionHelper { return detail; } - public Object editDisbursementDetail(final Integer loanID, final Integer disbursementId, - final String approvalAmount, final String expectedDisbursementDate, - final String updatedExpectedDisbursementDate, final String updatedPrincipal, + public Object editDisbursementDetail(final Integer loanID, final Integer disbursementId, final String approvalAmount, + final String expectedDisbursementDate, final String updatedExpectedDisbursementDate, final String updatedPrincipal, final String jsonAttributeToGetBack) { - return Utils.performServerPut(this.requestSpec, this.responseSpec, - createEditDisbursementURL(loanID, disbursementId), getEditDisbursementsAsJSON(approvalAmount, - expectedDisbursementDate, updatedExpectedDisbursementDate, updatedPrincipal), + return Utils.performServerPut(this.requestSpec, this.responseSpec, createEditDisbursementURL(loanID, disbursementId), + getEditDisbursementsAsJSON(approvalAmount, expectedDisbursementDate, updatedExpectedDisbursementDate, updatedPrincipal), jsonAttributeToGetBack); } - public Object addAndDeleteDisbursementDetail(final Integer loanID, final String approvalAmount, - final String expectedDisbursementDate, List disbursementData, - final String jsonAttributeToGetBack) { + public Object addAndDeleteDisbursementDetail(final Integer loanID, final String approvalAmount, final String expectedDisbursementDate, + List disbursementData, final String jsonAttributeToGetBack) { return Utils.performServerPut(this.requestSpec, this.responseSpec, createAddAndDeleteDisbursementURL(loanID), - getAddAndDeleteDisbursementsAsJSON(approvalAmount, expectedDisbursementDate, disbursementData), - jsonAttributeToGetBack); + getAddAndDeleteDisbursementsAsJSON(approvalAmount, expectedDisbursementDate, disbursementData), jsonAttributeToGetBack); } private String createEditDisbursementURL(Integer loanID, Integer disbursementId) { - return "/fineract-provider/api/v1/loans/" + loanID + "/disbursements/" + disbursementId + "?" - + Utils.TENANT_IDENTIFIER; + return "/fineract-provider/api/v1/loans/" + loanID + "/disbursements/" + disbursementId + "?" + Utils.TENANT_IDENTIFIER; } private String createAddAndDeleteDisbursementURL(Integer loanID) { - return "/fineract-provider/api/v1/loans/" + loanID + "/disbursements/editDisbursements?" - + Utils.TENANT_IDENTIFIER; + return "/fineract-provider/api/v1/loans/" + loanID + "/disbursements/editDisbursements?" + Utils.TENANT_IDENTIFIER; } public static String getEditDisbursementsAsJSON(final String approvalAmount, final String expectedDisbursementDate, @@ -804,8 +756,8 @@ public class LoanTransactionHelper { return json; } - public static String getAddAndDeleteDisbursementsAsJSON(final String approvalAmount, - final String expectedDisbursementDate, final List disbursementData) { + public static String getAddAndDeleteDisbursementsAsJSON(final String approvalAmount, final String expectedDisbursementDate, + final List disbursementData) { final HashMap map = new HashMap<>(); map.put("locale", "en"); map.put("dateFormat", "dd MMMM yyyy"); @@ -849,14 +801,12 @@ public class LoanTransactionHelper { String legalFormType = null; requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA); return Utils.performServerTemplatePost(requestSpec, responseSpec, - LOAN_ACCOUNT_URL + "/uploadtemplate" + "?" + Utils.TENANT_IDENTIFIER, legalFormType, file, locale, - dateFormat); + LOAN_ACCOUNT_URL + "/uploadtemplate" + "?" + Utils.TENANT_IDENTIFIER, legalFormType, file, locale, dateFormat); } public String getOutputTemplateLocation(final String importDocumentId) { requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN); return Utils.performServerOutputTemplateLocationGet(requestSpec, responseSpec, - "/fineract-provider/api/v1/imports/getOutputTemplateLocation" + "?" + Utils.TENANT_IDENTIFIER, - importDocumentId); + "/fineract-provider/api/v1/imports/getOutputTemplateLocation" + "?" + Utils.TENANT_IDENTIFIER, importDocumentId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/CampaignsHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/CampaignsHelper.java index ea233a8f4..2d50e3bf4 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/CampaignsHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/CampaignsHelper.java @@ -38,6 +38,7 @@ import org.slf4j.LoggerFactory; import org.springframework.util.Assert; public class CampaignsHelper { + private final static Logger LOG = LoggerFactory.getLogger(CampaignsHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; @@ -56,54 +57,48 @@ public class CampaignsHelper { public Integer createCampaign(String reportName, Integer triggerType) { LOG.info("---------------------------------CREATING A CAMPAIGN---------------------------------------------"); final String CREATE_SMS_CAMPAIGNS_URL = SMS_CAMPAIGNS_URL + "?" + Utils.TENANT_IDENTIFIER; - return Utils.performServerPost(requestSpec, responseSpec, CREATE_SMS_CAMPAIGNS_URL, - getCreateCampaignJSON(reportName, triggerType), "resourceId"); + return Utils.performServerPost(requestSpec, responseSpec, CREATE_SMS_CAMPAIGNS_URL, getCreateCampaignJSON(reportName, triggerType), + "resourceId"); } - public void verifyCampaignCreatedOnServer(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer generatedCampaignId) { + public void verifyCampaignCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer generatedCampaignId) { LOG.info("------------------------------CHECK CAMPAIGN DETAILS------------------------------------\n"); - final String RETRIEVE_SMS_CAMPAIGNS_URL = SMS_CAMPAIGNS_URL + "/" + generatedCampaignId + "?" - + Utils.TENANT_IDENTIFIER; - final Integer responseCampaignId = Utils.performServerGet(requestSpec, responseSpec, RETRIEVE_SMS_CAMPAIGNS_URL, - "id"); + final String RETRIEVE_SMS_CAMPAIGNS_URL = SMS_CAMPAIGNS_URL + "/" + generatedCampaignId + "?" + Utils.TENANT_IDENTIFIER; + final Integer responseCampaignId = Utils.performServerGet(requestSpec, responseSpec, RETRIEVE_SMS_CAMPAIGNS_URL, "id"); assertEquals(generatedCampaignId, responseCampaignId, "ERROR IN CREATING THE CAMPAIGN"); } public Integer updateCampaign(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer generatedCampaignId, String reportName, Integer triggerType) { LOG.info("------------------------------UPDATE CAMPAIGN DETAILS------------------------------------\n"); - final String UPDATE_SMS_CAMPAIGNS_URL = SMS_CAMPAIGNS_URL + "/" + generatedCampaignId + "?" - + Utils.TENANT_IDENTIFIER; - return Utils.performServerPut(requestSpec, responseSpec, UPDATE_SMS_CAMPAIGNS_URL, - getUpdateCampaignJSON(reportName, triggerType), "resourceId"); + final String UPDATE_SMS_CAMPAIGNS_URL = SMS_CAMPAIGNS_URL + "/" + generatedCampaignId + "?" + Utils.TENANT_IDENTIFIER; + return Utils.performServerPut(requestSpec, responseSpec, UPDATE_SMS_CAMPAIGNS_URL, getUpdateCampaignJSON(reportName, triggerType), + "resourceId"); } public Integer deleteCampaign(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer generatedCampaignId) { LOG.info("------------------------------DELETE CAMPAIGN DETAILS------------------------------------\n"); - final String DELETE_SMS_CAMPAIGNS_URL = SMS_CAMPAIGNS_URL + "/" + generatedCampaignId + "?" - + Utils.TENANT_IDENTIFIER; + final String DELETE_SMS_CAMPAIGNS_URL = SMS_CAMPAIGNS_URL + "/" + generatedCampaignId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerDelete(requestSpec, responseSpec, DELETE_SMS_CAMPAIGNS_URL, "resourceId"); } - public Integer performActionsOnCampaign(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer generatedCampaignId, String command) { - LOG.info( - "------------------------------PERFORM ACTION ON CAMPAIGN DETAILS------------------------------------\n"); - final String SMS_CAMPAIGNS_ACTION_URL = SMS_CAMPAIGNS_URL + "/" + generatedCampaignId + "?command=" + command - + "&" + Utils.TENANT_IDENTIFIER; + public Integer performActionsOnCampaign(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer generatedCampaignId, String command) { + LOG.info("------------------------------PERFORM ACTION ON CAMPAIGN DETAILS------------------------------------\n"); + final String SMS_CAMPAIGNS_ACTION_URL = SMS_CAMPAIGNS_URL + "/" + generatedCampaignId + "?command=" + command + "&" + + Utils.TENANT_IDENTIFIER; String actionDate = Utils.getLocalDateOfTenant().toString(DATE_FORMAT); - return Utils.performServerPost(requestSpec, responseSpec, SMS_CAMPAIGNS_ACTION_URL, - getJSONForCampaignAction(command, actionDate), "resourceId"); + return Utils.performServerPost(requestSpec, responseSpec, SMS_CAMPAIGNS_ACTION_URL, getJSONForCampaignAction(command, actionDate), + "resourceId"); } - public Object performActionsOnCampaignWithFailure(final Integer generatedCampaignId, String command, - String actionDate, String responseJsonAttribute) { - LOG.info( - "--------------------------PERFORM ACTION ON CAMPAIGN DETAILS WITH FAILURE-------------------------------\n"); - final String SMS_CAMPAIGNS_ACTION_URL = SMS_CAMPAIGNS_URL + "/" + generatedCampaignId + "?command=" + command - + "&" + Utils.TENANT_IDENTIFIER; + public Object performActionsOnCampaignWithFailure(final Integer generatedCampaignId, String command, String actionDate, + String responseJsonAttribute) { + LOG.info("--------------------------PERFORM ACTION ON CAMPAIGN DETAILS WITH FAILURE-------------------------------\n"); + final String SMS_CAMPAIGNS_ACTION_URL = SMS_CAMPAIGNS_URL + "/" + generatedCampaignId + "?command=" + command + "&" + + Utils.TENANT_IDENTIFIER; return Utils.performServerPost(this.requestSpec, this.responseSpec, SMS_CAMPAIGNS_ACTION_URL, getJSONForCampaignAction(command, actionDate), responseJsonAttribute); } @@ -179,15 +174,14 @@ public class CampaignsHelper { LOG.info("--------------------------------- GET REPORTS OPTIONS -------------------------------"); Assert.notNull(jsonAttributeToGetBack, "jsonAttributeToGetBack may not be null"); final String templateUrl = SMS_CAMPAIGNS_URL + "/template?" + Utils.TENANT_IDENTIFIER; - final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when() - .get(templateUrl).andReturn().asString(); + final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(templateUrl).andReturn() + .asString(); Assert.notNull(json, "json"); ArrayList reportsList = new ArrayList<>(); String reportsString = new Gson().toJson(from(json).get(jsonAttributeToGetBack)); Assert.notNull(reportsString, "reportsString"); final Gson gson = new Gson(); - final Type typeOfHashMap = new TypeToken>() { - }.getType(); + final Type typeOfHashMap = new TypeToken>() {}.getType(); reportsList = gson.fromJson(reportsString, typeOfHashMap); return reportsList; } @@ -197,9 +191,7 @@ public class CampaignsHelper { if (reports != null && !reports.isEmpty()) { for (ReportData reportData : reports) { - if (reportName.equals(reportData.getReportName())) { - return reportData.getReportId(); - } + if (reportName.equals(reportData.getReportName())) { return reportData.getReportId(); } } } Assert.notNull(null, "null"); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/Currency.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/Currency.java index 50442bdf7..ca7e4d450 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/Currency.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/Currency.java @@ -27,8 +27,7 @@ public class Currency { String nameCode; String displayLabel; - public Currency(String code, String name, Integer decimalPlaces, String displaySymbol, - String nameCode, String displayLabel) { + public Currency(String code, String name, Integer decimalPlaces, String displaySymbol, String nameCode, String displayLabel) { this.code = code; this.name = name; this.decimalPlaces = decimalPlaces; @@ -38,11 +37,10 @@ public class Currency { } public boolean isValid() { - return (this.code != null && this.code.length() == 3) && - (this.name != null && this.name.length() > 0) && - (this.decimalPlaces != null && this.decimalPlaces >= 0) && - (this.nameCode != null && this.nameCode.startsWith("currency.")) && - (this.displayLabel != null && this.displayLabel.length() > 0); + return (this.code != null && this.code.length() == 3) && (this.name != null && this.name.length() > 0) + && (this.decimalPlaces != null && this.decimalPlaces >= 0) + && (this.nameCode != null && this.nameCode.startsWith("currency.")) + && (this.displayLabel != null && this.displayLabel.length() > 0); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/CurrencyHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/CurrencyHelper.java index d9e0a5edd..aeb8e79fd 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/CurrencyHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/CurrencyHelper.java @@ -36,12 +36,12 @@ import org.slf4j.LoggerFactory; import org.springframework.util.Assert; public class CurrencyHelper { + private final static Logger LOG = LoggerFactory.getLogger(CurrencyHelper.class); private static final String CURRENCY_URL = "/fineract-provider/api/v1/currencies?" + Utils.TENANT_IDENTIFIER; private static final String CURRENCY_URL_SELECTED = CURRENCY_URL + "&fields=selectedCurrencyOptions"; - private static final List PERMITTED_CURRENCY_ARRAY = Arrays.asList("currencyOptions", - "selectedCurrencyOptions"); + private static final List PERMITTED_CURRENCY_ARRAY = Arrays.asList("currencyOptions", "selectedCurrencyOptions"); private static final List PERMITTED_CURRENCY_ARRAY_SELECTED = Arrays.asList("selectedCurrencyOptions"); @@ -63,13 +63,11 @@ public class CurrencyHelper { private ArrayList getCurrencies(final String getUrl, final List permittedCurrencyArrays) { LOG.info("--------------------------------- GET CURRENCY OPTIONS -------------------------------"); - final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getUrl) - .andReturn().asString(); + final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getUrl).andReturn().asString(); final Gson gson = new Gson(); Assert.notNull(json, "json"); final ArrayList currencyList = new ArrayList(); - final Type typeOfHashMap = new TypeToken>>() { - }.getType(); + final Type typeOfHashMap = new TypeToken>>() {}.getType(); final Map> responseMap = gson.fromJson(json, typeOfHashMap); for (Map.Entry> entry : responseMap.entrySet()) { Assert.isTrue(permittedCurrencyArrays.contains(entry.getKey()), "permittedCurrencyArrays"); @@ -82,12 +80,11 @@ public class CurrencyHelper { public List updateCurrencies(final List currencies) { LOG.info("--------------------------------- UPDATE CURRENCY OPTIONS -------------------------------"); - final String json = given().spec(requestSpec).body(getUpdateJSON(currencies)).expect().spec(responseSpec).log() - .ifError().when().put(CURRENCY_URL).andReturn().asString(); + final String json = given().spec(requestSpec).body(getUpdateJSON(currencies)).expect().spec(responseSpec).log().ifError().when() + .put(CURRENCY_URL).andReturn().asString(); final Gson gson = new Gson(); Assert.notNull(json, "json"); - final Type typeOfHashMap = new TypeToken>>>() { - }.getType(); + final Type typeOfHashMap = new TypeToken>>>() {}.getType(); final Map>> responseMap = gson.fromJson(json, typeOfHashMap); return responseMap.get("changes").get("currencies"); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/EntityDatatableChecksHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/EntityDatatableChecksHelper.java index daebf48fe..35373112f 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/EntityDatatableChecksHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/EntityDatatableChecksHelper.java @@ -27,6 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EntityDatatableChecksHelper { + private final static Logger LOG = LoggerFactory.getLogger(EntityDatatableChecksHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; @@ -38,21 +39,23 @@ public class EntityDatatableChecksHelper { this.responseSpec = responseSpec; } - public Integer createEntityDatatableCheck(final String apptableName, final String datatableName, final int status, final Integer productId) { + public Integer createEntityDatatableCheck(final String apptableName, final String datatableName, final int status, + final Integer productId) { return Utils.performServerPost(this.requestSpec, this.responseSpec, DATATABLE_CHECK_URL + "?" + Utils.TENANT_IDENTIFIER, getTestEdcAsJSON(apptableName, datatableName, status, productId), "resourceId"); } public Integer deleteEntityDatatableCheck(final Integer entityDatatableCheckId) { - return Utils.performServerDelete(requestSpec, responseSpec, DATATABLE_CHECK_URL + "/" + entityDatatableCheckId + "?" - + Utils.TENANT_IDENTIFIER, "resourceId"); + return Utils.performServerDelete(requestSpec, responseSpec, + DATATABLE_CHECK_URL + "/" + entityDatatableCheckId + "?" + Utils.TENANT_IDENTIFIER, "resourceId"); } public String retrieveEntityDatatableCheck() { return Utils.performServerGet(requestSpec, responseSpec, DATATABLE_CHECK_URL + "?" + Utils.TENANT_IDENTIFIER, null); } - public static String getTestEdcAsJSON(final String apptableName, final String datatableName, final int status, final Integer productId) { + public static String getTestEdcAsJSON(final String apptableName, final String datatableName, final int status, + final Integer productId) { final HashMap map = new HashMap<>(); map.put("entity", apptableName); map.put("status", status); @@ -61,7 +64,7 @@ public class EntityDatatableChecksHelper { map.put("productId", productId); } String requestJsonString = new Gson().toJson(map); - LOG.info("map : {}" , requestJsonString); + LOG.info("map : {}", requestJsonString); return requestJsonString; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/EntityDatatableChecksIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/EntityDatatableChecksIntegrationTest.java index baff70f43..dfc2d1a16 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/EntityDatatableChecksIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/EntityDatatableChecksIntegrationTest.java @@ -50,6 +50,7 @@ import org.slf4j.LoggerFactory; * Retrieval of Entity-Datatable Check */ public class EntityDatatableChecksIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(EntityDatatableChecksIntegrationTest.class); private RequestSpecification requestSpec; private ResponseSpecification responseSpec; diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/StaffHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/StaffHelper.java old mode 100755 new mode 100644 index 39f4cbef5..b3988b84a --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/StaffHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/organisation/StaffHelper.java @@ -30,6 +30,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StaffHelper { + private final static Logger LOG = LoggerFactory.getLogger(StaffHelper.class); private static final String TRANSFER_STAFF_URL = "/fineract-provider/api/v1/groups"; @@ -37,18 +38,17 @@ public class StaffHelper { public static final String GROUP_ID = "groupId"; - public static Integer transferStaffToGroup(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final Integer groupId,final Integer staffToTransfer ,final String note){ - final String url = TRANSFER_STAFF_URL + "/" + groupId + "?command=transferStaff&"+ Utils.TENANT_IDENTIFIER; + final Integer groupId, final Integer staffToTransfer, final String note) { + final String url = TRANSFER_STAFF_URL + "/" + groupId + "?command=transferStaff&" + Utils.TENANT_IDENTIFIER; return Utils.performServerPost(requestSpec, responseSpec, url, transferStaffToGroupAsJSON(staffToTransfer, note), GROUP_ID); } - public static String transferStaffToGroupAsJSON(final Integer staffToTransferId,final String note) { + public static String transferStaffToGroupAsJSON(final Integer staffToTransferId, final String note) { final HashMap map = new HashMap<>(); map.put("staffId", staffToTransferId); map.put("note", note); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } @@ -60,14 +60,14 @@ public class StaffHelper { return createStaffWithJson(requestSpec, responseSpec, createStaffAsJSON()); } - public static Map createStaffWithJson(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String json) { + public static Map createStaffWithJson(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String json) { final String url = CREATE_STAFF_URL + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerPost(requestSpec, responseSpec, url, json, ""); } - public static Map getStaff(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer staffId) { + public static Map getStaff(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer staffId) { final String url = CREATE_STAFF_URL + "/" + staffId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, url, ""); } @@ -83,8 +83,8 @@ public class StaffHelper { return Utils.performServerGet(requestSpec, responseSpec, url, ""); } - public static Map updateStaff(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer staffId, final Map changes) { + public static Map updateStaff(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer staffId, final Map changes) { final String url = CREATE_STAFF_URL + "/" + staffId + "?" + Utils.TENANT_IDENTIFIER; final String json = new Gson().toJson(changes); return Utils.performServerPut(requestSpec, responseSpec, url, json, ""); @@ -99,12 +99,11 @@ public class StaffHelper { map.put("lastname", Utils.randomNameGenerator("Doe_", 4)); map.put("isLoanOfficer", true); - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } - public static Map getMapWithJoiningDate() - { + public static Map getMapWithJoiningDate() { HashMap map = new HashMap<>(); map.put("locale", "en"); @@ -118,22 +117,22 @@ public class StaffHelper { final Map map = getMapWithJoiningDate(); final List fieldList = Arrays.asList(fields); - if(fieldList.contains("officeId")) { + if (fieldList.contains("officeId")) { map.put("officeId", 1); } - if(fieldList.contains("firstname")) { + if (fieldList.contains("firstname")) { map.put("firstname", Utils.randomNameGenerator("michael_", 5)); } - if(fieldList.contains("lastname")) { + if (fieldList.contains("lastname")) { map.put("lastname", Utils.randomNameGenerator("Doe_", 4)); } - if(fieldList.contains("isLoanOfficer")) { + if (fieldList.contains("isLoanOfficer")) { map.put("isLoanOfficer", true); } - if(fieldList.contains("mobileNo")) { + if (fieldList.contains("mobileNo")) { map.put("mobileNo", "+123515198"); } - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/provisioning/ProvisioningHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/provisioning/ProvisioningHelper.java index 6a50a2ca5..356d574c5 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/provisioning/ProvisioningHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/provisioning/ProvisioningHelper.java @@ -37,11 +37,11 @@ public class ProvisioningHelper { map.put("definitions", addProvisioningCategories(categories, liability, expense)); DateFormat simple = new SimpleDateFormat("dd MMMM yyyy"); String formattedString = simple.format(Utils.getLocalDateOfTenant().toDate()); - Random rand = new Random() ; - String criteriaName = "General Provisioning Criteria" + formattedString+rand.nextLong(); + Random rand = new Random(); + String criteriaName = "General Provisioning Criteria" + formattedString + rand.nextLong(); map.put("criteriaName", criteriaName); map.put("locale", "en"); - return map ; + return map; } public final static String createProvisioningEntryJson() { @@ -90,9 +90,9 @@ public class ProvisioningHelper { if (i == categories.size() - 1) { map.put("maxAge", 90000); } else { - map.put("maxAge", (i+1) * 30); + map.put("maxAge", (i + 1) * 30); } - map.put("provisioningPercentage", Float.valueOf((float)((i + 1) * 5.5))); + map.put("provisioningPercentage", Float.valueOf((float) ((i + 1) * 5.5))); map.put("liabilityAccount", liability.getAccountID()); map.put("expenseAccount", expense.getAccountID()); list.add(map); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/provisioning/ProvisioningTransactionHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/provisioning/ProvisioningTransactionHelper.java index e976a6912..1b02bc90c 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/provisioning/ProvisioningTransactionHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/provisioning/ProvisioningTransactionHelper.java @@ -24,20 +24,20 @@ import java.util.ArrayList; import java.util.Map; import org.apache.fineract.integrationtests.common.Utils; - public class ProvisioningTransactionHelper { - private static final String PROVISIONING_CATEGORY_URL = "/fineract-provider/api/v1/provisioningcategory?" + Utils.TENANT_IDENTIFIER ; + private static final String PROVISIONING_CATEGORY_URL = "/fineract-provider/api/v1/provisioningcategory?" + Utils.TENANT_IDENTIFIER; - private static final String CREATE_PROVISIONING_CRITERIA_URL = "/fineract-provider/api/v1/provisioningcriteria?" + Utils.TENANT_IDENTIFIER; + private static final String CREATE_PROVISIONING_CRITERIA_URL = "/fineract-provider/api/v1/provisioningcriteria?" + + Utils.TENANT_IDENTIFIER; private static final String CREATE_PROVISIONING_ENTRY_URL = "/fineract-provider/api/v1/provisioningentries?" + Utils.TENANT_IDENTIFIER; private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; public ProvisioningTransactionHelper(RequestSpecification requestSpec, ResponseSpecification responeSpec) { - this.requestSpec = requestSpec ; - this.responseSpec = responeSpec ; + this.requestSpec = requestSpec; + this.responseSpec = responeSpec; } public ArrayList retrieveAllProvisioningCategories() { @@ -45,46 +45,49 @@ public class ProvisioningTransactionHelper { } public Integer createProvisioningCriteria(final String provsioningCriteriaJson) { - return Utils.performServerPost(this.requestSpec, this.responseSpec, CREATE_PROVISIONING_CRITERIA_URL, provsioningCriteriaJson, "resourceId"); + return Utils.performServerPost(this.requestSpec, this.responseSpec, CREATE_PROVISIONING_CRITERIA_URL, provsioningCriteriaJson, + "resourceId"); } public Map retrieveProvisioningCriteria(final Integer criteriaId) { - String url = "/fineract-provider/api/v1/provisioningcriteria/"+criteriaId+"?"+Utils.TENANT_IDENTIFIER ; + String url = "/fineract-provider/api/v1/provisioningcriteria/" + criteriaId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, url, ""); } public Integer updateProvisioningCriteria(final Integer criteriaId, final String provsioningCriteriaJson) { - String url = "/fineract-provider/api/v1/provisioningcriteria/"+criteriaId+"?"+Utils.TENANT_IDENTIFIER ; + String url = "/fineract-provider/api/v1/provisioningcriteria/" + criteriaId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerPut(this.requestSpec, this.responseSpec, url, provsioningCriteriaJson, "resourceId"); } public Integer deleteProvisioningCriteria(final Integer criteriaId) { - String url = "/fineract-provider/api/v1/provisioningcriteria/"+criteriaId+"?"+Utils.TENANT_IDENTIFIER; + String url = "/fineract-provider/api/v1/provisioningcriteria/" + criteriaId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerDelete(this.requestSpec, this.responseSpec, url, "resourceId"); } public Integer createProvisioningEntries(final String provsioningCriteriaJson) { - return Utils.performServerPost(this.requestSpec, this.responseSpec, CREATE_PROVISIONING_ENTRY_URL, provsioningCriteriaJson, "resourceId"); + return Utils.performServerPost(this.requestSpec, this.responseSpec, CREATE_PROVISIONING_ENTRY_URL, provsioningCriteriaJson, + "resourceId"); } public Integer updateProvisioningEntry(final String command, final Integer entryId, String jsonBody) { String url = "/fineract-provider/api/v1/provisioningentries/" + entryId + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; - return Utils.performServerPost(requestSpec, responseSpec, url, jsonBody, "resourceId") ; + return Utils.performServerPost(requestSpec, responseSpec, url, jsonBody, "resourceId"); } public Map retrieveProvisioningEntry(final Integer provisioningEntry) { - String url = "/fineract-provider/api/v1/provisioningentries/"+provisioningEntry+"?"+Utils.TENANT_IDENTIFIER; - return Utils.performServerGet(requestSpec, responseSpec, url, "") ; + String url = "/fineract-provider/api/v1/provisioningentries/" + provisioningEntry + "?" + Utils.TENANT_IDENTIFIER; + return Utils.performServerGet(requestSpec, responseSpec, url, ""); } public Map retrieveProvisioningEntries(final Integer provisioningEntry) { - String url = "/fineract-provider/api/v1/provisioningentries/entries?entryId="+provisioningEntry+"&"+Utils.TENANT_IDENTIFIER; - return Utils.performServerGet(requestSpec, responseSpec, url, "") ; + String url = "/fineract-provider/api/v1/provisioningentries/entries?entryId=" + provisioningEntry + "&" + Utils.TENANT_IDENTIFIER; + return Utils.performServerGet(requestSpec, responseSpec, url, ""); } public Map retrieveAllProvisioningEntries() { - String url = "/fineract-provider/api/v1/provisioningentries?dateFormat=dd MMMM yyyy"+"&"+"locale=en"+"&"+Utils.TENANT_IDENTIFIER; - return Utils.performServerGet(requestSpec, responseSpec, url, "") ; + String url = "/fineract-provider/api/v1/provisioningentries?dateFormat=dd MMMM yyyy" + "&" + "locale=en" + "&" + + Utils.TENANT_IDENTIFIER; + return Utils.performServerGet(requestSpec, responseSpec, url, ""); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/rates/RatesHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/rates/RatesHelper.java index 5608bc5a6..7c1043f8e 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/rates/RatesHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/rates/RatesHelper.java @@ -26,73 +26,63 @@ import java.util.HashMap; import org.apache.fineract.integrationtests.common.CommonConstants; import org.apache.fineract.integrationtests.common.Utils; -@SuppressWarnings({"rawtypes", "unchecked"}) +@SuppressWarnings({ "rawtypes", "unchecked" }) public class RatesHelper { - private static final String RATES_URL = "/fineract-provider/api/v1/rates"; - private static final String CREATE_RATES_URL = RATES_URL + "?" + Utils.TENANT_IDENTIFIER; - private final static String PERCENTAGE = "10"; - private final static Integer PRODUCT_APPLY_LOAN = 1; - private final static Boolean ACTIVE = true; + private static final String RATES_URL = "/fineract-provider/api/v1/rates"; + private static final String CREATE_RATES_URL = RATES_URL + "?" + Utils.TENANT_IDENTIFIER; + private final static String PERCENTAGE = "10"; + private final static Integer PRODUCT_APPLY_LOAN = 1; + private final static Boolean ACTIVE = true; - public static ArrayList getRates(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { - return (ArrayList) Utils - .performServerGet(requestSpec, responseSpec, RATES_URL + "?" + Utils.TENANT_IDENTIFIER, ""); - } + public static ArrayList getRates(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + return (ArrayList) Utils.performServerGet(requestSpec, responseSpec, RATES_URL + "?" + Utils.TENANT_IDENTIFIER, ""); + } + public static Integer createRates(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String request) { + return Utils.performServerPost(requestSpec, responseSpec, CREATE_RATES_URL, request, "resourceId"); + } - public static Integer createRates(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, - final String request) { - return Utils - .performServerPost(requestSpec, responseSpec, CREATE_RATES_URL, request, "resourceId"); - } + public static HashMap getRateById(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer rateId) { + return Utils.performServerGet(requestSpec, responseSpec, RATES_URL + "/" + rateId + "?" + Utils.TENANT_IDENTIFIER, ""); + } - public static HashMap getRateById(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, - final Integer rateId) { - return Utils.performServerGet(requestSpec, responseSpec, - RATES_URL + "/" + rateId + "?" + Utils.TENANT_IDENTIFIER, ""); - } + public static HashMap updateRates(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer rateId, final String request) { + return Utils.performServerPut(requestSpec, responseSpec, RATES_URL + "/" + rateId + "?" + Utils.TENANT_IDENTIFIER, request, + CommonConstants.RESPONSE_CHANGES); + } - public static HashMap updateRates(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, - final Integer rateId, final String request) { - return Utils.performServerPut(requestSpec, responseSpec, - RATES_URL + "/" + rateId + "?" + Utils.TENANT_IDENTIFIER, request, - CommonConstants.RESPONSE_CHANGES); - } + public static String getLoanRateJSON() { + return getLoanRateJSON(RatesHelper.PRODUCT_APPLY_LOAN, RatesHelper.PERCENTAGE); + } - public static String getLoanRateJSON() { - return getLoanRateJSON(RatesHelper.PRODUCT_APPLY_LOAN, RatesHelper.PERCENTAGE); - } + public static String getLoanRateJSON(final Integer productApply, final String percentage) { + final HashMap map = populateDefaultsForLoan(); + map.put("percentage", percentage); + map.put("productApply", productApply); + String crateRateJSON = new Gson().toJson(map); + return crateRateJSON; + } - public static String getLoanRateJSON(final Integer productApply, final String percentage) { - final HashMap map = populateDefaultsForLoan(); - map.put("percentage", percentage); - map.put("productApply", productApply); - String crateRateJSON = new Gson().toJson(map); - return crateRateJSON; - } + public static HashMap populateDefaultsForLoan() { + final HashMap map = new HashMap<>(); + map.put("active", RatesHelper.ACTIVE); + map.put("percentage", RatesHelper.PERCENTAGE); + map.put("locale", "en"); + map.put("productApply", RatesHelper.PRODUCT_APPLY_LOAN); + map.put("name", Utils.randomNameGenerator("Rate_Loans_", 6)); + return map; + } - public static HashMap populateDefaultsForLoan() { - final HashMap map = new HashMap<>(); - map.put("active", RatesHelper.ACTIVE); - map.put("percentage", RatesHelper.PERCENTAGE); - map.put("locale", "en"); - map.put("productApply", RatesHelper.PRODUCT_APPLY_LOAN); - map.put("name", Utils.randomNameGenerator("Rate_Loans_", 6)); - return map; - } - - public static String getModifyRateJSON() { - final HashMap map = new HashMap<>(); - map.put("percentage", "15.0"); - map.put("locale", "en"); - String json = new Gson().toJson(map); - return json; - } + public static String getModifyRateJSON() { + final HashMap map = new HashMap<>(); + map.put("percentage", "15.0"); + map.put("locale", "en"); + String json = new Gson().toJson(map); + return json; + } } - diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositAccountHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositAccountHelper.java index b58c875a0..bf402209b 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositAccountHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositAccountHelper.java @@ -34,19 +34,18 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "unused", "rawtypes" }) public class RecurringDepositAccountHelper { + private final static Logger LOG = LoggerFactory.getLogger(RecurringDepositAccountHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; - public RecurringDepositAccountHelper(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public RecurringDepositAccountHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { this.requestSpec = requestSpec; this.responseSpec = responseSpec; } private static final String RECURRING_DEPOSIT_ACCOUNT_URL = "/fineract-provider/api/v1/recurringdepositaccounts"; - private static final String APPLY_RECURRING_DEPOSIT_ACCOUNT_URL = RECURRING_DEPOSIT_ACCOUNT_URL + "?" - + Utils.TENANT_IDENTIFIER; + private static final String APPLY_RECURRING_DEPOSIT_ACCOUNT_URL = RECURRING_DEPOSIT_ACCOUNT_URL + "?" + Utils.TENANT_IDENTIFIER; private static final String APPROVE_RECURRING_DEPOSIT_COMMAND = "approve"; private static final String UNDO_APPROVAL_RECURRING_DEPOSIT_COMMAND = "undoapproval"; private static final String REJECT_RECURRING_DEPOSIT_COMMAND = "reject"; @@ -151,14 +150,13 @@ public class RecurringDepositAccountHelper { public static Integer applyRecurringDepositApplication(final String recurringDepositAccountAsJson, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { LOG.info("--------------------- APPLYING FOR RECURRING DEPOSIT ACCOUNT ------------------------"); - return Utils.performServerPost(requestSpec, responseSpec, APPLY_RECURRING_DEPOSIT_ACCOUNT_URL, - recurringDepositAccountAsJson, CommonConstants.RESPONSE_RESOURCE_ID); + return Utils.performServerPost(requestSpec, responseSpec, APPLY_RECURRING_DEPOSIT_ACCOUNT_URL, recurringDepositAccountAsJson, + CommonConstants.RESPONSE_RESOURCE_ID); } - public static HashMap getRecurringDepositAccountById(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer accountID) { - final String GET_RECURRING_DEPOSIT_BY_ID_URL = RECURRING_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" - + Utils.TENANT_IDENTIFIER; + public static HashMap getRecurringDepositAccountById(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer accountID) { + final String GET_RECURRING_DEPOSIT_BY_ID_URL = RECURRING_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" + Utils.TENANT_IDENTIFIER; LOG.info("------------------------ RETRIEVING RECURRING DEPOSIT ACCOUNT BY ID -------------------------"); return Utils.performServerGet(requestSpec, responseSpec, GET_RECURRING_DEPOSIT_BY_ID_URL, ""); } @@ -217,8 +215,7 @@ public class RecurringDepositAccountHelper { } public HashMap updateRecurringDepositAccount(final String clientID, final String productID, final String accountID, - final String validFrom, final String validTo, final String penalInterestType, - final String submittedOnDate) { + final String validFrom, final String validTo, final String penalInterestType, final String submittedOnDate) { DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US); Calendar todaysDate = Calendar.getInstance(); @@ -226,145 +223,119 @@ public class RecurringDepositAccountHelper { todaysDate.add(Calendar.DATE, -1); final String SUBMITTED_ON_DATE = dateFormat.format(todaysDate.getTime()); final String EXPECTED_FIRST_DEPOSIT_ON_ON_DATE = SUBMITTED_ON_DATE; - final String recurringDepositApplicationJSON = new RecurringDepositAccountHelper(this.requestSpec, - this.responseSpec).withSubmittedOnDate(SUBMITTED_ON_DATE) - .withExpectedFirstDepositOnDate(EXPECTED_FIRST_DEPOSIT_ON_ON_DATE) - .build(clientID, productID, penalInterestType); + final String recurringDepositApplicationJSON = new RecurringDepositAccountHelper(this.requestSpec, this.responseSpec) + .withSubmittedOnDate(SUBMITTED_ON_DATE).withExpectedFirstDepositOnDate(EXPECTED_FIRST_DEPOSIT_ON_ON_DATE) + .build(clientID, productID, penalInterestType); return Utils.performServerPut(this.requestSpec, this.responseSpec, - RECURRING_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" + Utils.TENANT_IDENTIFIER, - recurringDepositApplicationJSON, CommonConstants.RESPONSE_CHANGES); + RECURRING_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" + Utils.TENANT_IDENTIFIER, recurringDepositApplicationJSON, + CommonConstants.RESPONSE_CHANGES); } - public HashMap updateInterestCalculationConfigForRecurringDeposit(final String clientID, final String productID, - final String accountID, final String submittedOnDate, final String validFrom, final String validTo, - final String numberOfDaysPerYear, final String penalInterestType, final String interestCalculationType, - final String interestCompoundingPeriodType, final String interestPostingPeriodType, - final String expectedFirstDepositOnDate) { + public HashMap updateInterestCalculationConfigForRecurringDeposit(final String clientID, final String productID, final String accountID, + final String submittedOnDate, final String validFrom, final String validTo, final String numberOfDaysPerYear, + final String penalInterestType, final String interestCalculationType, final String interestCompoundingPeriodType, + final String interestPostingPeriodType, final String expectedFirstDepositOnDate) { - final String recurringDepositApplicationJSON = new RecurringDepositAccountHelper(this.requestSpec, - this.responseSpec) // - .withSubmittedOnDate(submittedOnDate) // - .withNumberOfDaysPerYear(numberOfDaysPerYear) // - .withInterestCalculationPeriodType(interestCalculationType) // - .withInterestCompoundingPeriodType(interestCompoundingPeriodType) // - .withInterestPostingPeriodType(interestPostingPeriodType) // - .withExpectedFirstDepositOnDate(expectedFirstDepositOnDate) // - .build(clientID, productID, penalInterestType); + final String recurringDepositApplicationJSON = new RecurringDepositAccountHelper(this.requestSpec, this.responseSpec) // + .withSubmittedOnDate(submittedOnDate) // + .withNumberOfDaysPerYear(numberOfDaysPerYear) // + .withInterestCalculationPeriodType(interestCalculationType) // + .withInterestCompoundingPeriodType(interestCompoundingPeriodType) // + .withInterestPostingPeriodType(interestPostingPeriodType) // + .withExpectedFirstDepositOnDate(expectedFirstDepositOnDate) // + .build(clientID, productID, penalInterestType); return Utils.performServerPut(this.requestSpec, this.responseSpec, - RECURRING_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" + Utils.TENANT_IDENTIFIER, - recurringDepositApplicationJSON, CommonConstants.RESPONSE_CHANGES); + RECURRING_DEPOSIT_ACCOUNT_URL + "/" + accountID + "?" + Utils.TENANT_IDENTIFIER, recurringDepositApplicationJSON, + CommonConstants.RESPONSE_CHANGES); } - public Integer updateTransactionForRecurringDeposit(final Integer accountID, final Integer transactionId, - final String transactionDate, final Float transactionAmount) { - LOG.info( - "--------------------------------- UPDATE RECURRING DEPOSIT TRANSACTION ------------------------------------"); + public Integer updateTransactionForRecurringDeposit(final Integer accountID, final Integer transactionId, final String transactionDate, + final Float transactionAmount) { + LOG.info("--------------------------------- UPDATE RECURRING DEPOSIT TRANSACTION ------------------------------------"); return Utils.performServerPost(this.requestSpec, this.responseSpec, RECURRING_DEPOSIT_ACCOUNT_URL + "/" + accountID + "/transactions/" + transactionId + "?command=" + MODIFY_TRANSACTION_COMMAND, getUpdateTransactionAsJSON(transactionDate, transactionAmount), CommonConstants.RESPONSE_RESOURCE_ID); } - public Integer undoTransactionForRecurringDeposit(final Integer accountID, final Integer transactionId, - final String transactionDate, final Float transactionAmount) { - LOG.info( - "--------------------------------- UNDO RECURRING DEPOSIT TRANSACTION ------------------------------------"); + public Integer undoTransactionForRecurringDeposit(final Integer accountID, final Integer transactionId, final String transactionDate, + final Float transactionAmount) { + LOG.info("--------------------------------- UNDO RECURRING DEPOSIT TRANSACTION ------------------------------------"); return Utils.performServerPost(this.requestSpec, this.responseSpec, - RECURRING_DEPOSIT_ACCOUNT_URL + "/" + accountID + "/transactions/" + transactionId + "?command=" - + UNDO_TRANSACTION_COMMAND, + RECURRING_DEPOSIT_ACCOUNT_URL + "/" + accountID + "/transactions/" + transactionId + "?command=" + UNDO_TRANSACTION_COMMAND, getUpdateTransactionAsJSON(transactionDate, transactionAmount), CommonConstants.RESPONSE_RESOURCE_ID); } public HashMap approveRecurringDeposit(final Integer recurringDepositAccountID, final String approvedOnDate) { - LOG.info( - "--------------------------------- APPROVING RECURRING DEPOSIT APPLICATION ------------------------------------"); + LOG.info("--------------------------------- APPROVING RECURRING DEPOSIT APPLICATION ------------------------------------"); return performRecurringDepositApplicationActions( createRecurringDepositOperationURL(APPROVE_RECURRING_DEPOSIT_COMMAND, recurringDepositAccountID), getApproveRecurringDepositAccountAsJSON(approvedOnDate)); } public HashMap undoApproval(final Integer recurringDepositAccountID) { - LOG.info( - "--------------------------------- UNDO APPROVING RECURRING DEPOSIT APPLICATION -------------------------------"); + LOG.info("--------------------------------- UNDO APPROVING RECURRING DEPOSIT APPLICATION -------------------------------"); final String undoBodyJson = "{'note':'UNDO APPROVAL'}"; return performRecurringDepositApplicationActions( - createRecurringDepositOperationURL(UNDO_APPROVAL_RECURRING_DEPOSIT_COMMAND, recurringDepositAccountID), - undoBodyJson); + createRecurringDepositOperationURL(UNDO_APPROVAL_RECURRING_DEPOSIT_COMMAND, recurringDepositAccountID), undoBodyJson); } public HashMap rejectApplication(final Integer recurringDepositAccountID, final String rejectedOnDate) { - LOG.info( - "--------------------------------- REJECT RECURRING DEPOSIT APPLICATION -------------------------------"); + LOG.info("--------------------------------- REJECT RECURRING DEPOSIT APPLICATION -------------------------------"); return performRecurringDepositApplicationActions( createRecurringDepositOperationURL(REJECT_RECURRING_DEPOSIT_COMMAND, recurringDepositAccountID), getRejectedRecurringDepositAsJSON(rejectedOnDate)); } - public HashMap withdrawApplication(final Integer recurringDepositAccountID, - final String withdrawApplicationOnDate) { - LOG.info( - "--------------------------------- WITHDRAW RECURRING DEPOSIT APPLICATION -------------------------------"); + public HashMap withdrawApplication(final Integer recurringDepositAccountID, final String withdrawApplicationOnDate) { + LOG.info("--------------------------------- WITHDRAW RECURRING DEPOSIT APPLICATION -------------------------------"); return performRecurringDepositApplicationActions( - createRecurringDepositOperationURL(WITHDRAWN_BY_CLIENT_RECURRING_DEPOSIT_COMMAND, - recurringDepositAccountID), + createRecurringDepositOperationURL(WITHDRAWN_BY_CLIENT_RECURRING_DEPOSIT_COMMAND, recurringDepositAccountID), getWithdrawnRecurringDepositAccountAsJSON(withdrawApplicationOnDate)); } public HashMap activateRecurringDeposit(final Integer recurringDepositAccountID, final String activationDate) { - LOG.info( - "---------------------------------- ACTIVATING RECURRING DEPOSIT APPLICATION ----------------------------------"); + LOG.info("---------------------------------- ACTIVATING RECURRING DEPOSIT APPLICATION ----------------------------------"); return performRecurringDepositApplicationActions( createRecurringDepositOperationURL(ACTIVATE_RECURRING_DEPOSIT_COMMAND, recurringDepositAccountID), getActivatedRecurringDepositAccountAsJSON(activationDate)); } - public Object deleteRecurringDepositApplication(final Integer recurringDepositAccountID, - final String jsonAttributeToGetBack) { - LOG.info( - "---------------------------------- DELETE RECURRING DEPOSIT APPLICATION ----------------------------------"); + public Object deleteRecurringDepositApplication(final Integer recurringDepositAccountID, final String jsonAttributeToGetBack) { + LOG.info("---------------------------------- DELETE RECURRING DEPOSIT APPLICATION ----------------------------------"); return Utils.performServerDelete(this.requestSpec, this.responseSpec, - RECURRING_DEPOSIT_ACCOUNT_URL + "/" + recurringDepositAccountID + "?" + Utils.TENANT_IDENTIFIER, - jsonAttributeToGetBack); + RECURRING_DEPOSIT_ACCOUNT_URL + "/" + recurringDepositAccountID + "?" + Utils.TENANT_IDENTIFIER, jsonAttributeToGetBack); } public Integer calculateInterestForRecurringDeposit(final Integer recurringDepositAccountId) { - LOG.info( - "--------------------------------- CALCULATING INTEREST FOR RECURRING DEPOSIT --------------------------------"); + LOG.info("--------------------------------- CALCULATING INTEREST FOR RECURRING DEPOSIT --------------------------------"); return (Integer) performRecurringDepositActions( - createRecurringDepositCalculateInterestURL(CALCULATE_INTEREST_RECURRING_DEPOSIT_COMMAND, - recurringDepositAccountId), + createRecurringDepositCalculateInterestURL(CALCULATE_INTEREST_RECURRING_DEPOSIT_COMMAND, recurringDepositAccountId), getCalculatedInterestForRecurringDepositApplicationAsJSON(), CommonConstants.RESPONSE_RESOURCE_ID); } public Integer postInterestForRecurringDeposit(final Integer recurringDepositAccountId) { - LOG.info( - "--------------------------------- POST INTEREST FOR RECURRING DEPOSIT --------------------------------"); + LOG.info("--------------------------------- POST INTEREST FOR RECURRING DEPOSIT --------------------------------"); return (Integer) performRecurringDepositActions( - createRecurringDepositCalculateInterestURL(POST_INTEREST_RECURRING_DEPOSIT_COMMAND, - recurringDepositAccountId), + createRecurringDepositCalculateInterestURL(POST_INTEREST_RECURRING_DEPOSIT_COMMAND, recurringDepositAccountId), getCalculatedInterestForRecurringDepositApplicationAsJSON(), CommonConstants.RESPONSE_RESOURCE_ID); } public Integer depositToRecurringDepositAccount(final Integer recurringDepositAccountId, final Float depositAmount, final String depositedOnDate) { - LOG.info( - "--------------------------------- DEPOSIT TO RECURRING DEPOSIT ACCOUNT --------------------------------"); + LOG.info("--------------------------------- DEPOSIT TO RECURRING DEPOSIT ACCOUNT --------------------------------"); return (Integer) performRecurringDepositActions( createDepositToRecurringDepositURL(DEPOSIT_INTO_RECURRING_DEPOSIT_COMMAND, recurringDepositAccountId), - getDepositToRecurringDepositAccountAsJSON(depositAmount, depositedOnDate), - CommonConstants.RESPONSE_RESOURCE_ID); + getDepositToRecurringDepositAccountAsJSON(depositAmount, depositedOnDate), CommonConstants.RESPONSE_RESOURCE_ID); } - public HashMap calculatePrematureAmountForRecurringDeposit(final Integer recurringDepositAccountId, - final String closedOnDate) { - LOG.info( - "--------------------- CALCULATING PREMATURE AMOUNT FOR RECURRING DEPOSIT ----------------------------"); + public HashMap calculatePrematureAmountForRecurringDeposit(final Integer recurringDepositAccountId, final String closedOnDate) { + LOG.info("--------------------- CALCULATING PREMATURE AMOUNT FOR RECURRING DEPOSIT ----------------------------"); return (HashMap) performRecurringDepositActions( - createRecurringDepositCalculateInterestURL(CALCULATE_PREMATURE_AMOUNT_COMMAND, - recurringDepositAccountId), + createRecurringDepositCalculateInterestURL(CALCULATE_PREMATURE_AMOUNT_COMMAND, recurringDepositAccountId), getCalculatedPrematureAmountForRecurringDepositAccountAsJSON(closedOnDate), ""); } @@ -373,8 +344,7 @@ public class RecurringDepositAccountHelper { LOG.info("--------------------- PREMATURE CLOSE FOR RECURRING DEPOSIT ----------------------------"); return performRecurringDepositActions( createRecurringDepositCalculateInterestURL(PREMATURE_CLOSE_COMMAND, recurringDepositAccountId), - getPrematureCloseForRecurringDepositAccountAsJSON(closedOnDate, closureType, toSavingsId), - jsonAttributeToGetBack); + getPrematureCloseForRecurringDepositAccountAsJSON(closedOnDate, closureType, toSavingsId), jsonAttributeToGetBack); } private String getApproveRecurringDepositAccountAsJSON(final String approvedOnDate) { @@ -459,8 +429,8 @@ public class RecurringDepositAccountHelper { return recurringDepositAccountPrematureClosureJson; } - private String getPrematureCloseForRecurringDepositAccountAsJSON(final String closedOnDate, - final String closureType, final Integer toSavingsId) { + private String getPrematureCloseForRecurringDepositAccountAsJSON(final String closedOnDate, final String closureType, + final Integer toSavingsId) { final HashMap map = new HashMap<>(); map.put("locale", CommonConstants.LOCALE); map.put("dateFormat", CommonConstants.DATE_FORMAT); @@ -476,8 +446,7 @@ public class RecurringDepositAccountHelper { } private String createRecurringDepositOperationURL(final String command, final Integer recurringDepositAccountID) { - return RECURRING_DEPOSIT_ACCOUNT_URL + "/" + recurringDepositAccountID + "?command=" + command + "&" - + Utils.TENANT_IDENTIFIER; + return RECURRING_DEPOSIT_ACCOUNT_URL + "/" + recurringDepositAccountID + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; } private Object performRecurringDepositActions(final String postURLForRecurringDeposit, final String jsonToBeSent, @@ -486,26 +455,23 @@ public class RecurringDepositAccountHelper { jsonAttributeToGetBack); } - private HashMap performRecurringDepositApplicationActions(final String postURLForRecurringDepositAction, - final String jsonToBeSent) { + private HashMap performRecurringDepositApplicationActions(final String postURLForRecurringDepositAction, final String jsonToBeSent) { HashMap status = null; - final HashMap response = Utils.performServerPost(this.requestSpec, this.responseSpec, - postURLForRecurringDepositAction, jsonToBeSent, CommonConstants.RESPONSE_CHANGES); + final HashMap response = Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForRecurringDepositAction, + jsonToBeSent, CommonConstants.RESPONSE_CHANGES); if (response != null) { status = (HashMap) response.get("status"); } return status; } - private String createRecurringDepositCalculateInterestURL(final String command, - final Integer recurringDepositAccountID) { - return RECURRING_DEPOSIT_ACCOUNT_URL + "/" + recurringDepositAccountID + "?command=" + command + "&" - + Utils.TENANT_IDENTIFIER; + private String createRecurringDepositCalculateInterestURL(final String command, final Integer recurringDepositAccountID) { + return RECURRING_DEPOSIT_ACCOUNT_URL + "/" + recurringDepositAccountID + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; } private String createDepositToRecurringDepositURL(final String command, final Integer recurringDepositAccountID) { - return RECURRING_DEPOSIT_ACCOUNT_URL + "/" + recurringDepositAccountID + "/transactions" + "?command=" + command - + "&" + Utils.TENANT_IDENTIFIER; + return RECURRING_DEPOSIT_ACCOUNT_URL + "/" + recurringDepositAccountID + "/transactions" + "?command=" + command + "&" + + Utils.TENANT_IDENTIFIER; } public RecurringDepositAccountHelper withSubmittedOnDate(final String recurringDepositApplicationSubmittedDate) { @@ -529,8 +495,7 @@ public class RecurringDepositAccountHelper { return this; } - public RecurringDepositAccountHelper withInterestCompoundingPeriodType( - final String interestCompoundingPeriodTypeId) { + public RecurringDepositAccountHelper withInterestCompoundingPeriodType(final String interestCompoundingPeriodTypeId) { this.interestCompoundingPeriodType = interestCompoundingPeriodTypeId; return this; } @@ -550,4 +515,4 @@ public class RecurringDepositAccountHelper { return this; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositAccountStatusChecker.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositAccountStatusChecker.java index 0f86360a3..ef8bed391 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositAccountStatusChecker.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositAccountStatusChecker.java @@ -30,50 +30,52 @@ import org.slf4j.LoggerFactory; @SuppressWarnings("rawtypes") public class RecurringDepositAccountStatusChecker { + private final static Logger LOG = LoggerFactory.getLogger(RecurringDepositAccountStatusChecker.class); private static final String RECURRING_DEPOSIT_ACCOUNT_URL = "/fineract-provider/api/v1/recurringdepositaccounts"; public static void verifyRecurringDepositIsApproved(final HashMap recurringDepositStatusHashMap) { LOG.info("-------------------- VERIFYING RECURRING DEPOSIT APPLICATION IS APPROVED --------------------"); assertTrue(getStatus(recurringDepositStatusHashMap, "approved"), "Error in Approving Recurring deposit application"); - LOG.info("{}",recurringDepositStatusHashMap.toString()); + LOG.info("{}", recurringDepositStatusHashMap.toString()); } public static void verifyRecurringDepositIsPending(final HashMap recurringDepositStatusHashMap) { LOG.info("-------------------- VERIFYING RECURRING DEPOSIT APPLICATION IS PENDING --------------------"); assertTrue(getStatus(recurringDepositStatusHashMap, "submittedAndPendingApproval"), - "RECURRING DEPOSIT ACCOUNT IS NOT IN PENDING STATE"); - LOG.info("{}",recurringDepositStatusHashMap.toString()); + "RECURRING DEPOSIT ACCOUNT IS NOT IN PENDING STATE"); + LOG.info("{}", recurringDepositStatusHashMap.toString()); } public static void verifyRecurringDepositIsActive(final HashMap recurringDepositStatusHashMap) { LOG.info("----------------- VERIFYING RECURRING DEPOSIT APPLICATION IS ACTIVE -----------------"); assertTrue(getStatus(recurringDepositStatusHashMap, "active"), "ERROR IN ACTIVATING THE RECURRING DEPOSIT APPLICATION"); - LOG.info("{}",recurringDepositStatusHashMap.toString()); + LOG.info("{}", recurringDepositStatusHashMap.toString()); } public static void verifyRecurringDepositIsRejected(final HashMap recurringDepositStatusHashMap) { LOG.info("-------------- VERIFYING RECURRING DEPOSIT APPLICATION IS REJECTED ----------------"); assertTrue(getStatus(recurringDepositStatusHashMap, "rejected"), "ERROR IN REJECTING THE RECURRING DEPOSIT APPLICATION"); - LOG.info("{}",recurringDepositStatusHashMap.toString()); + LOG.info("{}", recurringDepositStatusHashMap.toString()); } public static void verifyRecurringDepositIsWithdrawn(final HashMap recurringDepositStatusHashMap) { LOG.info("---------------- VERIFYING RECURRING DEPOSIT APPLICATION IS WITHDRAWN ----------------"); - assertTrue(getStatus(recurringDepositStatusHashMap, "withdrawnByApplicant"), "ERROR IN WITHDRAW THE RECURRING DEPOSIT APPLICATION"); - LOG.info("{}",recurringDepositStatusHashMap.toString()); + assertTrue(getStatus(recurringDepositStatusHashMap, "withdrawnByApplicant"), + "ERROR IN WITHDRAW THE RECURRING DEPOSIT APPLICATION"); + LOG.info("{}", recurringDepositStatusHashMap.toString()); } public static void verifyRecurringDepositAccountIsClosed(final HashMap recurringDepositStatusHashMap) { LOG.info("--------------------- VERIFYING RECURRING DEPOSIT APPLICATION IS CLOSED ---------------------"); assertTrue(getStatus(recurringDepositStatusHashMap, "closed"), "ERROR IN CLOSING THE RECURRING DEPOSIT APPLICATION"); - LOG.info("{}",recurringDepositStatusHashMap.toString()); + LOG.info("{}", recurringDepositStatusHashMap.toString()); } public static void verifyRecurringDepositAccountIsNotActive(final HashMap recurringDepositStatusHashMap) { LOG.info("------------------ VERIFYING RECURRING DEPOSIT APPLICATION IS INACTIVE --------------------"); Assertions.assertFalse(getStatus(recurringDepositStatusHashMap, "active")); - LOG.info("{}",recurringDepositStatusHashMap.toString()); + LOG.info("{}", recurringDepositStatusHashMap.toString()); } public static HashMap getStatusOfRecurringDepositAccount(final RequestSpecification requestSpec, @@ -86,17 +88,17 @@ public class RecurringDepositAccountStatusChecker { public static void verifyRecurringDepositAccountIsPrematureClosed(HashMap recurringDepositStatusHashMap) { LOG.info("--------------------- VERIFYING RECURRING DEPOSIT APPLICATION IS CLOSED ---------------------"); assertTrue(getStatus(recurringDepositStatusHashMap, "prematureClosed"), - "ERROR IN PREMATURELY CLOSING THE RECURRING DEPOSIT ACCOUNT"); - LOG.info("{}",recurringDepositStatusHashMap.toString()); + "ERROR IN PREMATURELY CLOSING THE RECURRING DEPOSIT ACCOUNT"); + LOG.info("{}", recurringDepositStatusHashMap.toString()); } public static void verifyRecurringDepositAccountIsMatured(HashMap recurringDepositStatusHashMap) { LOG.info("--------------------- VERIFYING RECURRING DEPOSIT APPLICATION IS MATURED ---------------------"); assertTrue(getStatus(recurringDepositStatusHashMap, "matured"), "ERROR IN MATURITY JOB OF THE RECURRING DEPOSIT ACCOUNT"); - LOG.info("{}",recurringDepositStatusHashMap.toString()); + LOG.info("{}", recurringDepositStatusHashMap.toString()); } private static boolean getStatus(final HashMap recurringDepositStatusMap, final String recurringDepositStatusString) { return (Boolean) recurringDepositStatusMap.get(recurringDepositStatusString); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositProductHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositProductHelper.java index b598c17f7..49ae0815e 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositProductHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/recurringdeposit/RecurringDepositProductHelper.java @@ -32,6 +32,7 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "unused", "rawtypes" }) public class RecurringDepositProductHelper { + private final static Logger LOG = LoggerFactory.getLogger(RecurringDepositProductHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; @@ -155,7 +156,7 @@ public class RecurringDepositProductHelper { } String RecurringDepositProductCreateJson = new Gson().toJson(map); - LOG.info("{}",RecurringDepositProductCreateJson); + LOG.info("{}", RecurringDepositProductCreateJson); return RecurringDepositProductCreateJson; } @@ -198,7 +199,6 @@ public class RecurringDepositProductHelper { return this; } - private Map getAccountMappingForCashBased() { final Map map = new HashMap<>(); if (accountList != null) { @@ -236,8 +236,8 @@ public class RecurringDepositProductHelper { public static ArrayList retrieveAllRecurringDepositProducts(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { LOG.info("----------------- RETRIEVING ALL RECURRING DEPOSIT PRODUCTS---------------------------"); - final ArrayList response = Utils.performServerGet(requestSpec, responseSpec, RECURRING_DEPOSIT_PRODUCT_URL + "?" - + Utils.TENANT_IDENTIFIER, ""); + final ArrayList response = Utils.performServerGet(requestSpec, responseSpec, + RECURRING_DEPOSIT_PRODUCT_URL + "?" + Utils.TENANT_IDENTIFIER, ""); return response; } @@ -458,4 +458,4 @@ public class RecurringDepositProductHelper { return chartSlabs; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/report/ReportData.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/report/ReportData.java index d64e39388..800a84621 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/report/ReportData.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/report/ReportData.java @@ -44,8 +44,8 @@ public class ReportData { this.reportDescription = reportDescription; } - public static ReportData instance(final Long reportId, final String reportName, final String reportType, - final String reportSubType, final Map reportParamName, final String reportDescription) { + public static ReportData instance(final Long reportId, final String reportName, final String reportType, final String reportSubType, + final Map reportParamName, final String reportDescription) { return new ReportData(reportId, reportName, reportType, reportSubType, reportParamName, reportDescription); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/AccountTransferHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/AccountTransferHelper.java index c2621f966..a9f21dd93 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/AccountTransferHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/AccountTransferHelper.java @@ -27,6 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AccountTransferHelper { + private final static Logger LOG = LoggerFactory.getLogger(AccountTransferHelper.class); private static final String ACCOUNT_TRANSFER_URL = "/fineract-provider/api/v1/accounttransfers"; private static final String LOAN_REFUND_BY_TRANSFER_URL = "/fineract-provider/api/v1/accounttransfers/refundByTransfer"; @@ -47,9 +48,8 @@ public class AccountTransferHelper { this.responseSpec = responseSpec; } - public String build(final String fromAccountId, final String fromClientId, final String toAccountId, - final String toClientId, final String fromAccountType, final String toAccountType, - final String transferAmount) { + public String build(final String fromAccountId, final String fromClientId, final String toAccountId, final String toClientId, + final String fromAccountType, final String toAccountType, final String transferAmount) { final HashMap map = new HashMap<>(); map.put("dateFormat", "dd MMMM yyyy"); @@ -76,26 +76,25 @@ public class AccountTransferHelper { } public Integer accountTransfer(final Integer fromClientId, final Integer fromAccountId, final Integer toClientId, - final Integer toAccountId, final String fromAccountType, final String toAccountType, - final String transferAmount) { + final Integer toAccountId, final String fromAccountType, final String toAccountType, final String transferAmount) { LOG.info("--------------------------------ACCOUNT TRANSFER--------------------------------"); final String accountTransferJSON = new AccountTransferHelper(this.requestSpec, this.responseSpec) // .withTransferOnDate(ACCOUNT_TRANSFER_DATE) // - .build(fromAccountId.toString(), fromClientId.toString(), toAccountId.toString(), toClientId.toString(), - fromAccountType, toAccountType, transferAmount); - return Utils.performServerPost(this.requestSpec, this.responseSpec, - ACCOUNT_TRANSFER_URL + "?" + Utils.TENANT_IDENTIFIER, accountTransferJSON, "savingsId"); + .build(fromAccountId.toString(), fromClientId.toString(), toAccountId.toString(), toClientId.toString(), fromAccountType, + toAccountType, transferAmount); + return Utils.performServerPost(this.requestSpec, this.responseSpec, ACCOUNT_TRANSFER_URL + "?" + Utils.TENANT_IDENTIFIER, + accountTransferJSON, "savingsId"); } public Integer refundLoanByTransfer(final String date, final Integer fromClientId, final Integer fromAccountId, - final Integer toClientId, final Integer toAccountId, final String fromAccountType, - final String toAccountType, final String transferAmount) { + final Integer toClientId, final Integer toAccountId, final String fromAccountType, final String toAccountType, + final String transferAmount) { LOG.info("--------------------------------ACCOUNT TRANSFER--------------------------------"); final String accountTransferJSON = new AccountTransferHelper(this.requestSpec, this.responseSpec) // .withTransferOnDate(date) // - .build(fromAccountId.toString(), fromClientId.toString(), toAccountId.toString(), toClientId.toString(), - fromAccountType, toAccountType, transferAmount); - return Utils.performServerPost(this.requestSpec, this.responseSpec, - LOAN_REFUND_BY_TRANSFER_URL + "?" + Utils.TENANT_IDENTIFIER, accountTransferJSON, "savingsId"); + .build(fromAccountId.toString(), fromClientId.toString(), toAccountId.toString(), toClientId.toString(), fromAccountType, + toAccountType, transferAmount); + return Utils.performServerPost(this.requestSpec, this.responseSpec, LOAN_REFUND_BY_TRANSFER_URL + "?" + Utils.TENANT_IDENTIFIER, + accountTransferJSON, "savingsId"); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsAccountHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsAccountHelper.java index f898d21fc..959f912ad 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsAccountHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsAccountHelper.java @@ -107,17 +107,17 @@ public class SavingsAccountHelper { } public Integer applyForSavingsApplicationOnDate(final Integer ID, final Integer savingsProductID, final String accountType, - final String submittedOnDate) { + final String submittedOnDate) { return applyForSavingsApplicationOnDate(ID, savingsProductID, accountType, null, false, submittedOnDate); } public Integer applyForSavingsApplicationWithExternalId(final Integer ID, final Integer savingsProductID, final String accountType, - String externalId, boolean withdrawalFeeForTransfers) { + String externalId, boolean withdrawalFeeForTransfers) { return applyForSavingsApplicationOnDate(ID, savingsProductID, accountType, externalId, withdrawalFeeForTransfers, CREATED_DATE); } public Integer applyForSavingsApplicationOnDate(final Integer ID, final Integer savingsProductID, final String accountType, - String externalId, boolean withdrawalFeeForTransfers, final String submittedOnDate) { + String externalId, boolean withdrawalFeeForTransfers, final String submittedOnDate) { LOG.info("--------------------------------APPLYING FOR SAVINGS APPLICATION--------------------------------"); final String savingsApplicationJSON = new SavingsApplicationTestBuilder() // .withExternalId(externalId) // @@ -149,28 +149,30 @@ public class SavingsAccountHelper { savingsApplicationJSON, responseAttribute); } - public HashMap updateSavingsAccount(final Integer ID, final Integer savingsProductID, final Integer savingsId, final String accountType) { + public HashMap updateSavingsAccount(final Integer ID, final Integer savingsProductID, final Integer savingsId, + final String accountType) { final String savingsApplicationJSON = new SavingsApplicationTestBuilder() // .withSubmittedOnDate(CREATED_DATE_PLUS_ONE) // .build(ID.toString(), savingsProductID.toString(), accountType); - return Utils.performServerPut(this.requestSpec, this.responseSpec, SAVINGS_ACCOUNT_URL + "/" + savingsId + "?" - + Utils.TENANT_IDENTIFIER, savingsApplicationJSON, CommonConstants.RESPONSE_CHANGES); + return Utils.performServerPut(this.requestSpec, this.responseSpec, + SAVINGS_ACCOUNT_URL + "/" + savingsId + "?" + Utils.TENANT_IDENTIFIER, savingsApplicationJSON, + CommonConstants.RESPONSE_CHANGES); } - //GLIM_GSIM_TESTING + + // GLIM_GSIM_TESTING public Integer applyForGsimApplication(List> clientArray) { LOG.info("----------------------------APPLYING FOR GSIM SAVINGS APPLICATION----------------------------"); LOG.info("clientArray is : {} ", clientArray); String clientArrays = new SavingsApplicationTestBuilder() // - .withClientArray(clientArray) - .build(); + .withClientArray(clientArray).build(); return SavingsAccountHelper.applyForGsimApplication(clientArrays, requestSpec, responseSpec); } public static Integer applyForGsimApplication(final String clientArrays, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { - return Utils.performServerPost(requestSpec,responseSpec, SAVINGS_ACCOUNT_URL + GSIM_SAVINGS +"?" + Utils.TENANT_IDENTIFIER, - clientArrays, "gsimId"); + return Utils.performServerPost(requestSpec, responseSpec, SAVINGS_ACCOUNT_URL + GSIM_SAVINGS + "?" + Utils.TENANT_IDENTIFIER, + clientArrays, "gsimId"); } public HashMap updateSavingsAccountWithHoldTaxStatus(final Integer savingsId, final boolean value) { @@ -178,8 +180,9 @@ public class SavingsAccountHelper { map.put("withHoldTax", value); String json = new Gson().toJson(map); - return Utils.performServerPut(this.requestSpec, this.responseSpec, SAVINGS_ACCOUNT_URL + "/" + savingsId + "?command=" - + UPDATE_WITHHOLD_TAX_STATUS + "&" + Utils.TENANT_IDENTIFIER, json, CommonConstants.RESPONSE_CHANGES); + return Utils.performServerPut(this.requestSpec, this.responseSpec, + SAVINGS_ACCOUNT_URL + "/" + savingsId + "?command=" + UPDATE_WITHHOLD_TAX_STATUS + "&" + Utils.TENANT_IDENTIFIER, json, + CommonConstants.RESPONSE_CHANGES); } public HashMap approveSavings(final Integer savingsID) { @@ -221,7 +224,8 @@ public class SavingsAccountHelper { public HashMap activateSavings(final Integer savingsID) { LOG.info("---------------------------------- ACTIVATING SAVINGS APPLICATION ----------------------------------"); - return performSavingApplicationActions(createSavingsOperationURL(ACTIVATE_SAVINGS_COMMAND, savingsID), getActivatedSavingsAsJSON(), IS_BLOCK); + return performSavingApplicationActions(createSavingsOperationURL(ACTIVATE_SAVINGS_COMMAND, savingsID), getActivatedSavingsAsJSON(), + IS_BLOCK); } public HashMap closeSavingsAccount(final Integer savingsID, String withdrawBalance) { @@ -232,8 +236,8 @@ public class SavingsAccountHelper { public Object deleteSavingsApplication(final Integer savingsId, final String jsonAttributeToGetBack) { LOG.info("---------------------------------- DELETE SAVINGS APPLICATION ----------------------------------"); - return Utils.performServerDelete(this.requestSpec, this.responseSpec, SAVINGS_ACCOUNT_URL + "/" + savingsId + "?" - + Utils.TENANT_IDENTIFIER, jsonAttributeToGetBack); + return Utils.performServerDelete(this.requestSpec, this.responseSpec, + SAVINGS_ACCOUNT_URL + "/" + savingsId + "?" + Utils.TENANT_IDENTIFIER, jsonAttributeToGetBack); } @@ -289,7 +293,7 @@ public class SavingsAccountHelper { getPeriodChargeRequestJSON(chargeId, addDueDate, amount), CommonConstants.RESPONSE_RESOURCE_ID); } - public Integer addChargesForSavingsWithDueDate(final Integer savingsId, final Integer chargeId, String addDueDate,Integer amount) { + public Integer addChargesForSavingsWithDueDate(final Integer savingsId, final Integer chargeId, String addDueDate, Integer amount) { return (Integer) performSavingActions(SAVINGS_ACCOUNT_URL + "/" + savingsId + "/charges?" + Utils.TENANT_IDENTIFIER, getPeriodChargeRequestJSONWithDueDate(chargeId, addDueDate, amount), CommonConstants.RESPONSE_RESOURCE_ID); } @@ -305,27 +309,29 @@ public class SavingsAccountHelper { } public HashMap updateCharges(final Integer chargeId, final Integer savingsId) { - return Utils.performServerPut(this.requestSpec, this.responseSpec, SAVINGS_ACCOUNT_URL + "/" + savingsId + "/charges/" + chargeId - + "?" + Utils.TENANT_IDENTIFIER, getModifyChargeJSON(), CommonConstants.RESPONSE_CHANGES); + return Utils.performServerPut(this.requestSpec, this.responseSpec, + SAVINGS_ACCOUNT_URL + "/" + savingsId + "/charges/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, getModifyChargeJSON(), + CommonConstants.RESPONSE_CHANGES); } public Integer deleteCharge(final Integer chargeId, final Integer savingsId) { - return Utils.performServerDelete(this.requestSpec, this.responseSpec, SAVINGS_ACCOUNT_URL + "/" + savingsId + "/charges/" - + chargeId + "?" + Utils.TENANT_IDENTIFIER, CommonConstants.RESPONSE_RESOURCE_ID); + return Utils.performServerDelete(this.requestSpec, this.responseSpec, + SAVINGS_ACCOUNT_URL + "/" + savingsId + "/charges/" + chargeId + "?" + Utils.TENANT_IDENTIFIER, + CommonConstants.RESPONSE_RESOURCE_ID); } public HashMap blockSavings(final Integer savingsID) { LOG.info("---------------------------------- BLOCKING SAVINGS ACCOUNT ----------------------------------"); Boolean isBlock = true; - return performSavingApplicationActions(createSavingsOperationURL(BLOCK_SAVINGS_COMMAND, savingsID), - getActivatedSavingsAsJSON(), isBlock); + return performSavingApplicationActions(createSavingsOperationURL(BLOCK_SAVINGS_COMMAND, savingsID), getActivatedSavingsAsJSON(), + isBlock); } public HashMap unblockSavings(final Integer savingsID) { LOG.info("---------------------------------- UNBLOCKING SAVINGS ACCOUNT ----------------------------------"); Boolean isBlock = true; - return performSavingApplicationActions(createSavingsOperationURL(UNBLOCK_SAVINGS_COMMAND, savingsID), - getActivatedSavingsAsJSON(), isBlock); + return performSavingApplicationActions(createSavingsOperationURL(UNBLOCK_SAVINGS_COMMAND, savingsID), getActivatedSavingsAsJSON(), + isBlock); } public HashMap blockDebit(final Integer savingsID) { @@ -505,13 +511,12 @@ public class SavingsAccountHelper { return savingsAccountJson; } - private String createSavingsOperationURL(final String command, final Integer savingsID) { return SAVINGS_ACCOUNT_URL + "/" + savingsID + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; } private String createSavingsGsimOperationURL(final String command, final Integer gsimID) { - return SAVINGS_ACCOUNT_URL + GSIM_SAVINGS_COMMAND +"/" + gsimID + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; + return SAVINGS_ACCOUNT_URL + GSIM_SAVINGS_COMMAND + "/" + gsimID + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; } private String createSavingsTransactionURL(final String command, final Integer savingsID) { @@ -585,7 +590,8 @@ public class SavingsAccountHelper { return response; } - private HashMap performSavingApplicationActions(final String postURLForSavingsTransaction, final String jsonToBeSent, final Boolean IS_BLOCK) { + private HashMap performSavingApplicationActions(final String postURLForSavingsTransaction, final String jsonToBeSent, + final Boolean IS_BLOCK) { HashMap status = null; final HashMap response = Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForSavingsTransaction, jsonToBeSent, CommonConstants.RESPONSE_CHANGES); @@ -626,7 +632,7 @@ public class SavingsAccountHelper { map.put("locale", CommonConstants.LOCALE); map.put("monthDayFormat", "dd MMMM"); map.put("dateFormat", "dd MMMM yyy"); - if(addDueDate){ + if (addDueDate) { map.put("dueDate", "10 January 2013"); } String json = new Gson().toJson(map); @@ -721,29 +727,30 @@ public class SavingsAccountHelper { } public Workbook getSavingsWorkbook(String dateFormat) throws IOException { - requestSpec.header(HttpHeaders.CONTENT_TYPE,"application/vnd.ms-excel"); - byte[] byteArray=Utils.performGetBinaryResponse(requestSpec,responseSpec,SAVINGS_ACCOUNT_URL+"/downloadtemplate"+"?"+ - Utils.TENANT_IDENTIFIER+"&dateFormat="+dateFormat); - InputStream inputStream= new ByteArrayInputStream(byteArray); - Workbook workbook=new HSSFWorkbook(inputStream); + requestSpec.header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel"); + byte[] byteArray = Utils.performGetBinaryResponse(requestSpec, responseSpec, + SAVINGS_ACCOUNT_URL + "/downloadtemplate" + "?" + Utils.TENANT_IDENTIFIER + "&dateFormat=" + dateFormat); + InputStream inputStream = new ByteArrayInputStream(byteArray); + Workbook workbook = new HSSFWorkbook(inputStream); return workbook; } public String importSavingsTemplate(File file) { - String locale="en"; - String dateFormat="dd MMMM yyyy"; - String legalFormType= null; + String locale = "en"; + String dateFormat = "dd MMMM yyyy"; + String legalFormType = null; requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA); - return Utils.performServerTemplatePost(requestSpec,responseSpec,SAVINGS_ACCOUNT_URL+"/uploadtemplate"+"?"+Utils.TENANT_IDENTIFIER, - legalFormType,file,locale,dateFormat); + return Utils.performServerTemplatePost(requestSpec, responseSpec, + SAVINGS_ACCOUNT_URL + "/uploadtemplate" + "?" + Utils.TENANT_IDENTIFIER, legalFormType, file, locale, dateFormat); } - public String getOutputTemplateLocation(final String importDocumentId){ - requestSpec.header(HttpHeaders.CONTENT_TYPE,MediaType.TEXT_PLAIN); - return Utils.performServerOutputTemplateLocationGet(requestSpec,responseSpec,"/fineract-provider/api/v1/imports/getOutputTemplateLocation"+"?" - +Utils.TENANT_IDENTIFIER,importDocumentId); + public String getOutputTemplateLocation(final String importDocumentId) { + requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN); + return Utils.performServerOutputTemplateLocationGet(requestSpec, responseSpec, + "/fineract-provider/api/v1/imports/getOutputTemplateLocation" + "?" + Utils.TENANT_IDENTIFIER, importDocumentId); } - //gsim testing + + // gsim testing public HashMap approveGsimSavings(final Integer gsimID) { LOG.info("---------------GSIM APPROVAL---------------"); return approveGsimSavingsOnDate(gsimID, null); @@ -765,7 +772,6 @@ public class SavingsAccountHelper { getRejectedSavingsAsJSON(CREATED_DATE_PLUS_ONE), IS_BLOCK); } - public List rejectGsimApplicationWithErrorCode(final Integer gsimID, final String date) { LOG.info("--------------------------------- REJECT SAVINGS APPLICATION -------------------------------"); return (List) performSavingActions(createSavingsGsimOperationURL(REJECT_SAVINGS_COMMAND, gsimID), getRejectedSavingsAsJSON(date), @@ -775,30 +781,32 @@ public class SavingsAccountHelper { public HashMap undoApprovalGsimSavings(final Integer gsimId) { LOG.info("--------------------------------- UNDO APPROVING GSIM SAVINGS APPLICATION -------------------------------"); final String undoBodyJson = "{'note':'UNDO APPROVAL'}"; - return performSavingApplicationActions(createSavingsGsimOperationURL(UNDO_APPROVAL_SAVINGS_COMMAND, gsimId), undoBodyJson, IS_BLOCK); + return performSavingApplicationActions(createSavingsGsimOperationURL(UNDO_APPROVAL_SAVINGS_COMMAND, gsimId), undoBodyJson, + IS_BLOCK); } public Integer depositGsimApplication(Integer savingsID, List> savingsArray) { LOG.info("--------------------------------- DEPOSIT GSIM SAVINGS APPLICATION -------------------------------"); String savingsArrays = new SavingsApplicationTestBuilder() // - .withSavingsArray(savingsArray) - .build(); + .withSavingsArray(savingsArray).build(); LOG.info("savingsArray : {} ", savingsArrays); return SavingsAccountHelper.depositGsimApplication(savingsID, savingsArrays, requestSpec, responseSpec); } public static Integer depositGsimApplication(Integer savingsID, final String savingsArrays, final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + final ResponseSpecification responseSpec) { - final String depositGsimURL= SAVINGS_ACCOUNT_URL +"/"+savingsID+"/transactions"+"?"+"command="+GSIM_DEPOSIT_SAVINGS_COMMAND +"&"+ Utils.TENANT_IDENTIFIER; + final String depositGsimURL = SAVINGS_ACCOUNT_URL + "/" + savingsID + "/transactions" + "?" + "command=" + + GSIM_DEPOSIT_SAVINGS_COMMAND + "&" + Utils.TENANT_IDENTIFIER; LOG.info("depositGsimURL : {} ", depositGsimURL); - return Utils.performServerPost(requestSpec,responseSpec,depositGsimURL,savingsArrays, CommonConstants.RESPONSE_RESOURCE_ID); + return Utils.performServerPost(requestSpec, responseSpec, depositGsimURL, savingsArrays, CommonConstants.RESPONSE_RESOURCE_ID); } public HashMap activateGsimSavings(final Integer gsimID) { LOG.info("---------------------------------- ACTIVATING GSIM SAVINGS APPLICATION ----------------------------------"); - return performSavingApplicationActions(createSavingsGsimOperationURL(ACTIVATE_SAVINGS_COMMAND, gsimID), getActivatedSavingsAsJSON(), IS_BLOCK); + return performSavingApplicationActions(createSavingsGsimOperationURL(ACTIVATE_SAVINGS_COMMAND, gsimID), getActivatedSavingsAsJSON(), + IS_BLOCK); } public HashMap closeGsimSavingsAccount(final Integer gsimID, String withdrawBalance) { @@ -817,7 +825,8 @@ public class SavingsAccountHelper { public HashMap updateGsimApplication(final Integer gsimID, final Integer clientID, final Integer groupID, final Integer productID) { LOG.info("--------------------------------- UPDATE GSIM SAVINGS APPLICATION -------------------------------"); final String GSIM_URL = "/fineract-provider/api/v1/savingsaccounts/gsim/" + gsimID + "?" + Utils.TENANT_IDENTIFIER; - return Utils.performServerPut(requestSpec, responseSpec, GSIM_URL, updateGsimJSON(clientID.toString(), groupID.toString(), productID.toString()), ""); + return Utils.performServerPut(requestSpec, responseSpec, GSIM_URL, + updateGsimJSON(clientID.toString(), groupID.toString(), productID.toString()), ""); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsApplicationTestBuilder.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsApplicationTestBuilder.java old mode 100755 new mode 100644 index 6fdddaec5..8109fa37f --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsApplicationTestBuilder.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsApplicationTestBuilder.java @@ -26,7 +26,6 @@ import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class SavingsApplicationTestBuilder { private final static Logger LOG = LoggerFactory.getLogger(SavingsApplicationTestBuilder.class); @@ -41,8 +40,8 @@ public class SavingsApplicationTestBuilder { private List> datatables = null; - private List> clientArray =null; - private List> savingsArray =null; + private List> clientArray = null; + private List> savingsArray = null; public String build(final String ID, final String savingsProductId, final String accountType) { @@ -66,19 +65,18 @@ public class SavingsApplicationTestBuilder { } String savingsApplicationJSON = new Gson().toJson(map); - LOG.info("{}",savingsApplicationJSON); + LOG.info("{}", savingsApplicationJSON); return savingsApplicationJSON; } - public String build() - { + public String build() { final HashMap map = new HashMap<>(); - if(this.clientArray != null) { - map.put("clientArray", this.clientArray) ; + if (this.clientArray != null) { + map.put("clientArray", this.clientArray); } - if(this.savingsArray != null) { - map.put("savingsArray", this.savingsArray) ; + if (this.savingsArray != null) { + map.put("savingsArray", this.savingsArray); } String GsimApplicationJSON = new Gson().toJson(map); return GsimApplicationJSON; @@ -109,16 +107,16 @@ public class SavingsApplicationTestBuilder { return this; } - public SavingsApplicationTestBuilder withClientArray(final List> clientArray) { + public SavingsApplicationTestBuilder withClientArray(final List> clientArray) { this.clientArray = new ArrayList<>(); this.clientArray.addAll(clientArray); return this; } - public SavingsApplicationTestBuilder withSavingsArray(final List> savingsArray) { + public SavingsApplicationTestBuilder withSavingsArray(final List> savingsArray) { this.savingsArray = new ArrayList<>(); this.savingsArray.addAll(savingsArray); return this; - } + } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsProductHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsProductHelper.java index 00675343f..d35e4d950 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsProductHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsProductHelper.java @@ -95,7 +95,6 @@ public class SavingsProductHelper { private Boolean withgsimID = null; private Integer gsimID = null; - public String build() { final HashMap map = new HashMap<>(); @@ -138,7 +137,7 @@ public class SavingsProductHelper { if (this.accountingRule.equals(CASH_BASED)) { map.putAll(getAccountMappingForCashBased()); } - if(this.isDormancyTrackingActive){ + if (this.isDormancyTrackingActive) { map.put("isDormancyTrackingActive", Boolean.toString(this.isDormancyTrackingActive)); map.put("daysToInactive", this.daysToInactive); map.put("daysToDormancy", this.daysToDormancy); @@ -147,7 +146,7 @@ public class SavingsProductHelper { } String savingsProductCreateJson = new Gson().toJson(map); - LOG.info("{}",savingsProductCreateJson); + LOG.info("{}", savingsProductCreateJson); return savingsProductCreateJson; } @@ -237,7 +236,7 @@ public class SavingsProductHelper { } public SavingsProductHelper withgsimID(final Integer gsimID) { - if(withgsimID !=null) { + if (withgsimID != null) { this.gsimID = gsimID; } return this; @@ -288,8 +287,8 @@ public class SavingsProductHelper { return Utils.performServerPost(requestSpec, responseSpec, CREATE_SAVINGS_PRODUCT_URL, savingsProductJSON, "resourceId"); } - public static void verifySavingsProductCreatedOnServer(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer generatedProductID) { + public static void verifySavingsProductCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer generatedProductID) { LOG.info("------------------------------CHECK CLIENT DETAILS------------------------------------\n"); final String GET_SAVINGS_PRODUCT_URL = SAVINGS_PRODUCT_URL + "/" + generatedProductID + "?" + Utils.TENANT_IDENTIFIER; final Integer responseSavingsProductID = Utils.performServerGet(requestSpec, responseSpec, GET_SAVINGS_PRODUCT_URL, "id"); diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsStatusChecker.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsStatusChecker.java old mode 100755 new mode 100644 index 1098259a6..cd0169efc --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsStatusChecker.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/savings/SavingsStatusChecker.java @@ -29,34 +29,30 @@ import org.slf4j.LoggerFactory; @SuppressWarnings("rawtypes") public class SavingsStatusChecker { + private final static Logger LOG = LoggerFactory.getLogger(SavingsStatusChecker.class); private static final String SAVINGS_ACCOUNT_URL = "/fineract-provider/api/v1/savingsaccounts"; public static void verifySavingsIsApproved(final HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS APPROVED ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS APPROVED ------------------------------------"); assertTrue(getStatus(savingsStatusHashMap, "approved"), "ERROR IN APPROVING SAVINGS APPLICATION"); LOG.info("Savings Application Status: {} \n", savingsStatusHashMap); } public static void verifySavingsIsPending(final HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS PENDING ------------------------------------"); - assertTrue(getStatus(savingsStatusHashMap, "submittedAndPendingApproval"), - "SAVINGS ACCOUNT IS NOT IN PENDING STATE"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS PENDING ------------------------------------"); + assertTrue(getStatus(savingsStatusHashMap, "submittedAndPendingApproval"), "SAVINGS ACCOUNT IS NOT IN PENDING STATE"); LOG.info("Savings Application Status: {} \n", savingsStatusHashMap); } public static void verifySavingsIsActive(final HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); assertTrue(getStatus(savingsStatusHashMap, "active"), "ERROR IN ACTIVATING THE SAVINGS APPLICATION"); LOG.info("Savings Application Status: {} \n", savingsStatusHashMap); } public static void verifySavingsIsRejected(final HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS REJECTED ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS REJECTED ------------------------------------"); assertTrue(getStatus(savingsStatusHashMap, "rejected"), "ERROR IN REJECTING THE SAVINGS APPLICATION"); LOG.info("Savings Application Status: {} \n", savingsStatusHashMap); } @@ -64,33 +60,30 @@ public class SavingsStatusChecker { public static void verifySavingsIsWithdrawn(final HashMap savingsStatusHashMap) { LOG.info( "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS WITHDRAWN ------------------------------------"); - assertTrue(getStatus(savingsStatusHashMap, "withdrawnByApplicant"), - "ERROR IN WITHDRAW THE SAVINGS APPLICATION"); + assertTrue(getStatus(savingsStatusHashMap, "withdrawnByApplicant"), "ERROR IN WITHDRAW THE SAVINGS APPLICATION"); LOG.info("Savings Application Status: {}", savingsStatusHashMap); } public static void verifySavingsAccountIsClosed(final HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS CLOSED ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS CLOSED ------------------------------------"); assertTrue(getStatus(savingsStatusHashMap, "closed"), "ERROR IN CLOSING THE SAVINGS APPLICATION"); LOG.info("Savings Application Status: {}", savingsStatusHashMap); } public static void verifySavingsAccountIsNotActive(final HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS INACTIVE ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS INACTIVE ------------------------------------"); assertTrue(getStatus(savingsStatusHashMap, "active")); LOG.info("Savings Application Status: {} \n", savingsStatusHashMap); } - public static HashMap getStatusOfSavings(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer savingsID) { + public static HashMap getStatusOfSavings(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer savingsID) { final String url = SAVINGS_ACCOUNT_URL + "/" + savingsID + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, url, "status"); } - public static HashMap getSubStatusOfSavings(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer savingsID) { + public static HashMap getSubStatusOfSavings(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer savingsID) { final String url = SAVINGS_ACCOUNT_URL + "/" + savingsID + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, url, "subStatus"); } @@ -100,36 +93,31 @@ public class SavingsStatusChecker { } public static void verifySavingsSubStatusInactive(HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); assertTrue(getStatus(savingsStatusHashMap, "inactive"), "UNEXPECTED SAVINGS ACCOUNT SUB STATUS"); LOG.info("Savings Application Sub Status: {} ", savingsStatusHashMap.toString()); } public static void verifySavingsSubStatusDormant(HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); assertTrue(getStatus(savingsStatusHashMap, "dormant"), "UNEXPECTED SAVINGS ACCOUNT SUB STATUS"); LOG.info("Savings Application Sub Status: {} ", savingsStatusHashMap.toString()); } public static void verifySavingsSubStatusEscheat(HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); assertTrue(getStatus(savingsStatusHashMap, "escheat"), "UNEXPECTED SAVINGS ACCOUNT SUB STATUS"); LOG.info("Savings Application Sub Status: {} ", savingsStatusHashMap.toString()); } public static void verifySavingsSubStatusNone(HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------"); assertTrue(getStatus(savingsStatusHashMap, "none"), "UNEXPECTED SAVINGS ACCOUNT SUB STATUS"); LOG.info("Savings Application Sub Status: {} ", savingsStatusHashMap.toString()); } public static void verifySavingsSubStatusblock(HashMap savingsStatusHashMap) { - LOG.info( - "\n-------------------------------------- VERIFYING SAVINGS ACCOUNT IS BLOCKED ------------------------------------"); + LOG.info("\n-------------------------------------- VERIFYING SAVINGS ACCOUNT IS BLOCKED ------------------------------------"); assertTrue(getStatus(savingsStatusHashMap, "block"), "block"); LOG.info("Savings Application Sub Status: {} ", savingsStatusHashMap.toString()); } @@ -142,17 +130,15 @@ public class SavingsStatusChecker { } public static void verifySavingsSubStatusIsDebitBlocked(HashMap savingsStatusHashMap) { - LOG.info( - "\n--------------------- VERIFYING SAVINGS APPLICATION IS BLOCKED FOR DEBIT TRANSACTIONS ---------------------"); + LOG.info("\n--------------------- VERIFYING SAVINGS APPLICATION IS BLOCKED FOR DEBIT TRANSACTIONS ---------------------"); assertTrue(getStatus(savingsStatusHashMap, "blockDebit"), "status is blockDebit"); LOG.info("Savings Application Sub Status: {} ", savingsStatusHashMap.toString()); } public static void verifySavingsSubStatusIsCreditBlocked(HashMap savingsStatusHashMap) { - LOG.info( - "\n---------------------- VERIFYING SAVINGS APPLICATION IS BLOCKED FOR CREDIT TRANSACTIONS ---------------"); + LOG.info("\n---------------------- VERIFYING SAVINGS APPLICATION IS BLOCKED FOR CREDIT TRANSACTIONS ---------------"); assertTrue(getStatus(savingsStatusHashMap, "blockCredit"), "blockCredit "); LOG.info("Savings Application Sub Status: {} ", savingsStatusHashMap.toString()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/DividendsIntegrationTests.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/DividendsIntegrationTests.java index fcc39b89f..95b21a1b8 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/DividendsIntegrationTests.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/DividendsIntegrationTests.java @@ -39,11 +39,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - public class DividendsIntegrationTests { - private final String[] dates = {"01 Jan 2015", "01 Apr 2015", "01 Oct 2015", "01 Dec 2015", "01 Mar 2016"} ; - private final String[] shares = {"100", "200", "300", "100", "500"} ; + private final String[] dates = { "01 Jan 2015", "01 Apr 2015", "01 Oct 2015", "01 Dec 2015", "01 Mar 2016" }; + private final String[] shares = { "100", "200", "300", "100", "500" }; private RequestSpecification requestSpec; private ResponseSpecification responseSpec; @@ -60,24 +59,24 @@ public class DividendsIntegrationTests { @Test public void testCreateDividends() { DateFormat simple = new SimpleDateFormat("dd MMM yyyy"); - final Integer productId = createShareProduct() ; - ArrayList clients = new ArrayList<>() ; - ArrayList savingAccounts = new ArrayList<>() ; - ArrayList shareAccounts = new ArrayList<>() ; - for(int i = 0 ; i < 5; i++) { + final Integer productId = createShareProduct(); + ArrayList clients = new ArrayList<>(); + ArrayList savingAccounts = new ArrayList<>(); + ArrayList shareAccounts = new ArrayList<>(); + for (int i = 0; i < 5; i++) { final Integer clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec); - clients.add(clientId) ; + clients.add(clientId); Assertions.assertNotNull(clientId); Integer savingsAccountId = SavingsAccountHelper.openSavingsAccount(requestSpec, responseSpec, clientId, "1000"); - savingAccounts.add(savingsAccountId) ; + savingAccounts.add(savingsAccountId); Assertions.assertNotNull(savingsAccountId); final Integer shareAccountId = createShareAccount(clientId, productId, savingsAccountId, dates[i], shares[i]); - shareAccounts.add(shareAccountId) ; + shareAccounts.add(shareAccountId); Assertions.assertNotNull(shareAccountId); - Map shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + Map shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, + responseSpec); Assertions.assertNotNull(shareAccountData); - // Approve share Account + // Approve share Account Map approveMap = new HashMap<>(); approveMap.put("note", "Share Account Approval Note"); approveMap.put("dateFormat", "dd MMMM yyyy"); @@ -85,7 +84,7 @@ public class DividendsIntegrationTests { approveMap.put("locale", "en"); String approve = new Gson().toJson(approveMap); ShareAccountTransactionHelper.postCommand("approve", shareAccountId, approve, requestSpec, responseSpec); - //Activate Share Account + // Activate Share Account Map activateMap = new HashMap<>(); activateMap.put("dateFormat", "dd MMMM yyyy"); activateMap.put("activatedDate", "01 Jan 2016"); @@ -94,20 +93,21 @@ public class DividendsIntegrationTests { ShareAccountTransactionHelper.postCommand("activate", shareAccountId, activateJson, requestSpec, responseSpec); } - Map dividendsMap = new HashMap<>() ; - dividendsMap.put("dividendPeriodStartDate", "01 Jan 2015") ; - dividendsMap.put("dividendPeriodEndDate", "01 Apr 2016") ; - dividendsMap.put("dividendAmount", "50000") ; + Map dividendsMap = new HashMap<>(); + dividendsMap.put("dividendPeriodStartDate", "01 Jan 2015"); + dividendsMap.put("dividendPeriodEndDate", "01 Apr 2016"); + dividendsMap.put("dividendAmount", "50000"); dividendsMap.put("dateFormat", "dd MMMM yyyy"); dividendsMap.put("locale", "en"); String createDividendsJson = new Gson().toJson(dividendsMap); - final Integer dividendId = ShareDividendsTransactionHelper.createShareProductDividends(productId, createDividendsJson, requestSpec, responseSpec) ; + final Integer dividendId = ShareDividendsTransactionHelper.createShareProductDividends(productId, createDividendsJson, requestSpec, + responseSpec); Map productdividends = ShareDividendsTransactionHelper.retrieveAllDividends(productId, requestSpec, responseSpec); Assertions.assertEquals("1", String.valueOf(productdividends.get("totalFilteredRecords"))); - Map dividend = ((List>)productdividends.get("pageItems")).get(0) ; - Assertions.assertEquals("50000.0", String.valueOf(dividend.get("amount"))) ; - Map status = (Map)dividend.get("status") ; + Map dividend = ((List>) productdividends.get("pageItems")).get(0); + Assertions.assertEquals("50000.0", String.valueOf(dividend.get("amount"))); + Map status = (Map) dividend.get("status"); Assertions.assertEquals("shareAccountDividendStatusType.initiated", String.valueOf(status.get("code"))); List startdateList = (List) dividend.get("dividendPeriodStartDate"); Calendar cal = Calendar.getInstance(); @@ -120,37 +120,36 @@ public class DividendsIntegrationTests { Date endDate = cal.getTime(); Assertions.assertEquals("01 Apr 2016", simple.format(endDate)); - - - Map dividenddetails = ShareDividendsTransactionHelper.retrieveDividendDetails(productId, dividendId, requestSpec, responseSpec) ; + Map dividenddetails = ShareDividendsTransactionHelper.retrieveDividendDetails(productId, dividendId, requestSpec, + responseSpec); Assertions.assertEquals("5", String.valueOf(dividenddetails.get("totalFilteredRecords"))); - List> pageItems = (List>)dividenddetails.get("pageItems") ; - for(Map dividendData: pageItems) { - Map accountData = (Map) dividendData.get("accountData") ; - String accountId = String.valueOf(accountData.get("id")) ; - if(String.valueOf(shareAccounts.get(0)).equals(accountId)) { + List> pageItems = (List>) dividenddetails.get("pageItems"); + for (Map dividendData : pageItems) { + Map accountData = (Map) dividendData.get("accountData"); + String accountId = String.valueOf(accountData.get("id")); + if (String.valueOf(shareAccounts.get(0)).equals(accountId)) { Assertions.assertEquals("11320.755", String.valueOf(dividendData.get("amount"))); - }else if(String.valueOf(shareAccounts.get(1)).equals(accountId)) { + } else if (String.valueOf(shareAccounts.get(1)).equals(accountId)) { Assertions.assertEquals("18172.791", String.valueOf(dividendData.get("amount"))); - }else if(String.valueOf(shareAccounts.get(2)).equals(accountId)) { + } else if (String.valueOf(shareAccounts.get(2)).equals(accountId)) { Assertions.assertEquals("13629.593", String.valueOf(dividendData.get("amount"))); - }else if(String.valueOf(shareAccounts.get(3)).equals(accountId)) { + } else if (String.valueOf(shareAccounts.get(3)).equals(accountId)) { Assertions.assertEquals("3028.7983", String.valueOf(dividendData.get("amount"))); - }else if(String.valueOf(shareAccounts.get(4)).equals(accountId)) { + } else if (String.valueOf(shareAccounts.get(4)).equals(accountId)) { Assertions.assertEquals("3848.0637", String.valueOf(dividendData.get("amount"))); } - Map statusMap = (Map) dividendData.get("status") ; - Assertions.assertEquals("shareAccountDividendStatusType.initiated", String.valueOf(statusMap.get("code"))) ; + Map statusMap = (Map) dividendData.get("status"); + Assertions.assertEquals("shareAccountDividendStatusType.initiated", String.valueOf(statusMap.get("code"))); } - String jsonString = "" ; - ShareDividendsTransactionHelper.postCommand("approve", productId, dividendId, jsonString, requestSpec, responseSpec) ; + String jsonString = ""; + ShareDividendsTransactionHelper.postCommand("approve", productId, dividendId, jsonString, requestSpec, responseSpec); productdividends = ShareDividendsTransactionHelper.retrieveAllDividends(productId, requestSpec, responseSpec); Assertions.assertEquals("1", String.valueOf(productdividends.get("totalFilteredRecords"))); - dividend = ((List>)productdividends.get("pageItems")).get(0) ; - Assertions.assertEquals("50000.0", String.valueOf(dividend.get("amount"))) ; - status = (Map)dividend.get("status") ; + dividend = ((List>) productdividends.get("pageItems")).get(0); + Assertions.assertEquals("50000.0", String.valueOf(dividend.get("amount"))); + status = (Map) dividend.get("status"); Assertions.assertEquals("shareAccountDividendStatusType.approved", String.valueOf(status.get("code"))); startdateList = (List) dividend.get("dividendPeriodStartDate"); cal = Calendar.getInstance(); @@ -163,25 +162,25 @@ public class DividendsIntegrationTests { endDate = cal.getTime(); Assertions.assertEquals("01 Apr 2016", simple.format(endDate)); - dividenddetails = ShareDividendsTransactionHelper.retrieveDividendDetails(productId, dividendId, requestSpec, responseSpec) ; + dividenddetails = ShareDividendsTransactionHelper.retrieveDividendDetails(productId, dividendId, requestSpec, responseSpec); Assertions.assertEquals("5", String.valueOf(dividenddetails.get("totalFilteredRecords"))); - pageItems = (List>)dividenddetails.get("pageItems") ; - for(Map dividendData: pageItems) { - Map accountData = (Map) dividendData.get("accountData") ; - String accountId = String.valueOf(accountData.get("id")) ; - if(String.valueOf(shareAccounts.get(0)).equals(accountId)) { + pageItems = (List>) dividenddetails.get("pageItems"); + for (Map dividendData : pageItems) { + Map accountData = (Map) dividendData.get("accountData"); + String accountId = String.valueOf(accountData.get("id")); + if (String.valueOf(shareAccounts.get(0)).equals(accountId)) { Assertions.assertEquals("11320.755", String.valueOf(dividendData.get("amount"))); - }else if(String.valueOf(shareAccounts.get(1)).equals(accountId)) { + } else if (String.valueOf(shareAccounts.get(1)).equals(accountId)) { Assertions.assertEquals("18172.791", String.valueOf(dividendData.get("amount"))); - }else if(String.valueOf(shareAccounts.get(2)).equals(accountId)) { + } else if (String.valueOf(shareAccounts.get(2)).equals(accountId)) { Assertions.assertEquals("13629.593", String.valueOf(dividendData.get("amount"))); - }else if(String.valueOf(shareAccounts.get(3)).equals(accountId)) { + } else if (String.valueOf(shareAccounts.get(3)).equals(accountId)) { Assertions.assertEquals("3028.7983", String.valueOf(dividendData.get("amount"))); - }else if(String.valueOf(shareAccounts.get(4)).equals(accountId)) { + } else if (String.valueOf(shareAccounts.get(4)).equals(accountId)) { Assertions.assertEquals("3848.0637", String.valueOf(dividendData.get("amount"))); } - Map statusMap = (Map) dividendData.get("status") ; - Assertions.assertEquals("shareAccountDividendStatusType.initiated", String.valueOf(statusMap.get("code"))) ; + Map statusMap = (Map) dividendData.get("status"); + Assertions.assertEquals("shareAccountDividendStatusType.initiated", String.valueOf(statusMap.get("code"))); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountHelper.java index 016e88b00..23f1c2498 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountHelper.java @@ -27,118 +27,119 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ShareAccountHelper { + private final static Logger LOG = LoggerFactory.getLogger(ShareAccountHelper.class); private static final String LOCALE = "en_GB"; - private String clientId ; + private String clientId; - private String productId ; + private String productId; - private String submittedDate ; + private String submittedDate; - private String externalId ; + private String externalId; - private String savingsAccountId ; + private String savingsAccountId; - private String requestedShares ; + private String requestedShares; - private String applicationDate ; + private String applicationDate; - private String allowDividendCalculationForInactiveClients ; + private String allowDividendCalculationForInactiveClients; - private String minimumActivePeriod ; + private String minimumActivePeriod; - private String minimumActivePeriodFrequencyType ; + private String minimumActivePeriodFrequencyType; - private String lockinPeriodFrequency ; + private String lockinPeriodFrequency; - private String lockinPeriodFrequencyType ; + private String lockinPeriodFrequencyType; - private List> charges = null ; - //chargeId , amount + private List> charges = null; + // chargeId , amount public String build() { final HashMap map = new HashMap<>(); map.put("locale", LOCALE); - if(this.clientId != null) { - map.put("clientId", this.clientId) ; + if (this.clientId != null) { + map.put("clientId", this.clientId); } - if(this.productId != null) { - map.put("productId", this.productId) ; + if (this.productId != null) { + map.put("productId", this.productId); } map.put("dateFormat", "dd MMMM yyyy"); - if(this.savingsAccountId != null) { - map.put("savingsAccountId", savingsAccountId) ; + if (this.savingsAccountId != null) { + map.put("savingsAccountId", savingsAccountId); } - if(externalId != null) { - map.put("externalId", this.externalId) ; + if (externalId != null) { + map.put("externalId", this.externalId); } - if(submittedDate != null) { - map.put("submittedDate", this.submittedDate) ; + if (submittedDate != null) { + map.put("submittedDate", this.submittedDate); } - if(applicationDate != null) { - map.put("applicationDate", this.applicationDate) ; + if (applicationDate != null) { + map.put("applicationDate", this.applicationDate); } - if(this.requestedShares != null) { - map.put("requestedShares", this.requestedShares) ; + if (this.requestedShares != null) { + map.put("requestedShares", this.requestedShares); } - if(this.allowDividendCalculationForInactiveClients != null) { - map.put("allowDividendCalculationForInactiveClients", this.allowDividendCalculationForInactiveClients) ; + if (this.allowDividendCalculationForInactiveClients != null) { + map.put("allowDividendCalculationForInactiveClients", this.allowDividendCalculationForInactiveClients); } - if(this.charges != null) { - map.put("charges", this.charges) ; + if (this.charges != null) { + map.put("charges", this.charges); } String shareAccountCreateJson = new Gson().toJson(map); - LOG.info("{}",shareAccountCreateJson); + LOG.info("{}", shareAccountCreateJson); return shareAccountCreateJson; } public ShareAccountHelper withClientId(final String clientId) { - this.clientId = clientId ; - return this ; + this.clientId = clientId; + return this; } public ShareAccountHelper withProductId(final String productId) { - this.productId = productId ; - return this ; + this.productId = productId; + return this; } public ShareAccountHelper withSavingsAccountId(final String savingsAccountId) { - this.savingsAccountId = savingsAccountId ; - return this ; + this.savingsAccountId = savingsAccountId; + return this; } public ShareAccountHelper withSubmittedDate(final String submittedDate) { - this.submittedDate = submittedDate ; - return this ; + this.submittedDate = submittedDate; + return this; } public ShareAccountHelper withRequestedShares(final String requestedShares) { - this.requestedShares = requestedShares ; - return this ; + this.requestedShares = requestedShares; + return this; } public ShareAccountHelper withApplicationDate(final String applicationDate) { - this.applicationDate = applicationDate ; - return this ; + this.applicationDate = applicationDate; + return this; } public ShareAccountHelper withExternalId(final String externalId) { - this.externalId = externalId ; - return this ; + this.externalId = externalId; + return this; } - public ShareAccountHelper withCharges(final List> charges) { - this.charges = new ArrayList<>() ; - this.charges.addAll(charges) ; - return this ; + public ShareAccountHelper withCharges(final List> charges) { + this.charges = new ArrayList<>(); + this.charges.addAll(charges); + return this; } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountIntegrationTests.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountIntegrationTests.java index ed5e06434..0110a4a35 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountIntegrationTests.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountIntegrationTests.java @@ -44,6 +44,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ShareAccountIntegrationTests { + private final static Logger LOG = LoggerFactory.getLogger(ShareAccountIntegrationTests.class); private RequestSpecification requestSpec; private ResponseSpecification responseSpec; @@ -68,8 +69,8 @@ public class ShareAccountIntegrationTests { LOG.info("------------------------------CREATING SHARE PRODUCT COMPLETE---------------------------------------"); LOG.info("------------------------------RETRIEVING SHARE PRODUCT---------------------------------------"); - Map shareProductData = ShareProductTransactionHelper - .retrieveShareProduct(shareProductId, requestSpec, responseSpec); + Map shareProductData = ShareProductTransactionHelper.retrieveShareProduct(shareProductId, requestSpec, + responseSpec); Assertions.assertNotNull(shareProductData); shareProductHelper.verifyShareProduct(shareProductData); @@ -108,8 +109,8 @@ public class ShareAccountIntegrationTests { Assertions.assertNotNull(savingsAccountId); final Integer shareAccountId = createShareAccount(clientId, productId, savingsAccountId); Assertions.assertNotNull(shareAccountId); - Map shareProductData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + Map shareProductData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, + responseSpec); Assertions.assertNotNull(shareProductData); Map shareAccountDataForUpdate = new HashMap<>(); @@ -158,11 +159,11 @@ public class ShareAccountIntegrationTests { charges.add(createCharge(redeemChargeId, "1")); final Integer shareAccountId = createShareAccount(clientId, productId, savingsAccountId, charges); Assertions.assertNotNull(shareAccountId); - Map shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + Map shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, + responseSpec); Assertions.assertNotNull(shareAccountData); - // Approve share Account + // Approve share Account Map approveMap = new HashMap<>(); approveMap.put("note", "Share Account Approval Note"); approveMap.put("dateFormat", "dd MMMM yyyy"); @@ -170,8 +171,7 @@ public class ShareAccountIntegrationTests { approveMap.put("locale", "en"); String approve = new Gson().toJson(approveMap); ShareAccountTransactionHelper.postCommand("approve", shareAccountId, approve, requestSpec, responseSpec); - shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, responseSpec); Map statusMap = (Map) shareAccountData.get("status"); Assertions.assertEquals("shareAccountStatusType.approved", String.valueOf(statusMap.get("code"))); Map timelineMap = (Map) shareAccountData.get("timeline"); @@ -232,8 +232,8 @@ public class ShareAccountIntegrationTests { charges.add(createCharge(redeemChargeId, "1")); final Integer shareAccountId = createShareAccount(clientId, productId, savingsAccountId, charges); Assertions.assertNotNull(shareAccountId); - Map shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + Map shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, + responseSpec); Assertions.assertNotNull(shareAccountData); // Reject share Account @@ -241,8 +241,7 @@ public class ShareAccountIntegrationTests { rejectMap.put("note", "Share Account Rejection Note"); String rejectJson = new Gson().toJson(rejectMap); ShareAccountTransactionHelper.postCommand("reject", shareAccountId, rejectJson, requestSpec, responseSpec); - shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, responseSpec); DateFormat simple = new SimpleDateFormat("dd MMM yyyy"); Map statusMap = (Map) shareAccountData.get("status"); Assertions.assertEquals("shareAccountStatusType.rejected", String.valueOf(statusMap.get("code"))); @@ -274,7 +273,7 @@ public class ShareAccountIntegrationTests { } else if (transactionType.equals("charge.payment")) { Assertions.assertEquals("2.0", String.valueOf(transaction.get("amount"))); Assertions.assertEquals("0", String.valueOf(transaction.get("amountPaid"))); - Date transactionDate = DateUtils.getDateOfTenant() ; + Date transactionDate = DateUtils.getDateOfTenant(); Assertions.assertEquals(simple.format(transactionDate), simple.format(date)); } } @@ -307,11 +306,11 @@ public class ShareAccountIntegrationTests { charges.add(createCharge(redeemChargeId, "1")); final Integer shareAccountId = createShareAccount(clientId, productId, savingsAccountId, charges); Assertions.assertNotNull(shareAccountId); - Map shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + Map shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, + responseSpec); Assertions.assertNotNull(shareAccountData); - // Approve share Account + // Approve share Account Map approveMap = new HashMap<>(); approveMap.put("note", "Share Account Approval Note"); approveMap.put("dateFormat", "dd MMMM yyyy"); @@ -319,8 +318,7 @@ public class ShareAccountIntegrationTests { approveMap.put("locale", "en"); String approve = new Gson().toJson(approveMap); ShareAccountTransactionHelper.postCommand("approve", shareAccountId, approve, requestSpec, responseSpec); - shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, responseSpec); Map statusMap = (Map) shareAccountData.get("status"); Assertions.assertEquals("shareAccountStatusType.approved", String.valueOf(statusMap.get("code"))); Map timelineMap = (Map) shareAccountData.get("timeline"); @@ -335,8 +333,7 @@ public class ShareAccountIntegrationTests { String undoApprovalJson = new Gson().toJson(undoApprovalMap); ShareAccountTransactionHelper.postCommand("undoapproval", shareAccountId, undoApprovalJson, requestSpec, responseSpec); - shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, responseSpec); statusMap = (Map) shareAccountData.get("status"); Assertions.assertEquals("shareAccountStatusType.submitted.and.pending.approval", String.valueOf(statusMap.get("code"))); @@ -393,8 +390,8 @@ public class ShareAccountIntegrationTests { charges.add(createCharge(redeemChargeId, "1")); final Integer shareAccountId = createShareAccount(clientId, productId, savingsAccountId, charges); Assertions.assertNotNull(shareAccountId); - Map shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + Map shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, + responseSpec); Assertions.assertNotNull(shareAccountData); Map shareAccountDataForUpdate = new HashMap<>(); @@ -433,25 +430,25 @@ public class ShareAccountIntegrationTests { } } - //charges verification - List> chargesList = (List>) shareAccountData.get("charges") ; - for(Map chargeDef: chargesList) { - Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType") ; - String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")) ; - if(chargeTimeType.equals("chargeTimeType.activation")) { + // charges verification + List> chargesList = (List>) shareAccountData.get("charges"); + for (Map chargeDef : chargesList) { + Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType"); + String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")); + if (chargeTimeType.equals("chargeTimeType.activation")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharespurchase")) { + } else if (chargeTimeType.equals("chargeTimeType.sharespurchase")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharesredeem")) { + } else if (chargeTimeType.equals("chargeTimeType.sharesredeem")) { Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amountOrPercentage"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("0", String.valueOf(chargeDef.get("amountPaid"))); - }else { + } else { Assertions.fail("Other Charge defintion found"); } } @@ -464,8 +461,7 @@ public class ShareAccountIntegrationTests { approveMap.put("locale", "en"); String approve = new Gson().toJson(approveMap); ShareAccountTransactionHelper.postCommand("approve", shareAccountId, approve, requestSpec, responseSpec); - shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, responseSpec); Map statusMap = (Map) shareAccountData.get("status"); Assertions.assertEquals("shareAccountStatusType.approved", String.valueOf(statusMap.get("code"))); Map timelineMap = (Map) shareAccountData.get("timeline"); @@ -475,25 +471,25 @@ public class ShareAccountIntegrationTests { Date approvedDate = cal.getTime(); Assertions.assertEquals("01 Jan 2016", simple.format(approvedDate)); - //charges verification - chargesList = (List>) shareAccountData.get("charges") ; - for(Map chargeDef: chargesList) { - Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType") ; - String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")) ; - if(chargeTimeType.equals("chargeTimeType.activation")) { + // charges verification + chargesList = (List>) shareAccountData.get("charges"); + for (Map chargeDef : chargesList) { + Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType"); + String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")); + if (chargeTimeType.equals("chargeTimeType.activation")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharespurchase")) { + } else if (chargeTimeType.equals("chargeTimeType.sharespurchase")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharesredeem")) { + } else if (chargeTimeType.equals("chargeTimeType.sharesredeem")) { Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amountOrPercentage"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("0", String.valueOf(chargeDef.get("amountPaid"))); - }else { + } else { Assertions.fail("Other Charge defintion found"); } } @@ -540,25 +536,25 @@ public class ShareAccountIntegrationTests { } } - //charges verification - chargesList = (List>) shareAccountData.get("charges") ; - for(Map chargeDef: chargesList) { - Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType") ; - String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")) ; - if(chargeTimeType.equals("chargeTimeType.activation")) { + // charges verification + chargesList = (List>) shareAccountData.get("charges"); + for (Map chargeDef : chargesList) { + Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType"); + String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")); + if (chargeTimeType.equals("chargeTimeType.activation")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharespurchase")) { + } else if (chargeTimeType.equals("chargeTimeType.sharespurchase")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharesredeem")) { + } else if (chargeTimeType.equals("chargeTimeType.sharesredeem")) { Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amountOrPercentage"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("0", String.valueOf(chargeDef.get("amountPaid"))); - }else { + } else { Assertions.fail("Other Charge defintion found"); } } @@ -614,25 +610,25 @@ public class ShareAccountIntegrationTests { } } - //charges verification - chargesList = (List>) shareAccountData.get("charges") ; - for(Map chargeDef: chargesList) { - Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType") ; - String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")) ; - if(chargeTimeType.equals("chargeTimeType.activation")) { + // charges verification + chargesList = (List>) shareAccountData.get("charges"); + for (Map chargeDef : chargesList) { + Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType"); + String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")); + if (chargeTimeType.equals("chargeTimeType.activation")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharespurchase")) { + } else if (chargeTimeType.equals("chargeTimeType.sharespurchase")) { Assertions.assertEquals("4.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharesredeem")) { + } else if (chargeTimeType.equals("chargeTimeType.sharesredeem")) { Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amountOrPercentage"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("0", String.valueOf(chargeDef.get("amountPaid"))); - }else { + } else { Assertions.fail("Other Charge defintion found"); } } @@ -688,25 +684,25 @@ public class ShareAccountIntegrationTests { } } - //charges verification - chargesList = (List>) shareAccountData.get("charges") ; - for(Map chargeDef: chargesList) { - Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType") ; - String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")) ; - if(chargeTimeType.equals("chargeTimeType.activation")) { + // charges verification + chargesList = (List>) shareAccountData.get("charges"); + for (Map chargeDef : chargesList) { + Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType"); + String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")); + if (chargeTimeType.equals("chargeTimeType.activation")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharespurchase")) { + } else if (chargeTimeType.equals("chargeTimeType.sharespurchase")) { Assertions.assertEquals("4.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("4.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharesredeem")) { + } else if (chargeTimeType.equals("chargeTimeType.sharesredeem")) { Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amountOrPercentage"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("0", String.valueOf(chargeDef.get("amountPaid"))); - }else { + } else { Assertions.fail("Other Charge defintion found"); } } @@ -750,25 +746,25 @@ public class ShareAccountIntegrationTests { } } - //charges verification - chargesList = (List>) shareAccountData.get("charges") ; - for(Map chargeDef: chargesList) { - Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType") ; - String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")) ; - if(chargeTimeType.equals("chargeTimeType.activation")) { + // charges verification + chargesList = (List>) shareAccountData.get("charges"); + for (Map chargeDef : chargesList) { + Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType"); + String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")); + if (chargeTimeType.equals("chargeTimeType.activation")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharespurchase")) { + } else if (chargeTimeType.equals("chargeTimeType.sharespurchase")) { Assertions.assertEquals("6.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("4.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharesredeem")) { + } else if (chargeTimeType.equals("chargeTimeType.sharesredeem")) { Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amountOrPercentage"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("0", String.valueOf(chargeDef.get("amountPaid"))); - }else { + } else { Assertions.fail("Other Charge defintion found"); } } @@ -812,25 +808,25 @@ public class ShareAccountIntegrationTests { } } - //charges verification - chargesList = (List>) shareAccountData.get("charges") ; - for(Map chargeDef: chargesList) { - Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType") ; - String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")) ; - if(chargeTimeType.equals("chargeTimeType.activation")) { + // charges verification + chargesList = (List>) shareAccountData.get("charges"); + for (Map chargeDef : chargesList) { + Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType"); + String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")); + if (chargeTimeType.equals("chargeTimeType.activation")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharespurchase")) { + } else if (chargeTimeType.equals("chargeTimeType.sharespurchase")) { Assertions.assertEquals("6.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("6.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharesredeem")) { + } else if (chargeTimeType.equals("chargeTimeType.sharesredeem")) { Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amountOrPercentage"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("0", String.valueOf(chargeDef.get("amountPaid"))); - }else { + } else { Assertions.fail("Other Charge defintion found"); } } @@ -889,25 +885,25 @@ public class ShareAccountIntegrationTests { } } - //charges verification - chargesList = (List>) shareAccountData.get("charges") ; - for(Map chargeDef: chargesList) { - Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType") ; - String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")) ; - if(chargeTimeType.equals("chargeTimeType.activation")) { + // charges verification + chargesList = (List>) shareAccountData.get("charges"); + for (Map chargeDef : chargesList) { + Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType"); + String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")); + if (chargeTimeType.equals("chargeTimeType.activation")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharespurchase")) { + } else if (chargeTimeType.equals("chargeTimeType.sharespurchase")) { Assertions.assertEquals("6.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("6.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharesredeem")) { + } else if (chargeTimeType.equals("chargeTimeType.sharesredeem")) { Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amountOrPercentage"))); Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amountPaid"))); - }else { + } else { Assertions.fail("Other Charge defintion found"); } } @@ -915,7 +911,7 @@ public class ShareAccountIntegrationTests { Assertions.assertEquals("30", String.valueOf(summaryMap.get("totalApprovedShares"))); Assertions.assertEquals("0", String.valueOf(summaryMap.get("totalPendingForApprovalShares"))); - //Close Share Account + // Close Share Account Map closeAccountMap = new HashMap<>(); closeAccountMap.put("note", "Share Account Close Note"); closeAccountMap.put("dateFormat", "dd MMMM yyyy"); @@ -923,8 +919,7 @@ public class ShareAccountIntegrationTests { closeAccountMap.put("locale", "en"); String closeJson = new Gson().toJson(closeAccountMap); ShareAccountTransactionHelper.postCommand("close", shareAccountId, closeJson, requestSpec, responseSpec); - shareAccountData = ShareAccountTransactionHelper - .retrieveShareAccount(shareAccountId, requestSpec, responseSpec); + shareAccountData = ShareAccountTransactionHelper.retrieveShareAccount(shareAccountId, requestSpec, responseSpec); statusMap = (Map) shareAccountData.get("status"); Assertions.assertEquals("shareAccountStatusType.closed", String.valueOf(statusMap.get("code"))); transactions = (List>) shareAccountData.get("purchasedShares"); @@ -960,39 +955,39 @@ public class ShareAccountIntegrationTests { Assertions.assertEquals("1.0", String.valueOf(transaction.get("chargeAmount"))); Map transactionstatusMap = (Map) transaction.get("status"); Assertions.assertEquals("purchasedSharesStatusType.approved", String.valueOf(transactionstatusMap.get("code"))); - }else if (transactionType.equals("purchasedSharesType.redeemed") && transactionDate.equals("10 May 2016")) { + } else if (transactionType.equals("purchasedSharesType.redeemed") && transactionDate.equals("10 May 2016")) { Assertions.assertEquals("30", String.valueOf(transaction.get("numberOfShares"))); Assertions.assertEquals("59.0", String.valueOf(transaction.get("amount"))); Assertions.assertEquals("59.0", String.valueOf(transaction.get("amountPaid"))); Assertions.assertEquals("1.0", String.valueOf(transaction.get("chargeAmount"))); Map transactionstatusMap = (Map) transaction.get("status"); Assertions.assertEquals("purchasedSharesStatusType.approved", String.valueOf(transactionstatusMap.get("code"))); - }else if (transactionType.equals("charge.payment")) { + } else if (transactionType.equals("charge.payment")) { Assertions.assertEquals("2.0", String.valueOf(transaction.get("amount"))); Assertions.assertEquals("2.0", String.valueOf(transaction.get("amountPaid"))); Assertions.assertEquals("0", String.valueOf(transaction.get("chargeAmount"))); Assertions.assertEquals("01 Jan 2016", transactionDate); } } - //charges verification - chargesList = (List>) shareAccountData.get("charges") ; - for(Map chargeDef: chargesList) { - Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType") ; - String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")) ; - if(chargeTimeType.equals("chargeTimeType.activation")) { + // charges verification + chargesList = (List>) shareAccountData.get("charges"); + for (Map chargeDef : chargesList) { + Map chargeTimeTypeMap = (Map) chargeDef.get("chargeTimeType"); + String chargeTimeType = String.valueOf(chargeTimeTypeMap.get("code")); + if (chargeTimeType.equals("chargeTimeType.activation")) { Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharespurchase")) { + } else if (chargeTimeType.equals("chargeTimeType.sharespurchase")) { Assertions.assertEquals("6.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("6.0", String.valueOf(chargeDef.get("amountPaid"))); - }else if(chargeTimeType.equals("chargeTimeType.sharesredeem")) { + } else if (chargeTimeType.equals("chargeTimeType.sharesredeem")) { Assertions.assertEquals("1.0", String.valueOf(chargeDef.get("amountOrPercentage"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amount"))); Assertions.assertEquals("0.0", String.valueOf(chargeDef.get("amountOutstanding"))); Assertions.assertEquals("2.0", String.valueOf(chargeDef.get("amountPaid"))); - }else { + } else { Assertions.fail("Other Charge defintion found"); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountTransactionHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountTransactionHelper.java index d36cf893e..282d1db64 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountTransactionHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareAccountTransactionHelper.java @@ -45,8 +45,8 @@ public class ShareAccountTransactionHelper { return Utils.performServerPut(requestSpec, responseSpec, url, shareAccountJson, "resourceId"); } - public static Integer postCommand(final String command, final Integer shareAccountId, String jsonBody, final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public static Integer postCommand(final String command, final Integer shareAccountId, String jsonBody, + final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { String url = SHARE_ACCOUNT_URL + "/" + shareAccountId + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; return Utils.performServerPost(requestSpec, responseSpec, url, jsonBody, "resourceId"); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareDividendsTransactionHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareDividendsTransactionHelper.java index 662ebc5e2..4e78f54c4 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareDividendsTransactionHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareDividendsTransactionHelper.java @@ -23,34 +23,33 @@ import io.restassured.specification.ResponseSpecification; import java.util.Map; import org.apache.fineract.integrationtests.common.Utils; - - public class ShareDividendsTransactionHelper { private static final String SHARE_PRODUCT_URL = "/fineract-provider/api/v1/shareproduct"; - private static final String DIVIDEND = "dividend" ; + private static final String DIVIDEND = "dividend"; - public static Integer createShareProductDividends(final Integer productId, final String dividendJson, final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { - String url = SHARE_PRODUCT_URL + "/" + productId + "/" + DIVIDEND + "?" + Utils.TENANT_IDENTIFIER ; + public static Integer createShareProductDividends(final Integer productId, final String dividendJson, + final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + String url = SHARE_PRODUCT_URL + "/" + productId + "/" + DIVIDEND + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerPost(requestSpec, responseSpec, url, dividendJson, "subResourceId"); } - public static Integer postCommand(final String command, final Integer productId, final Integer dividendId, String jsonBody, final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { - String url = SHARE_PRODUCT_URL + "/" + productId + "/"+DIVIDEND + "/"+ dividendId + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; + public static Integer postCommand(final String command, final Integer productId, final Integer dividendId, String jsonBody, + final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + String url = SHARE_PRODUCT_URL + "/" + productId + "/" + DIVIDEND + "/" + dividendId + "?command=" + command + "&" + + Utils.TENANT_IDENTIFIER; return Utils.performServerPut(requestSpec, responseSpec, url, jsonBody, "resourceId"); } - public static Map retrieveDividendDetails(final Integer productId, final Integer dividendId, final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { - String url = SHARE_PRODUCT_URL + "/" + productId + "/"+DIVIDEND + "/"+ dividendId +"?" + Utils.TENANT_IDENTIFIER; + public static Map retrieveDividendDetails(final Integer productId, final Integer dividendId, + final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + String url = SHARE_PRODUCT_URL + "/" + productId + "/" + DIVIDEND + "/" + dividendId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, url, ""); } public static Map retrieveAllDividends(final Integer productId, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { - String url = SHARE_PRODUCT_URL + "/" + productId + "/"+DIVIDEND +"?" + Utils.TENANT_IDENTIFIER; + String url = SHARE_PRODUCT_URL + "/" + productId + "/" + DIVIDEND + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, url, ""); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareProductHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareProductHelper.java index 76ffc0a03..c1b9f7c1c 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareProductHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareProductHelper.java @@ -32,8 +32,8 @@ import org.junit.jupiter.api.Assertions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class ShareProductHelper { + private final static Logger LOG = LoggerFactory.getLogger(ShareProductHelper.class); private static final String NONE = "1"; private static final String CASH_BASED = "2"; @@ -48,11 +48,11 @@ public class ShareProductHelper { private String totalShares = "10000"; private final String currencyCode = USD; private String sharesIssued = "10000"; - private String unitPrice = "2.0" ; - private String minimumShares = "10" ; - private String nominalShares = "20" ; - private String maximumShares = "3000" ; - private String allowDividendCalculationForInactiveClients = "true" ; + private String unitPrice = "2.0"; + private String minimumShares = "10"; + private String nominalShares = "20"; + private String maximumShares = "3000"; + private String allowDividendCalculationForInactiveClients = "true"; private String lockinPeriodFrequency = "1"; private String lockinPeriodFrequencyType = "0"; private String accountingRule = NONE; @@ -60,9 +60,8 @@ public class ShareProductHelper { String minimumActivePeriodForDividends = "1"; String minimumactiveperiodFrequencyType = "0"; - private List> charges = null ; - private List> marketPrices = null ; - + private List> charges = null; + private List> marketPrices = null; public String build() { final HashMap map = new HashMap<>(); @@ -73,126 +72,129 @@ public class ShareProductHelper { map.put("locale", LOCALE); map.put("digitsAfterDecimal", DIGITS_AFTER_DECIMAL); map.put("inMultiplesOf", IN_MULTIPLES_OF); - map.put("totalShares", this.totalShares) ; + map.put("totalShares", this.totalShares); map.put("sharesIssued", this.sharesIssued); - map.put("unitPrice", this.unitPrice) ; - map.put("minimumShares", this.minimumShares) ; - map.put("nominalShares", this.nominalShares) ; - map.put("maximumShares", this.maximumShares) ; - map.put("allowDividendCalculationForInactiveClients", this.allowDividendCalculationForInactiveClients) ; - map.put("accountingRule", this.accountingRule) ; - map.put("minimumActivePeriodForDividends", this.minimumActivePeriodForDividends) ; - map.put("minimumactiveperiodFrequencyType", this.minimumactiveperiodFrequencyType) ; - map.put("lockinPeriodFrequency", this.lockinPeriodFrequency) ; - map.put("lockinPeriodFrequencyType", this.lockinPeriodFrequencyType) ; + map.put("unitPrice", this.unitPrice); + map.put("minimumShares", this.minimumShares); + map.put("nominalShares", this.nominalShares); + map.put("maximumShares", this.maximumShares); + map.put("allowDividendCalculationForInactiveClients", this.allowDividendCalculationForInactiveClients); + map.put("accountingRule", this.accountingRule); + map.put("minimumActivePeriodForDividends", this.minimumActivePeriodForDividends); + map.put("minimumactiveperiodFrequencyType", this.minimumactiveperiodFrequencyType); + map.put("lockinPeriodFrequency", this.lockinPeriodFrequency); + map.put("lockinPeriodFrequencyType", this.lockinPeriodFrequencyType); - if(charges != null) { - map.put("chargesSelected", charges) ; + if (charges != null) { + map.put("chargesSelected", charges); } - if(marketPrices != null) { - map.put("marketPricePeriods", marketPrices) ; + if (marketPrices != null) { + map.put("marketPricePeriods", marketPrices); } String shareProductCreateJson = new Gson().toJson(map); - LOG.info("{}",shareProductCreateJson); + LOG.info("{}", shareProductCreateJson); return shareProductCreateJson; } public ShareProductHelper withCashBasedAccounting() { - this.accountingRule = CASH_BASED ; - return this ; + this.accountingRule = CASH_BASED; + return this; } public ShareProductHelper withMarketPrice() { - this.marketPrices = new ArrayList<>() ; - LocalDate currentDate = DateUtils.getLocalDateOfTenant() ; - String[] prices = {"3.0", "4.0", "5.0", "6.0", "7.0"} ; + this.marketPrices = new ArrayList<>(); + LocalDate currentDate = DateUtils.getLocalDateOfTenant(); + String[] prices = { "3.0", "4.0", "5.0", "6.0", "7.0" }; DateFormat simple = new SimpleDateFormat("dd MMMM yyyy"); - for(int i =0 ; i < prices.length; i++) { - currentDate = currentDate.plusMonths(2) ; - Map marketPrice = new HashMap<>() ; - marketPrice.put("fromDate", simple.format(currentDate)) ; - marketPrice.put("shareValue", prices[i]) ; - this.marketPrices.add(marketPrice) ; + for (int i = 0; i < prices.length; i++) { + currentDate = currentDate.plusMonths(2); + Map marketPrice = new HashMap<>(); + marketPrice.put("fromDate", simple.format(currentDate)); + marketPrice.put("shareValue", prices[i]); + this.marketPrices.add(marketPrice); } - return this ; + return this; } public ShareProductHelper withCharges(final ArrayList charges) { - if(charges != null && !charges.isEmpty()) { - this.charges = new ArrayList<>() ; - for(Long chargeId: charges) { - Map charge = new HashMap<>() ; - charge.put("id", String.valueOf(chargeId.longValue())) ; - this.charges.add(charge) ; + if (charges != null && !charges.isEmpty()) { + this.charges = new ArrayList<>(); + for (Long chargeId : charges) { + Map charge = new HashMap<>(); + charge.put("id", String.valueOf(chargeId.longValue())); + this.charges.add(charge); } } - return this ; + return this; } @SuppressWarnings("unchecked") public void verifyShareProduct(Map shareProductData) { - String productName = (String)shareProductData.get("name") ; + String productName = (String) shareProductData.get("name"); Assertions.assertEquals(this.productName, productName); - String shortName = (String)shareProductData.get("shortName") ; + String shortName = (String) shareProductData.get("shortName"); Assertions.assertEquals(this.shortName, shortName); - String description = (String)shareProductData.get("description") ; + String description = (String) shareProductData.get("description"); Assertions.assertEquals(this.description, description); - Map currency = (Map)shareProductData.get("currency") ; - String currencyCode = currency.get("code") ; + Map currency = (Map) shareProductData.get("currency"); + String currencyCode = currency.get("code"); Assertions.assertEquals(this.currencyCode, currencyCode); - String digitsAfterDecimal = String.valueOf(currency.get("decimalPlaces")) ; + String digitsAfterDecimal = String.valueOf(currency.get("decimalPlaces")); Assertions.assertEquals(DIGITS_AFTER_DECIMAL, digitsAfterDecimal); - String inMultiplesOf = String.valueOf(currency.get("inMultiplesOf")) ; + String inMultiplesOf = String.valueOf(currency.get("inMultiplesOf")); Assertions.assertEquals(IN_MULTIPLES_OF, inMultiplesOf); - String totalShares = String.valueOf(shareProductData.get("totalShares")) ; + String totalShares = String.valueOf(shareProductData.get("totalShares")); Assertions.assertEquals(this.totalShares, totalShares); - String sharesIssued = String.valueOf(shareProductData.get("totalSharesIssued")) ; + String sharesIssued = String.valueOf(shareProductData.get("totalSharesIssued")); Assertions.assertEquals(this.sharesIssued, sharesIssued); - String unitPrice = String.valueOf(shareProductData.get("unitPrice")) ; + String unitPrice = String.valueOf(shareProductData.get("unitPrice")); Assertions.assertEquals(this.unitPrice, unitPrice); - String minimumShares = String.valueOf(shareProductData.get("minimumShares")) ; + String minimumShares = String.valueOf(shareProductData.get("minimumShares")); Assertions.assertEquals(this.minimumShares, minimumShares); - String nominalShares = String.valueOf(shareProductData.get("nominalShares")) ; + String nominalShares = String.valueOf(shareProductData.get("nominalShares")); Assertions.assertEquals(this.nominalShares, nominalShares); - String maximumShares = String.valueOf(shareProductData.get("maximumShares")) ; + String maximumShares = String.valueOf(shareProductData.get("maximumShares")); Assertions.assertEquals(this.maximumShares, maximumShares); - String allowDividendCalculationForInactiveClients = String.valueOf(shareProductData.get("allowDividendCalculationForInactiveClients")) ; + String allowDividendCalculationForInactiveClients = String + .valueOf(shareProductData.get("allowDividendCalculationForInactiveClients")); Assertions.assertEquals(this.allowDividendCalculationForInactiveClients, allowDividendCalculationForInactiveClients); - Map accountingRuleMap = (Map) shareProductData.get("accountingRule") ; - String accountingRule = String.valueOf(accountingRuleMap.get("id")) ; + Map accountingRuleMap = (Map) shareProductData.get("accountingRule"); + String accountingRule = String.valueOf(accountingRuleMap.get("id")); Assertions.assertEquals(this.accountingRule, accountingRule); - String minimumActivePeriodForDividends = String.valueOf(shareProductData.get("minimumActivePeriod")) ; + String minimumActivePeriodForDividends = String.valueOf(shareProductData.get("minimumActivePeriod")); Assertions.assertEquals(this.minimumActivePeriodForDividends, minimumActivePeriodForDividends); - Map minimumActivePeriodType = (Map) shareProductData.get("minimumActivePeriodForDividendsTypeEnum") ; - String minimumactiveperiodFrequencyType = String.valueOf(minimumActivePeriodType.get("id")) ; + Map minimumActivePeriodType = (Map) shareProductData.get("minimumActivePeriodForDividendsTypeEnum"); + String minimumactiveperiodFrequencyType = String.valueOf(minimumActivePeriodType.get("id")); Assertions.assertEquals(this.minimumactiveperiodFrequencyType, minimumactiveperiodFrequencyType); - String lockinPeriodFrequency = String.valueOf(shareProductData.get("lockinPeriod")) ; + String lockinPeriodFrequency = String.valueOf(shareProductData.get("lockinPeriod")); Assertions.assertEquals(this.lockinPeriodFrequency, lockinPeriodFrequency); - Map lockinPeriodType = (Map) shareProductData.get("lockPeriodTypeEnum") ; - String lockinPeriodFrequencyType = String.valueOf(lockinPeriodType.get("id")) ; + Map lockinPeriodType = (Map) shareProductData.get("lockPeriodTypeEnum"); + String lockinPeriodFrequencyType = String.valueOf(lockinPeriodType.get("id")); Assertions.assertEquals(this.lockinPeriodFrequencyType, lockinPeriodFrequencyType); - //ArrayList> charges = (ArrayList>)shareProductData.get("chargesSelected") ; + // ArrayList> charges = (ArrayList>)shareProductData.get("chargesSelected") ; - // ArrayList> marketPrices = (ArrayList>)shareProductData.get("marketPricePeriods") ; + // ArrayList> marketPrices = (ArrayList>)shareProductData.get("marketPricePeriods") ; } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareProductTransactionHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareProductTransactionHelper.java index fb7a20cfb..83393fba0 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareProductTransactionHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/shares/ShareProductTransactionHelper.java @@ -23,7 +23,6 @@ import io.restassured.specification.ResponseSpecification; import java.util.Map; import org.apache.fineract.integrationtests.common.Utils; - public class ShareProductTransactionHelper { private static final String SHARE_PRODUCT_URL = "/fineract-provider/api/v1/products/share"; @@ -36,14 +35,13 @@ public class ShareProductTransactionHelper { public static Map retrieveShareProduct(final Integer shareProductId, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { - String url = SHARE_PRODUCT_URL+"/"+shareProductId+"?"+Utils.TENANT_IDENTIFIER ; + String url = SHARE_PRODUCT_URL + "/" + shareProductId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, url, ""); } public static Integer updateShareProduct(final Integer shareProductId, final String provsioningCriteriaJson, - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { - String url = SHARE_PRODUCT_URL+"/"+shareProductId+"?"+Utils.TENANT_IDENTIFIER ; + final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + String url = SHARE_PRODUCT_URL + "/" + shareProductId + "?" + Utils.TENANT_IDENTIFIER; return Utils.performServerPut(requestSpec, responseSpec, url, provsioningCriteriaJson, "resourceId"); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/AccountNumberPreferencesHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/AccountNumberPreferencesHelper.java index a817fd2b6..8a9d6c569 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/AccountNumberPreferencesHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/AccountNumberPreferencesHelper.java @@ -27,6 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AccountNumberPreferencesHelper { + private final static Logger LOG = LoggerFactory.getLogger(AccountNumberPreferencesHelper.class); private final RequestSpecification requestSpec; @@ -34,186 +35,134 @@ public class AccountNumberPreferencesHelper { private static final String ACCOUNT_NUMBER_FORMATS_REQUEST_URL = "/fineract-provider/api/v1/accountnumberformats"; - public AccountNumberPreferencesHelper( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public AccountNumberPreferencesHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { this.requestSpec = requestSpec; this.responseSpec = responseSpec; } - public Object createClientAccountNumberPreference( - ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + public Object createClientAccountNumberPreference(ResponseSpecification responseSpec, String jsonAttributeToGetBack) { LOG.info("---------------------------------CREATING CLIENT ACCOUNT NUMBER PREFERENCE------------------------------------------"); - final String requestJSON = new AccountNumberPreferencesTestBuilder() - .clientBuild(); + final String requestJSON = new AccountNumberPreferencesTestBuilder().clientBuild(); - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" - + Utils.TENANT_IDENTIFIER; + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER; - return Utils.performServerPost(this.requestSpec, responseSpec, URL, - requestJSON, jsonAttributeToGetBack); + return Utils.performServerPost(this.requestSpec, responseSpec, URL, requestJSON, jsonAttributeToGetBack); } - public Object createLoanAccountNumberPreference( - ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + public Object createLoanAccountNumberPreference(ResponseSpecification responseSpec, String jsonAttributeToGetBack) { LOG.info("---------------------------------CREATING LOAN ACCOUNT NUMBER PREFERENCE------------------------------------------"); - final String requestJSON = new AccountNumberPreferencesTestBuilder() - .loanBuild(); + final String requestJSON = new AccountNumberPreferencesTestBuilder().loanBuild(); - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" - + Utils.TENANT_IDENTIFIER; - return Utils.performServerPost(this.requestSpec, responseSpec, URL, - requestJSON, jsonAttributeToGetBack); + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER; + return Utils.performServerPost(this.requestSpec, responseSpec, URL, requestJSON, jsonAttributeToGetBack); } - public Object createSavingsAccountNumberPreference( - ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + public Object createSavingsAccountNumberPreference(ResponseSpecification responseSpec, String jsonAttributeToGetBack) { LOG.info("---------------------------------CREATING SAVINGS ACCOUNT NUMBER PREFERENCE------------------------------------------"); - final String requestJSON = new AccountNumberPreferencesTestBuilder() - .savingsBuild(); + final String requestJSON = new AccountNumberPreferencesTestBuilder().savingsBuild(); - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" - + Utils.TENANT_IDENTIFIER; - return Utils.performServerPost(this.requestSpec, responseSpec, URL, - requestJSON, jsonAttributeToGetBack); + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER; + return Utils.performServerPost(this.requestSpec, responseSpec, URL, requestJSON, jsonAttributeToGetBack); } - public Object createGroupsAccountNumberPreference( - ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + public Object createGroupsAccountNumberPreference(ResponseSpecification responseSpec, String jsonAttributeToGetBack) { LOG.info("---------------------------------CREATING GROUPS ACCOUNT NUMBER PREFERENCE------------------------------------------"); - final String requestJSON = new AccountNumberPreferencesTestBuilder() - .groupsBuild(); + final String requestJSON = new AccountNumberPreferencesTestBuilder().groupsBuild(); - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" - + Utils.TENANT_IDENTIFIER; - return Utils.performServerPost(this.requestSpec, responseSpec, URL, - requestJSON, jsonAttributeToGetBack); + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER; + return Utils.performServerPost(this.requestSpec, responseSpec, URL, requestJSON, jsonAttributeToGetBack); } - public Object createCenterAccountNumberPreference( - ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + public Object createCenterAccountNumberPreference(ResponseSpecification responseSpec, String jsonAttributeToGetBack) { LOG.info("---------------------------------CREATING CENTER ACCOUNT NUMBER PREFERENCE------------------------------------------"); - final String requestJSON = new AccountNumberPreferencesTestBuilder() - .centerBuild(); + final String requestJSON = new AccountNumberPreferencesTestBuilder().centerBuild(); - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" - + Utils.TENANT_IDENTIFIER; - return Utils.performServerPost(this.requestSpec, responseSpec, URL, - requestJSON, jsonAttributeToGetBack); + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER; + return Utils.performServerPost(this.requestSpec, responseSpec, URL, requestJSON, jsonAttributeToGetBack); } - public HashMap createAccountNumberPreferenceWithInvalidData( - ResponseSpecification responseSpec, String accountType, + public HashMap createAccountNumberPreferenceWithInvalidData(ResponseSpecification responseSpec, String accountType, String prefixType, String jsonAttributeToGetBack) { - final String requestJSON = new AccountNumberPreferencesTestBuilder() - .invalidDataBuild(accountType, prefixType); + final String requestJSON = new AccountNumberPreferencesTestBuilder().invalidDataBuild(accountType, prefixType); - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" - + Utils.TENANT_IDENTIFIER; - return Utils.performServerPost(this.requestSpec, responseSpec, URL, - requestJSON, jsonAttributeToGetBack); + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER; + return Utils.performServerPost(this.requestSpec, responseSpec, URL, requestJSON, jsonAttributeToGetBack); } - public HashMap updateAccountNumberPreference( - final Integer accountNumberFormatId, final String prefixType, + public HashMap updateAccountNumberPreference(final Integer accountNumberFormatId, final String prefixType, ResponseSpecification responseSpec, String jsonAttributeToGetBack) { - final String requestJSON = new AccountNumberPreferencesTestBuilder() - .updatePrefixType(prefixType); + final String requestJSON = new AccountNumberPreferencesTestBuilder().updatePrefixType(prefixType); - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" - + accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER; + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" + accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER; - return Utils.performServerPut(this.requestSpec, responseSpec, URL, - requestJSON, jsonAttributeToGetBack); + return Utils.performServerPut(this.requestSpec, responseSpec, URL, requestJSON, jsonAttributeToGetBack); } - public HashMap deleteAccountNumberPreference( - final Integer accountNumberFormatId, - ResponseSpecification responseSpec, String jsonAttributeToGetBack) { + public HashMap deleteAccountNumberPreference(final Integer accountNumberFormatId, ResponseSpecification responseSpec, + String jsonAttributeToGetBack) { LOG.info("---------------------------------DELETING ACCOUNT NUMBER PREFERENCE------------------------------------------"); - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" - + accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER; + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" + accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER; - return Utils.performServerDelete(this.requestSpec, responseSpec, URL, - jsonAttributeToGetBack); + return Utils.performServerDelete(this.requestSpec, responseSpec, URL, jsonAttributeToGetBack); } - public Object getAccountNumberPreference( - final Integer accountNumberFormatId, - final String jsonAttributeToGetBack) { - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" - + accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER; + public Object getAccountNumberPreference(final Integer accountNumberFormatId, final String jsonAttributeToGetBack) { + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" + accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER; - return Utils.performServerGet(requestSpec, responseSpec, URL, - jsonAttributeToGetBack); + return Utils.performServerGet(requestSpec, responseSpec, URL, jsonAttributeToGetBack); } public ArrayList> getAllAccountNumberPreferences() { - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" - + Utils.TENANT_IDENTIFIER; - final ArrayList> response = Utils - .performServerGet(requestSpec, responseSpec, URL, ""); + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER; + final ArrayList> response = Utils.performServerGet(requestSpec, responseSpec, URL, ""); return response; } - public void verifyCreationOfAccountNumberPreferences( - final Integer clientAccountNumberPreferenceId, - final Integer loanAccountNumberPreferenceId, - final Integer savingsAccountNumberPreferenceId, - final Integer groupsAccountNumberPreferenceId, - final Integer centerAccountNumberPreferenceId, + public void verifyCreationOfAccountNumberPreferences(final Integer clientAccountNumberPreferenceId, + final Integer loanAccountNumberPreferenceId, final Integer savingsAccountNumberPreferenceId, + final Integer groupsAccountNumberPreferenceId, final Integer centerAccountNumberPreferenceId, ResponseSpecification responseSpec, RequestSpecification requestSpec) { - final String clientURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" - + clientAccountNumberPreferenceId + "?" - + Utils.TENANT_IDENTIFIER; + final String clientURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" + clientAccountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER; Utils.performServerGet(requestSpec, responseSpec, clientURL, "id"); - final String loanURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" - + loanAccountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER; + final String loanURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" + loanAccountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER; Utils.performServerGet(requestSpec, responseSpec, loanURL, "id"); - final String savingsURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" - + savingsAccountNumberPreferenceId + "?" + final String savingsURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" + savingsAccountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER; Utils.performServerGet(requestSpec, responseSpec, savingsURL, "id"); - final String groupsURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" - + groupsAccountNumberPreferenceId + "?" - + Utils.TENANT_IDENTIFIER; + final String groupsURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" + groupsAccountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER; Utils.performServerGet(requestSpec, responseSpec, groupsURL, "id"); - final String centerURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" - + centerAccountNumberPreferenceId + "?" - + Utils.TENANT_IDENTIFIER; + final String centerURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" + centerAccountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER; Utils.performServerGet(requestSpec, responseSpec, centerURL, "id"); } - public void verifyUpdationOfAccountNumberPreferences( - final Integer accountNumberPreferenceId, - ResponseSpecification responseSpec, RequestSpecification requestSpec) { + public void verifyUpdationOfAccountNumberPreferences(final Integer accountNumberPreferenceId, ResponseSpecification responseSpec, + RequestSpecification requestSpec) { - final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" - + accountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER; + final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/" + accountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER; Utils.performServerGet(requestSpec, responseSpec, URL, "id"); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/AccountNumberPreferencesTestBuilder.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/AccountNumberPreferencesTestBuilder.java index 33f125805..44829bbc1 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/AccountNumberPreferencesTestBuilder.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/AccountNumberPreferencesTestBuilder.java @@ -22,6 +22,7 @@ import com.google.gson.Gson; import java.util.HashMap; public class AccountNumberPreferencesTestBuilder { + private String clientAccountType = "1"; private String clientPrefixType = "101"; private String loanAccountType = "2"; diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/CodeHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/CodeHelper.java index 8439bdc8c..4403c8723 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/CodeHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/CodeHelper.java @@ -44,42 +44,34 @@ public class CodeHelper { public static final String CODE_VALUE_POSITION_ATTRIBUTE_NAME = "position"; public static final String CODE_VALUE_URL = "/fineract-provider/api/v1/codes/[codeId]/codevalues"; - public static Object createCode(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String codeName, + public static Object createCode(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String codeName, final String jsonAttributeToGetback) { - return Utils.performServerPost(requestSpec, responseSpec, CODE_URL - + "?" + Utils.TENANT_IDENTIFIER, getTestCodeAsJSON(codeName), + return Utils.performServerPost(requestSpec, responseSpec, CODE_URL + "?" + Utils.TENANT_IDENTIFIER, getTestCodeAsJSON(codeName), jsonAttributeToGetback); } - public static Object updateCode(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer codeId, + public static Object updateCode(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer codeId, final String codeName, final String jsonAttributeToGetback) { - return Utils.performServerPut(requestSpec, responseSpec, CODE_URL + "/" - + codeId + "?" + Utils.TENANT_IDENTIFIER, + return Utils.performServerPut(requestSpec, responseSpec, CODE_URL + "/" + codeId + "?" + Utils.TENANT_IDENTIFIER, getTestCodeAsJSON(codeName), jsonAttributeToGetback); } - public static Object getCodeById(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer codeId, + public static Object getCodeById(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer codeId, final String jsonAttributeToGetback) { - return Utils.performServerGet(requestSpec, responseSpec, CODE_URL + "/" - + codeId + "?" + Utils.TENANT_IDENTIFIER, + return Utils.performServerGet(requestSpec, responseSpec, CODE_URL + "/" + codeId + "?" + Utils.TENANT_IDENTIFIER, jsonAttributeToGetback); } - public static HashMap getCodeByName( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final String codeName) { + public static HashMap getCodeByName(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final String codeName) { final HashMap code = new HashMap<>(); - ArrayList> getAllCodes = CodeHelper - .getAllCodes(requestSpec, responseSpec); + ArrayList> getAllCodes = CodeHelper.getAllCodes(requestSpec, responseSpec); for (HashMap map : getAllCodes) { String name = (String) map.get("name"); if (name.equals(codeName)) { @@ -92,47 +84,36 @@ public class CodeHelper { return code; } - public static HashMap retrieveOrCreateCodeValue( - Integer codeId, final RequestSpecification requestSpec, + public static HashMap retrieveOrCreateCodeValue(Integer codeId, final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { Integer codeValueId = null; - final List> codeValuesList = CodeHelper - .getCodeValuesForCode(requestSpec, responseSpec, codeId, ""); + final List> codeValuesList = CodeHelper.getCodeValuesForCode(requestSpec, responseSpec, codeId, ""); /* If Code Values doesn't exist,then create Code value */ if (codeValuesList.size() == 0) { final Integer codeValuePosition = 0; final String codeValue = Utils.randomNameGenerator("", 3); - codeValueId = (Integer) CodeHelper.createCodeValue(requestSpec, - responseSpec, codeId, codeValue, codeValuePosition, + codeValueId = (Integer) CodeHelper.createCodeValue(requestSpec, responseSpec, codeId, codeValue, codeValuePosition, "subResourceId"); } else { return codeValuesList.get(0); } return Utils.performServerGet(requestSpec, responseSpec, - CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" - + codeValueId.toString() + "?" - + Utils.TENANT_IDENTIFIER, ""); + CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" + codeValueId.toString() + "?" + Utils.TENANT_IDENTIFIER, ""); } - public static ArrayList> getAllCodes( - final RequestSpecification requestSpec, + public static ArrayList> getAllCodes(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { - return Utils.performServerGet(requestSpec, responseSpec, CODE_URL + "?" - + Utils.TENANT_IDENTIFIER, ""); + return Utils.performServerGet(requestSpec, responseSpec, CODE_URL + "?" + Utils.TENANT_IDENTIFIER, ""); } - public static Object getSystemDefinedCodes( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { + public static Object getSystemDefinedCodes(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { - final String getResponse = given().spec(requestSpec).expect() - .spec(responseSpec).when() - .get(CodeHelper.CODE_URL + "?" + Utils.TENANT_IDENTIFIER) - .asString(); + final String getResponse = given().spec(requestSpec).expect().spec(responseSpec).when() + .get(CodeHelper.CODE_URL + "?" + Utils.TENANT_IDENTIFIER).asString(); final JsonPath getResponseJsonPath = new JsonPath(getResponse); @@ -147,8 +128,7 @@ public class CodeHelper { return new Gson().toJson(map); } - public static String getTestCodeValueAsJSON(final String codeValueName, - final String description, final Integer position) { + public static String getTestCodeValueAsJSON(final String codeValueName, final String description, final Integer position) { final HashMap map = new HashMap<>(); map.put(CODE_VALUE_NAME_ATTRIBUTE_NAME, codeValueName); if (description != null) { @@ -158,94 +138,68 @@ public class CodeHelper { return new Gson().toJson(map); } - public static Object deleteCodeById(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer codeId, - final String jsonAttributeToGetback) { + public static Object deleteCodeById(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer codeId, final String jsonAttributeToGetback) { - return Utils.performServerDelete(requestSpec, responseSpec, CODE_URL - + "/" + codeId + "?" + Utils.TENANT_IDENTIFIER, + return Utils.performServerDelete(requestSpec, responseSpec, CODE_URL + "/" + codeId + "?" + Utils.TENANT_IDENTIFIER, jsonAttributeToGetback); } - public static Object createCodeValue( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer codeId, - final String codeValueName, final Integer position, - final String jsonAttributeToGetback) { + public static Object createCodeValue(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer codeId, final String codeValueName, final Integer position, final String jsonAttributeToGetback) { String description = null; - return createCodeValue(requestSpec, responseSpec, codeId, - codeValueName, description, position, jsonAttributeToGetback); + return createCodeValue(requestSpec, responseSpec, codeId, codeValueName, description, position, jsonAttributeToGetback); } - public static Object createCodeValue( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer codeId, - final String codeValueName, final String description, - final Integer position, final String jsonAttributeToGetback) { + public static Object createCodeValue(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer codeId, final String codeValueName, final String description, final Integer position, + final String jsonAttributeToGetback) { return Utils.performServerPost(requestSpec, responseSpec, - CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "?" - + Utils.TENANT_IDENTIFIER, - getTestCodeValueAsJSON(codeValueName, description, position), + CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "?" + Utils.TENANT_IDENTIFIER, + getTestCodeValueAsJSON(codeValueName, description, position), jsonAttributeToGetback); + } + + public static List> getCodeValuesForCode(final RequestSpecification requestSpec, + final ResponseSpecification responseSpec, final Integer codeId, final String jsonAttributeToGetback) { + + return Utils.performServerGet(requestSpec, responseSpec, + CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "?" + Utils.TENANT_IDENTIFIER, jsonAttributeToGetback); + + } + + public static Object getCodeValueById(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer codeId, final Integer codeValueId, final String jsonAttributeToGetback) { + + return Utils.performServerGet(requestSpec, responseSpec, + CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" + codeValueId.toString() + "?" + Utils.TENANT_IDENTIFIER, jsonAttributeToGetback); } - public static List> getCodeValuesForCode( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer codeId, - final String jsonAttributeToGetback) { - - return Utils.performServerGet(requestSpec, responseSpec, - CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "?" - + Utils.TENANT_IDENTIFIER, jsonAttributeToGetback); - - } - - public static Object getCodeValueById( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer codeId, - final Integer codeValueId, final String jsonAttributeToGetback) { - - return Utils.performServerGet(requestSpec, responseSpec, - CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" - + codeValueId.toString() + "?" - + Utils.TENANT_IDENTIFIER, jsonAttributeToGetback); - } - - public static Object deleteCodeValueById( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer codeId, - final Integer codeValueId, final String jsonAttributeToGetback) { + public static Object deleteCodeValueById(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer codeId, final Integer codeValueId, final String jsonAttributeToGetback) { return Utils.performServerDelete(requestSpec, responseSpec, - CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" - + codeValueId.toString() + "?" - + Utils.TENANT_IDENTIFIER, jsonAttributeToGetback); + CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" + codeValueId.toString() + "?" + Utils.TENANT_IDENTIFIER, + jsonAttributeToGetback); } - public static Object updateCodeValue( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer codeId, - final Integer codeValueId, final String codeValueName, - final Integer position, final String jsonAttributeToGetback) { + public static Object updateCodeValue(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer codeId, final Integer codeValueId, final String codeValueName, final Integer position, + final String jsonAttributeToGetback) { String description = null; - return updateCodeValue(requestSpec, responseSpec, codeId, codeValueId, - codeValueName, description, position, jsonAttributeToGetback); + return updateCodeValue(requestSpec, responseSpec, codeId, codeValueId, codeValueName, description, position, + jsonAttributeToGetback); } - public static Object updateCodeValue( - final RequestSpecification requestSpec, - final ResponseSpecification responseSpec, final Integer codeId, - final Integer codeValueId, final String codeValueName, - final String description, final Integer position, + public static Object updateCodeValue(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer codeId, final Integer codeValueId, final String codeValueName, final String description, final Integer position, final String jsonAttributeToGetback) { return Utils.performServerPut(requestSpec, responseSpec, - CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" - + codeValueId + "?" + Utils.TENANT_IDENTIFIER, - getTestCodeValueAsJSON(codeValueName, description, position), - jsonAttributeToGetback); + CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/" + codeValueId + "?" + Utils.TENANT_IDENTIFIER, + getTestCodeValueAsJSON(codeValueName, description, position), jsonAttributeToGetback); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/DatatableHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/DatatableHelper.java index 2606c434f..8bc93ee5a 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/DatatableHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/system/DatatableHelper.java @@ -31,6 +31,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DatatableHelper { + private final static Logger LOG = LoggerFactory.getLogger(DatatableHelper.class); private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; @@ -48,8 +49,8 @@ public class DatatableHelper { } public String deleteDatatable(final String datatableName) { - return Utils.performServerDelete(this.requestSpec, this.responseSpec, DATATABLE_URL + "/" + datatableName + "?" + Utils.TENANT_IDENTIFIER, - "resourceIdentifier"); + return Utils.performServerDelete(this.requestSpec, this.responseSpec, + DATATABLE_URL + "/" + datatableName + "?" + Utils.TENANT_IDENTIFIER, "resourceIdentifier"); } public Integer deleteDatatableEntries(final String datatableName, final Integer apptableId, String jsonAttributeToGetBack) { @@ -61,8 +62,8 @@ public class DatatableHelper { public static void verifyDatatableCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String generatedDatatableName) { LOG.info("------------------------------CHECK DATATABLE DETAILS------------------------------------\n"); - final String responseRegisteredTableName = Utils.performServerGet(requestSpec, responseSpec, DATATABLE_URL + "/" - + generatedDatatableName + "?" + Utils.TENANT_IDENTIFIER, "registeredTableName"); + final String responseRegisteredTableName = Utils.performServerGet(requestSpec, responseSpec, + DATATABLE_URL + "/" + generatedDatatableName + "?" + Utils.TENANT_IDENTIFIER, "registeredTableName"); assertEquals(generatedDatatableName, responseRegisteredTableName, "ERROR IN CREATING THE DATATABLE"); } @@ -78,7 +79,7 @@ public class DatatableHelper { addDatatableColumns(datatableColumnsList, "Date of Approval", "Date", false, null); map.put("columns", datatableColumnsList); String requestJsonString = new Gson().toJson(map); - LOG.info("map : {}" , requestJsonString); + LOG.info("map : {}", requestJsonString); return requestJsonString; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/interoperation/InteropHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/interoperation/InteropHelper.java index 3659a15e9..09bfbec6c 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/interoperation/InteropHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/interoperation/InteropHelper.java @@ -66,8 +66,8 @@ public class InteropHelper { private final BigDecimal amount; private final BigDecimal fee; - public InteropHelper(RequestSpecification requestSpec, ResponseSpecification responseSpec, String tenantId, - String accountExternalId, String transactionCode, String currency, BigDecimal amount, BigDecimal fee) { + public InteropHelper(RequestSpecification requestSpec, ResponseSpecification responseSpec, String tenantId, String accountExternalId, + String transactionCode, String currency, BigDecimal amount, BigDecimal fee) { this.requestSpec = requestSpec; this.responseSpec = responseSpec; this.tenantId = tenantId; @@ -78,7 +78,8 @@ public class InteropHelper { this.fee = fee; } - public InteropHelper(RequestSpecification requestSpec, ResponseSpecification responseSpec, String accountExternalId, String transactionCode) { + public InteropHelper(RequestSpecification requestSpec, ResponseSpecification responseSpec, String accountExternalId, + String transactionCode) { this(requestSpec, responseSpec, Utils.DEFAULT_TENANT, accountExternalId, transactionCode, "TZS", BigDecimal.TEN, BigDecimal.ONE); } @@ -199,7 +200,8 @@ public class InteropHelper { } /** - * @param role PAYEE role is not valid for transaction request + * @param role + * PAYEE role is not valid for transaction request * @return response json */ public String postTransactionRequest(String requestCode, InteropTransactionRole role) { @@ -352,4 +354,4 @@ public class InteropHelper { public static String getJsonAttribute(String json, String attrName) { return JsonPath.from(json).get(attrName); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/interoperation/InteropTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/interoperation/InteropTest.java index 685442991..234968a28 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/interoperation/InteropTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/interoperation/InteropTest.java @@ -63,7 +63,7 @@ public class InteropTest { private final static String MIN_REQUIRED_BALANCE = null; private final static String MIN_OPENING_BALANCE = "100000.0"; private final static boolean ENFORCE_MIN_REQUIRED_BALANCE = false; - private final static MathContext MATHCONTEXT = new MathContext(12, RoundingMode.HALF_EVEN); + private final static MathContext MATHCONTEXT = new MathContext(12, RoundingMode.HALF_EVEN); private RequestSpecification requestSpec; private ResponseSpecification responseSpec; @@ -121,22 +121,16 @@ public class InteropTest { private void createSavingsProduct() { LOG.debug("------------------------------ Create Interoperable Saving Product ---------------------------------------"); - Account[] accounts = {accountHelper.createAssetAccount(), accountHelper.createIncomeAccount(), accountHelper.createExpenseAccount(), - accountHelper.createLiabilityAccount()}; + Account[] accounts = { accountHelper.createAssetAccount(), accountHelper.createIncomeAccount(), + accountHelper.createExpenseAccount(), accountHelper.createLiabilityAccount() }; SavingsProductHelper savingsProductHelper = new SavingsProductHelper(); - final String savingsProductJSON = savingsProductHelper - .withCurrencyCode(interopHelper.getCurrency()) - .withNominalAnnualInterestRate(BigDecimal.ZERO) - .withInterestCompoundingPeriodTypeAsDaily() - .withInterestPostingPeriodTypeAsMonthly() - .withInterestCalculationPeriodTypeAsDailyBalance() - .withMinBalanceForInterestCalculation(MIN_INTEREST_CALCULATON_BALANCE) - .withMinRequiredBalance(MIN_REQUIRED_BALANCE) + final String savingsProductJSON = savingsProductHelper.withCurrencyCode(interopHelper.getCurrency()) + .withNominalAnnualInterestRate(BigDecimal.ZERO).withInterestCompoundingPeriodTypeAsDaily() + .withInterestPostingPeriodTypeAsMonthly().withInterestCalculationPeriodTypeAsDailyBalance() + .withMinBalanceForInterestCalculation(MIN_INTEREST_CALCULATON_BALANCE).withMinRequiredBalance(MIN_REQUIRED_BALANCE) .withEnforceMinRequiredBalance(Boolean.toString(ENFORCE_MIN_REQUIRED_BALANCE)) - .withMinimumOpenningBalance(MIN_OPENING_BALANCE) - .withAccountingRuleAsCashBased(accounts) - .build(); + .withMinimumOpenningBalance(MIN_OPENING_BALANCE).withAccountingRuleAsCashBased(accounts).build(); savingsProductId = SavingsProductHelper.createSavingsProduct(savingsProductJSON, requestSpec, responseSpec); Assertions.assertNotNull(savingsProductId); @@ -151,7 +145,8 @@ public class InteropTest { private void openSavingsAccount() { LOG.debug("------------------------------ Create Interoperable Saving Account ---------------------------------------"); - savingsId = savingsAccountHelper.applyForSavingsApplicationWithExternalId(clientId, savingsProductId, ACCOUNT_TYPE_INDIVIDUAL, interopHelper.getAccountExternalId(), true); + savingsId = savingsAccountHelper.applyForSavingsApplicationWithExternalId(clientId, savingsProductId, ACCOUNT_TYPE_INDIVIDUAL, + interopHelper.getAccountExternalId(), true); Assertions.assertNotNull(savingsId); HashMap savingsStatusHashMap = SavingsStatusChecker.getStatusOfSavings(requestSpec, responseSpec, savingsId); @@ -215,7 +210,8 @@ public class InteropTest { Map fee = json.getMap(InteropUtil.PARAM_FSP_FEE); Assertions.assertNotNull(fee); BigDecimal feeAmount = ObjectConverter.convertObjectTo(fee.get(InteropUtil.PARAM_AMOUNT), BigDecimal.class); - Assertions.assertTrue(MathUtil.isEqualTo(interopHelper.getFee(), feeAmount), "Quote fee expected: " + interopHelper.getFee() + ", actual: " + feeAmount); + Assertions.assertTrue(MathUtil.isEqualTo(interopHelper.getFee(), feeAmount), + "Quote fee expected: " + interopHelper.getFee() + ", actual: " + feeAmount); Assertions.assertEquals(interopHelper.getCurrency(), fee.get(InteropUtil.PARAM_CURRENCY)); // payee @@ -252,9 +248,11 @@ public class InteropTest { BigDecimal transferAmount = interopHelper.getTransferAmount(); BigDecimal expectedHold = MathUtil.add(onHold, transferAmount, MATHCONTEXT); - Assertions.assertTrue(MathUtil.isEqualTo(expectedHold, onHold2), "On hold amount expected: " + expectedHold + ", actual: " + onHold2); + Assertions.assertTrue(MathUtil.isEqualTo(expectedHold, onHold2), + "On hold amount expected: " + expectedHold + ", actual: " + onHold2); BigDecimal expectedBalance = MathUtil.subtract(balance, transferAmount, MATHCONTEXT); - Assertions.assertTrue(MathUtil.isEqualTo(expectedBalance, balance2), "Balance amount expected: " + expectedBalance + ", actual: " + balance2); + Assertions.assertTrue(MathUtil.isEqualTo(expectedBalance, balance2), + "Balance amount expected: " + expectedBalance + ", actual: " + balance2); // payer response = interopHelper.createTransfer(transferCode, InteropTransactionRole.PAYER); @@ -268,7 +266,8 @@ public class InteropTest { BigDecimal onHold3 = ObjectConverter.convertObjectTo(savingsJson.get(SavingsApiConstants.savingsAmountOnHold), BigDecimal.class); BigDecimal balance3 = ObjectConverter.convertObjectTo(savingsJson.get(PARAM_ACCOUNT_BALANCE), BigDecimal.class); Assertions.assertTrue(MathUtil.isEqualTo(onHold, onHold3), "On hold amount expected: " + onHold + ", actual: " + onHold3); - Assertions.assertTrue(MathUtil.isEqualTo(expectedBalance, balance3), "Balance amount expected: " + expectedBalance + ", actual: " + balance3); + Assertions.assertTrue(MathUtil.isEqualTo(expectedBalance, balance3), + "Balance amount expected: " + expectedBalance + ", actual: " + balance3); // payee response = interopHelper.createTransfer(transferCode, InteropTransactionRole.PAYEE); @@ -283,6 +282,7 @@ public class InteropTest { BigDecimal balance4 = ObjectConverter.convertObjectTo(savingsJson.get(PARAM_ACCOUNT_BALANCE), BigDecimal.class); expectedBalance = MathUtil.subtract(balance, interopHelper.getFee(), MATHCONTEXT); Assertions.assertTrue(MathUtil.isEqualTo(onHold, onHold4), "On hold amount expected: " + onHold + ", actual: " + onHold4); - Assertions.assertTrue(MathUtil.isEqualTo(balance, balance4), "Balance amount expected: " + expectedBalance + ", actual: " + balance4); + Assertions.assertTrue(MathUtil.isEqualTo(balance, balance4), + "Balance amount expected: " + expectedBalance + ", actual: " + balance4); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorHelper.java old mode 100755 new mode 100644 index c16fc23f7..c2fc377d7 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorHelper.java @@ -49,8 +49,8 @@ public class GuarantorHelper { } public HashMap deleteGuarantor(final Integer guarantorId, final Integer fundId, final Integer loanId) { - return Utils.performServerDelete(this.requestSpec, this.responseSpec, LOAN_URL + loanId + GUARANTOR_API_URL + guarantorId + TENANT - + "&guarantorFundingId=" + fundId, ""); + return Utils.performServerDelete(this.requestSpec, this.responseSpec, + LOAN_URL + loanId + GUARANTOR_API_URL + guarantorId + TENANT + "&guarantorFundingId=" + fundId, ""); } public HashMap deleteGuarantor(final Integer guarantorId, final Integer loanId) { diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorTest.java old mode 100755 new mode 100644 index d351e0c6b..a36d0adcf --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorTest.java @@ -49,18 +49,19 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GuarantorTest { + private final static Logger LOG = LoggerFactory.getLogger(GuarantorTest.class); private ResponseSpecification responseSpec; private RequestSpecification requestSpec; private LoanTransactionHelper loanTransactionHelper; private GuarantorHelper guarantorHelper; private SavingsAccountHelper savingsAccountHelper; - private final Float self1_balance = Float.valueOf((float)5000); - private final Float external1_balance = Float.valueOf((float)5000); - private final Float external2_balance = Float.valueOf((float)5000); - private final Float self1_guarantee = Float.valueOf((float)2000); - private final Float external1_guarantee = Float.valueOf((float)2000); - private final Float external2_guarantee = Float.valueOf((float)1000); + private final Float self1_balance = Float.valueOf((float) 5000); + private final Float external1_balance = Float.valueOf((float) 5000); + private final Float external2_balance = Float.valueOf((float) 5000); + private final Float self1_guarantee = Float.valueOf((float) 2000); + private final Float external1_guarantee = Float.valueOf((float) 2000); + private final Float external2_guarantee = Float.valueOf((float) 1000); @BeforeEach public void setUp() throws Exception { @@ -77,9 +78,9 @@ public class GuarantorTest { @Test public void testGuarantor() { - Float self1_hold_funds = Float.valueOf((float)0); - Float external1_hold_funds = Float.valueOf((float)0); - Float external2_hold_funds = Float.valueOf((float)0); + Float self1_hold_funds = Float.valueOf((float) 0); + Float external1_hold_funds = Float.valueOf((float) 0); + Float external2_hold_funds = Float.valueOf((float) 0); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer clientID_external = ClientHelper.createClient(this.requestSpec, this.responseSpec); @@ -162,9 +163,9 @@ public class GuarantorTest { LOG.info("-----------------------------------UNDO APPROVE LOAN-----------------------------------------"); loanStatusHashMap = this.loanTransactionHelper.undoApproval(loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - verifySavingsOnHoldBalance(selfSavigsId, Float.valueOf((float)0)); - verifySavingsOnHoldBalance(externalSavigsId_1, Float.valueOf((float)0)); - verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float)0)); + verifySavingsOnHoldBalance(selfSavigsId, Float.valueOf((float) 0)); + verifySavingsOnHoldBalance(externalSavigsId_1, Float.valueOf((float) 0)); + verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float) 0)); LOG.info("-----------------------------------APPROVE LOAN-----------------------------------------"); loanStatusHashMap = this.loanTransactionHelper.approveLoan(LOAN_DISBURSEMENT_DATE, loanID); @@ -184,8 +185,8 @@ public class GuarantorTest { todaysDate.add(Calendar.DAY_OF_MONTH, -7 * 3); String LOAN_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); Float totalDueForCurrentPeriod = (Float) loanSchedule.get(1).get("totalDueForPeriod"); - external1_hold_funds -= Float.valueOf((float)827.5867); - external2_hold_funds -= Float.valueOf((float)413.7933); + external1_hold_funds -= Float.valueOf((float) 827.5867); + external2_hold_funds -= Float.valueOf((float) 413.7933); this.loanTransactionHelper.makeRepayment(LOAN_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); verifySavingsOnHoldBalance(selfSavigsId, self1_hold_funds); verifySavingsOnHoldBalance(externalSavigsId_1, external1_hold_funds); @@ -196,8 +197,8 @@ public class GuarantorTest { todaysDate.add(Calendar.DAY_OF_MONTH, -7 * 2); LOAN_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); totalDueForCurrentPeriod = (Float) loanSchedule.get(2).get("totalDueForPeriod"); - external1_hold_funds -= Float.valueOf((float)831.4067); - external2_hold_funds -= Float.valueOf((float)415.7033333); + external1_hold_funds -= Float.valueOf((float) 831.4067); + external2_hold_funds -= Float.valueOf((float) 415.7033333); this.loanTransactionHelper.makeRepayment(LOAN_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); verifySavingsOnHoldBalance(selfSavigsId, self1_hold_funds); verifySavingsOnHoldBalance(externalSavigsId_1, external1_hold_funds); @@ -208,20 +209,20 @@ public class GuarantorTest { todaysDate.add(Calendar.DAY_OF_MONTH, -7); LOAN_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); totalDueForCurrentPeriod = (Float) loanSchedule.get(3).get("totalDueForPeriod"); - self1_hold_funds -= Float.valueOf((float)741.355); + self1_hold_funds -= Float.valueOf((float) 741.355); this.loanTransactionHelper.makeRepayment(LOAN_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); verifySavingsOnHoldBalance(selfSavigsId, self1_hold_funds); - verifySavingsOnHoldBalance(externalSavigsId_1, Float.valueOf((float)0)); - verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float)0)); + verifySavingsOnHoldBalance(externalSavigsId_1, Float.valueOf((float) 0)); + verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float) 0)); // forth repayment todaysDate = Calendar.getInstance(); LOAN_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); totalDueForCurrentPeriod = (Float) loanSchedule.get(3).get("totalDueForPeriod"); this.loanTransactionHelper.makeRepayment(LOAN_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); - verifySavingsOnHoldBalance(selfSavigsId, Float.valueOf((float)0)); - verifySavingsOnHoldBalance(externalSavigsId_1, Float.valueOf((float)0)); - verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float)0)); + verifySavingsOnHoldBalance(selfSavigsId, Float.valueOf((float) 0)); + verifySavingsOnHoldBalance(externalSavigsId_1, Float.valueOf((float) 0)); + verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float) 0)); loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanAccountIsClosed(loanStatusHashMap); @@ -232,9 +233,9 @@ public class GuarantorTest { @Test public void testGuarantor_UNDO_DISBURSAL() { - Float self1_hold_funds = Float.valueOf((float)0); - Float external1_hold_funds = Float.valueOf((float)0); - Float external2_hold_funds = Float.valueOf((float)0); + Float self1_hold_funds = Float.valueOf((float) 0); + Float external1_hold_funds = Float.valueOf((float) 0); + Float external2_hold_funds = Float.valueOf((float) 0); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer clientID_external = ClientHelper.createClient(this.requestSpec, this.responseSpec); @@ -319,9 +320,9 @@ public class GuarantorTest { LOG.info("-----------------------------------UNDO APPROVE LOAN-----------------------------------------"); loanStatusHashMap = this.loanTransactionHelper.undoApproval(loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - verifySavingsOnHoldBalance(selfSavigsId, Float.valueOf((float)0)); - verifySavingsOnHoldBalance(externalSavigsId_1, Float.valueOf((float)0)); - verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float)0)); + verifySavingsOnHoldBalance(selfSavigsId, Float.valueOf((float) 0)); + verifySavingsOnHoldBalance(externalSavigsId_1, Float.valueOf((float) 0)); + verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float) 0)); LOG.info("-----------------------------------APPROVE LOAN-----------------------------------------"); loanStatusHashMap = this.loanTransactionHelper.approveLoan(LOAN_DISBURSEMENT_DATE, loanID); @@ -375,8 +376,8 @@ public class GuarantorTest { todaysDate.add(Calendar.DAY_OF_MONTH, -7 * 3); String LOAN_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); Float totalDueForCurrentPeriod = (Float) loanSchedule.get(1).get("totalDueForPeriod"); - external1_hold_funds -= Float.valueOf((float)827.5867); - external2_hold_funds -= Float.valueOf((float)413.7933); + external1_hold_funds -= Float.valueOf((float) 827.5867); + external2_hold_funds -= Float.valueOf((float) 413.7933); this.loanTransactionHelper.makeRepayment(LOAN_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); verifySavingsOnHoldBalance(selfSavigsId, self1_hold_funds); verifySavingsOnHoldBalance(externalSavigsId_3, external1_hold_funds); @@ -387,8 +388,8 @@ public class GuarantorTest { todaysDate.add(Calendar.DAY_OF_MONTH, -7 * 2); LOAN_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); totalDueForCurrentPeriod = (Float) loanSchedule.get(2).get("totalDueForPeriod"); - external1_hold_funds -= Float.valueOf((float)831.4067); - external2_hold_funds -= Float.valueOf((float)415.7033333); + external1_hold_funds -= Float.valueOf((float) 831.4067); + external2_hold_funds -= Float.valueOf((float) 415.7033333); this.loanTransactionHelper.makeRepayment(LOAN_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); verifySavingsOnHoldBalance(selfSavigsId, self1_hold_funds); verifySavingsOnHoldBalance(externalSavigsId_3, external1_hold_funds); @@ -399,11 +400,11 @@ public class GuarantorTest { todaysDate.add(Calendar.DAY_OF_MONTH, -7); LOAN_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); totalDueForCurrentPeriod = (Float) loanSchedule.get(3).get("totalDueForPeriod"); - Float self1_hold_funds_temp = self1_hold_funds - Float.valueOf((float)741.355); + Float self1_hold_funds_temp = self1_hold_funds - Float.valueOf((float) 741.355); HashMap transactionDetail = this.loanTransactionHelper.makeRepayment(LOAN_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); verifySavingsOnHoldBalance(selfSavigsId, self1_hold_funds_temp); - verifySavingsOnHoldBalance(externalSavigsId_3, Float.valueOf((float)0)); - verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float)0)); + verifySavingsOnHoldBalance(externalSavigsId_3, Float.valueOf((float) 0)); + verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float) 0)); // undo repayment this.loanTransactionHelper.adjustLoanTransaction(loanID, (Integer) transactionDetail.get(CommonConstants.RESPONSE_RESOURCE_ID), @@ -416,17 +417,17 @@ public class GuarantorTest { loanStatusHashMap = this.loanTransactionHelper.undoDisbursal(loanID); LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); - verifySavingsOnHoldBalance(selfSavigsId, Float.valueOf((float)self1_guarantee)); - verifySavingsOnHoldBalance(externalSavigsId_3, Float.valueOf((float)external1_guarantee)); - verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float)external2_guarantee)); + verifySavingsOnHoldBalance(selfSavigsId, Float.valueOf((float) self1_guarantee)); + verifySavingsOnHoldBalance(externalSavigsId_3, Float.valueOf((float) external1_guarantee)); + verifySavingsOnHoldBalance(externalSavigsId_2, Float.valueOf((float) external2_guarantee)); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testGuarantor_RECOVER_GUARANTEES() { - Float self1_hold_funds = Float.valueOf((float)0); - Float external1_hold_funds = Float.valueOf((float)0); + Float self1_hold_funds = Float.valueOf((float) 0); + Float external1_hold_funds = Float.valueOf((float) 0); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer clientID_external = ClientHelper.createClient(this.requestSpec, this.responseSpec); @@ -478,14 +479,14 @@ public class GuarantorTest { todaysDate.add(Calendar.DAY_OF_MONTH, -14); String LOAN_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); Float totalDueForCurrentPeriod = (Float) loanSchedule.get(1).get("totalDueForPeriod"); - external1_hold_funds -= Float.valueOf((float)993.104); + external1_hold_funds -= Float.valueOf((float) 993.104); this.loanTransactionHelper.makeRepayment(LOAN_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); verifySavingsOnHoldBalance(selfSavigsId, self1_hold_funds); verifySavingsOnHoldBalance(externalSavigsId_1, external1_hold_funds); this.loanTransactionHelper.recoverFromGuarantor(loanID); - verifySavingsBalanceAndOnHoldBalance(selfSavigsId, Float.valueOf((float)0), self1_balance - self1_hold_funds); - verifySavingsBalanceAndOnHoldBalance(externalSavigsId_1, Float.valueOf((float)0), external1_balance - external1_hold_funds); + verifySavingsBalanceAndOnHoldBalance(selfSavigsId, Float.valueOf((float) 0), self1_balance - self1_hold_funds); + verifySavingsBalanceAndOnHoldBalance(externalSavigsId_1, Float.valueOf((float) 0), external1_balance - external1_hold_funds); } @@ -493,17 +494,17 @@ public class GuarantorTest { @Test public void testGuarantor_RECOVER_GUARANTEES_WITH_MORE_GUARANTEE() { - Float self1_hold_funds = Float.valueOf((float)0); - Float external1_hold_funds = Float.valueOf((float)0); + Float self1_hold_funds = Float.valueOf((float) 0); + Float external1_hold_funds = Float.valueOf((float) 0); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer clientID_external = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID_external); - Float selfBalance = Float.valueOf((float)10000); - Float externalBalance = Float.valueOf((float)10000); - Float selfguarantee = Float.valueOf((float)6000); - Float externalguarantee = Float.valueOf((float)7000); + Float selfBalance = Float.valueOf((float) 10000); + Float externalBalance = Float.valueOf((float) 10000); + Float selfguarantee = Float.valueOf((float) 6000); + Float externalguarantee = Float.valueOf((float) 7000); final Integer selfSavigsId = SavingsAccountHelper.openSavingsAccount(this.requestSpec, this.responseSpec, clientID, String.valueOf(selfBalance)); @@ -520,8 +521,9 @@ public class GuarantorTest { HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - String guarantorJSON = new GuarantorTestBuilder().existingCustomerWithGuaranteeAmount(String.valueOf(clientID), - String.valueOf(selfSavigsId), String.valueOf(selfguarantee)).build(); + String guarantorJSON = new GuarantorTestBuilder() + .existingCustomerWithGuaranteeAmount(String.valueOf(clientID), String.valueOf(selfSavigsId), String.valueOf(selfguarantee)) + .build(); Integer selfGuarantee = this.guarantorHelper.createGuarantor(loanID, guarantorJSON); verifySavingsOnHoldBalance(selfSavigsId, null); Assertions.assertNotNull(selfGuarantee); @@ -551,24 +553,24 @@ public class GuarantorTest { todaysDate.add(Calendar.DAY_OF_MONTH, -14); String LOAN_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); Float totalDueForCurrentPeriod = (Float) loanSchedule.get(1).get("totalDueForPeriod"); - external1_hold_funds -= Float.valueOf((float)3227.588); + external1_hold_funds -= Float.valueOf((float) 3227.588); this.loanTransactionHelper.makeRepayment(LOAN_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); verifySavingsOnHoldBalance(selfSavigsId, self1_hold_funds); verifySavingsOnHoldBalance(externalSavigsId_1, external1_hold_funds); this.loanTransactionHelper.recoverFromGuarantor(loanID); - verifySavingsBalanceAndOnHoldBalance(selfSavigsId, Float.valueOf((float)0), selfBalance - Float.valueOf((float)4615.385)); - verifySavingsBalanceAndOnHoldBalance(externalSavigsId_1, Float.valueOf((float)0), externalBalance - Float.valueOf((float)2901.8553)); + verifySavingsBalanceAndOnHoldBalance(selfSavigsId, Float.valueOf((float) 0), selfBalance - Float.valueOf((float) 4615.385)); + verifySavingsBalanceAndOnHoldBalance(externalSavigsId_1, Float.valueOf((float) 0), + externalBalance - Float.valueOf((float) 2901.8553)); } - @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testGuarantor_WRITE_OFF_LOAN() { - Float self1_hold_funds = Float.valueOf((float)0); - Float external1_hold_funds = Float.valueOf((float)0); + Float self1_hold_funds = Float.valueOf((float) 0); + Float external1_hold_funds = Float.valueOf((float) 0); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); final Integer clientID_external = ClientHelper.createClient(this.requestSpec, this.responseSpec); @@ -620,7 +622,7 @@ public class GuarantorTest { todaysDate.add(Calendar.DAY_OF_MONTH, -14); String LOAN_REPAYMENT_DATE = dateFormat.format(todaysDate.getTime()); Float totalDueForCurrentPeriod = (Float) loanSchedule.get(1).get("totalDueForPeriod"); - external1_hold_funds -= Float.valueOf((float)993.104); + external1_hold_funds -= Float.valueOf((float) 993.104); this.loanTransactionHelper.makeRepayment(LOAN_REPAYMENT_DATE, totalDueForCurrentPeriod, loanID); verifySavingsOnHoldBalance(selfSavigsId, self1_hold_funds); verifySavingsOnHoldBalance(externalSavigsId_1, external1_hold_funds); @@ -628,8 +630,8 @@ public class GuarantorTest { todaysDate = Calendar.getInstance(); String LOAN_WRITEOFF_DATE = dateFormat.format(todaysDate.getTime()); this.loanTransactionHelper.writeOffLoan(LOAN_WRITEOFF_DATE, loanID); - verifySavingsBalanceAndOnHoldBalance(selfSavigsId, Float.valueOf((float)0), self1_balance); - verifySavingsBalanceAndOnHoldBalance(externalSavigsId_1, Float.valueOf((float)0), external1_balance); + verifySavingsBalanceAndOnHoldBalance(selfSavigsId, Float.valueOf((float) 0), self1_balance); + verifySavingsBalanceAndOnHoldBalance(externalSavigsId_1, Float.valueOf((float) 0), external1_balance); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorTestBuilder.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorTestBuilder.java old mode 100755 new mode 100644 index e1fe97d57..304720048 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorTestBuilder.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/loanaccount/guarantor/GuarantorTestBuilder.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GuarantorTestBuilder { + private final static Logger LOG = LoggerFactory.getLogger(GuarantorTestBuilder.class); private static final String GUARANTOR_TYPE_CUSTOMER = "1"; @SuppressWarnings("unused") @@ -59,7 +60,7 @@ public class GuarantorTestBuilder { map.put("amount", guaranteeAmount); map.put("savingsId", savingsId); } - LOG.info("map : {}" , map); + LOG.info("map : {}", map); return new Gson().toJson(map); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/useradministration/roles/RolesHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/useradministration/roles/RolesHelper.java index 22bc67649..570c30d98 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/useradministration/roles/RolesHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/useradministration/roles/RolesHelper.java @@ -49,15 +49,18 @@ public class RolesHelper { return role; } - public static Integer disableRole(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer roleId) { + public static Integer disableRole(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer roleId) { return Utils.performServerPost(requestSpec, responseSpec, createRoleOperationURL(DISABLE_ROLE_COMMAND, roleId), "", "resourceId"); } - public static Integer enableRole(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer roleId) { + public static Integer enableRole(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer roleId) { return Utils.performServerPost(requestSpec, responseSpec, createRoleOperationURL(ENABLE_ROLE_COMMAND, roleId), "", "resourceId"); } - public static Integer deleteRole(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer roleId) { + public static Integer deleteRole(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer roleId) { return Utils.performServerDelete(requestSpec, responseSpec, createRoleOperationURL(ENABLE_ROLE_COMMAND, roleId), "resourceId"); } @@ -65,4 +68,4 @@ public class RolesHelper { return ROLE_URL + "/" + roleId + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/useradministration/users/UserHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/useradministration/users/UserHelper.java index 0f122de34..6300d4f7d 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/useradministration/users/UserHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/useradministration/users/UserHelper.java @@ -22,62 +22,65 @@ import io.restassured.specification.RequestSpecification; import io.restassured.specification.ResponseSpecification; import org.apache.fineract.integrationtests.common.Utils; - public class UserHelper { + private static final String CREATE_USER_URL = "/fineract-provider/api/v1/users?" + Utils.TENANT_IDENTIFIER; private static final String USER_URL = "/fineract-provider/api/v1/users"; - public static Integer createUser(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, int roleId, int staffId) { + public static Integer createUser(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, int roleId, + int staffId) { return Utils.performServerPost(requestSpec, responseSpec, CREATE_USER_URL, getTestCreateUserAsJSON(roleId, staffId), "resourceId"); } - public static Object createUser(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, int roleId, int staffId, String username, String attribute) { - return Utils.performServerPost(requestSpec, responseSpec, CREATE_USER_URL, getTestCreateUserAsJSON(roleId, staffId, username), attribute); + public static Object createUser(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, int roleId, + int staffId, String username, String attribute) { + return Utils.performServerPost(requestSpec, responseSpec, CREATE_USER_URL, getTestCreateUserAsJSON(roleId, staffId, username), + attribute); } - public static Object createUserForSelfService(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, int roleId, int staffId, int clientId, String attribute) { - return Utils.performServerPost(requestSpec, responseSpec, CREATE_USER_URL, getTestCreateUserAsJSONForSelfService(roleId, staffId, clientId), attribute); + + public static Object createUserForSelfService(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + int roleId, int staffId, int clientId, String attribute) { + return Utils.performServerPost(requestSpec, responseSpec, CREATE_USER_URL, + getTestCreateUserAsJSONForSelfService(roleId, staffId, clientId), attribute); } public static String getTestCreateUserAsJSON(int roleId, int staffId) { return "{ \"username\": \"" + Utils.randomNameGenerator("User_Name_", 3) + "\", \"firstname\": \"Test\", \"lastname\": \"User\", \"email\": \"whatever@mifos.org\"," - + " \"officeId\": \"1\", \"staffId\": " + "\"" - + staffId +"\",\"roles\": [\"" - + roleId + "\"], \"sendPasswordToEmail\": false}"; + + " \"officeId\": \"1\", \"staffId\": " + "\"" + staffId + "\",\"roles\": [\"" + roleId + + "\"], \"sendPasswordToEmail\": false}"; } private static String getTestCreateUserAsJSON(int roleId, int staffId, String username) { - return "{ \"username\": \"" + username - + "\", \"firstname\": \"Test\", \"lastname\": \"User\", \"email\": \"whatever@mifos.org\"," - + " \"officeId\": \"1\", \"staffId\": " + "\"" - + staffId +"\",\"roles\": [\"" - + roleId + "\"], \"sendPasswordToEmail\": false}"; + return "{ \"username\": \"" + username + "\", \"firstname\": \"Test\", \"lastname\": \"User\", \"email\": \"whatever@mifos.org\"," + + " \"officeId\": \"1\", \"staffId\": " + "\"" + staffId + "\",\"roles\": [\"" + roleId + + "\"], \"sendPasswordToEmail\": false}"; } private static String getTestUpdateUserAsJSON(String username) { - return "{ \"username\": \"" + username - + "\", \"firstname\": \"Test\", \"lastname\": \"User\", \"email\": \"whatever@mifos.org\"," - + " \"officeId\": \"1\"}"; + return "{ \"username\": \"" + username + "\", \"firstname\": \"Test\", \"lastname\": \"User\", \"email\": \"whatever@mifos.org\"," + + " \"officeId\": \"1\"}"; } + public static String getTestCreateUserAsJSONForSelfService(int roleId, int staffId, int clientId) { return "{ \"username\": \"" + Utils.randomNameGenerator("User_Name_", 3) + "\", \"firstname\": \"Test\", \"lastname\": \"User\", \"email\": \"whatever@mifos.org\"," - + " \"officeId\": \"1\", \"staffId\": " + "\"" - + staffId +"\",\"roles\": [\"" - + roleId + "\"], \"sendPasswordToEmail\": false," - +"\"isSelfServiceUser\" : true," - +"\"clients\" : [\""+clientId+"\"]}"; + + " \"officeId\": \"1\", \"staffId\": " + "\"" + staffId + "\",\"roles\": [\"" + roleId + + "\"], \"sendPasswordToEmail\": false," + "\"isSelfServiceUser\" : true," + "\"clients\" : [\"" + clientId + "\"]}"; } - public static Integer deleteUser(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer userId) { + public static Integer deleteUser(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, + final Integer userId) { return Utils.performServerDelete(requestSpec, responseSpec, createRoleOperationURL(userId), "resourceId"); } - public static Object updateUser(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, int userId, String username, String attribute) { - return Utils.performServerPut(requestSpec, responseSpec, createRoleOperationURL(userId), getTestUpdateUserAsJSON(username), attribute); + public static Object updateUser(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, int userId, + String username, String attribute) { + return Utils.performServerPut(requestSpec, responseSpec, createRoleOperationURL(userId), getTestUpdateUserAsJSON(username), + attribute); } private static String createRoleOperationURL(final Integer userId) { return USER_URL + "/" + userId + "?" + Utils.TENANT_IDENTIFIER; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsDecliningBalanceHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsDecliningBalanceHelper.java index 29750d90f..d03001ba1 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsDecliningBalanceHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsDecliningBalanceHelper.java @@ -33,10 +33,13 @@ import org.apache.fineract.integrationtests.common.loans.LoanProductTestBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@SuppressWarnings({"rawtypes", "unchecked"}) +@SuppressWarnings({ "rawtypes", "unchecked" }) public class VariableInstallmentsDecliningBalanceHelper { + private final static Logger LOG = LoggerFactory.getLogger(VariableInstallmentsDecliningBalanceHelper.class); - public static String createLoanProductWithoutVaribleConfig(final boolean multiDisburseLoan, final String accountingRule, final Account... accounts) { + + public static String createLoanProductWithoutVaribleConfig(final boolean multiDisburseLoan, final String accountingRule, + final Account... accounts) { LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); final String loanProductJSON = new LoanProductTestBuilder() // .withPrincipal("1,00,000.00") // @@ -49,10 +52,11 @@ public class VariableInstallmentsDecliningBalanceHelper { .withInterestTypeAsDecliningBalance() // .withTranches(multiDisburseLoan) // .withAccounting(accountingRule, accounts).build(null); - return loanProductJSON ; + return loanProductJSON; } - public static String createLoanProductWithVaribleConfig(final boolean multiDisburseLoan, final String accountingRule, final Account... accounts) { + public static String createLoanProductWithVaribleConfig(final boolean multiDisburseLoan, final String accountingRule, + final Account... accounts) { LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); final String loanProductJSON = new LoanProductTestBuilder() // .withPrincipal("1,00,000.00") // @@ -67,10 +71,11 @@ public class VariableInstallmentsDecliningBalanceHelper { .withInterestCalculationPeriodTypeAsRepaymentPeriod(true)// .withVariableInstallmentsConfig(Boolean.TRUE, Integer.valueOf(5), Integer.valueOf(90))// .withAccounting(accountingRule, accounts).build(null); - return loanProductJSON ; + return loanProductJSON; } - public static String createLoanProductWithVaribleConfigwithEqualPrincipal(final boolean multiDisburseLoan, final String accountingRule, final Account... accounts) { + public static String createLoanProductWithVaribleConfigwithEqualPrincipal(final boolean multiDisburseLoan, final String accountingRule, + final Account... accounts) { LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); final String loanProductJSON = new LoanProductTestBuilder() // .withPrincipal("1,00,000.00") // @@ -85,7 +90,7 @@ public class VariableInstallmentsDecliningBalanceHelper { .withInterestCalculationPeriodTypeAsRepaymentPeriod(true)// .withVariableInstallmentsConfig(Boolean.TRUE, Integer.valueOf(5), Integer.valueOf(90))// .withAccounting(accountingRule, accounts).build(null); - return loanProductJSON ; + return loanProductJSON; } public static String applyForLoanApplication(final Integer clientID, final Integer loanProductID, List charges, @@ -105,11 +110,11 @@ public class VariableInstallmentsDecliningBalanceHelper { .withExpectedDisbursementDate("20 September 2011") // .withSubmittedOnDate("20 September 2011") // .withCharges(charges).build(clientID.toString(), loanProductID.toString(), savingsId); - return loanApplicationJSON ; + return loanApplicationJSON; } - public static String applyForLoanApplicationWithEqualPrincipal(final Integer clientID, final Integer loanProductID, List charges, - final String savingsId, String principal) { + public static String applyForLoanApplicationWithEqualPrincipal(final Integer clientID, final Integer loanProductID, + List charges, final String savingsId, String principal) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); final String loanApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal(principal) // @@ -125,7 +130,7 @@ public class VariableInstallmentsDecliningBalanceHelper { .withExpectedDisbursementDate("20 September 2011") // .withSubmittedOnDate("20 September 2011") // .withCharges(charges).build(clientID.toString(), loanProductID.toString(), savingsId); - return loanApplicationJSON ; + return loanApplicationJSON; } public static String createDeleteVariations(ArrayList deletedInstallments) { @@ -195,7 +200,7 @@ public class VariableInstallmentsDecliningBalanceHelper { ArrayList dueDate = (ArrayList) firstSchedule.get("dueDate"); Map tosend = new HashMap(); tosend.put("dueDate", formatDate(dueDate)); - tosend.put("installmentAmount", 30000) ; + tosend.put("installmentAmount", 30000); toReturn.add(tosend); return toReturn; } @@ -239,10 +244,11 @@ public class VariableInstallmentsDecliningBalanceHelper { ArrayList toReturn = new ArrayList<>(); Map tosend = new HashMap(); tosend.put("dueDate", date); - tosend.put("principal", 30000) ; + tosend.put("principal", 30000); toReturn.add(tosend); return toReturn; } + private static ArrayList createDeletedMap(String date) { ArrayList toReturn = new ArrayList<>(); Map tosend = new HashMap(); @@ -255,7 +261,7 @@ public class VariableInstallmentsDecliningBalanceHelper { ArrayList toReturn = new ArrayList<>(); Map tosend = new HashMap(); tosend.put("dueDate", date); - tosend.put("installmentAmount", 30000) ; + tosend.put("installmentAmount", 30000); toReturn.add(tosend); return toReturn; } @@ -273,12 +279,12 @@ public class VariableInstallmentsDecliningBalanceHelper { private static ArrayList createDateModifyMap(String[] date, String[] newdate, String[] installments) { ArrayList toReturn = new ArrayList<>(); - for(int i = 0 ; i < date.length; i++) { + for (int i = 0; i < date.length; i++) { Map tosend = new HashMap(); tosend.put("dueDate", date[i]); - tosend.put("modifiedDueDate", newdate[i]) ; - if(i < installments.length) { - tosend.put("installmentAmount", installments[i]) ; + tosend.put("modifiedDueDate", newdate[i]); + if (i < installments.length) { + tosend.put("installmentAmount", installments[i]); } toReturn.add(tosend); } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsFlatHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsFlatHelper.java index 6ff1b6886..37364c6da 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsFlatHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsFlatHelper.java @@ -33,10 +33,13 @@ import org.apache.fineract.integrationtests.common.loans.LoanProductTestBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@SuppressWarnings({"rawtypes", "unchecked"}) +@SuppressWarnings({ "rawtypes", "unchecked" }) public class VariableInstallmentsFlatHelper { + private final static Logger LOG = LoggerFactory.getLogger(VariableInstallmentsFlatHelper.class); - public static String createLoanProductWithVaribleConfig(final boolean multiDisburseLoan, final String accountingRule, final Account... accounts) { + + public static String createLoanProductWithVaribleConfig(final boolean multiDisburseLoan, final String accountingRule, + final Account... accounts) { LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); final String loanProductJSON = new LoanProductTestBuilder() // .withPrincipal("1,00,000.00") // @@ -44,17 +47,14 @@ public class VariableInstallmentsFlatHelper { .withRepaymentAfterEvery("1") // .withRepaymentTypeAsMonth() // .withinterestRatePerPeriod("1") // - .withAmortizationTypeAsEqualPrincipalPayment() - .withInterestTypeAsFlat() // + .withAmortizationTypeAsEqualPrincipalPayment().withInterestTypeAsFlat() // .withTranches(multiDisburseLoan) // .withInterestCalculationPeriodTypeAsRepaymentPeriod(true)// .withVariableInstallmentsConfig(Boolean.TRUE, Integer.valueOf(5), Integer.valueOf(90))// .withAccounting(accountingRule, accounts).build(null); - return loanProductJSON ; + return loanProductJSON; } - - public static String applyForLoanApplication(final Integer clientID, final Integer loanProductID, List charges, final String savingsId, String principal) { LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); @@ -72,7 +72,7 @@ public class VariableInstallmentsFlatHelper { .withExpectedDisbursementDate("20 September 2011") // .withSubmittedOnDate("20 September 2011") // .withCharges(charges).build(clientID.toString(), loanProductID.toString(), savingsId); - return loanApplicationJSON ; + return loanApplicationJSON; } public static String createDeleteVariations(ArrayList deletedInstallments) { @@ -150,25 +150,24 @@ public class VariableInstallmentsFlatHelper { private static ArrayList createDateModifyMap(String[] date, String[] newdate, String[] principal) { ArrayList toReturn = new ArrayList<>(); - for(int i = 0 ; i < date.length; i++) { + for (int i = 0; i < date.length; i++) { Map tosend = new HashMap(); tosend.put("dueDate", date[i]); - tosend.put("modifiedDueDate", newdate[i]) ; - if(i < principal.length) { - tosend.put("principal", principal[i]) ; + tosend.put("modifiedDueDate", newdate[i]); + if (i < principal.length) { + tosend.put("principal", principal[i]); } toReturn.add(tosend); } return toReturn; } - private static ArrayList createModifyMap(Map firstSchedule) { ArrayList toReturn = new ArrayList<>(); ArrayList dueDate = (ArrayList) firstSchedule.get("dueDate"); Map tosend = new HashMap(); tosend.put("dueDate", formatDate(dueDate)); - tosend.put("principal", 30000) ; + tosend.put("principal", 30000); toReturn.add(tosend); return toReturn; } @@ -198,7 +197,7 @@ public class VariableInstallmentsFlatHelper { ArrayList toReturn = new ArrayList<>(); Map tosend = new HashMap(); tosend.put("dueDate", date); - tosend.put("principal", 30000) ; + tosend.put("principal", 30000); toReturn.add(tosend); return toReturn; } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsIntegrationTest.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsIntegrationTest.java index 4026e4542..15943115d 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsIntegrationTest.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableInstallmentsIntegrationTest.java @@ -36,8 +36,9 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@SuppressWarnings({"rawtypes", "unchecked"}) +@SuppressWarnings({ "rawtypes", "unchecked" }) public class VariableInstallmentsIntegrationTest { + private final static Logger LOG = LoggerFactory.getLogger(VariableInstallmentsIntegrationTest.class); private static final String NONE = "1"; private RequestSpecification requestSpec; @@ -58,230 +59,273 @@ public class VariableInstallmentsIntegrationTest { final String json = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); final Integer loanProductID = this.loanTransactionHelper.getLoanProductId(json); LOG.info("------------------------------RETRIEVING CREATED LOAN PRODUCT DETAILS ---------------------------------------"); - Map loanProduct = (Map)loanTransactionHelper.getLoanProductDetail(requestSpec, responseSpec, loanProductID, "") ; - Assertions.assertTrue((Boolean)loanProduct.get("allowVariableInstallments")) ; - Assertions.assertEquals(Integer.valueOf(5), loanProduct.get("minimumGap")) ; - Assertions.assertEquals(Integer.valueOf(90), loanProduct.get("maximumGap")) ; + Map loanProduct = (Map) loanTransactionHelper.getLoanProductDetail(requestSpec, responseSpec, loanProductID, ""); + Assertions.assertTrue((Boolean) loanProduct.get("allowVariableInstallments")); + Assertions.assertEquals(Integer.valueOf(5), loanProduct.get("minimumGap")); + Assertions.assertEquals(Integer.valueOf(90), loanProduct.get("maximumGap")); } - @Test public void testLoanProductCreation() { - final String josn = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithoutVaribleConfig(false, NONE); + final String josn = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithoutVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(josn); LOG.info("------------------------------RETRIEVING CREATED LOAN PRODUCT DETAILS ---------------------------------------"); - Map loanProduct = (Map)loanTransactionHelper.getLoanProductDetail(requestSpec, responseSpec, loanProductID, "") ; - Assertions.assertTrue(!(Boolean)loanProduct.get("allowVariableInstallments")) ; + Map loanProduct = (Map) loanTransactionHelper.getLoanProductDetail(requestSpec, responseSpec, loanProductID, ""); + Assertions.assertTrue(!(Boolean) loanProduct.get("allowVariableInstallments")); } @Test public void testDeleteInstallmentsWithDecliningBalanceEqualInstallments() { - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplication(clientID, loanProductID, null, null, "1,00,000.00"); + final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplication(clientID, loanProductID, null, null, + "1,00,000.00"); final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - //Integer loanID = 49 ; - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; - ArrayList toDelete = new ArrayList<>() ; - toDelete.add(periods.get(1)) ; - String toDeletedata = VariableInstallmentsDecliningBalanceHelper.createDeleteVariations(toDelete) ; - HashMap modifiedReschdule = transactionHelper.validateVariations(toDeletedata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData(new String[] {"20 November 2011", "20 December 2011", "20 January 2012"}, - new String[] {"34675.47", "34675.47", "36756.26"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(toDeletedata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + // Integer loanID = 49 ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); + ArrayList toDelete = new ArrayList<>(); + toDelete.add(periods.get(1)); + String toDeletedata = VariableInstallmentsDecliningBalanceHelper.createDeleteVariations(toDelete); + HashMap modifiedReschdule = transactionHelper.validateVariations(toDeletedata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData( + new String[] { "20 November 2011", "20 December 2011", "20 January 2012" }, + new String[] { "34675.47", "34675.47", "36756.26" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(toDeletedata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } + private void assertAfterSubmit(ArrayList serverData, ArrayList expectedData) { - Assertions.assertTrue(serverData.size() == expectedData.size()) ; - for(int i = 0 ; i < serverData.size(); i++) { - Map serverMap = serverData.get(i) ; - Map expectedMap = expectedData.get(i) ; - Assertions.assertTrue(VariableInstallmentsDecliningBalanceHelper.formatDate((ArrayList)serverMap.get("dueDate")).equals(expectedMap.get("dueDate"))) ; - Assertions.assertTrue(serverMap.get("totalOutstandingForPeriod").toString().equals(expectedMap.get("installmentAmount"))) ; + Assertions.assertTrue(serverData.size() == expectedData.size()); + for (int i = 0; i < serverData.size(); i++) { + Map serverMap = serverData.get(i); + Map expectedMap = expectedData.get(i); + Assertions.assertTrue(VariableInstallmentsDecliningBalanceHelper.formatDate((ArrayList) serverMap.get("dueDate")) + .equals(expectedMap.get("dueDate"))); + Assertions.assertTrue(serverMap.get("totalOutstandingForPeriod").toString().equals(expectedMap.get("installmentAmount"))); } } @Test public void testAddInstallmentsWithDecliningBalanceEqualInstallments() { - //31 October 2011 - 5000 - //Result: 20 October 2011 - 21,215.84, 31 October 2011 - 5000, 20 November 2011 26,477.31, 20 December 2011 26,477.31, 20 January 2012 25,947.7 - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); + // 31 October 2011 - 5000 + // Result: 20 October 2011 - 21,215.84, 31 October 2011 - 5000, 20 + // November 2011 26,477.31, 20 December 2011 26,477.31, 20 January 2012 + // 25,947.7 + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplication(clientID, loanProductID, null, null, "1,00,000.00"); + final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplication(clientID, loanProductID, null, null, + "1,00,000.00"); final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - // Integer loanID = 57 ; - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; - String addVariationsjsondata = VariableInstallmentsDecliningBalanceHelper.createAddVariations() ; - HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData(new String[] {"20 October 2011", "31 October 2011", "20 November 2011", "20 December 2011", "20 January 2012"}, - new String[] {"21215.84", "5000.0", "26477.31", "26477.31", "25947.7"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(addVariationsjsondata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + // Integer loanID = 57 ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); + String addVariationsjsondata = VariableInstallmentsDecliningBalanceHelper.createAddVariations(); + HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData( + new String[] { "20 October 2011", "31 October 2011", "20 November 2011", "20 December 2011", "20 January 2012" }, + new String[] { "21215.84", "5000.0", "26477.31", "26477.31", "25947.7" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(addVariationsjsondata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } @Test public void testModifyInstallmentWithDecliningBalanceEqualInstallments() { - //20 October 2011 - 30000 modify - //Result 20 October 2011 - 30000.0, 20 November 2011 - 24,966.34, 20 December 2011 - 24,966.34, 20 January 2012 - 24,966.33 - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); + // 20 October 2011 - 30000 modify + // Result 20 October 2011 - 30000.0, 20 November 2011 - 24,966.34, 20 + // December 2011 - 24,966.34, 20 January 2012 - 24,966.33 + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplication(clientID, loanProductID, null, null, "1,00,000.00"); + final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplication(clientID, loanProductID, null, null, + "1,00,000.00"); final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - //Integer loanID = 57 ; - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; - String addVariationsjsondata = VariableInstallmentsDecliningBalanceHelper.createModifiyVariations((Map)periods.get(1)) ; //0th position will have disbursement - HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData(new String[] {"20 October 2011", "20 November 2011", "20 December 2011", "20 January 2012"}, - new String[] {"30000.0", "24966.34", "24966.34", "24966.33"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(addVariationsjsondata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + // Integer loanID = 57 ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); + String addVariationsjsondata = VariableInstallmentsDecliningBalanceHelper.createModifiyVariations((Map) periods.get(1)); // 0th + // position + // will + // have + // disbursement + HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData( + new String[] { "20 October 2011", "20 November 2011", "20 December 2011", "20 January 2012" }, + new String[] { "30000.0", "24966.34", "24966.34", "24966.33" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(addVariationsjsondata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } @Test public void testAllVariationsDecliningBalancewithEqualInstallments() { - // Request: Delete 20 December 2011 26,262.38, Modify 20 November 2011 from 26,262.38 to 30000, Add 25 December 2011 5000 - // Result: 20 October 2011 - 26262.38, 20 November 2011 - 30000, 25 December 2011 - 5000, 20 January 2012 - 44077 - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); + // Request: Delete 20 December 2011 26,262.38, Modify 20 November 2011 + // from 26,262.38 to 30000, Add 25 December 2011 5000 + // Result: 20 October 2011 - 26262.38, 20 November 2011 - 30000, 25 + // December 2011 - 5000, 20 January 2012 - 44077 + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplication(clientID, loanProductID, null, null, "1,00,000.00"); + final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplication(clientID, loanProductID, null, null, + "1,00,000.00"); final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - //Integer loanID = 57 ; - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; + // Integer loanID = 57 ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); - String addVariationsjsondata = VariableInstallmentsDecliningBalanceHelper.createAllVariations() ; //0th position will have disbursement - HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData(new String[] {"20 October 2011", "20 November 2011", "25 December 2011", "20 January 2012"}, - new String[] {"26262.38", "30000.0", "5000.0", "44077.0"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(addVariationsjsondata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + String addVariationsjsondata = VariableInstallmentsDecliningBalanceHelper.createAllVariations(); // 0th + // position + // will + // have + // disbursement + HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData( + new String[] { "20 October 2011", "20 November 2011", "25 December 2011", "20 January 2012" }, + new String[] { "26262.38", "30000.0", "5000.0", "44077.0" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(addVariationsjsondata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } @Test public void testAllVariationsDecliningBalancewithEqualPrincipal() { - // Request: Delete 20 December 2011 26,262.38, Modify 20 November 2011 from 26,262.38 to 30000, Add 25 December 2011 5000 - // Result: 20 October 2011 - 27000.0, 20 November 2011 - 31500.0, 25 December 2011 - 6045.16, 20 January 2012 - 40670.97 - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfigwithEqualPrincipal(false, NONE); + // Request: Delete 20 December 2011 26,262.38, Modify 20 November 2011 + // from 26,262.38 to 30000, Add 25 December 2011 5000 + // Result: 20 October 2011 - 27000.0, 20 November 2011 - 31500.0, 25 + // December 2011 - 6045.16, 20 January 2012 - 40670.97 + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsDecliningBalanceHelper + .createLoanProductWithVaribleConfigwithEqualPrincipal(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplicationWithEqualPrincipal(clientID, loanProductID, null, null, "1,00,000.00"); + final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplicationWithEqualPrincipal(clientID, loanProductID, + null, null, "1,00,000.00"); final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - // Integer loanID = 109 ; - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; + // Integer loanID = 109 ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); - String addVariationsjsondata = VariableInstallmentsDecliningBalanceHelper.createAllVariationsWithEqualPrincipal() ; //0th position will have disbursement - HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData(new String[] {"20 October 2011", "20 November 2011", "25 December 2011", "20 January 2012"}, - new String[] {"27000.0", "31500.0", "6045.16", "40670.97"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(addVariationsjsondata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + String addVariationsjsondata = VariableInstallmentsDecliningBalanceHelper.createAllVariationsWithEqualPrincipal(); // 0th + // position + // will + // have + // disbursement + HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData( + new String[] { "20 October 2011", "20 November 2011", "25 December 2011", "20 January 2012" }, + new String[] { "27000.0", "31500.0", "6045.16", "40670.97" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(addVariationsjsondata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } @Test public void testModifyDatesWithDecliningBalanceEqualInstallments() { - //Modify 20 December 2011:25000 -> 04 January 2012:20000 - //Modify 20 January 2012 -> 08 February 2012 - //Result 20 October 2011 -26262.38, 20 November 2011 - 26262.38, 04 January 2012 -20000, 08 February 2012 - 33242.97 - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); + // Modify 20 December 2011:25000 -> 04 January 2012:20000 + // Modify 20 January 2012 -> 08 February 2012 + // Result 20 October 2011 -26262.38, 20 November 2011 - 26262.38, 04 + // January 2012 -20000, 08 February 2012 - 33242.97 + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsDecliningBalanceHelper.createLoanProductWithVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); - final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplication(clientID, loanProductID, null, null, "1,00,000.00"); + final String json = VariableInstallmentsDecliningBalanceHelper.applyForLoanApplication(clientID, loanProductID, null, null, + "1,00,000.00"); final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - //Integer loanID = 57 ; + // Integer loanID = 57 ; - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); // // - String addVariationsjsondata = VariableInstallmentsDecliningBalanceHelper.createModifiyDateVariations(new String[]{"20 December 2011", "20 January 2012"}, new String[]{"04 January 2012", "08 February 2012"}, new String[]{"20000"}) ; //0th position will have disbursement - HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData(new String[] {"20 October 2011", "20 November 2011", "04 January 2012", "08 February 2012"}, - new String[] {"26262.38", "26262.38", "20000.0", "33242.97"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(addVariationsjsondata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + String addVariationsjsondata = VariableInstallmentsDecliningBalanceHelper.createModifiyDateVariations( + new String[] { "20 December 2011", "20 January 2012" }, new String[] { "04 January 2012", "08 February 2012" }, + new String[] { "20000" }); // 0th position will have + // disbursement + HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsDecliningBalanceHelper.constructVerifyData( + new String[] { "20 October 2011", "20 November 2011", "04 January 2012", "08 February 2012" }, + new String[] { "26262.38", "26262.38", "20000.0", "33242.97" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(addVariationsjsondata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } // Interest Type is FLAT @Test public void testDeleteInstallmentsWithInterestTypeFlat() { - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsFlatHelper.createLoanProductWithVaribleConfig(false, NONE); + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsFlatHelper.createLoanProductWithVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); @@ -289,31 +333,35 @@ public class VariableInstallmentsIntegrationTest { final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; - ArrayList toDelete = new ArrayList<>() ; - toDelete.add(periods.get(1)) ; - String toDeletedata = VariableInstallmentsFlatHelper.createDeleteVariations(toDelete) ; - HashMap modifiedReschdule = transactionHelper.validateVariations(toDeletedata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsFlatHelper.constructVerifyData(new String[] {"20 November 2011", "20 December 2011", "20 January 2012"}, - new String[] {"36000.0", "36000.0", "36000.0"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(toDeletedata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); + ArrayList toDelete = new ArrayList<>(); + toDelete.add(periods.get(1)); + String toDeletedata = VariableInstallmentsFlatHelper.createDeleteVariations(toDelete); + HashMap modifiedReschdule = transactionHelper.validateVariations(toDeletedata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsFlatHelper.constructVerifyData( + new String[] { "20 November 2011", "20 December 2011", "20 January 2012" }, + new String[] { "36000.0", "36000.0", "36000.0" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(toDeletedata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } @Test public void testAddInstallmentsWithInterestTypeFlat() { - //31 October 2011 - 5000 - //Result: 20 October 2011 - 21600.0, 31 October 2011 - 6600.0, 20 November 2011 26600.0, 20 December 2011 26600.0, 20 January 2012 26600.0 - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsFlatHelper.createLoanProductWithVaribleConfig(false, NONE); + // 31 October 2011 - 5000 + // Result: 20 October 2011 - 21600.0, 31 October 2011 - 6600.0, 20 + // November 2011 26600.0, 20 December 2011 26600.0, 20 January 2012 + // 26600.0 + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsFlatHelper.createLoanProductWithVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); @@ -321,30 +369,33 @@ public class VariableInstallmentsIntegrationTest { final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - //Integer loanID = 67 ; - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; - String addVariationsjsondata = VariableInstallmentsFlatHelper.createAddVariations() ; - HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsFlatHelper.constructVerifyData(new String[] {"20 October 2011", "31 October 2011", "20 November 2011", "20 December 2011", "20 January 2012"}, - new String[] {"21600.0", "6600.0", "26600.0", "26600.0", "26600.0"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(addVariationsjsondata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + // Integer loanID = 67 ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); + String addVariationsjsondata = VariableInstallmentsFlatHelper.createAddVariations(); + HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsFlatHelper.constructVerifyData( + new String[] { "20 October 2011", "31 October 2011", "20 November 2011", "20 December 2011", "20 January 2012" }, + new String[] { "21600.0", "6600.0", "26600.0", "26600.0", "26600.0" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(addVariationsjsondata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } @Test public void testModifyInstallmentsWithInterestTypeisFlat() { - //20 October 2011 - 30000 modify - //Result 20 October 2011 - 32000.0, 20 November 2011 - 25333.33, 20 December 2011 - 25333.33, 20 January 2012 - 25333.34 - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsFlatHelper.createLoanProductWithVaribleConfig(false, NONE); + // 20 October 2011 - 30000 modify + // Result 20 October 2011 - 32000.0, 20 November 2011 - 25333.33, 20 + // December 2011 - 25333.33, 20 January 2012 - 25333.34 + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsFlatHelper.createLoanProductWithVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); @@ -352,30 +403,38 @@ public class VariableInstallmentsIntegrationTest { final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - //Integer loanID = 67 ; - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; - String addVariationsjsondata = VariableInstallmentsFlatHelper.createModifiyVariations((Map)periods.get(1)) ; //0th position will have disbursement - HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsFlatHelper.constructVerifyData(new String[] {"20 October 2011", "20 November 2011", "20 December 2011", "20 January 2012"}, - new String[] {"32000.0", "25333.33", "25333.33", "25333.34"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(addVariationsjsondata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + // Integer loanID = 67 ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); + String addVariationsjsondata = VariableInstallmentsFlatHelper.createModifiyVariations((Map) periods.get(1)); // 0th + // position + // will + // have + // disbursement + HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsFlatHelper.constructVerifyData( + new String[] { "20 October 2011", "20 November 2011", "20 December 2011", "20 January 2012" }, + new String[] { "32000.0", "25333.33", "25333.33", "25333.34" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(addVariationsjsondata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } @Test public void testAllVariationsWithInterestTypeFlat() { - // Request: Delete 20 December 2011 25000.0, Modify 20 November 2011 from 25,000 to 30000, Add 25 December 2011 5000 - // Result: 20 October 2011 - 27000.0, 20 November 2011 - 32000.0, 25 December 2011 - 7000.0, 20 January 2012 - 42000.0 - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsFlatHelper.createLoanProductWithVaribleConfig(false, NONE); + // Request: Delete 20 December 2011 25000.0, Modify 20 November 2011 + // from 25,000 to 30000, Add 25 December 2011 5000 + // Result: 20 October 2011 - 27000.0, 20 November 2011 - 32000.0, 25 + // December 2011 - 7000.0, 20 January 2012 - 42000.0 + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsFlatHelper.createLoanProductWithVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); @@ -383,32 +442,39 @@ public class VariableInstallmentsIntegrationTest { final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - //Integer loanID = 67 ; - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; + // Integer loanID = 67 ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); - String addVariationsjsondata = VariableInstallmentsFlatHelper.createAllVariations() ; //0th position will have disbursement - HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsFlatHelper.constructVerifyData(new String[] {"20 October 2011", "20 November 2011", "25 December 2011", "20 January 2012"}, - new String[] {"27000.0", "32000.0", "7000.0", "42000.0"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(addVariationsjsondata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + String addVariationsjsondata = VariableInstallmentsFlatHelper.createAllVariations(); // 0th + // position + // will + // have + // disbursement + HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsFlatHelper.constructVerifyData( + new String[] { "20 October 2011", "20 November 2011", "25 December 2011", "20 January 2012" }, + new String[] { "27000.0", "32000.0", "7000.0", "42000.0" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(addVariationsjsondata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } @Test public void testModifyDatesWithInterestTypeFlat() { - //Modify 20 December 2011:25000 -> 04 January 2012:20000 - //Modify 20 January 2012 -> 08 February 2012 - //Result 20 October 2011 -27306.45, 20 November 2011 - 27306.45, 04 January 2012 -22306.45, 08 February 2012 - 32306.46 - VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec) ; - final String loanProductJson = VariableInstallmentsFlatHelper.createLoanProductWithVaribleConfig(false, NONE); + // Modify 20 December 2011:25000 -> 04 January 2012:20000 + // Modify 20 January 2012 -> 08 February 2012 + // Result 20 October 2011 -27306.45, 20 November 2011 - 27306.45, 04 + // January 2012 -22306.45, 08 February 2012 - 32306.46 + VariableIntallmentsTransactionHelper transactionHelper = new VariableIntallmentsTransactionHelper(requestSpec, responseSpec); + final String loanProductJson = VariableInstallmentsFlatHelper.createLoanProductWithVaribleConfig(false, NONE); Integer loanProductID = this.loanTransactionHelper.getLoanProductId(loanProductJson); final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); @@ -416,24 +482,29 @@ public class VariableInstallmentsIntegrationTest { final Integer loanID = this.loanTransactionHelper.getLoanId(json); HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - //Integer loanID = 67 ; + // Integer loanID = 67 ; - Map list = transactionHelper.retrieveSchedule(loanID) ; - Map repaymentSchedule = (Map)list.get("repaymentSchedule") ; - ArrayList periods = (ArrayList)repaymentSchedule.get("periods") ; + Map list = transactionHelper.retrieveSchedule(loanID); + Map repaymentSchedule = (Map) list.get("repaymentSchedule"); + ArrayList periods = (ArrayList) repaymentSchedule.get("periods"); // // - String addVariationsjsondata = VariableInstallmentsFlatHelper.createModifiyDateVariations(new String[]{"20 December 2011", "20 January 2012"}, new String[]{"04 January 2012", "08 February 2012"}, new String[]{"20000"}) ; //0th position will have disbursement - HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID) ; - ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods") ; - ArrayList toVerifyData = VariableInstallmentsFlatHelper.constructVerifyData(new String[] {"20 October 2011", "20 November 2011", "04 January 2012", "08 February 2012"}, - new String[] {"27306.45", "27306.45", "22306.45", "32306.46"}) ; - assertAfterSubmit(newperiods, toVerifyData) ; - transactionHelper.submitVariations(addVariationsjsondata, loanID) ; - list = transactionHelper.retrieveSchedule(loanID) ; - repaymentSchedule = (Map)list.get("repaymentSchedule") ; - periods = (ArrayList)repaymentSchedule.get("periods") ; - periods.remove(0) ; //Repayments Schedule includes disbursement also. So remove this. - assertAfterSubmit(periods, toVerifyData) ; + String addVariationsjsondata = VariableInstallmentsFlatHelper.createModifiyDateVariations( + new String[] { "20 December 2011", "20 January 2012" }, new String[] { "04 January 2012", "08 February 2012" }, + new String[] { "20000" }); // 0th position will have + // disbursement + HashMap modifiedReschdule = transactionHelper.validateVariations(addVariationsjsondata, loanID); + ArrayList newperiods = (ArrayList) modifiedReschdule.get("periods"); + ArrayList toVerifyData = VariableInstallmentsFlatHelper.constructVerifyData( + new String[] { "20 October 2011", "20 November 2011", "04 January 2012", "08 February 2012" }, + new String[] { "27306.45", "27306.45", "22306.45", "32306.46" }); + assertAfterSubmit(newperiods, toVerifyData); + transactionHelper.submitVariations(addVariationsjsondata, loanID); + list = transactionHelper.retrieveSchedule(loanID); + repaymentSchedule = (Map) list.get("repaymentSchedule"); + periods = (ArrayList) repaymentSchedule.get("periods"); + periods.remove(0); // Repayments Schedule includes disbursement also. So + // remove this. + assertAfterSubmit(periods, toVerifyData); } } diff --git a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableIntallmentsTransactionHelper.java b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableIntallmentsTransactionHelper.java index 21f6690fe..121b42b40 100644 --- a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableIntallmentsTransactionHelper.java +++ b/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/variableinstallments/VariableIntallmentsTransactionHelper.java @@ -24,34 +24,31 @@ import java.util.HashMap; import java.util.Map; import org.apache.fineract.integrationtests.common.Utils; - @SuppressWarnings("rawtypes") public class VariableIntallmentsTransactionHelper { - private final String URL = "https://localhost:8443/fineract-provider/api/v1/loans/" ; + private final String URL = "https://localhost:8443/fineract-provider/api/v1/loans/"; private final RequestSpecification requestSpec; private final ResponseSpecification responseSpec; - public VariableIntallmentsTransactionHelper(final RequestSpecification requestSpec, - final ResponseSpecification responseSpec) { - this.requestSpec = requestSpec ; - this.responseSpec = responseSpec ; + public VariableIntallmentsTransactionHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + this.requestSpec = requestSpec; + this.responseSpec = responseSpec; } - public Map retrieveSchedule(Integer loanId) { - String url = URL+loanId+"?associations=repaymentSchedule&exclude=guarantors&"+Utils.TENANT_IDENTIFIER ; + String url = URL + loanId + "?associations=repaymentSchedule&exclude=guarantors&" + Utils.TENANT_IDENTIFIER; return Utils.performServerGet(requestSpec, responseSpec, url, ""); } public HashMap validateVariations(final String exceptions, Integer loanId) { - String url = URL+loanId+"/schedule?command=calculateLoanSchedule&"+Utils.TENANT_IDENTIFIER ; + String url = URL + loanId + "/schedule?command=calculateLoanSchedule&" + Utils.TENANT_IDENTIFIER; return Utils.performServerPost(this.requestSpec, this.responseSpec, url, exceptions, ""); } public HashMap submitVariations(final String exceptions, Integer loanId) { - String url = URL+loanId+"/schedule?command=addVariations&"+Utils.TENANT_IDENTIFIER ; + String url = URL + loanId + "/schedule?command=addVariations&" + Utils.TENANT_IDENTIFIER; return Utils.performServerPost(this.requestSpec, this.responseSpec, url, exceptions, ""); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/ServerApplication.java b/fineract-provider/src/main/java/org/apache/fineract/ServerApplication.java index a2991a76e..34d3175de 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/ServerApplication.java +++ b/fineract-provider/src/main/java/org/apache/fineract/ServerApplication.java @@ -29,11 +29,12 @@ import org.springframework.context.annotation.Import; import org.springframework.context.annotation.ImportResource; /** - * Fineract main() application which launches Fineract in an embedded Tomcat HTTP - * (using Spring Boot). + * Fineract main() application which launches Fineract in an embedded Tomcat + * HTTP (using Spring Boot). * * The DataSource used is a to a "normal" external database (not use MariaDB4j). - * This DataSource can be configured with parameters, see {@link DataSourceProperties}. + * This DataSource can be configured with parameters, see + * {@link DataSourceProperties}. * * You can easily launch this via Debug as Java Application in your IDE - * without needing command line Gradle stuff, no need to build and deploy a WAR, @@ -48,7 +49,7 @@ public class ServerApplication extends SpringBootServletInitializer { @Import({ EmbeddedTomcatWithSSLConfiguration.class }) @ImportResource({ "classpath*:META-INF/spring/hikariDataSource.xml" }) - private static class Configuration extends AbstractApplicationConfiguration { } + private static class Configuration extends AbstractApplicationConfiguration {} @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { @@ -61,6 +62,6 @@ public class ServerApplication extends SpringBootServletInitializer { public static void main(String[] args) throws IOException { ConfigurableApplicationContext ctx = configureApplication(new SpringApplicationBuilder(ServerApplication.class)).run(args); - //ApplicationExitUtil.waitForKeyPressToCleanlyExit(ctx); + // ApplicationExitUtil.waitForKeyPressToCleanlyExit(ctx); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/api/AccrualAccountingApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/api/AccrualAccountingApiResource.java old mode 100755 new mode 100644 index c4195ce69..073ec0826 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/api/AccrualAccountingApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/api/AccrualAccountingApiResource.java @@ -32,7 +32,6 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -// import org.apache.fineract.accounting.accrual.swagger.runaccuralPost; import org.apache.fineract.commands.domain.CommandWrapper; import org.apache.fineract.commands.service.CommandWrapperBuilder; import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService; @@ -45,10 +44,9 @@ import org.springframework.stereotype.Component; @Path("/runaccruals") @Component @Scope("singleton") -@Api(tags = {"Periodic Accrual Accounting"}) +@Api(tags = { "Periodic Accrual Accounting" }) @SwaggerDefinition(tags = { - @Tag(name = "Periodic Accrual Accounting", description = "Periodic Accrual is to accrue the loan income till the specific date or till batch job scheduled time.\n") -}) + @Tag(name = "Periodic Accrual Accounting", description = "Periodic Accrual is to accrue the loan income till the specific date or till batch job scheduled time.\n") }) public class AccrualAccountingApiResource { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @@ -66,9 +64,12 @@ public class AccrualAccountingApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Executes Periodic Accrual Accounting", httpMethod = "POST", notes = "Mandatory Fields\n" + "\n" + "tillDate\n") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", required = true, type = "body", dataTypeClass = AccrualAccountingApiResourceSwagger.PostRunaccrualsRequest.class, value = "Request Body\n" + "\n" + "Field Descriptions: \n" + "tillDate: \n" + "which specifies periodic accruals should happen till the given Date" )}) - @ApiResponses({@ApiResponse(code = 200, message = "OK")}) - public String executePeriodicAccrualAccounting( @ApiParam(hidden = true) final String jsonRequestBody) { + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", required = true, type = "body", dataTypeClass = AccrualAccountingApiResourceSwagger.PostRunaccrualsRequest.class, value = "Request Body\n" + + "\n" + "Field Descriptions: \n" + "tillDate: \n" + + "which specifies periodic accruals should happen till the given Date") }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK") }) + public String executePeriodicAccrualAccounting(@ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().excuteAccrualAccounting().withJson(jsonRequestBody).build(); @@ -77,4 +78,4 @@ public class AccrualAccountingApiResource { return this.apiJsonSerializerService.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/api/AccrualAccountingApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/api/AccrualAccountingApiResourceSwagger.java index aee84ee4e..3b1b3e41e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/api/AccrualAccountingApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/api/AccrualAccountingApiResourceSwagger.java @@ -25,12 +25,14 @@ import io.swagger.annotations.ApiModelProperty; * Created by sanyam on 24/7/17. */ final class AccrualAccountingApiResourceSwagger { + private AccrualAccountingApiResourceSwagger() { // don't allow to instantiate; use only for live API documentation } @ApiModel(value = "runaccrualsRequest") public static final class PostRunaccrualsRequest { + private PostRunaccrualsRequest() { // don't allow to instantiate; use only for live API documentation } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/handler/ExecutePeriodicAccrualCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/handler/ExecutePeriodicAccrualCommandHandler.java old mode 100755 new mode 100644 index b1724bdd0..0b02be9fa --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/handler/ExecutePeriodicAccrualCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/handler/ExecutePeriodicAccrualCommandHandler.java @@ -43,4 +43,4 @@ public class ExecutePeriodicAccrualCommandHandler implements NewCommandSourceHan public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.executeLoansPeriodicAccrual(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/serialization/AccrualAccountingDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/serialization/AccrualAccountingDataValidator.java old mode 100755 new mode 100644 index d541ad24a..5b5e8ff29 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/serialization/AccrualAccountingDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/serialization/AccrualAccountingDataValidator.java @@ -53,8 +53,7 @@ public final class AccrualAccountingDataValidator { private final FromJsonHelper fromApiJsonHelper; private static final Set LOAN_PERIODIC_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(accrueTillParamName, AccrualAccountingConstants.localeParamName, - AccrualAccountingConstants.dateFormatParamName)); + Arrays.asList(accrueTillParamName, AccrualAccountingConstants.localeParamName, AccrualAccountingConstants.dateFormatParamName)); @Autowired public AccrualAccountingDataValidator(final FromJsonHelper fromApiJsonfromApiJsonHelper) { @@ -81,4 +80,4 @@ public final class AccrualAccountingDataValidator { public void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/service/AccrualAccountingWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/service/AccrualAccountingWritePlatformServiceImpl.java old mode 100755 new mode 100644 index a7458408a..4584410db --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/service/AccrualAccountingWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/accrual/service/AccrualAccountingWritePlatformServiceImpl.java @@ -59,7 +59,8 @@ public class AccrualAccountingWritePlatformServiceImpl implements AccrualAccount final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(PERIODIC_ACCRUAL_ACCOUNTING_RESOURCE_NAME); - baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(PERIODIC_ACCRUAL_ACCOUNTING_EXECUTION_ERROR_CODE, e.getMessage()); + baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(PERIODIC_ACCRUAL_ACCOUNTING_EXECUTION_ERROR_CODE, + e.getMessage()); throw new PlatformApiDataValidationException(dataValidationErrors); } return CommandProcessingResult.empty(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosureJsonInputParams.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosureJsonInputParams.java old mode 100755 new mode 100644 index da8733322..2f12c63c6 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosureJsonInputParams.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosureJsonInputParams.java @@ -25,6 +25,7 @@ import java.util.Set; * Enum of all parameters passed in while creating/updating a loan product ***/ public enum GLClosureJsonInputParams { + ID("id"), OFFICE_ID("officeId"), CLOSING_DATE("closingDate"), COMMENTS("comments"), LOCALE("locale"), DATE_FORMAT("dateFormat"); private final String value; @@ -52,4 +53,4 @@ public enum GLClosureJsonInputParams { public String getValue() { return this.value; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosuresApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosuresApiResource.java old mode 100755 new mode 100644 index 78fd491e1..33ca125e8 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosuresApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosuresApiResource.java @@ -61,15 +61,17 @@ import org.springframework.stereotype.Component; @Path("/glclosures") @Component @Scope("singleton") -@Api(tags = {"Accounting Closure"}) +@Api(tags = { "Accounting Closure" }) @SwaggerDefinition(tags = { - @Tag(name = "Accounting Closure", description = "An accounting closure indicates that no more journal entries may be logged (or reversed) in the system, either manually or via the portfolio with an entry date prior to the defined closure date\n" + "\n" + "Field Descriptions\n" + "closingDate\n" + "The date for which the accounting closure is defined\n" + "officeId\n" + "The identifer of the branch for which accounting has been closed\n" + "comments\n" + "Description associated with an Accounting closure") -}) + @Tag(name = "Accounting Closure", description = "An accounting closure indicates that no more journal entries may be logged (or reversed) in the system, either manually or via the portfolio with an entry date prior to the defined closure date\n" + + "\n" + "Field Descriptions\n" + "closingDate\n" + "The date for which the accounting closure is defined\n" + "officeId\n" + + "The identifer of the branch for which accounting has been closed\n" + "comments\n" + + "Description associated with an Accounting closure") }) public class GLClosuresApiResource { - private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "officeId", "officeName", - "closingDate", "deleted", "createdDate", "lastUpdatedDate", "createdByUserId", "createdByUsername", "lastUpdatedByUserId", - "lastUpdatedByUsername")); + private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "officeId", "officeName", "closingDate", "deleted", "createdDate", "lastUpdatedDate", "createdByUserId", + "createdByUsername", "lastUpdatedByUserId", "lastUpdatedByUsername")); private final String resourceNameForPermission = "GLCLOSURE"; @@ -97,8 +99,10 @@ public class GLClosuresApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "List Accounting closures", notes = "Example Requests:\n" + "\n" + "glclosures") - @ApiResponses({@ApiResponse(code = 200, response = GLClosuresApiResourceSwagger.GetGlClosureResponse.class, message = "", responseContainer = "list")}) - public String retrieveAllClosures(@Context final UriInfo uriInfo, @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId) { + @ApiResponses({ + @ApiResponse(code = 200, response = GLClosuresApiResourceSwagger.GetGlClosureResponse.class, message = "", responseContainer = "list") }) + public String retrieveAllClosures(@Context final UriInfo uriInfo, + @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); final List glClosureDatas = this.glClosureReadPlatformService.retrieveAllGLClosures(officeId); @@ -111,9 +115,11 @@ public class GLClosuresApiResource { @Path("{glClosureId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve an Accounting Closure", notes = "Example Requests:\n" + "\n" + "glclosures/1\n" + "\n" + "\n" + "/glclosures/1?fields=officeName,closingDate") - @ApiResponses({@ApiResponse(code = 200, message = "", response = GLClosuresApiResourceSwagger.GetGlClosureResponse.class)}) - public String retreiveClosure(@PathParam("glClosureId") @ApiParam(value = "glClosureId") final Long glClosureId, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve an Accounting Closure", notes = "Example Requests:\n" + "\n" + "glclosures/1\n" + "\n" + "\n" + + "/glclosures/1?fields=officeName,closingDate") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = GLClosuresApiResourceSwagger.GetGlClosureResponse.class) }) + public String retreiveClosure(@PathParam("glClosureId") @ApiParam(value = "glClosureId") final Long glClosureId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); @@ -132,8 +138,9 @@ public class GLClosuresApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create an Accounting Closure", notes = "Mandatory Fields\n" + "officeId,closingDate") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", required = true, type = "body", dataTypeClass = GLClosuresApiResourceSwagger.PostGlClosuresRequest.class, value = "Request Body")}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = GLClosuresApiResourceSwagger.PostGlClosuresResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", required = true, type = "body", dataTypeClass = GLClosuresApiResourceSwagger.PostGlClosuresRequest.class, value = "Request Body") }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = GLClosuresApiResourceSwagger.PostGlClosuresResponse.class) }) public String createGLClosure(@ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createGLClosure().withJson(jsonRequestBody).build(); @@ -148,9 +155,11 @@ public class GLClosuresApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update an Accounting closure", notes = "Once an accounting closure is created, only the comments associated with it may be edited") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", value = "Request body", dataType = "body", dataTypeClass = GLClosuresApiResourceSwagger.PutGlClosuresRequest.class, required = true)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = GLClosuresApiResourceSwagger.PutGlClosuresResponse.class)}) - public String updateGLClosure(@PathParam("glClosureId") @ApiParam(value = "glClosureId") final Long glClosureId, @ApiParam(hidden = true) final String jsonRequestBody) { + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", value = "Request body", dataType = "body", dataTypeClass = GLClosuresApiResourceSwagger.PutGlClosuresRequest.class, required = true) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = GLClosuresApiResourceSwagger.PutGlClosuresResponse.class) }) + public String updateGLClosure(@PathParam("glClosureId") @ApiParam(value = "glClosureId") final Long glClosureId, + @ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateGLClosure(glClosureId).withJson(jsonRequestBody).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -163,7 +172,7 @@ public class GLClosuresApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete an accounting closure", notes = "Note: Only the latest accounting closure associated with a branch may be deleted.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = GLClosuresApiResourceSwagger.DeleteGlClosuresResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = GLClosuresApiResourceSwagger.DeleteGlClosuresResponse.class) }) public String deleteGLClosure(@PathParam("glClosureId") @ApiParam(value = "glclosureId") final Long glClosureId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteGLClosure(glClosureId).build(); @@ -172,4 +181,4 @@ public class GLClosuresApiResource { return this.apiJsonSerializerService.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosuresApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosuresApiResourceSwagger.java old mode 100755 new mode 100644 index 4ec02bdc5..703dd3328 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosuresApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/api/GLClosuresApiResourceSwagger.java @@ -23,6 +23,7 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.LocalDate; final class GLClosuresApiResourceSwagger { + private GLClosuresApiResourceSwagger() { // don't allow to instantiate; use only for live API documentation } @@ -35,6 +36,7 @@ final class GLClosuresApiResourceSwagger { @ApiModel(value = "GetGLClosureResponse") public static final class GetGlClosureResponse { + private GetGlClosureResponse() { // dont allow to initiatiate } @@ -68,9 +70,11 @@ final class GLClosuresApiResourceSwagger { @ApiModel(value = "PostGLCLosuresRequest") public static final class PostGlClosuresRequest { + private PostGlClosuresRequest() { // don't allow to instantiate; use only for live API documentation } + @ApiModelProperty(example = "1") public Long officeId; @ApiModelProperty(example = "06 December 2012") @@ -85,9 +89,11 @@ final class GLClosuresApiResourceSwagger { @ApiModel(value = "PostGlClosuresResponse") public static final class PostGlClosuresResponse { + private PostGlClosuresResponse() { // don't allow to instantiate; use only for live API documentation } + @ApiModelProperty(example = "1") public Long officeId; @ApiModelProperty(example = "9") @@ -96,18 +102,22 @@ final class GLClosuresApiResourceSwagger { @ApiModel(value = "PutGlClosuresRequest") public static final class PutGlClosuresRequest { + private PutGlClosuresRequest() { // don't allow to instantiate; use only for live API documentation } + @ApiModelProperty(example = "All transactions verified by Johnny Cash") public String comments; } @ApiModel(value = "PutGlClosuresResponse") - public static final class PutGlClosuresResponse{ + public static final class PutGlClosuresResponse { + private PutGlClosuresResponse() { // don't allow to instantiate; use only for live API documentation } + @ApiModelProperty(example = "1") public Long officeId; @ApiModelProperty(example = "9") @@ -117,8 +127,9 @@ final class GLClosuresApiResourceSwagger { } @ApiModel(value = "DeleteGlClosuresResponse") - public static final class DeleteGlClosuresResponse{ - private DeleteGlClosuresResponse(){ + public static final class DeleteGlClosuresResponse { + + private DeleteGlClosuresResponse() { } @@ -127,4 +138,4 @@ final class GLClosuresApiResourceSwagger { @ApiModelProperty(example = "9") public Long resourceId; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/command/GLClosureCommand.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/command/GLClosureCommand.java old mode 100755 new mode 100644 index 6c6d26b36..e59d75dab --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/command/GLClosureCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/command/GLClosureCommand.java @@ -56,8 +56,10 @@ public class GLClosureCommand { baseDataValidator.reset().parameter(GLClosureJsonInputParams.COMMENTS.getValue()).value(this.comments).ignoreIfNull() .notExceedingLengthOf(500); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForUpdate() { @@ -69,8 +71,10 @@ public class GLClosureCommand { .notExceedingLengthOf(500); baseDataValidator.reset().anyOfNotNull(this.comments); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/data/GLClosureData.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/data/GLClosureData.java old mode 100755 new mode 100644 index c5e3cb4ed..889d0c08d --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/data/GLClosureData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/data/GLClosureData.java @@ -84,4 +84,4 @@ public class GLClosureData { this.allowedOffices = allowedOffices; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/domain/GLClosure.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/domain/GLClosure.java old mode 100755 new mode 100644 index e1b7a03b9..f1626ef40 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/domain/GLClosure.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/domain/GLClosure.java @@ -36,7 +36,8 @@ import org.apache.fineract.infrastructure.core.domain.AbstractAuditableCustom; import org.apache.fineract.organisation.office.domain.Office; @Entity -@Table(name = "acc_gl_closure", uniqueConstraints = { @UniqueConstraint(columnNames = { "office_id", "closing_date" }, name = "office_id_closing_date") }) +@Table(name = "acc_gl_closure", uniqueConstraints = { + @UniqueConstraint(columnNames = { "office_id", "closing_date" }, name = "office_id_closing_date") }) public class GLClosure extends AbstractAuditableCustom { @ManyToOne @@ -99,4 +100,4 @@ public class GLClosure extends AbstractAuditableCustom { return this.office; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureDuplicateException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureDuplicateException.java old mode 100755 new mode 100644 index fc8712197..52862b03f --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureDuplicateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureDuplicateException.java @@ -28,8 +28,9 @@ import org.joda.time.LocalDate; public class GLClosureDuplicateException extends AbstractPlatformDomainRuleException { public GLClosureDuplicateException(final Long officeId, final LocalDate closureDate) { - super("error.msg.glclosure.glcode.duplicate", "An accounting closure for branch with Id " + officeId - + " already exists for the date " + closureDate, officeId, closureDate); + super("error.msg.glclosure.glcode.duplicate", + "An accounting closure for branch with Id " + officeId + " already exists for the date " + closureDate, officeId, + closureDate); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureInvalidDeleteException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureInvalidDeleteException.java old mode 100755 new mode 100644 index ee27086b4..53671463d --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureInvalidDeleteException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureInvalidDeleteException.java @@ -30,4 +30,4 @@ public class GLClosureInvalidDeleteException extends AbstractPlatformDomainRuleE super("error.msg.glclosure.invalid.delete", "The latest closure for office with Id " + officeId + " and name " + officeName + " is on " + latestclosureDate.toString() + ", please delete this closure first", latestclosureDate); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureInvalidException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureInvalidException.java old mode 100755 new mode 100644 index fd9cb2603..36815731a --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureInvalidException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureInvalidException.java @@ -28,12 +28,15 @@ public class GLClosureInvalidException extends AbstractPlatformDomainRuleExcepti /*** enum of reasons for invalid Accounting Closure **/ public static enum GlClosureInvalidReason { + FUTURE_DATE, ACCOUNTING_CLOSED; public String errorMessage() { if (name().toString().equalsIgnoreCase("FUTURE_DATE")) { return "Accounting closures cannot be made for a future date"; - } else if (name().toString().equalsIgnoreCase("ACCOUNTING_CLOSED")) { return "Accounting Closure for this branch has already been defined for a greater date"; } + } else if (name().toString().equalsIgnoreCase("ACCOUNTING_CLOSED")) { + return "Accounting Closure for this branch has already been defined for a greater date"; + } return name().toString(); } @@ -48,4 +51,4 @@ public class GLClosureInvalidException extends AbstractPlatformDomainRuleExcepti public GLClosureInvalidException(final GlClosureInvalidReason reason, final Date date) { super(reason.errorCode(), reason.errorMessage(), date); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureNotFoundException.java old mode 100755 new mode 100644 index 66e4c7774..b627444bf --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/exception/GLClosureNotFoundException.java @@ -29,4 +29,4 @@ public class GLClosureNotFoundException extends AbstractPlatformResourceNotFound public GLClosureNotFoundException(final Long id) { super("error.msg.glclosure.id.invalid", "Accounting Closure with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/CreateGLClosureCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/CreateGLClosureCommandHandler.java old mode 100755 new mode 100644 index d9c049e67..d4f1422cf --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/CreateGLClosureCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/CreateGLClosureCommandHandler.java @@ -44,4 +44,4 @@ public class CreateGLClosureCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createGLClosure(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/DeleteGLClosureCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/DeleteGLClosureCommandHandler.java old mode 100755 new mode 100644 index 4070fabdb..47e1ce23b --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/DeleteGLClosureCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/DeleteGLClosureCommandHandler.java @@ -43,4 +43,4 @@ public class DeleteGLClosureCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.closureWritePlatformService.deleteGLClosure(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/UpdateGLClosureCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/UpdateGLClosureCommandHandler.java old mode 100755 new mode 100644 index fe2ff964c..3b512f085 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/UpdateGLClosureCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/handler/UpdateGLClosureCommandHandler.java @@ -43,4 +43,4 @@ public class UpdateGLClosureCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.updateGLClosure(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/serialization/GLClosureCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/serialization/GLClosureCommandFromApiJsonDeserializer.java old mode 100755 new mode 100644 index 3a9919929..367948f2f --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/serialization/GLClosureCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/serialization/GLClosureCommandFromApiJsonDeserializer.java @@ -67,4 +67,4 @@ public final class GLClosureCommandFromApiJsonDeserializer extends AbstractFromA return new GLClosureCommand(id, officeId, closingDate, comments); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/service/GLClosureWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/service/GLClosureWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index c03d795c5..98db3741e --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/service/GLClosureWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/closure/service/GLClosureWritePlatformServiceJpaRepositoryImpl.java @@ -79,8 +79,9 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure // shouldn't be before an existing accounting closure final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(officeId); if (latestGLClosure != null) { - if (latestGLClosure.getClosingDate().after(closureDate)) { throw new GLClosureInvalidException( - GlClosureInvalidReason.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate()); } + if (latestGLClosure.getClosingDate().after(closureDate)) { + throw new GLClosureInvalidException(GlClosureInvalidReason.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate()); + } } final GLClosure glClosure = GLClosure.fromJson(office, command); @@ -101,7 +102,8 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure closureCommand.validateForUpdate(); // is the glClosure valid - final GLClosure glClosure = this.glClosureRepository.findById(glClosureId).orElseThrow(() -> new GLClosureNotFoundException(glClosureId)); + final GLClosure glClosure = this.glClosureRepository.findById(glClosureId) + .orElseThrow(() -> new GLClosureNotFoundException(glClosureId)); final Map changesOnly = glClosure.update(command); @@ -119,15 +121,16 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure final GLClosure glClosure = this.glClosureRepository.findById(glClosureId) .orElseThrow(() -> new GLClosureNotFoundException(glClosureId)); - /** * check if any closures are present for this branch at a later date * than this closure date **/ final Date closureDate = glClosure.getClosingDate(); final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(glClosure.getOffice().getId()); - if (latestGLClosure.getClosingDate().after(closureDate)) { throw new GLClosureInvalidDeleteException(latestGLClosure.getOffice() - .getId(), latestGLClosure.getOffice().getName(), latestGLClosure.getClosingDate()); } + if (latestGLClosure.getClosingDate().after(closureDate)) { + throw new GLClosureInvalidDeleteException(latestGLClosure.getOffice().getId(), latestGLClosure.getOffice().getName(), + latestGLClosure.getClosingDate()); + } this.glClosureRepository.delete(glClosure); @@ -140,9 +143,10 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure */ private void handleGLClosureIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { final Throwable realCause = dve.getMostSpecificCause(); - if (realCause.getMessage().contains("office_id_closing_date")) { throw new GLClosureDuplicateException( - command.longValueOfParameterNamed(GLClosureJsonInputParams.OFFICE_ID.getValue()), new LocalDate( - command.dateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue()))); } + if (realCause.getMessage().contains("office_id_closing_date")) { + throw new GLClosureDuplicateException(command.longValueOfParameterNamed(GLClosureJsonInputParams.OFFICE_ID.getValue()), + new LocalDate(command.dateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue()))); + } LOG.error("Error occured.", dve); throw new PlatformDataIntegrityException("error.msg.glClosure.unknown.data.integrity.issue", diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingConstants.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingConstants.java old mode 100755 new mode 100644 index 9098e1519..3df460077 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingConstants.java @@ -27,10 +27,13 @@ import org.apache.fineract.accounting.glaccount.domain.GLAccountType; public class AccountingConstants { - /*** Accounting placeholders for cash based accounting for loan products ***/ + /*** + * Accounting placeholders for cash based accounting for loan products + ***/ public static enum CashAccountsForLoan { - FUND_SOURCE(1), LOAN_PORTFOLIO(2), INTEREST_ON_LOANS(3), INCOME_FROM_FEES(4), INCOME_FROM_PENALTIES(5), LOSSES_WRITTEN_OFF(6), TRANSFERS_SUSPENSE( - 10), OVERPAYMENT(11), INCOME_FROM_RECOVERY(12); + + FUND_SOURCE(1), LOAN_PORTFOLIO(2), INTEREST_ON_LOANS(3), INCOME_FROM_FEES(4), INCOME_FROM_PENALTIES(5), LOSSES_WRITTEN_OFF( + 6), TRANSFERS_SUSPENSE(10), OVERPAYMENT(11), INCOME_FROM_RECOVERY(12); private final Integer value; @@ -60,10 +63,14 @@ public class AccountingConstants { } } - /*** Accounting placeholders for accrual based accounting for loan products ***/ + /*** + * Accounting placeholders for accrual based accounting for loan products + ***/ public static enum AccrualAccountsForLoan { - FUND_SOURCE(1), LOAN_PORTFOLIO(2), INTEREST_ON_LOANS(3), INCOME_FROM_FEES(4), INCOME_FROM_PENALTIES(5), LOSSES_WRITTEN_OFF(6), INTEREST_RECEIVABLE( - 7), FEES_RECEIVABLE(8), PENALTIES_RECEIVABLE(9), TRANSFERS_SUSPENSE(10), OVERPAYMENT(11), INCOME_FROM_RECOVERY(12); + + FUND_SOURCE(1), LOAN_PORTFOLIO(2), INTEREST_ON_LOANS(3), INCOME_FROM_FEES(4), INCOME_FROM_PENALTIES(5), LOSSES_WRITTEN_OFF( + 6), INTEREST_RECEIVABLE( + 7), FEES_RECEIVABLE(8), PENALTIES_RECEIVABLE(9), TRANSFERS_SUSPENSE(10), OVERPAYMENT(11), INCOME_FROM_RECOVERY(12); private final Integer value; @@ -99,14 +106,20 @@ public class AccountingConstants { * creating/updating a loan product ***/ public static enum LoanProductAccountingParams { - FUND_SOURCE("fundSourceAccountId"), LOAN_PORTFOLIO("loanPortfolioAccountId"), INTEREST_ON_LOANS("interestOnLoanAccountId"), INCOME_FROM_FEES( - "incomeFromFeeAccountId"), INCOME_FROM_PENALTIES("incomeFromPenaltyAccountId"), LOSSES_WRITTEN_OFF("writeOffAccountId"), OVERPAYMENT( - "overpaymentLiabilityAccountId"), INTEREST_RECEIVABLE("receivableInterestAccountId"), FEES_RECEIVABLE( - "receivableFeeAccountId"), PENALTIES_RECEIVABLE("receivablePenaltyAccountId"), TRANSFERS_SUSPENSE( - "transfersInSuspenseAccountId"), PAYMENT_CHANNEL_FUND_SOURCE_MAPPING("paymentChannelToFundSourceMappings"), PAYMENT_TYPE( - "paymentTypeId"), FEE_INCOME_ACCOUNT_MAPPING("feeToIncomeAccountMappings"), PENALTY_INCOME_ACCOUNT_MAPPING( - "penaltyToIncomeAccountMappings"), CHARGE_ID("chargeId"), INCOME_ACCOUNT_ID("incomeAccountId"), INCOME_FROM_RECOVERY( - "incomeFromRecoveryAccountId"); + + FUND_SOURCE("fundSourceAccountId"), LOAN_PORTFOLIO("loanPortfolioAccountId"), INTEREST_ON_LOANS( + "interestOnLoanAccountId"), INCOME_FROM_FEES("incomeFromFeeAccountId"), INCOME_FROM_PENALTIES( + "incomeFromPenaltyAccountId"), LOSSES_WRITTEN_OFF("writeOffAccountId"), OVERPAYMENT( + "overpaymentLiabilityAccountId"), INTEREST_RECEIVABLE("receivableInterestAccountId"), FEES_RECEIVABLE( + "receivableFeeAccountId"), PENALTIES_RECEIVABLE("receivablePenaltyAccountId"), TRANSFERS_SUSPENSE( + "transfersInSuspenseAccountId"), PAYMENT_CHANNEL_FUND_SOURCE_MAPPING( + "paymentChannelToFundSourceMappings"), PAYMENT_TYPE( + "paymentTypeId"), FEE_INCOME_ACCOUNT_MAPPING( + "feeToIncomeAccountMappings"), PENALTY_INCOME_ACCOUNT_MAPPING( + "penaltyToIncomeAccountMappings"), CHARGE_ID( + "chargeId"), INCOME_ACCOUNT_ID( + "incomeAccountId"), INCOME_FROM_RECOVERY( + "incomeFromRecoveryAccountId"); private final String value; @@ -125,11 +138,15 @@ public class AccountingConstants { } public static enum LoanProductAccountingDataParams { - FUND_SOURCE("fundSourceAccount"), LOAN_PORTFOLIO("loanPortfolioAccount"), INTEREST_ON_LOANS("interestOnLoanAccount"), INCOME_FROM_FEES( - "incomeFromFeeAccount"), INCOME_FROM_PENALTIES("incomeFromPenaltyAccount"), LOSSES_WRITTEN_OFF("writeOffAccount"), OVERPAYMENT( - "overpaymentLiabilityAccount"), INTEREST_RECEIVABLE("receivableInterestAccount"), FEES_RECEIVABLE("receivableFeeAccount"), PENALTIES_RECEIVABLE( - "receivablePenaltyAccount"), TRANSFERS_SUSPENSE("transfersInSuspenseAccount"), INCOME_ACCOUNT_ID("incomeAccount"), INCOME_FROM_RECOVERY( - "incomeFromRecoveryAccount"), LIABILITY_TRANSFER_SUSPENSE("liabilityTransferInSuspenseAccount"); + + FUND_SOURCE("fundSourceAccount"), LOAN_PORTFOLIO("loanPortfolioAccount"), INTEREST_ON_LOANS( + "interestOnLoanAccount"), INCOME_FROM_FEES("incomeFromFeeAccount"), INCOME_FROM_PENALTIES( + "incomeFromPenaltyAccount"), LOSSES_WRITTEN_OFF("writeOffAccount"), OVERPAYMENT( + "overpaymentLiabilityAccount"), INTEREST_RECEIVABLE("receivableInterestAccount"), FEES_RECEIVABLE( + "receivableFeeAccount"), PENALTIES_RECEIVABLE("receivablePenaltyAccount"), TRANSFERS_SUSPENSE( + "transfersInSuspenseAccount"), INCOME_ACCOUNT_ID("incomeAccount"), INCOME_FROM_RECOVERY( + "incomeFromRecoveryAccount"), LIABILITY_TRANSFER_SUSPENSE( + "liabilityTransferInSuspenseAccount"); private final String value; @@ -147,8 +164,11 @@ public class AccountingConstants { } } - /*** Accounting placeholders for cash based accounting for savings products ***/ + /*** + * Accounting placeholders for cash based accounting for savings products + ***/ public static enum CashAccountsForSavings { + SAVINGS_REFERENCE(1), SAVINGS_CONTROL(2), INTEREST_ON_SAVINGS(3), INCOME_FROM_FEES(4), INCOME_FROM_PENALTIES(5), TRANSFERS_SUSPENSE( 10), OVERDRAFT_PORTFOLIO_CONTROL(11), INCOME_FROM_INTEREST(12), LOSSES_WRITTEN_OFF(13), ESCHEAT_LIABILITY(14); @@ -185,13 +205,20 @@ public class AccountingConstants { * creating/updating a savings product ***/ public static enum SavingProductAccountingParams { + SAVINGS_REFERENCE("savingsReferenceAccountId"), SAVINGS_CONTROL("savingsControlAccountId"), INCOME_FROM_FEES( "incomeFromFeeAccountId"), INCOME_FROM_PENALTIES("incomeFromPenaltyAccountId"), INTEREST_ON_SAVINGS( - "interestOnSavingsAccountId"), PAYMENT_CHANNEL_FUND_SOURCE_MAPPING("paymentChannelToFundSourceMappings"), PAYMENT_TYPE( - "paymentTypeId"), FUND_SOURCE("fundSourceAccountId"), TRANSFERS_SUSPENSE("transfersInSuspenseAccountId"), FEE_INCOME_ACCOUNT_MAPPING( - "feeToIncomeAccountMappings"), PENALTY_INCOME_ACCOUNT_MAPPING("penaltyToIncomeAccountMappings"), CHARGE_ID("chargeId"), INCOME_ACCOUNT_ID( - "incomeAccountId"), OVERDRAFT_PORTFOLIO_CONTROL("overdraftPortfolioControlId"), INCOME_FROM_INTEREST("incomeFromInterestId"), LOSSES_WRITTEN_OFF( - "writeOffAccountId"), ESCHEAT_LIABILITY("escheatLiabilityId"); + "interestOnSavingsAccountId"), PAYMENT_CHANNEL_FUND_SOURCE_MAPPING( + "paymentChannelToFundSourceMappings"), PAYMENT_TYPE("paymentTypeId"), FUND_SOURCE( + "fundSourceAccountId"), TRANSFERS_SUSPENSE( + "transfersInSuspenseAccountId"), FEE_INCOME_ACCOUNT_MAPPING( + "feeToIncomeAccountMappings"), PENALTY_INCOME_ACCOUNT_MAPPING( + "penaltyToIncomeAccountMappings"), CHARGE_ID("chargeId"), INCOME_ACCOUNT_ID( + "incomeAccountId"), OVERDRAFT_PORTFOLIO_CONTROL( + "overdraftPortfolioControlId"), INCOME_FROM_INTEREST( + "incomeFromInterestId"), LOSSES_WRITTEN_OFF( + "writeOffAccountId"), ESCHEAT_LIABILITY( + "escheatLiabilityId"); private final String value; @@ -210,12 +237,15 @@ public class AccountingConstants { } public static enum SavingProductAccountingDataParams { - SAVINGS_REFERENCE("savingsReferenceAccount"), SAVINGS_CONTROL("savingsControlAccount"), INCOME_FROM_FEES("incomeFromFeeAccount"), INCOME_FROM_PENALTIES( - "incomeFromPenaltyAccount"), INTEREST_ON_SAVINGS("interestOnSavingsAccount"), PAYMENT_TYPE("paymentType"), FUND_SOURCE( - "fundSourceAccount"), TRANSFERS_SUSPENSE("transfersInSuspenseAccount"), PENALTY_INCOME_ACCOUNT_MAPPING( - "penaltyToIncomeAccountMappings"), CHARGE_ID("charge"), INCOME_ACCOUNT_ID("incomeAccount"), OVERDRAFT_PORTFOLIO_CONTROL( - "overdraftPortfolioControl"), INCOME_FROM_INTEREST("incomeFromInterest"), LOSSES_WRITTEN_OFF("writeOffAccount"), - ESCHEAT_LIABILITY("escheatLiabilityAccount"); + + SAVINGS_REFERENCE("savingsReferenceAccount"), SAVINGS_CONTROL("savingsControlAccount"), INCOME_FROM_FEES( + "incomeFromFeeAccount"), INCOME_FROM_PENALTIES("incomeFromPenaltyAccount"), INTEREST_ON_SAVINGS( + "interestOnSavingsAccount"), PAYMENT_TYPE("paymentType"), FUND_SOURCE("fundSourceAccount"), TRANSFERS_SUSPENSE( + "transfersInSuspenseAccount"), PENALTY_INCOME_ACCOUNT_MAPPING("penaltyToIncomeAccountMappings"), CHARGE_ID( + "charge"), INCOME_ACCOUNT_ID("incomeAccount"), OVERDRAFT_PORTFOLIO_CONTROL( + "overdraftPortfolioControl"), INCOME_FROM_INTEREST( + "incomeFromInterest"), LOSSES_WRITTEN_OFF( + "writeOffAccount"), ESCHEAT_LIABILITY("escheatLiabilityAccount"); private final String value; @@ -234,10 +264,12 @@ public class AccountingConstants { } public static enum FinancialActivity { - ASSET_TRANSFER(100, "assetTransfer", GLAccountType.ASSET), LIABILITY_TRANSFER(200, "liabilityTransfer", GLAccountType.LIABILITY), CASH_AT_MAINVAULT( - 101, "cashAtMainVault", GLAccountType.ASSET), CASH_AT_TELLER(102, "cashAtTeller", GLAccountType.ASSET), OPENING_BALANCES_TRANSFER_CONTRA( - 300, "openingBalancesTransferContra", GLAccountType.EQUITY), ASSET_FUND_SOURCE(103, "fundSource", GLAccountType.ASSET), PAYABLE_DIVIDENDS( - 201, "payableDividends", GLAccountType.LIABILITY); + + ASSET_TRANSFER(100, "assetTransfer", GLAccountType.ASSET), LIABILITY_TRANSFER(200, "liabilityTransfer", + GLAccountType.LIABILITY), CASH_AT_MAINVAULT(101, "cashAtMainVault", GLAccountType.ASSET), CASH_AT_TELLER(102, + "cashAtTeller", GLAccountType.ASSET), OPENING_BALANCES_TRANSFER_CONTRA(300, "openingBalancesTransferContra", + GLAccountType.EQUITY), ASSET_FUND_SOURCE(103, "fundSource", + GLAccountType.ASSET), PAYABLE_DIVIDENDS(201, "payableDividends", GLAccountType.LIABILITY); private final Integer value; private final String code; @@ -245,7 +277,7 @@ public class AccountingConstants { private static List financialActivities; static { - financialActivities = new ArrayList<>(); + financialActivities = new ArrayList<>(); for (final FinancialActivity type : FinancialActivity.values()) { FinancialActivityData financialActivityData = convertToFinancialActivityData(type); financialActivities.add(financialActivityData); @@ -306,8 +338,11 @@ public class AccountingConstants { } } - /*** Accounting placeholders for cash based accounting for Share products ***/ + /*** + * Accounting placeholders for cash based accounting for Share products + ***/ public static enum CashAccountsForShares { + SHARES_REFERENCE(1), SHARES_SUSPENSE(2), INCOME_FROM_FEES(3), SHARES_EQUITY(4); private final Integer value; @@ -343,6 +378,7 @@ public class AccountingConstants { * creating/updating a savings product ***/ public static enum SharesProductAccountingParams { + SHARES_REFERENCE("shareReferenceId"), SHARES_SUSPENSE("shareSuspenseId"), INCOME_FROM_FEES("incomeFromFeeAccountId"), SHARES_EQUITY( "shareEquityId"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingDropdownReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingDropdownReadPlatformService.java old mode 100755 new mode 100644 index d7301a821..988beb05e --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingDropdownReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingDropdownReadPlatformService.java @@ -43,4 +43,4 @@ public interface AccountingDropdownReadPlatformService { public Map> retrieveAccountMappingOptionsForShareProducts(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingDropdownReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingDropdownReadPlatformServiceImpl.java old mode 100755 new mode 100644 index fde72cdc5..d73a82408 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingDropdownReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingDropdownReadPlatformServiceImpl.java @@ -157,4 +157,4 @@ public class AccountingDropdownReadPlatformServiceImpl implements AccountingDrop includeEquityAccounts); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingRuleType.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingRuleType.java old mode 100755 new mode 100644 index a77f7ffff..640c6e79b --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingRuleType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/common/AccountingRuleType.java @@ -60,4 +60,4 @@ public enum AccountingRuleType { public String getCode() { return this.code; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsApiResource.java index b25fa7a9d..4fd498cbc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsApiResource.java @@ -56,10 +56,11 @@ import org.springframework.stereotype.Component; @Path("/financialactivityaccounts") @Component @Scope("singleton") -@Api(tags = {"Mapping Financial Activities to Accounts"}) +@Api(tags = { "Mapping Financial Activities to Accounts" }) @SwaggerDefinition(tags = { - @Tag(name = "Mapping Financial Activities to Accounts", description = "Organization Level Financial Activities like Asset and Liability Transfer can be mapped to GL Account. Integrated accounting takes these accounts into consideration when an Account transfer is made between a savings to loan/savings account and vice-versa\n" + "\n" + "Field Descriptions\n" + "financialActivityId\n" + "The identifier of the Financial Activity\n" + "glAccountId\n" + "The identifier of a GL Account ( Ledger Account) which shall be used as the default account for the selected Financial Activity") -}) + @Tag(name = "Mapping Financial Activities to Accounts", description = "Organization Level Financial Activities like Asset and Liability Transfer can be mapped to GL Account. Integrated accounting takes these accounts into consideration when an Account transfer is made between a savings to loan/savings account and vice-versa\n" + + "\n" + "Field Descriptions\n" + "financialActivityId\n" + "The identifier of the Financial Activity\n" + "glAccountId\n" + + "The identifier of a GL Account ( Ledger Account) which shall be used as the default account for the selected Financial Activity") }) public class FinancialActivityAccountsApiResource { private final FinancialActivityAccountReadPlatformService financialActivityAccountReadPlatformService; @@ -100,8 +101,10 @@ public class FinancialActivityAccountsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Financial Activities to Accounts Mappings", notes = "Example Requests:\n" + "\n" + "financialactivityaccounts") - @ApiResponses({@ApiResponse(code = 200, message = "", response = FinancialActivityAccountsApiResourceSwagger.GetFinancialActivityAccountsResponse.class, responseContainer = "list" )}) + @ApiOperation(value = "List Financial Activities to Accounts Mappings", notes = "Example Requests:\n" + "\n" + + "financialactivityaccounts") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = FinancialActivityAccountsApiResourceSwagger.GetFinancialActivityAccountsResponse.class, responseContainer = "list") }) public String retrieveAll(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(FinancialActivityAccountsConstants.resourceNameForPermission); @@ -116,8 +119,10 @@ public class FinancialActivityAccountsApiResource { @Path("{mappingId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Financial Activity to Account Mapping\n", notes = "Example Requests:\n" + "\n" + "financialactivityaccounts/1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = FinancialActivityAccountsApiResourceSwagger.GetFinancialActivityAccountsResponse.class)}) + @ApiOperation(value = "Retrieve a Financial Activity to Account Mapping\n", notes = "Example Requests:\n" + "\n" + + "financialactivityaccounts/1") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = FinancialActivityAccountsApiResourceSwagger.GetFinancialActivityAccountsResponse.class) }) public String retreive(@PathParam("mappingId") @ApiParam(value = "mappingId") final Long mappingId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(FinancialActivityAccountsConstants.resourceNameForPermission); @@ -136,9 +141,12 @@ public class FinancialActivityAccountsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a new Financial Activity to Accounts Mapping", notes = "Mandatory Fields\n" + "financialActivityId, glAccountId") - @ApiImplicitParams({@ApiImplicitParam(value = "Request body", paramType = "body", dataType = "body", dataTypeClass = FinancialActivityAccountsApiResourceSwagger.PostFinancialActivityAccountsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = FinancialActivityAccountsApiResourceSwagger.PostFinancialActivityAccountsResponse.class)}) + @ApiOperation(value = "Create a new Financial Activity to Accounts Mapping", notes = "Mandatory Fields\n" + + "financialActivityId, glAccountId") + @ApiImplicitParams({ + @ApiImplicitParam(value = "Request body", paramType = "body", dataType = "body", dataTypeClass = FinancialActivityAccountsApiResourceSwagger.PostFinancialActivityAccountsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = FinancialActivityAccountsApiResourceSwagger.PostFinancialActivityAccountsResponse.class) }) public String createGLAccount(@ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createOfficeToGLAccountMapping().withJson(jsonRequestBody) @@ -154,9 +162,12 @@ public class FinancialActivityAccountsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Financial Activity to Account Mapping", notes = "the API updates the Ledger account linked to a Financial Activity \n") - @ApiImplicitParams({@ApiImplicitParam(value = "Request body", dataType = "body", paramType = "body", dataTypeClass = FinancialActivityAccountsApiResourceSwagger.PostFinancialActivityAccountsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = FinancialActivityAccountsApiResourceSwagger.PutFinancialActivityAccountsResponse.class)}) - public String updateGLAccount(@PathParam("mappingId") @ApiParam(value = "mappingId") final Long mappingId, @ApiParam(hidden = true) final String jsonRequestBody) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "Request body", dataType = "body", paramType = "body", dataTypeClass = FinancialActivityAccountsApiResourceSwagger.PostFinancialActivityAccountsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = FinancialActivityAccountsApiResourceSwagger.PutFinancialActivityAccountsResponse.class) }) + public String updateGLAccount(@PathParam("mappingId") @ApiParam(value = "mappingId") final Long mappingId, + @ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateOfficeToGLAccountMapping(mappingId) .withJson(jsonRequestBody).build(); @@ -171,7 +182,8 @@ public class FinancialActivityAccountsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Financial Activity to Account Mapping") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FinancialActivityAccountsApiResourceSwagger.DeleteFinancialActivityAccountsResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FinancialActivityAccountsApiResourceSwagger.DeleteFinancialActivityAccountsResponse.class) }) public String deleteGLAccount(@PathParam("mappingId") @ApiParam(value = "mappingId") final Long mappingId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteOfficeToGLAccountMapping(mappingId).build(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsApiResourceSwagger.java index 8d7c0b480..f533a627e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsApiResourceSwagger.java @@ -27,14 +27,16 @@ import org.apache.fineract.accounting.glaccount.data.GLAccountData; * Created by sanyam on 24/7/17. */ final class FinancialActivityAccountsApiResourceSwagger { - private FinancialActivityAccountsApiResourceSwagger() { - } + + private FinancialActivityAccountsApiResourceSwagger() {} @ApiModel(value = "GetFinancialActivityAccountsResponse") - public static final class GetFinancialActivityAccountsResponse{ + public static final class GetFinancialActivityAccountsResponse { + private GetFinancialActivityAccountsResponse() { } + @ApiModelProperty(example = "1") public Long id; public FinancialActivityData financialActivityData; @@ -43,10 +45,12 @@ final class FinancialActivityAccountsApiResourceSwagger { } @ApiModel(value = "PostFinancialActivityAccountsRequest") - public static final class PostFinancialActivityAccountsRequest{ + public static final class PostFinancialActivityAccountsRequest { + private PostFinancialActivityAccountsRequest() { } + @ApiModelProperty(example = "200") public Long financialActivityId; @ApiModelProperty(example = "2") @@ -54,19 +58,23 @@ final class FinancialActivityAccountsApiResourceSwagger { } @ApiModel(value = "PostFinancialActivityAccountsResponse") - public static final class PostFinancialActivityAccountsResponse{ + public static final class PostFinancialActivityAccountsResponse { + private PostFinancialActivityAccountsResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "PutFinancialActivityAccountsRequest") - public static final class PutFinancialActivityAccountsRequest{ + public static final class PutFinancialActivityAccountsRequest { + private PutFinancialActivityAccountsRequest() { } + @ApiModelProperty(example = "200") public Long financialActivityId; @ApiModelProperty(example = "3") @@ -74,25 +82,32 @@ final class FinancialActivityAccountsApiResourceSwagger { } @ApiModel(value = "PutFinancialActivityAccountsResponse") - public static final class PutFinancialActivityAccountsResponse{ + public static final class PutFinancialActivityAccountsResponse { + private PutFinancialActivityAccountsResponse() { } - public final class PutFinancialActivityAccountscommentsSwagger{ - private PutFinancialActivityAccountscommentsSwagger(){} + + public final class PutFinancialActivityAccountscommentsSwagger { + + private PutFinancialActivityAccountscommentsSwagger() {} + @ApiModelProperty(example = "1") public Long glAccountId; } + @ApiModelProperty(example = "1") public Long resourceId; public PutFinancialActivityAccountscommentsSwagger comments; } @ApiModel(value = "DeleteFinancialActivityAccountsResponse") - public static final class DeleteFinancialActivityAccountsResponse{ + public static final class DeleteFinancialActivityAccountsResponse { + private DeleteFinancialActivityAccountsResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsConstants.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsConstants.java index 040b17b7a..fd7df951b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsConstants.java @@ -23,13 +23,13 @@ import java.util.HashSet; import java.util.Set; public class FinancialActivityAccountsConstants { + private static final String idParamName = "id"; private static final String factivityDataParamName = "financialActivityData"; private static final String glAccountDataParamName = "glAccountData"; private static final String glAccountOptionsParamName = "glAccountOptions"; private static final String financialActivityOptionsParamName = "financialActivityOptions"; public static final String resourceNameForPermission = "FINANCIALACTIVITYACCOUNT"; - protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(idParamName, factivityDataParamName, glAccountDataParamName, glAccountOptionsParamName, - financialActivityOptionsParamName)); + protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, factivityDataParamName, + glAccountDataParamName, glAccountOptionsParamName, financialActivityOptionsParamName)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsJsonInputParams.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsJsonInputParams.java index a1a5868a4..2972e7bea 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsJsonInputParams.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/api/FinancialActivityAccountsJsonInputParams.java @@ -25,6 +25,7 @@ import java.util.Set; * Enum of all parameters passed in while creating/updating a GL Account ***/ public enum FinancialActivityAccountsJsonInputParams { + FINANCIAL_ACTIVITY_ID("financialActivityId"), GL_ACCOUNT_ID("glAccountId"); private final String value; @@ -52,4 +53,4 @@ public enum FinancialActivityAccountsJsonInputParams { public String getValue() { return this.value; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/data/FinancialActivityAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/data/FinancialActivityAccountData.java index 599fa8ce1..82257dee4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/data/FinancialActivityAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/data/FinancialActivityAccountData.java @@ -38,7 +38,8 @@ public class FinancialActivityAccountData { this.financialActivityOptions = null; } - public FinancialActivityAccountData(final Long id, final FinancialActivityData financialActivityData, final GLAccountData glAccountData) { + public FinancialActivityAccountData(final Long id, final FinancialActivityData financialActivityData, + final GLAccountData glAccountData) { this.id = id; this.glAccountData = glAccountData; this.financialActivityData = financialActivityData; diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccount.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccount.java index ff1772456..ab8f18b54 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccount.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccount.java @@ -66,4 +66,4 @@ public class FinancialActivityAccount extends AbstractPersistableCustom { public void updateFinancialActivityType(final Integer financialActivityType) { this.financialActivityType = financialActivityType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccountRepository.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccountRepository.java index 940b57bda..3a6d0c9fb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccountRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccountRepository.java @@ -23,8 +23,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface FinancialActivityAccountRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface FinancialActivityAccountRepository + extends JpaRepository, JpaSpecificationExecutor { @Query("select faa from FinancialActivityAccount faa where faa.financialActivityType = :financialActivityType") FinancialActivityAccount findByFinancialActivityType(@Param("financialActivityType") int financialAccountType); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccountRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccountRepositoryWrapper.java index cac544c8a..fea37b6e3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccountRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/domain/FinancialActivityAccountRepositoryWrapper.java @@ -40,8 +40,7 @@ public class FinancialActivityAccountRepositoryWrapper { } public FinancialActivityAccount findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new FinancialActivityAccountNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new FinancialActivityAccountNotFoundException(id)); } public FinancialActivityAccount findByFinancialActivityTypeWithNotFoundDetection(final int financialActivityType) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/DuplicateFinancialActivityAccountFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/DuplicateFinancialActivityAccountFoundException.java index 919d4ff4a..51e547529 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/DuplicateFinancialActivityAccountFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/DuplicateFinancialActivityAccountFoundException.java @@ -36,4 +36,4 @@ public class DuplicateFinancialActivityAccountFoundException extends AbstractPla return errorCode; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/FinancialActivityAccountInvalidException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/FinancialActivityAccountInvalidException.java index 30ce965af..f5a34f08d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/FinancialActivityAccountInvalidException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/FinancialActivityAccountInvalidException.java @@ -31,14 +31,16 @@ public class FinancialActivityAccountInvalidException extends AbstractPlatformDo private final static String errorCode = "error.msg.financialActivityAccount.invalid"; public FinancialActivityAccountInvalidException(final FinancialActivity financialActivity, final GLAccount glAccount) { - super(errorCode, "Financial Activity '" + financialActivity.getCode() + "' with Id :" + financialActivity.getValue() - + "' can only be associated with a Ledger Account of Type " + financialActivity.getMappedGLAccountType().getCode() - + " the provided Ledger Account '" + glAccount.getName() + "(" + glAccount.getGlCode() - + ")' does not of the required type", financialActivity.getCode(), financialActivity.getValue(), financialActivity - .getMappedGLAccountType().getCode(), glAccount.getName(), glAccount.getGlCode()); + super(errorCode, + "Financial Activity '" + financialActivity.getCode() + "' with Id :" + financialActivity.getValue() + + "' can only be associated with a Ledger Account of Type " + financialActivity.getMappedGLAccountType().getCode() + + " the provided Ledger Account '" + glAccount.getName() + "(" + glAccount.getGlCode() + + ")' does not of the required type", + financialActivity.getCode(), financialActivity.getValue(), financialActivity.getMappedGLAccountType().getCode(), + glAccount.getName(), glAccount.getGlCode()); } public static String getErrorcode() { return errorCode; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/FinancialActivityAccountNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/FinancialActivityAccountNotFoundException.java index a05840785..a99523969 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/FinancialActivityAccountNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/exception/FinancialActivityAccountNotFoundException.java @@ -31,8 +31,9 @@ public class FinancialActivityAccountNotFoundException extends AbstractPlatformR } public FinancialActivityAccountNotFoundException(final Integer financialActivityType) { - super("error.msg.financialActivityAccount.not.found", "Financial Activity account with for the financial Activity with Id " - + financialActivityType + " does not exist", financialActivityType); + super("error.msg.financialActivityAccount.not.found", + "Financial Activity account with for the financial Activity with Id " + financialActivityType + " does not exist", + financialActivityType); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/CreateFinancialActivityAccountHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/CreateFinancialActivityAccountHandler.java index 9218678d5..b8c0403a0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/CreateFinancialActivityAccountHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/CreateFinancialActivityAccountHandler.java @@ -44,4 +44,4 @@ public class CreateFinancialActivityAccountHandler implements NewCommandSourceHa return this.writePlatformService.createFinancialActivityAccountMapping(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/DeleteFinancialActivityAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/DeleteFinancialActivityAccountCommandHandler.java index 6c53a7eef..e6c29b74a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/DeleteFinancialActivityAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/DeleteFinancialActivityAccountCommandHandler.java @@ -43,4 +43,4 @@ public class DeleteFinancialActivityAccountCommandHandler implements NewCommandS public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.deleteGLAccountActivityMapping(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/UpdateFinancialActivityAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/UpdateFinancialActivityAccountCommandHandler.java index d183cf26c..3da189c83 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/UpdateFinancialActivityAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/handler/UpdateFinancialActivityAccountCommandHandler.java @@ -43,4 +43,4 @@ public class UpdateFinancialActivityAccountCommandHandler implements NewCommandS public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.updateGLAccountActivityMapping(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/serialization/FinancialActivityAccountDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/serialization/FinancialActivityAccountDataValidator.java index 3f34f370a..9f6af9280 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/serialization/FinancialActivityAccountDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/serialization/FinancialActivityAccountDataValidator.java @@ -113,8 +113,10 @@ public final class FinancialActivityAccountDataValidator { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountReadPlatformService.java index 13424f0b6..c06b06bc1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountReadPlatformService.java @@ -31,4 +31,4 @@ public interface FinancialActivityAccountReadPlatformService { FinancialActivityAccountData getFinancialActivityAccountTemplate(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountReadPlatformServiceImpl.java index b9e4e6cee..3937de1c3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountReadPlatformServiceImpl.java @@ -91,7 +91,8 @@ public class FinancialActivityAccountReadPlatformServiceImpl implements Financia public FinancialActivityAccountMapper() { StringBuilder sb = new StringBuilder(300); - sb.append(" faa.id as id, faa.financial_activity_type as financialActivityId, glaccount.id as glAccountId,glaccount.name as glAccountName,glaccount.gl_code as glCode "); + sb.append( + " faa.id as id, faa.financial_activity_type as financialActivityId, glaccount.id as glAccountId,glaccount.name as glAccountName,glaccount.gl_code as glCode "); sb.append(" from acc_gl_financial_activity_account faa "); sb.append(" join acc_gl_account glaccount on glaccount.id = faa.gl_account_id"); sql = sb.toString(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountWritePlatformService.java index c3296aa3e..23a3063ca 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountWritePlatformService.java @@ -29,4 +29,4 @@ public interface FinancialActivityAccountWritePlatformService { CommandProcessingResult deleteGLAccountActivityMapping(Long mappingId, JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountWritePlatformServiceImpl.java index d1aa143b3..f1fff00d8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/financialactivityaccount/service/FinancialActivityAccountWritePlatformServiceImpl.java @@ -52,7 +52,8 @@ public class FinancialActivityAccountWritePlatformServiceImpl implements Financi @Autowired public FinancialActivityAccountWritePlatformServiceImpl( final FinancialActivityAccountRepositoryWrapper financialActivityAccountRepository, - final FinancialActivityAccountDataValidator fromApiJsonDeserializer, final GLAccountRepositoryWrapper glAccountRepositoryWrapper) { + final FinancialActivityAccountDataValidator fromApiJsonDeserializer, + final GLAccountRepositoryWrapper glAccountRepositoryWrapper) { this.financialActivityAccountRepository = financialActivityAccountRepository; this.fromApiJsonDeserializer = fromApiJsonDeserializer; this.glAccountRepositoryWrapper = glAccountRepositoryWrapper; @@ -77,10 +78,11 @@ public class FinancialActivityAccountWritePlatformServiceImpl implements Financi .withEntityId(financialActivityAccount.getId()) // .build(); } catch (DataIntegrityViolationException dataIntegrityViolationException) { - handleFinancialActivityAccountDataIntegrityIssues(command, dataIntegrityViolationException.getMostSpecificCause(), dataIntegrityViolationException); + handleFinancialActivityAccountDataIntegrityIssues(command, dataIntegrityViolationException.getMostSpecificCause(), + dataIntegrityViolationException); return CommandProcessingResult.empty(); - }catch(final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + } catch (final PersistenceException ee) { + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()); handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee); return CommandProcessingResult.empty(); } @@ -93,8 +95,9 @@ public class FinancialActivityAccountWritePlatformServiceImpl implements Financi private void validateFinancialActivityAndAccountMapping(FinancialActivityAccount financialActivityAccount) { FinancialActivity financialActivity = FinancialActivity.fromInt(financialActivityAccount.getFinancialActivityType()); GLAccount glAccount = financialActivityAccount.getGlAccount(); - if (!financialActivity.getMappedGLAccountType().getValue().equals(glAccount.getType())) { throw new FinancialActivityAccountInvalidException( - financialActivity, glAccount); } + if (!financialActivity.getMappedGLAccountType().getValue().equals(glAccount.getType())) { + throw new FinancialActivityAccountInvalidException(financialActivity, glAccount); + } } @Override @@ -127,10 +130,11 @@ public class FinancialActivityAccountWritePlatformServiceImpl implements Financi .with(changes) // .build(); } catch (DataIntegrityViolationException dataIntegrityViolationException) { - handleFinancialActivityAccountDataIntegrityIssues(command, dataIntegrityViolationException.getMostSpecificCause(), dataIntegrityViolationException); + handleFinancialActivityAccountDataIntegrityIssues(command, dataIntegrityViolationException.getMostSpecificCause(), + dataIntegrityViolationException); return CommandProcessingResult.empty(); - }catch(final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + } catch (final PersistenceException ee) { + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()); handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee); return CommandProcessingResult.empty(); } @@ -147,7 +151,8 @@ public class FinancialActivityAccountWritePlatformServiceImpl implements Financi .build(); } - private void handleFinancialActivityAccountDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { + private void handleFinancialActivityAccountDataIntegrityIssues(final JsonCommand command, final Throwable realCause, + final Exception dve) { if (realCause.getMessage().contains("financial_activity_type")) { final Integer financialActivityId = command .integerValueSansLocaleOfParameterNamed(FinancialActivityAccountsJsonInputParams.FINANCIAL_ACTIVITY_ID.getValue()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountJsonInputParams.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountJsonInputParams.java old mode 100755 new mode 100644 index a3d85ec62..7eceef626 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountJsonInputParams.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountJsonInputParams.java @@ -25,8 +25,9 @@ import java.util.Set; * Enum of all parameters passed in while creating/updating a GL Account ***/ public enum GLAccountJsonInputParams { - ID("id"), NAME("name"), PARENT_ID("parentId"), GL_CODE("glCode"), DISABLED("disabled"), MANUAL_ENTRIES_ALLOWED("manualEntriesAllowed"), TYPE( - "type"), USAGE("usage"), DESCRIPTION("description"), TAGID("tagId"); + + ID("id"), NAME("name"), PARENT_ID("parentId"), GL_CODE("glCode"), DISABLED("disabled"), MANUAL_ENTRIES_ALLOWED( + "manualEntriesAllowed"), TYPE("type"), USAGE("usage"), DESCRIPTION("description"), TAGID("tagId"); private final String value; @@ -53,4 +54,4 @@ public enum GLAccountJsonInputParams { public String getValue() { return this.value; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountsApiResource.java index b80c1fd0f..e0491d364 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountsApiResource.java @@ -75,17 +75,17 @@ import org.springframework.stereotype.Component; @Path("/glaccounts") @Component @Scope("singleton") -@Api(tags = {"General Ledger Account"}) +@Api(tags = { "General Ledger Account" }) @SwaggerDefinition(tags = { - @Tag(name = "General Ledger Account", description = "Ledger accounts represent an Individual account within an Organizations Chart Of Accounts(COA) and are assigned a name and unique number by which they can be identified. \n" + "All transactions relating to a company's assets, liabilities, owners' equity, revenue and expenses are recorded against these accounts") -}) + @Tag(name = "General Ledger Account", description = "Ledger accounts represent an Individual account within an Organizations Chart Of Accounts(COA) and are assigned a name and unique number by which they can be identified. \n" + + "All transactions relating to a company's assets, liabilities, owners' equity, revenue and expenses are recorded against these accounts") }) public class GLAccountsApiResource { - private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "parentId", "glCode", - "disabled", "manualEntriesAllowed", "type", "usage", "description", "assetHeaderAccountOptions", - "liabilityHeaderAccountOptions", "equityHeaderAccountOptions", "incomeHeaderAccountOptions", "expenseHeaderAccountOptions", - "nameDecorated", "tagId", "allowedAssetsTagOptions", "allowedLiabilitiesTagOptions", "allowedEquityTagOptions", - "allowedIncomeTagOptions", "allowedExpensesTagOptions", "creditAccounts", "debitAccounts")); + private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "parentId", "glCode", "disabled", + "manualEntriesAllowed", "type", "usage", "description", "assetHeaderAccountOptions", "liabilityHeaderAccountOptions", + "equityHeaderAccountOptions", "incomeHeaderAccountOptions", "expenseHeaderAccountOptions", "nameDecorated", "tagId", + "allowedAssetsTagOptions", "allowedLiabilitiesTagOptions", "allowedEquityTagOptions", "allowedIncomeTagOptions", + "allowedExpensesTagOptions", "creditAccounts", "debitAccounts")); private final String resourceNameForPermission = "GLACCOUNT"; @@ -99,15 +99,12 @@ public class GLAccountsApiResource { private final BulkImportWorkbookService bulkImportWorkbookService; private final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService; - - @Autowired public GLAccountsApiResource(final PlatformSecurityContext context, final GLAccountReadPlatformService glAccountReadPlatformService, final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final AccountingDropdownReadPlatformService dropdownReadPlatformService, - final CodeValueReadPlatformService codeValueReadPlatformService, - final BulkImportWorkbookService bulkImportWorkbookService, + final CodeValueReadPlatformService codeValueReadPlatformService, final BulkImportWorkbookService bulkImportWorkbookService, final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService) { this.context = context; this.apiRequestParameterHelper = apiRequestParameterHelper; @@ -116,17 +113,21 @@ public class GLAccountsApiResource { this.glAccountReadPlatformService = glAccountReadPlatformService; this.dropdownReadPlatformService = dropdownReadPlatformService; this.codeValueReadPlatformService = codeValueReadPlatformService; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve GL Accounts Template", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "glaccounts/template\n" + "glaccounts/template?type=1\n" + "\n" + "type is optional and integer value from 1 to 5.\n" + "\n" + "1.Assets \n" + "2.Liabilities \n" + "3.Equity \n" + "4.Income \n" + "5.Expenses") - @ApiResponses({@ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.GetGLAccountsTemplateResponse.class)}) - public String retrieveNewAccountDetails(@Context final UriInfo uriInfo, @QueryParam("type") @ApiParam(value = "type") final Integer type) { + @ApiOperation(value = "Retrieve GL Accounts Template", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "glaccounts/template\n" + + "glaccounts/template?type=1\n" + "\n" + "type is optional and integer value from 1 to 5.\n" + "\n" + "1.Assets \n" + + "2.Liabilities \n" + "3.Equity \n" + "4.Income \n" + "5.Expenses") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.GetGLAccountsTemplateResponse.class) }) + public String retrieveNewAccountDetails(@Context final UriInfo uriInfo, + @QueryParam("type") @ApiParam(value = "type") final Integer type) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); @@ -140,11 +141,17 @@ public class GLAccountsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List General Ledger Accounts", notes = "ARGUMENTS\n" + "type Integer optional manualEntriesAllowed boolean optional usage Integer optional disabled boolean optional parentId Long optional tagId Long optional\n" + "Example Requests:\n" + "\n" + "glaccounts\n" + "\n" + "\n" + "glaccounts?type=1&manualEntriesAllowed=true&usage=1&disabled=false\n" + "\n" + "glaccounts?fetchRunningBalance=true") - @ApiResponses({@ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.GetGLAccountsResponse.class, responseContainer = "list")}) + @ApiOperation(value = "List General Ledger Accounts", notes = "ARGUMENTS\n" + + "type Integer optional manualEntriesAllowed boolean optional usage Integer optional disabled boolean optional parentId Long optional tagId Long optional\n" + + "Example Requests:\n" + "\n" + "glaccounts\n" + "\n" + "\n" + + "glaccounts?type=1&manualEntriesAllowed=true&usage=1&disabled=false\n" + "\n" + "glaccounts?fetchRunningBalance=true") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.GetGLAccountsResponse.class, responseContainer = "list") }) public String retrieveAllAccounts(@Context final UriInfo uriInfo, @QueryParam("type") @ApiParam(value = "type") final Integer type, - @QueryParam("searchParam") @ApiParam(value = "searchParam") final String searchParam, @QueryParam("usage") @ApiParam(value = "usage") final Integer usage, - @QueryParam("manualEntriesAllowed") @ApiParam(value = "manualEntriesAllowed") final Boolean manualEntriesAllowed, @QueryParam("disabled") @ApiParam(value = "disabled") final Boolean disabled, + @QueryParam("searchParam") @ApiParam(value = "searchParam") final String searchParam, + @QueryParam("usage") @ApiParam(value = "usage") final Integer usage, + @QueryParam("manualEntriesAllowed") @ApiParam(value = "manualEntriesAllowed") final Boolean manualEntriesAllowed, + @QueryParam("disabled") @ApiParam(value = "disabled") final Boolean disabled, @QueryParam("fetchRunningBalance") @ApiParam(value = "fetchRunningBalance") final boolean runningBalance) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); @@ -160,9 +167,12 @@ public class GLAccountsApiResource { @Path("{glAccountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a General Ledger Account", notes = "Example Requests:\n" + "\n" + "glaccounts/1\n" + "\n" + "\n" + "glaccounts/1?template=true\n" + "\n" + "\n" + "glaccounts/1?fields=name,glCode\n" + "\n" + "\n" + "glaccounts/1?fetchRunningBalance=true") - @ApiResponses({@ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.GetGLAccountsResponse.class)}) - public String retreiveAccount(@PathParam("glAccountId") @ApiParam(value = "glAccountId") final Long glAccountId, @Context final UriInfo uriInfo, + @ApiOperation(value = "Retrieve a General Ledger Account", notes = "Example Requests:\n" + "\n" + "glaccounts/1\n" + "\n" + "\n" + + "glaccounts/1?template=true\n" + "\n" + "\n" + "glaccounts/1?fields=name,glCode\n" + "\n" + "\n" + + "glaccounts/1?fetchRunningBalance=true") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.GetGLAccountsResponse.class) }) + public String retreiveAccount(@PathParam("glAccountId") @ApiParam(value = "glAccountId") final Long glAccountId, + @Context final UriInfo uriInfo, @QueryParam("fetchRunningBalance") @ApiParam(value = "fetchRunningBalance") final boolean runningBalance) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); @@ -180,9 +190,11 @@ public class GLAccountsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a General Ledger Account", notes = "Note: You may optionally create Hierarchical Chart of Accounts by using the \"parentId\" property of an Account\n" + "Mandatory Fields: \n" + "name, glCode, type, usage and manualEntriesAllowed") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = GLAccountsApiResourceSwagger.PostGLAccountsRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.PostGLAccountsResponse.class)}) + @ApiOperation(value = "Create a General Ledger Account", notes = "Note: You may optionally create Hierarchical Chart of Accounts by using the \"parentId\" property of an Account\n" + + "Mandatory Fields: \n" + "name, glCode, type, usage and manualEntriesAllowed") + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = GLAccountsApiResourceSwagger.PostGLAccountsRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.PostGLAccountsResponse.class) }) public String createGLAccount(@ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createGLAccount().withJson(jsonRequestBody).build(); @@ -196,10 +208,13 @@ public class GLAccountsApiResource { @Path("{glAccountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Update an Accounting closure", notes = "Once an accounting closure is created, only the comments associated with it may be edited\n" + "\n") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = GLAccountsApiResourceSwagger.PutGLAccountsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.PutGLAccountsResponse.class)}) - public String updateGLAccount(@PathParam("glAccountId") @ApiParam(value = "glAccountId") final Long glAccountId, @ApiParam(hidden = true) final String jsonRequestBody) { + @ApiOperation(value = "Update an Accounting closure", notes = "Once an accounting closure is created, only the comments associated with it may be edited\n" + + "\n") + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = GLAccountsApiResourceSwagger.PutGLAccountsRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.PutGLAccountsResponse.class) }) + public String updateGLAccount(@PathParam("glAccountId") @ApiParam(value = "glAccountId") final Long glAccountId, + @ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateGLAccount(glAccountId).withJson(jsonRequestBody).build(); @@ -213,7 +228,7 @@ public class GLAccountsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete an accounting closure", notes = "Note: Only the latest accounting closure associated with a branch may be deleted.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.DeleteGLAccountsRequest.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = GLAccountsApiResourceSwagger.DeleteGLAccountsRequest.class) }) public String deleteGLAccount(@PathParam("glAccountId") @ApiParam(value = "glAccountId") final Long glAccountId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteGLAccount(glAccountId).build(); @@ -226,16 +241,16 @@ public class GLAccountsApiResource { private GLAccountData handleTemplate(final GLAccountData glAccountData) { final List accountTypeOptions = this.dropdownReadPlatformService.retrieveGLAccountTypeOptions(); final List usageOptions = this.dropdownReadPlatformService.retrieveGLAccountUsageOptions(); - final List assetHeaderAccountOptions = defaultIfEmpty(this.glAccountReadPlatformService - .retrieveAllEnabledHeaderGLAccounts(GLAccountType.ASSET)); - final List liabilityHeaderAccountOptions = defaultIfEmpty(this.glAccountReadPlatformService - .retrieveAllEnabledHeaderGLAccounts(GLAccountType.LIABILITY)); - final List equityHeaderAccountOptions = defaultIfEmpty(this.glAccountReadPlatformService - .retrieveAllEnabledHeaderGLAccounts(GLAccountType.EQUITY)); - final List incomeHeaderAccountOptions = defaultIfEmpty(this.glAccountReadPlatformService - .retrieveAllEnabledHeaderGLAccounts(GLAccountType.INCOME)); - final List expenseHeaderAccountOptions = defaultIfEmpty(this.glAccountReadPlatformService - .retrieveAllEnabledHeaderGLAccounts(GLAccountType.EXPENSE)); + final List assetHeaderAccountOptions = defaultIfEmpty( + this.glAccountReadPlatformService.retrieveAllEnabledHeaderGLAccounts(GLAccountType.ASSET)); + final List liabilityHeaderAccountOptions = defaultIfEmpty( + this.glAccountReadPlatformService.retrieveAllEnabledHeaderGLAccounts(GLAccountType.LIABILITY)); + final List equityHeaderAccountOptions = defaultIfEmpty( + this.glAccountReadPlatformService.retrieveAllEnabledHeaderGLAccounts(GLAccountType.EQUITY)); + final List incomeHeaderAccountOptions = defaultIfEmpty( + this.glAccountReadPlatformService.retrieveAllEnabledHeaderGLAccounts(GLAccountType.INCOME)); + final List expenseHeaderAccountOptions = defaultIfEmpty( + this.glAccountReadPlatformService.retrieveAllEnabledHeaderGLAccounts(GLAccountType.EXPENSE)); final Collection allowedAssetsTagOptions = this.codeValueReadPlatformService .retrieveCodeValuesByCode(AccountingConstants.ASSESTS_TAG_OPTION_CODE_NAME); final Collection allowedLiabilitiesTagOptions = this.codeValueReadPlatformService @@ -264,17 +279,17 @@ public class GLAccountsApiResource { @Path("downloadtemplate") @Produces("application/vnd.ms-excel") public Response getGlAccountsTemplate(@QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.CHART_OF_ACCOUNTS.toString(),null,null,dateFormat); + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.CHART_OF_ACCOUNTS.toString(), null, null, dateFormat); } @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postGlAccountsTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, @FormDataParam("dateFormat") final String dateFormat){ - Long importDocumentId= bulkImportWorkbookService.importWorkbook(GlobalEntityType.CHART_OF_ACCOUNTS.toString(), uploadedInputStream,fileDetail, - locale,dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + Long importDocumentId = bulkImportWorkbookService.importWorkbook(GlobalEntityType.CHART_OF_ACCOUNTS.toString(), uploadedInputStream, + fileDetail, locale, dateFormat); return this.apiJsonSerializerService.serialize(importDocumentId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountsApiResourceSwagger.java index 1408aac8e..d32fc3df7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/api/GLAccountsApiResourceSwagger.java @@ -30,13 +30,15 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; * Created by sanyam on 24/7/17. */ final class GLAccountsApiResourceSwagger { + private GLAccountsApiResourceSwagger() { } @ApiModel(value = "GetGLAccountsResponse") - public static final class GetGLAccountsResponse{ - private GetGLAccountsResponse(){ + public static final class GetGLAccountsResponse { + + private GetGLAccountsResponse() { } @@ -74,8 +76,9 @@ final class GLAccountsApiResourceSwagger { } @ApiModel(value = "GetGLAccountsTemplateResponse") - public static final class GetGLAccountsTemplateResponse{ - private GetGLAccountsTemplateResponse(){ + public static final class GetGLAccountsTemplateResponse { + + private GetGLAccountsTemplateResponse() { } @@ -102,8 +105,9 @@ final class GLAccountsApiResourceSwagger { } @ApiModel(value = "PostGLAccountsRequest") - public static final class PostGLAccountsRequest{ - private PostGLAccountsRequest(){ + public static final class PostGLAccountsRequest { + + private PostGLAccountsRequest() { } @@ -134,7 +138,8 @@ final class GLAccountsApiResourceSwagger { } @ApiModel(value = "PostGLAccountsResponse") - public static final class PostGLAccountsResponse{ + public static final class PostGLAccountsResponse { + private PostGLAccountsResponse() { } @@ -144,7 +149,8 @@ final class GLAccountsApiResourceSwagger { } @ApiModel(value = "PutGLAccountsRequest") - public static final class PutGLAccountsRequest{ + public static final class PutGLAccountsRequest { + private PutGLAccountsRequest() { } @@ -154,29 +160,36 @@ final class GLAccountsApiResourceSwagger { } @ApiModel(value = "PutGLAccountsResponse") - public static final class PutGLAccountsResponse{ + public static final class PutGLAccountsResponse { + private PutGLAccountsResponse() { } + @ApiModel - public static final class PutGLAccountsResponsechangesSwagger{ - private PutGLAccountsResponsechangesSwagger(){} + public static final class PutGLAccountsResponsechangesSwagger { + + private PutGLAccountsResponsechangesSwagger() {} + @ApiModelProperty(example = "Cash at Bangalore") public String name; } + @ApiModelProperty(example = "1") public int resourceId; public PutGLAccountsResponsechangesSwagger changes; } @ApiModel(value = "DeleteGLAccountsRequest") - public static final class DeleteGLAccountsRequest{ + public static final class DeleteGLAccountsRequest { + private DeleteGLAccountsRequest() { } - private static final class DeleteGLAccountsRequestchangesSwagger{ - private DeleteGLAccountsRequestchangesSwagger(){} + private static final class DeleteGLAccountsRequestchangesSwagger { + + private DeleteGLAccountsRequestchangesSwagger() {} } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/command/GLAccountCommand.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/command/GLAccountCommand.java index 4c8b9ef1c..d17e9250a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/command/GLAccountCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/command/GLAccountCommand.java @@ -87,8 +87,10 @@ public class GLAccountCommand { baseDataValidator.reset().parameter(GLAccountJsonInputParams.TAGID.getValue()).value(this.tagId).ignoreIfNull() .longGreaterThanZero(); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForUpdate() { @@ -117,8 +119,10 @@ public class GLAccountCommand { baseDataValidator.reset().anyOfNotNull(this.name, this.glCode, this.parentId, this.type, this.description, this.disabled); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } baseDataValidator.reset().parameter(GLAccountJsonInputParams.TAGID.getValue()).value(this.tagId).ignoreIfNull() .longGreaterThanZero(); } @@ -127,4 +131,4 @@ public class GLAccountCommand { return GLAccountUsage.HEADER.getValue().equals(this.usage); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/data/GLAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/data/GLAccountData.java old mode 100755 new mode 100644 index 6cc43e00d..bc5081ef8 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/data/GLAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/data/GLAccountData.java @@ -62,19 +62,16 @@ public class GLAccountData implements Serializable { final Collection allowedIncomeTagOptions; final Collection allowedExpensesTagOptions; - //import fields + // import fields private transient Integer rowIndex; - public static GLAccountData importInstance(String name, Long parentId, String glCode, Boolean manualEntriesAllowed, - EnumOptionData type, EnumOptionData usage, String description, CodeValueData tagId, - Integer rowIndex){ - return new GLAccountData(name,parentId,glCode,manualEntriesAllowed,type, - usage,description,tagId,rowIndex); + public static GLAccountData importInstance(String name, Long parentId, String glCode, Boolean manualEntriesAllowed, EnumOptionData type, + EnumOptionData usage, String description, CodeValueData tagId, Integer rowIndex) { + return new GLAccountData(name, parentId, glCode, manualEntriesAllowed, type, usage, description, tagId, rowIndex); } - private GLAccountData(String name, Long parentId, String glCode, Boolean manualEntriesAllowed, - EnumOptionData type, EnumOptionData usage, String description, CodeValueData tagId, - Integer rowIndex) { + private GLAccountData(String name, Long parentId, String glCode, Boolean manualEntriesAllowed, EnumOptionData type, + EnumOptionData usage, String description, CodeValueData tagId, Integer rowIndex) { this.name = name; this.parentId = parentId; @@ -192,8 +189,8 @@ public class GLAccountData implements Serializable { final CodeValueData tagId = null; final Long organizationRunningBalance = null; - return new GLAccountData(id, name, parentId, glCode, disabled, manualEntriesAllowed, type, usage, description, nameDecorated, - tagId, organizationRunningBalance); + return new GLAccountData(id, name, parentId, glCode, disabled, manualEntriesAllowed, type, usage, description, nameDecorated, tagId, + organizationRunningBalance); } public GLAccountData(final Long id, final String name, final String glCode) { @@ -244,5 +241,4 @@ public class GLAccountData implements Serializable { return null; } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccount.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccount.java index c5b7d67ad..047391cd8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccount.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccount.java @@ -98,8 +98,8 @@ public class GLAccount extends AbstractPersistableCustom { final String name = command.stringValueOfParameterNamed(GLAccountJsonInputParams.NAME.getValue()); final String glCode = command.stringValueOfParameterNamed(GLAccountJsonInputParams.GL_CODE.getValue()); final boolean disabled = command.booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.DISABLED.getValue()); - final boolean manualEntriesAllowed = command.booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED - .getValue()); + final boolean manualEntriesAllowed = command + .booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED.getValue()); final Integer usage = command.integerValueSansLocaleOfParameterNamed(GLAccountJsonInputParams.USAGE.getValue()); final Integer type = command.integerValueSansLocaleOfParameterNamed(GLAccountJsonInputParams.TYPE.getValue()); final String description = command.stringValueOfParameterNamed(GLAccountJsonInputParams.DESCRIPTION.getValue()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccountRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccountRepositoryWrapper.java old mode 100755 new mode 100644 index 39031bcda..d1973a829 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccountRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccountRepositoryWrapper.java @@ -38,7 +38,7 @@ public class GLAccountRepositoryWrapper { } public GLAccount findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id).orElseThrow(() -> new GLAccountNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new GLAccountNotFoundException(id)); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccountType.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccountType.java old mode 100755 new mode 100644 index e826f5fb7..55239c437 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccountType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/GLAccountType.java @@ -23,8 +23,9 @@ import java.util.Map; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public enum GLAccountType { - ASSET(1, "accountType.asset"), LIABILITY(2, "accountType.liability"), EQUITY(3, "accountType.equity"), INCOME(4, "accountType.income"), EXPENSE( - 5, "accountType.expense"); + + ASSET(1, "accountType.asset"), LIABILITY(2, "accountType.liability"), EQUITY(3, "accountType.equity"), INCOME(4, + "accountType.income"), EXPENSE(5, "accountType.expense"); private final Integer value; private final String code; @@ -61,24 +62,25 @@ public enum GLAccountType { i = i + 1; } } - public static EnumOptionData fromString(String accountType){ - Long accountTypeId=null; - if (accountType!=null && accountType.equalsIgnoreCase(ASSET.toString())){ - accountTypeId=1L; - return new EnumOptionData(accountTypeId,null,null); - }else if(accountType!=null && accountType.equalsIgnoreCase(LIABILITY.toString())) { + + public static EnumOptionData fromString(String accountType) { + Long accountTypeId = null; + if (accountType != null && accountType.equalsIgnoreCase(ASSET.toString())) { + accountTypeId = 1L; + return new EnumOptionData(accountTypeId, null, null); + } else if (accountType != null && accountType.equalsIgnoreCase(LIABILITY.toString())) { accountTypeId = 2L; return new EnumOptionData(accountTypeId, null, null); - }else if(accountType!=null && accountType.equalsIgnoreCase(EQUITY.toString())){ - accountTypeId=3L; - return new EnumOptionData(accountTypeId,null,null); - }else if(accountType!=null && accountType.equalsIgnoreCase(INCOME.toString())) { + } else if (accountType != null && accountType.equalsIgnoreCase(EQUITY.toString())) { + accountTypeId = 3L; + return new EnumOptionData(accountTypeId, null, null); + } else if (accountType != null && accountType.equalsIgnoreCase(INCOME.toString())) { accountTypeId = 4L; return new EnumOptionData(accountTypeId, null, null); - }else if(accountType!=null && accountType.equalsIgnoreCase(EXPENSE.toString())){ - accountTypeId=5L; - return new EnumOptionData(accountTypeId,null,null); - }else { + } else if (accountType != null && accountType.equalsIgnoreCase(EXPENSE.toString())) { + accountTypeId = 5L; + return new EnumOptionData(accountTypeId, null, null); + } else { return null; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalance.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalance.java index 78bd84ae1..56eca5838 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalance.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalance.java @@ -19,7 +19,6 @@ package org.apache.fineract.accounting.glaccount.domain; - import java.math.BigDecimal; import java.util.Date; import java.util.Objects; @@ -54,13 +53,13 @@ public class TrialBalance extends AbstractPersistableCustom { @Column(name = "closing_balance", nullable = false) private BigDecimal closingBalance; - public static TrialBalance getInstance(final Long officeId, final Long glAccountId, - final BigDecimal amount, final Date entryDate, final Date transactionDate) { + public static TrialBalance getInstance(final Long officeId, final Long glAccountId, final BigDecimal amount, final Date entryDate, + final Date transactionDate) { return new TrialBalance(officeId, glAccountId, amount, entryDate, transactionDate); } - private TrialBalance(final Long officeId, final Long glAccountId, - final BigDecimal amount, final Date entryDate, final Date transactionDate) { + private TrialBalance(final Long officeId, final Long glAccountId, final BigDecimal amount, final Date entryDate, + final Date transactionDate) { this.officeId = officeId; this.glAccountId = glAccountId; this.amount = amount; @@ -68,8 +67,7 @@ public class TrialBalance extends AbstractPersistableCustom { this.transactionDate = transactionDate; } - protected TrialBalance() { - } + protected TrialBalance() {} public Long getOfficeId() { return officeId; @@ -97,16 +95,11 @@ public class TrialBalance extends AbstractPersistableCustom { @Override public boolean equals(Object obj) { - if (!(obj instanceof TrialBalance)) { - return false; - } + if (!(obj instanceof TrialBalance)) { return false; } TrialBalance other = (TrialBalance) obj; - return Objects.equals(other.officeId, officeId) - && Objects.equals(other.glAccountId, glAccountId) - && Objects.equals(other.amount, amount) - && Objects.equals(other.entryDate, entryDate) - && Objects.equals(other.transactionDate, transactionDate) - && Objects.equals(other.closingBalance, closingBalance); + return Objects.equals(other.officeId, officeId) && Objects.equals(other.glAccountId, glAccountId) + && Objects.equals(other.amount, amount) && Objects.equals(other.entryDate, entryDate) + && Objects.equals(other.transactionDate, transactionDate) && Objects.equals(other.closingBalance, closingBalance); } @Override diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalanceRepository.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalanceRepository.java index e5827ba8f..e68c70d57 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalanceRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalanceRepository.java @@ -27,6 +27,5 @@ import org.springframework.data.repository.query.Param; public interface TrialBalanceRepository extends JpaRepository, JpaSpecificationExecutor { @Query(value = "select * from m_trial_balance where office_id=:officeId and account_id=:accountId and closing_balance is null order by created_date, entry_date", nativeQuery = true) - List findNewByOfficeAndAccount(@Param("officeId") final Long officeId, - @Param("accountId") final Long accountId); -} \ No newline at end of file + List findNewByOfficeAndAccount(@Param("officeId") final Long officeId, @Param("accountId") final Long accountId); +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalanceRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalanceRepositoryWrapper.java index 151e58878..aa2327a05 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalanceRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/domain/TrialBalanceRepositoryWrapper.java @@ -25,23 +25,22 @@ import org.springframework.stereotype.Service; @Service public class TrialBalanceRepositoryWrapper { - private final TrialBalanceRepository repository; + + private final TrialBalanceRepository repository; @Autowired - public TrialBalanceRepositoryWrapper(final TrialBalanceRepository repository){ - this.repository=repository; + public TrialBalanceRepositoryWrapper(final TrialBalanceRepository repository) { + this.repository = repository; } - public List findNewByOfficeAndAccount(final Long officeId, final Long accountId){ - final List trialBalanceList=this.repository.findNewByOfficeAndAccount(officeId,accountId); - if (trialBalanceList==null) { - throw new TrialBalanceNotFoundException(officeId, accountId); - } + public List findNewByOfficeAndAccount(final Long officeId, final Long accountId) { + final List trialBalanceList = this.repository.findNewByOfficeAndAccount(officeId, accountId); + if (trialBalanceList == null) { throw new TrialBalanceNotFoundException(officeId, accountId); } return trialBalanceList; } - public void save(final List tbRows){ + public void save(final List tbRows) { this.repository.saveAll(tbRows); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountDisableException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountDisableException.java index 8f56dcf89..251e87cc6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountDisableException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountDisableException.java @@ -25,11 +25,9 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR * when gl account is attached with any product(loan/saving) then we can not * disable the gl account */ -public class GLAccountDisableException extends - AbstractPlatformDomainRuleException { +public class GLAccountDisableException extends AbstractPlatformDomainRuleException { public GLAccountDisableException() { - super("error.msg.glaccount.attached.to.product", - "General Ledger Account is already attached to product."); + super("error.msg.glaccount.attached.to.product", "General Ledger Account is already attached to product."); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountDuplicateException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountDuplicateException.java old mode 100755 new mode 100644 index 94188df8a..fb9b831b3 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountDuplicateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountDuplicateException.java @@ -30,4 +30,4 @@ public class GLAccountDuplicateException extends AbstractPlatformDomainRuleExcep super("error.msg.glaccount.glcode.duplicate", "General Ledger Account with GL code " + glCode + " is already present", glCode); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidClassificationException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidClassificationException.java old mode 100755 new mode 100644 index b4d6a2be6..dce9a7e5c --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidClassificationException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidClassificationException.java @@ -29,4 +29,4 @@ public class GLAccountInvalidClassificationException extends AbstractPlatformDom public GLAccountInvalidClassificationException(final Integer usage) { super("error.msg.glaccount.usage.invalid", "The following COA usage is invalid: " + usage); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidDeleteException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidDeleteException.java old mode 100755 new mode 100644 index e74308df4..efd53a25b --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidDeleteException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidDeleteException.java @@ -28,19 +28,24 @@ public class GLAccountInvalidDeleteException extends AbstractPlatformDomainRuleE /*** Enum of reasons for invalid delete **/ public static enum GlAccountInvalidDeleteReason { + TRANSANCTIONS_LOGGED, HAS_CHILDREN; public String errorMessage() { if (name().toString().equalsIgnoreCase("TRANSANCTIONS_LOGGED")) { return "This GL Account cannot be deleted as it has transactions logged against it"; - } else if (name().toString().equalsIgnoreCase("HAS_CHILDREN")) { return "Cannot delete this Header GL Account without first deleting or reassinging its children"; } + } else if (name().toString().equalsIgnoreCase("HAS_CHILDREN")) { + return "Cannot delete this Header GL Account without first deleting or reassinging its children"; + } return name().toString(); } public String errorCode() { if (name().toString().equalsIgnoreCase("TRANSANCTIONS_LOGGED")) { return "error.msg.glaccount.glcode.invalid.delete.transactions.logged"; - } else if (name().toString().equalsIgnoreCase("HAS_CHILDREN")) { return "error.msg.glaccount.glcode.invalid.delete.has.children"; } + } else if (name().toString().equalsIgnoreCase("HAS_CHILDREN")) { + return "error.msg.glaccount.glcode.invalid.delete.has.children"; + } return name().toString(); } } @@ -48,4 +53,4 @@ public class GLAccountInvalidDeleteException extends AbstractPlatformDomainRuleE public GLAccountInvalidDeleteException(final GlAccountInvalidDeleteReason reason, final Long glAccountId) { super(reason.errorCode(), reason.errorMessage(), glAccountId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidParentException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidParentException.java old mode 100755 new mode 100644 index 34af779b9..e541d9c51 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidParentException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidParentException.java @@ -27,7 +27,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class GLAccountInvalidParentException extends AbstractPlatformDomainRuleException { public GLAccountInvalidParentException(final long glAccountId) { - super("error.msg.glaccount.parent.invalid", "The account with id " + glAccountId - + " is a 'Detail' account and cannot be used as a parent", glAccountId); + super("error.msg.glaccount.parent.invalid", + "The account with id " + glAccountId + " is a 'Detail' account and cannot be used as a parent", glAccountId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidUpdateException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidUpdateException.java old mode 100755 new mode 100644 index 2582345bd..1c88da238 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidUpdateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidUpdateException.java @@ -28,15 +28,20 @@ public class GLAccountInvalidUpdateException extends AbstractPlatformDomainRuleE /*** Enum of reasons for invalid delete **/ public static enum GlAccountInvalidUpdateReason { + TRANSANCTIONS_LOGGED; public String errorMessage() { - if (name().toString().equalsIgnoreCase("TRANSANCTIONS_LOGGED")) { return "This Usage of this (detail) GL Account as it already has transactions logged against it"; } + if (name().toString().equalsIgnoreCase("TRANSANCTIONS_LOGGED")) { + return "This Usage of this (detail) GL Account as it already has transactions logged against it"; + } return name().toString(); } public String errorCode() { - if (name().toString().equalsIgnoreCase("TRANSANCTIONS_LOGGED")) { return "error.msg.glaccount.glcode.invalid.update.transactions.logged"; } + if (name().toString().equalsIgnoreCase("TRANSANCTIONS_LOGGED")) { + return "error.msg.glaccount.glcode.invalid.update.transactions.logged"; + } return name().toString(); } } @@ -44,4 +49,4 @@ public class GLAccountInvalidUpdateException extends AbstractPlatformDomainRuleE public GLAccountInvalidUpdateException(final GlAccountInvalidUpdateReason reason, final Long glAccountId) { super(reason.errorCode(), reason.errorMessage(), glAccountId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidUsageException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidUsageException.java old mode 100755 new mode 100644 index 724f8d98f..b13f3fb63 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidUsageException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountInvalidUsageException.java @@ -29,4 +29,4 @@ public class GLAccountInvalidUsageException extends AbstractPlatformDomainRuleEx public GLAccountInvalidUsageException(final Integer type) { super("error.msg.glaccount.classification.invalid", "The following COA type is invalid: " + type); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountNotFoundException.java old mode 100755 new mode 100644 index 0262cec24..9e4d63ccf --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/exception/GLAccountNotFoundException.java @@ -28,4 +28,4 @@ public class GLAccountNotFoundException extends AbstractPlatformResourceNotFound public GLAccountNotFoundException(final Long id) { super("error.msg.glaccount.id.invalid", "General Ledger account with identifier " + id + " does not exist ", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/CreateGLAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/CreateGLAccountCommandHandler.java old mode 100755 new mode 100644 index 90d8a5445..8231a5f04 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/CreateGLAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/CreateGLAccountCommandHandler.java @@ -44,4 +44,4 @@ public class CreateGLAccountCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createGLAccount(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/DeleteGLAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/DeleteGLAccountCommandHandler.java old mode 100755 new mode 100644 index 859d38c01..37ddee545 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/DeleteGLAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/DeleteGLAccountCommandHandler.java @@ -43,4 +43,4 @@ public class DeleteGLAccountCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.deleteGLAccount(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/UpdateGLAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/UpdateGLAccountCommandHandler.java old mode 100755 new mode 100644 index 9112b35fc..21e2d74f5 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/UpdateGLAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/handler/UpdateGLAccountCommandHandler.java @@ -43,4 +43,4 @@ public class UpdateGLAccountCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.updateGLAccount(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/serialization/GLAccountCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/serialization/GLAccountCommandFromApiJsonDeserializer.java old mode 100755 new mode 100644 index 90f66a23e..f9a281491 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/serialization/GLAccountCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/serialization/GLAccountCommandFromApiJsonDeserializer.java @@ -63,8 +63,8 @@ public final class GLAccountCommandFromApiJsonDeserializer extends AbstractFromA final Long parentId = this.fromApiJsonHelper.extractLongNamed(GLAccountJsonInputParams.PARENT_ID.getValue(), element); final String glCode = this.fromApiJsonHelper.extractStringNamed(GLAccountJsonInputParams.GL_CODE.getValue(), element); final Boolean disabled = this.fromApiJsonHelper.extractBooleanNamed(GLAccountJsonInputParams.DISABLED.getValue(), element); - final Boolean manualEntriesAllowed = this.fromApiJsonHelper.extractBooleanNamed( - GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED.getValue(), element); + final Boolean manualEntriesAllowed = this.fromApiJsonHelper + .extractBooleanNamed(GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED.getValue(), element); final Integer type = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(GLAccountJsonInputParams.TYPE.getValue(), element); final Integer usage = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(GLAccountJsonInputParams.USAGE.getValue(), element); final String description = this.fromApiJsonHelper.extractStringNamed(GLAccountJsonInputParams.DESCRIPTION.getValue(), element); @@ -72,4 +72,4 @@ public final class GLAccountCommandFromApiJsonDeserializer extends AbstractFromA return new GLAccountCommand(id, name, parentId, glCode, disabled, manualEntriesAllowed, type, usage, description, tagId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountReadPlatformService.java index 62dcd38c2..91838ecc3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountReadPlatformService.java @@ -40,4 +40,4 @@ public interface GLAccountReadPlatformService { GLAccountData retrieveNewGLAccountDetails(final Integer type); List retrieveAccountsByTagId(final Long ruleId, final Integer transactionType); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountReadPlatformServiceImpl.java old mode 100755 new mode 100644 index d6fb88747..20a9139da --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountReadPlatformServiceImpl.java @@ -110,9 +110,12 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe @Override public List retrieveAllGLAccounts(final Integer accountClassification, final String searchParam, final Integer usage, - final Boolean manualTransactionsAllowed, final Boolean disabled, JournalEntryAssociationParametersData associationParametersData) { + final Boolean manualTransactionsAllowed, final Boolean disabled, + JournalEntryAssociationParametersData associationParametersData) { if (accountClassification != null) { - if (!checkValidGLAccountType(accountClassification)) { throw new GLAccountInvalidClassificationException(accountClassification); } + if (!checkValidGLAccountType(accountClassification)) { + throw new GLAccountInvalidClassificationException(accountClassification); + } } if (usage != null) { @@ -122,7 +125,7 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe final GLAccountMapper rm = new GLAccountMapper(associationParametersData); String sql = "select " + rm.schema(); // append SQL statement for fetching account totals - if (associationParametersData!=null) { + if (associationParametersData != null) { if (associationParametersData.isRunningBalanceRequired()) { sql = sql + " and gl_j.id in (select t1.id from (select t2.account_id, max(t2.id) as id from " + "(select id, max(entry_date) as entry_date, account_id from acc_gl_journal_entry where is_running_balance_calculated = 1 " @@ -133,8 +136,8 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe final Object[] paramaterArray = new Object[3]; int arrayPos = 0; boolean filtersPresent = false; - if ((accountClassification != null) || StringUtils.isNotBlank(searchParam) || (usage != null) - || (manualTransactionsAllowed != null) || (disabled != null)) { + if ((accountClassification != null) || StringUtils.isNotBlank(searchParam) || (usage != null) || (manualTransactionsAllowed != null) + || (disabled != null)) { filtersPresent = true; sql += " where"; } @@ -195,7 +198,7 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe } } - sql+=" ORDER BY gl_code ASC"; + sql += " ORDER BY gl_code ASC"; final Object[] finalObjectArray = Arrays.copyOf(paramaterArray, arrayPos); return this.jdbcTemplate.query(sql, rm, finalObjectArray); @@ -231,7 +234,8 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe @Override public List retrieveAllEnabledDetailGLAccounts() { - return retrieveAllGLAccounts(null, null, GLAccountUsage.DETAIL.getValue(), null, false, new JournalEntryAssociationParametersData()); + return retrieveAllGLAccounts(null, null, GLAccountUsage.DETAIL.getValue(), null, false, + new JournalEntryAssociationParametersData()); } private static boolean checkValidGLAccountType(final int type) { @@ -281,4 +285,4 @@ public class GLAccountReadPlatformServiceImpl implements GLAccountReadPlatformSe } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountWritePlatformServiceJpaRepositoryImpl.java index 8e68984e5..5e2a52d78 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/glaccount/service/GLAccountWritePlatformServiceJpaRepositoryImpl.java @@ -120,11 +120,8 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount try { final GLAccountCommand accountCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json()); accountCommand.validateForUpdate(); - if (command.hasParameter(GLAccountJsonInputParams.DISABLED - .getValue()) - && command - .booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.DISABLED - .getValue())) { + if (command.hasParameter(GLAccountJsonInputParams.DISABLED.getValue()) + && command.booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.DISABLED.getValue())) { validateForAttachedProduct(glAccountId); } final Long parentId = command.longValueOfParameterNamed(GLAccountJsonInputParams.PARENT_ID.getValue()); @@ -159,8 +156,9 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount if (glAccount.isHeaderAccount()) { final List journalEntriesForAccount = this.glJournalEntryRepository .findFirstJournalEntryForAccount(glAccountId); - if (journalEntriesForAccount.size() > 0) { throw new GLAccountInvalidUpdateException( - GlAccountInvalidUpdateReason.TRANSANCTIONS_LOGGED, glAccountId); } + if (journalEntriesForAccount.size() > 0) { + throw new GLAccountInvalidUpdateException(GlAccountInvalidUpdateReason.TRANSANCTIONS_LOGGED, glAccountId); + } } } @@ -168,8 +166,8 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount this.glAccountRepository.saveAndFlush(glAccount); } - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(glAccount.getId()) - .with(changesOnly).build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(glAccount.getId()).with(changesOnly) + .build(); } catch (final DataIntegrityViolationException dve) { handleGLAccountDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); @@ -180,11 +178,9 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount String sql = "select count(*) from acc_product_mapping acc where acc.gl_account_id = ?"; try { int count = this.jdbcTemplate.queryForObject(sql, Integer.class, glAccountId); - if (count > 0) { - throw new GLAccountDisableException(); - } + if (count > 0) { throw new GLAccountDisableException(); } } catch (EmptyResultDataAccessException e) { - LOG.error("Problem encountered in validateForAttachedProduct()",e); + LOG.error("Problem encountered in validateForAttachedProduct()", e); } } @@ -195,13 +191,15 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount .orElseThrow(() -> new GLAccountNotFoundException(glAccountId)); // validate this isn't a header account that has children - if (glAccount.isHeaderAccount() && glAccount.getChildren().size() > 0) { throw new GLAccountInvalidDeleteException( - GlAccountInvalidDeleteReason.HAS_CHILDREN, glAccountId); } + if (glAccount.isHeaderAccount() && glAccount.getChildren().size() > 0) { + throw new GLAccountInvalidDeleteException(GlAccountInvalidDeleteReason.HAS_CHILDREN, glAccountId); + } // does this account have transactions logged against it final List journalEntriesForAccount = this.glJournalEntryRepository.findFirstJournalEntryForAccount(glAccountId); - if (journalEntriesForAccount.size() > 0) { throw new GLAccountInvalidDeleteException( - GlAccountInvalidDeleteReason.TRANSANCTIONS_LOGGED, glAccountId); } + if (journalEntriesForAccount.size() > 0) { + throw new GLAccountInvalidDeleteException(GlAccountInvalidDeleteReason.TRANSANCTIONS_LOGGED, glAccountId); + } this.glAccountRepository.delete(glAccount); return new CommandProcessingResultBuilder().withEntityId(glAccountId).build(); @@ -241,20 +239,20 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount private CodeValue retrieveTagId(final Long tagId, final GLAccountType accountType) { CodeValue glAccountTagType = null; if (accountType.isAssetType()) { - glAccountTagType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( - AccountingConstants.ASSESTS_TAG_OPTION_CODE_NAME, tagId); + glAccountTagType = this.codeValueRepositoryWrapper + .findOneByCodeNameAndIdWithNotFoundDetection(AccountingConstants.ASSESTS_TAG_OPTION_CODE_NAME, tagId); } else if (accountType.isLiabilityType()) { - glAccountTagType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( - AccountingConstants.LIABILITIES_TAG_OPTION_CODE_NAME, tagId); + glAccountTagType = this.codeValueRepositoryWrapper + .findOneByCodeNameAndIdWithNotFoundDetection(AccountingConstants.LIABILITIES_TAG_OPTION_CODE_NAME, tagId); } else if (accountType.isEquityType()) { - glAccountTagType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( - AccountingConstants.EQUITY_TAG_OPTION_CODE_NAME, tagId); + glAccountTagType = this.codeValueRepositoryWrapper + .findOneByCodeNameAndIdWithNotFoundDetection(AccountingConstants.EQUITY_TAG_OPTION_CODE_NAME, tagId); } else if (accountType.isIncomeType()) { - glAccountTagType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( - AccountingConstants.INCOME_TAG_OPTION_CODE_NAME, tagId); + glAccountTagType = this.codeValueRepositoryWrapper + .findOneByCodeNameAndIdWithNotFoundDetection(AccountingConstants.INCOME_TAG_OPTION_CODE_NAME, tagId); } else if (accountType.isExpenseType()) { - glAccountTagType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( - AccountingConstants.EXPENSES_TAG_OPTION_CODE_NAME, tagId); + glAccountTagType = this.codeValueRepositoryWrapper + .findOneByCodeNameAndIdWithNotFoundDetection(AccountingConstants.EXPENSES_TAG_OPTION_CODE_NAME, tagId); } return glAccountTagType; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntriesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntriesApiResource.java old mode 100755 new mode 100644 index 9887bbce7..ccbe09569 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntriesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntriesApiResource.java @@ -73,16 +73,16 @@ import org.springframework.stereotype.Component; @Path("/journalentries") @Component @Scope("singleton") -@Api(tags = {"Journal Entries"}) +@Api(tags = { "Journal Entries" }) @SwaggerDefinition(tags = { - @Tag(name = "Journal Entries", description = "A journal entry refers to the logging of transactions against general ledger accounts. A journal entry may consist of several line items, each of which is either a \"debit\" or a \"credit\". The total amount of the debits must equal the total amount of the credits or the journal entry is said to be \"unbalanced\" \n" + "\n" + "A journal entry directly changes the account balances on the general ledger") -}) + @Tag(name = "Journal Entries", description = "A journal entry refers to the logging of transactions against general ledger accounts. A journal entry may consist of several line items, each of which is either a \"debit\" or a \"credit\". The total amount of the debits must equal the total amount of the credits or the journal entry is said to be \"unbalanced\" \n" + + "\n" + "A journal entry directly changes the account balances on the general ledger") }) public class JournalEntriesApiResource { - private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "officeId", "officeName", - "glAccountName", "glAccountId", "glAccountCode", "glAccountType", "transactionDate", "entryType", "amount", "transactionId", - "manualEntry", "entityType", "entityId", "createdByUserId", "createdDate", "createdByUserName", "comments", "reversed", - "referenceNumber", "currency", "transactionDetails")); + private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "officeId", "officeName", "glAccountName", "glAccountId", "glAccountCode", "glAccountType", + "transactionDate", "entryType", "amount", "transactionId", "manualEntry", "entityType", "entityId", "createdByUserId", + "createdDate", "createdByUserName", "comments", "reversed", "referenceNumber", "currency", "transactionDetails")); private final String resourceNameForPermission = "JOURNALENTRY"; @@ -94,7 +94,6 @@ public class JournalEntriesApiResource { private final BulkImportWorkbookService bulkImportWorkbookService; private final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService; - @Autowired public JournalEntriesApiResource(final PlatformSecurityContext context, final JournalEntryReadPlatformService journalEntryReadPlatformService, @@ -107,24 +106,37 @@ public class JournalEntriesApiResource { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; this.apiJsonSerializerService = toApiJsonSerializer; this.journalEntryReadPlatformService = journalEntryReadPlatformService; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; } @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Journal Entries", notes = "The list capability of journal entries can support pagination and sorting.\n\n" + "Example Requests:\n" + "\n" + "journalentries\n" + "\n" + "journalentries?transactionId=PB37X8Y21EQUY4S\n" + "\n" + "journalentries?officeId=1&manualEntriesOnly=true&fromDate=1 July 2013&toDate=15 July 2013&dateFormat=dd MMMM yyyy&locale=en\n" + "\n" + "journalentries?fields=officeName,glAccountName,transactionDate\n" + "\n" + "journalentries?offset=10&limit=50\n" + "\n" + "journalentries?orderBy=transactionId&sortOrder=DESC\n" + "\n" + "journalentries?runningBalance=true\n" + "\n" + "journalentries?transactionDetails=true\n" + "\n" + "journalentries?loanId=12\n" + "\n" + "journalentries?savingsId=24") - @ApiResponses({@ApiResponse(code = 200, message = "", response = JournalEntryData.class, responseContainer = "list")}) + @ApiOperation(value = "List Journal Entries", notes = "The list capability of journal entries can support pagination and sorting.\n\n" + + "Example Requests:\n" + "\n" + "journalentries\n" + "\n" + "journalentries?transactionId=PB37X8Y21EQUY4S\n" + "\n" + + "journalentries?officeId=1&manualEntriesOnly=true&fromDate=1 July 2013&toDate=15 July 2013&dateFormat=dd MMMM yyyy&locale=en\n" + + "\n" + "journalentries?fields=officeName,glAccountName,transactionDate\n" + "\n" + "journalentries?offset=10&limit=50\n" + + "\n" + "journalentries?orderBy=transactionId&sortOrder=DESC\n" + "\n" + "journalentries?runningBalance=true\n" + "\n" + + "journalentries?transactionDetails=true\n" + "\n" + "journalentries?loanId=12\n" + "\n" + "journalentries?savingsId=24") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = JournalEntryData.class, responseContainer = "list") }) public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, - @QueryParam("glAccountId") @ApiParam(value = "glAccountId") final Long glAccountId, @QueryParam("manualEntriesOnly") @ApiParam(value = "manualEntriesOnly") final Boolean onlyManualEntries, - @QueryParam("fromDate") @ApiParam(value = "fromDate") final DateParam fromDateParam, @QueryParam("toDate") @ApiParam(value = "toDate") final DateParam toDateParam, - @QueryParam("transactionId") @ApiParam(value = "transactionId") final String transactionId, @QueryParam("entityType") @ApiParam(value = "entityType") final Integer entityType, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, - @QueryParam("locale") @ApiParam(value = "locale") final String locale, @QueryParam("dateFormat") @ApiParam(value = "dateFormat") final String dateFormat, - @QueryParam("loanId") @ApiParam(value = "loanId") final Long loanId, @QueryParam("savingsId") @ApiParam(value = "savingsId") final Long savingsId, - @QueryParam("runningBalance") @ApiParam(value = "runningBalance") final boolean runningBalance, @QueryParam("transactionDetails") @ApiParam(value = "transactionDetails") final boolean transactionDetails) { + @QueryParam("glAccountId") @ApiParam(value = "glAccountId") final Long glAccountId, + @QueryParam("manualEntriesOnly") @ApiParam(value = "manualEntriesOnly") final Boolean onlyManualEntries, + @QueryParam("fromDate") @ApiParam(value = "fromDate") final DateParam fromDateParam, + @QueryParam("toDate") @ApiParam(value = "toDate") final DateParam toDateParam, + @QueryParam("transactionId") @ApiParam(value = "transactionId") final String transactionId, + @QueryParam("entityType") @ApiParam(value = "entityType") final Integer entityType, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, + @QueryParam("locale") @ApiParam(value = "locale") final String locale, + @QueryParam("dateFormat") @ApiParam(value = "dateFormat") final String dateFormat, + @QueryParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @QueryParam("savingsId") @ApiParam(value = "savingsId") final Long savingsId, + @QueryParam("runningBalance") @ApiParam(value = "runningBalance") final boolean runningBalance, + @QueryParam("transactionDetails") @ApiParam(value = "transactionDetails") final boolean transactionDetails) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); @@ -152,10 +164,13 @@ public class JournalEntriesApiResource { @Path("{journalEntryId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a single Entry", notes = "Example Requests:\n" + "\n" + "journalentries/1\n" + "\n" + "\n" + "\n" + "journalentries/1?fields=officeName,glAccountId,entryType,amount\n" + "\n" + "journalentries/1?runningBalance=true\n" + "\n" + "journalentries/1?transactionDetails=true") - @ApiResponses({@ApiResponse(code = 200, message = "", response = JournalEntryData.class)}) - public String retreiveJournalEntryById(@PathParam("journalEntryId") @ApiParam(value = "journalEntryId") final Long journalEntryId, @Context final UriInfo uriInfo, - @QueryParam("runningBalance") @ApiParam(value = "runningBalance") final boolean runningBalance, @QueryParam("transactionDetails") @ApiParam(value = "transactionDetails") final boolean transactionDetails) { + @ApiOperation(value = "Retrieve a single Entry", notes = "Example Requests:\n" + "\n" + "journalentries/1\n" + "\n" + "\n" + "\n" + + "journalentries/1?fields=officeName,glAccountId,entryType,amount\n" + "\n" + "journalentries/1?runningBalance=true\n" + "\n" + + "journalentries/1?transactionDetails=true") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = JournalEntryData.class) }) + public String retreiveJournalEntryById(@PathParam("journalEntryId") @ApiParam(value = "journalEntryId") final Long journalEntryId, + @Context final UriInfo uriInfo, @QueryParam("runningBalance") @ApiParam(value = "runningBalance") final boolean runningBalance, + @QueryParam("transactionDetails") @ApiParam(value = "transactionDetails") final boolean transactionDetails) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(transactionDetails, @@ -170,10 +185,16 @@ public class JournalEntriesApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create \"Balanced\" Journal Entries", notes = "Note: A Balanced (simple) Journal entry would have atleast one \"Debit\" and one \"Credit\" entry whose amounts are equal \n" + "Compound Journal entries may have \"n\" debits and \"m\" credits where both \"m\" and \"n\" are greater than 0 and the net sum or all debits and credits are equal \n\n" + "\n" + "Mandatory Fields\n" + "officeId, transactionDate\n\n" + "\ncredits- glAccountId, amount, comments\n\n " + "\ndebits- glAccountId, amount, comments\n\n " + "\n" + "Optional Fields\n" + "paymentTypeId, accountNumber, checkNumber, routingCode, receiptNumber, bankNumber") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = JournalEntryCommand.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = JournalEntriesApiResourceSwagger.PostJournalEntriesResponse.class)}) - public String createGLJournalEntry(@ApiParam(hidden = true) final String jsonRequestBody, @QueryParam("command") @ApiParam(value = "command") final String commandParam) { + @ApiOperation(value = "Create \"Balanced\" Journal Entries", notes = "Note: A Balanced (simple) Journal entry would have atleast one \"Debit\" and one \"Credit\" entry whose amounts are equal \n" + + "Compound Journal entries may have \"n\" debits and \"m\" credits where both \"m\" and \"n\" are greater than 0 and the net sum or all debits and credits are equal \n\n" + + "\n" + "Mandatory Fields\n" + "officeId, transactionDate\n\n" + "\ncredits- glAccountId, amount, comments\n\n " + + "\ndebits- glAccountId, amount, comments\n\n " + "\n" + "Optional Fields\n" + + "paymentTypeId, accountNumber, checkNumber, routingCode, receiptNumber, bankNumber") + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = JournalEntryCommand.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = JournalEntriesApiResourceSwagger.PostJournalEntriesResponse.class) }) + public String createGLJournalEntry(@ApiParam(hidden = true) final String jsonRequestBody, + @QueryParam("command") @ApiParam(value = "command") final String commandParam) { CommandProcessingResult result = null; if (is(commandParam, "updateRunningBalance")) { @@ -195,10 +216,14 @@ public class JournalEntriesApiResource { @Path("{transactionId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Update Running balances for Journal Entries", notes = "This API calculates the running balances for office. If office ID not provided this API calculates running balances for all offices. \n" + "Mandatory Fields\n" + "officeId") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = JournalEntriesApiResourceSwagger.PostJournalEntriesTransactionIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = JournalEntriesApiResourceSwagger.PostJournalEntriesTransactionIdResponse.class)}) - public String createReversalJournalEntry(@ApiParam(hidden = true) final String jsonRequestBody, @PathParam("transactionId") @ApiParam(value = "transactionId") final String transactionId, + @ApiOperation(value = "Update Running balances for Journal Entries", notes = "This API calculates the running balances for office. If office ID not provided this API calculates running balances for all offices. \n" + + "Mandatory Fields\n" + "officeId") + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = JournalEntriesApiResourceSwagger.PostJournalEntriesTransactionIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = JournalEntriesApiResourceSwagger.PostJournalEntriesTransactionIdResponse.class) }) + public String createReversalJournalEntry(@ApiParam(hidden = true) final String jsonRequestBody, + @PathParam("transactionId") @ApiParam(value = "transactionId") final String transactionId, @QueryParam("command") @ApiParam(value = "command") final String commandParam) { CommandProcessingResult result = null; if (is(commandParam, "reverse")) { @@ -219,14 +244,14 @@ public class JournalEntriesApiResource { public String retrieveJournalEntries(@QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, @QueryParam("entryId") final Long entryId, @Context final UriInfo uriInfo) { this.context.authenticatedUser(); - String transactionId = "P"+entryId ; - SearchParameters params = SearchParameters.forPagination(offset, limit) ; - Page entries = this.journalEntryReadPlatformService.retrieveAll(params, null, null, null, null, transactionId, PortfolioProductType.PROVISIONING.getValue(), null) ; + String transactionId = "P" + entryId; + SearchParameters params = SearchParameters.forPagination(offset, limit); + Page entries = this.journalEntryReadPlatformService.retrieveAll(params, null, null, null, null, transactionId, + PortfolioProductType.PROVISIONING.getValue(), null); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.apiJsonSerializerService.serialize(settings, entries, RESPONSE_DATA_PARAMETERS); } - @GET @Path("openingbalance") @Consumes({ MediaType.APPLICATION_JSON }) @@ -235,8 +260,8 @@ public class JournalEntriesApiResource { @QueryParam("currencyCode") final String currencyCode) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); - final OfficeOpeningBalancesData officeOpeningBalancesData = this.journalEntryReadPlatformService.retrieveOfficeOpeningBalances( - officeId, currencyCode); + final OfficeOpeningBalancesData officeOpeningBalancesData = this.journalEntryReadPlatformService + .retrieveOfficeOpeningBalances(officeId, currencyCode); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.apiJsonSerializerService.serialize(settings, officeOpeningBalancesData); } @@ -250,19 +275,17 @@ public class JournalEntriesApiResource { @Produces("application/vnd.ms-excel") public Response getJournalEntriesTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.GL_JOURNAL_ENTRIES.toString(), - officeId,null,dateFormat); + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.GL_JOURNAL_ENTRIES.toString(), officeId, null, dateFormat); } @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postJournalEntriesTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, - @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId =this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.GL_JOURNAL_ENTRIES.toString(), - uploadedInputStream,fileDetail, locale,dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.GL_JOURNAL_ENTRIES.toString(), + uploadedInputStream, fileDetail, locale, dateFormat); return this.apiJsonSerializerService.serialize(importDocumentId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntriesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntriesApiResourceSwagger.java index de91a8595..86b09db53 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntriesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntriesApiResourceSwagger.java @@ -25,14 +25,16 @@ import io.swagger.annotations.ApiModelProperty; * Created by sanyam on 25/7/17. */ final class JournalEntriesApiResourceSwagger { - private JournalEntriesApiResourceSwagger(){} + + private JournalEntriesApiResourceSwagger() {} @ApiModel(value = "PostJournalEntriesResponse") public static final class PostJournalEntriesResponse { - private PostJournalEntriesResponse(){ + private PostJournalEntriesResponse() { } + @ApiModelProperty(value = "1") public Long officeId; @ApiModelProperty(value = "RS9MCISID4WK1ZM") @@ -42,18 +44,22 @@ final class JournalEntriesApiResourceSwagger { @ApiModel(value = "PostJournalEntriesTransactionIdRequest") public static final class PostJournalEntriesTransactionIdRequest { + private PostJournalEntriesTransactionIdRequest() { } + @ApiModelProperty(value = "1") public Long officeId; } @ApiModel(value = "PostJournalEntriesTransactionIdResponse") public static final class PostJournalEntriesTransactionIdResponse { + private PostJournalEntriesTransactionIdResponse() { } + @ApiModelProperty(value = "1") public Long officeId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntryJsonInputParams.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntryJsonInputParams.java old mode 100755 new mode 100644 index 95a7e2716..8aabf4446 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntryJsonInputParams.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/api/JournalEntryJsonInputParams.java @@ -25,10 +25,12 @@ import java.util.Set; * Enum of all parameters passed in while creating/updating a journal Entry ***/ public enum JournalEntryJsonInputParams { - OFFICE_ID("officeId"), TRANSACTION_DATE("transactionDate"), COMMENTS("comments"), CREDITS("credits"), DEBITS("debits"), LOCALE("locale"), DATE_FORMAT( - "dateFormat"), REFERENCE_NUMBER("referenceNumber"), USE_ACCOUNTING_RULE("useAccountingRule"), ACCOUNTING_RULE("accountingRule"), AMOUNT( - "amount"), CURRENCY_CODE("currencyCode"), PAYMENT_TYPE_ID("paymentTypeId"), ACCOUNT_NUMBER("accountNumber"), CHECK_NUMBER( - "checkNumber"), ROUTING_CODE("routingCode"), RECEIPT_NUMBER("receiptNumber"), BANK_NUMBER("bankNumber"); + + OFFICE_ID("officeId"), TRANSACTION_DATE("transactionDate"), COMMENTS("comments"), CREDITS("credits"), DEBITS("debits"), LOCALE( + "locale"), DATE_FORMAT("dateFormat"), REFERENCE_NUMBER("referenceNumber"), USE_ACCOUNTING_RULE( + "useAccountingRule"), ACCOUNTING_RULE("accountingRule"), AMOUNT("amount"), CURRENCY_CODE( + "currencyCode"), PAYMENT_TYPE_ID("paymentTypeId"), ACCOUNT_NUMBER("accountNumber"), CHECK_NUMBER( + "checkNumber"), ROUTING_CODE("routingCode"), RECEIPT_NUMBER("receiptNumber"), BANK_NUMBER("bankNumber"); private final String value; @@ -55,4 +57,4 @@ public enum JournalEntryJsonInputParams { public String getValue() { return this.value; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/command/JournalEntryCommand.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/command/JournalEntryCommand.java old mode 100755 new mode 100644 index 8640c7ab1..ef16c3b6e --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/command/JournalEntryCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/command/JournalEntryCommand.java @@ -123,8 +123,10 @@ public class JournalEntryCommand { } baseDataValidator.reset().parameter("amount").value(this.amount).ignoreIfNull().zeroOrPositiveAmount(); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } /** @@ -168,4 +170,4 @@ public class JournalEntryCommand { return this.accountingRuleId; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/command/SingleDebitOrCreditEntryCommand.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/command/SingleDebitOrCreditEntryCommand.java old mode 100755 new mode 100644 index fe972e82d..4ff4393ff --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/command/SingleDebitOrCreditEntryCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/command/SingleDebitOrCreditEntryCommand.java @@ -68,4 +68,4 @@ public class SingleDebitOrCreditEntryCommand { return this.parametersPassedInRequest; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/CreditDebit.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/CreditDebit.java index 0be9f1a2e..7bc18bc64 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/CreditDebit.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/CreditDebit.java @@ -21,6 +21,7 @@ package org.apache.fineract.accounting.journalentry.data; import java.math.BigDecimal; public class CreditDebit { + private final Long glAccountId; private final BigDecimal amount; diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/JournalEntryData.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/JournalEntryData.java old mode 100755 new mode 100644 index 295bf92ec..347ae8802 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/JournalEntryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/JournalEntryData.java @@ -78,7 +78,7 @@ public class JournalEntryData { @SuppressWarnings("unused") private final TransactionDetailData transactionDetails; - //import fields + // import fields private transient Integer rowIndex; private String dateFormat; private String locale; @@ -92,34 +92,32 @@ public class JournalEntryData { private String receiptNumber; private String bankNumber; - public static JournalEntryData importInstance(Long officeId,LocalDate transactionDate,String currencyCode, Long paymentTypeId, - Integer rowIndex,List credits, Listdebits, - String accountNumber,String checkNumber,String routingCode,String receiptNumber,String bankNumber, - String comments,String locale,String dateFormat){ - return new JournalEntryData(officeId, transactionDate, currencyCode, - paymentTypeId, rowIndex, credits, debits,accountNumber,checkNumber,routingCode, - receiptNumber,bankNumber,comments,locale,dateFormat); + public static JournalEntryData importInstance(Long officeId, LocalDate transactionDate, String currencyCode, Long paymentTypeId, + Integer rowIndex, List credits, List debits, String accountNumber, String checkNumber, + String routingCode, String receiptNumber, String bankNumber, String comments, String locale, String dateFormat) { + return new JournalEntryData(officeId, transactionDate, currencyCode, paymentTypeId, rowIndex, credits, debits, accountNumber, + checkNumber, routingCode, receiptNumber, bankNumber, comments, locale, dateFormat); } - private JournalEntryData(Long officeId,LocalDate transactionDate,String currencyCode, Long paymentTypeId, - Integer rowIndex,List credits, Listdebits, - String accountNumber,String checkNumber,String routingCode,String receiptNumber, - String bankNumber,String comments,String locale,String dateFormat) { + + private JournalEntryData(Long officeId, LocalDate transactionDate, String currencyCode, Long paymentTypeId, Integer rowIndex, + List credits, List debits, String accountNumber, String checkNumber, String routingCode, + String receiptNumber, String bankNumber, String comments, String locale, String dateFormat) { this.officeId = officeId; - this.dateFormat= dateFormat; - this.locale= locale; + this.dateFormat = dateFormat; + this.locale = locale; this.transactionDate = transactionDate; - this.currencyCode=currencyCode; + this.currencyCode = currencyCode; this.rowIndex = rowIndex; this.credits = credits; this.debits = debits; this.paymentTypeId = paymentTypeId; - this.accountNumber=accountNumber; - this.checkNumber=checkNumber; - this.routingCode=routingCode; - this.receiptNumber=receiptNumber; - this.bankNumber=bankNumber; - this.comments=comments; + this.accountNumber = accountNumber; + this.checkNumber = checkNumber; + this.routingCode = routingCode; + this.receiptNumber = receiptNumber; + this.bankNumber = bankNumber; + this.comments = comments; this.id = null; this.officeName = null; this.glAccountName = null; @@ -157,19 +155,17 @@ public class JournalEntryData { this.debits.add(debit); } - - public void addCredits(CreditDebit credit) { this.credits.add(credit); } - public JournalEntryData(final Long id, final Long officeId, final String officeName, final String glAccountName, - final Long glAccountId, final String glAccountCode, final EnumOptionData glAccountClassification, - final LocalDate transactionDate, final EnumOptionData entryType, final BigDecimal amount, final String transactionId, - final Boolean manualEntry, final EnumOptionData entityType, final Long entityId, final Long createdByUserId, - final LocalDate createdDate, final String createdByUserName, final String comments, final Boolean reversed, - final String referenceNumber, final BigDecimal officeRunningBalance, final BigDecimal organizationRunningBalance, - final Boolean runningBalanceComputed, final TransactionDetailData transactionDetailData, final CurrencyData currency) { + public JournalEntryData(final Long id, final Long officeId, final String officeName, final String glAccountName, final Long glAccountId, + final String glAccountCode, final EnumOptionData glAccountClassification, final LocalDate transactionDate, + final EnumOptionData entryType, final BigDecimal amount, final String transactionId, final Boolean manualEntry, + final EnumOptionData entityType, final Long entityId, final Long createdByUserId, final LocalDate createdDate, + final String createdByUserName, final String comments, final Boolean reversed, final String referenceNumber, + final BigDecimal officeRunningBalance, final BigDecimal organizationRunningBalance, final Boolean runningBalanceComputed, + final TransactionDetailData transactionDetailData, final CurrencyData currency) { this.id = id; this.officeId = officeId; this.officeName = officeName; @@ -257,4 +253,4 @@ public class JournalEntryData { public String getTransactionId() { return transactionId; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/JournalEntryDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/JournalEntryDataValidator.java old mode 100755 new mode 100644 index 1d14658af..5ca7e340d --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/JournalEntryDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/JournalEntryDataValidator.java @@ -60,8 +60,10 @@ public class JournalEntryDataValidator { baseDataValidator.reset().parameter(JournalEntryJsonInputParams.OFFICE_ID.getValue()).value(officeId).ignoreIfNull() .longGreaterThanZero(); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/LoanTransactionDTO.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/LoanTransactionDTO.java old mode 100755 new mode 100644 index e6d8b62c5..e61ffaded --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/LoanTransactionDTO.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/LoanTransactionDTO.java @@ -133,11 +133,11 @@ public class LoanTransactionDTO { return this.isAccountTransfer; } - public void setIsLoanToLoanTransfer(boolean isLoanToLoanTransfer) { - this.isLoanToLoanTransfer = isLoanToLoanTransfer; - } + public void setIsLoanToLoanTransfer(boolean isLoanToLoanTransfer) { + this.isLoanToLoanTransfer = isLoanToLoanTransfer; + } - public boolean isLoanToLoanTransfer(){ - return this.isLoanToLoanTransfer; - } + public boolean isLoanToLoanTransfer() { + return this.isLoanToLoanTransfer; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/TransactionTypeEnumData.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/TransactionTypeEnumData.java index d31025b2a..f2ddffaf7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/TransactionTypeEnumData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/data/TransactionTypeEnumData.java @@ -38,4 +38,4 @@ public class TransactionTypeEnumData { return this.id; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/domain/JournalEntry.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/domain/JournalEntry.java old mode 100755 new mode 100644 index 9949982d0..3aab4a19a --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/domain/JournalEntry.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/domain/JournalEntry.java @@ -173,6 +173,7 @@ public class JournalEntry extends AbstractAuditableCustom { public void setAmount(BigDecimal amount) { this.amount = amount; } + public void setReversalJournalEntry(final JournalEntry reversalJournalEntry) { this.reversalJournalEntry = reversalJournalEntry; } @@ -217,9 +218,8 @@ public class JournalEntry extends AbstractAuditableCustom { return this.entityType; } - public Long getShareTransactionId() { return this.shareTransactionId; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/domain/JournalEntryRepository.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/domain/JournalEntryRepository.java old mode 100755 new mode 100644 index c12fa9de1..8014c64f8 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/domain/JournalEntryRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/domain/JournalEntryRepository.java @@ -24,8 +24,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface JournalEntryRepository extends JpaRepository, JpaSpecificationExecutor, - JournalEntryRepositoryCustom { +public interface JournalEntryRepository + extends JpaRepository, JpaSpecificationExecutor, JournalEntryRepositoryCustom { @Query("select journalEntry from JournalEntry journalEntry where journalEntry.transactionId= :transactionId and journalEntry.reversed=false and journalEntry.manualEntry=true") List findUnReversedManualJournalEntriesByTransactionId(@Param("transactionId") String transactionId); @@ -37,14 +37,22 @@ public interface JournalEntryRepository extends JpaRepository findNonReversedContraTansactionIds(@Param("contraId") Long contraId, @Param("officeId") Long officeId); @Query("select journalEntry from JournalEntry journalEntry where journalEntry.entityId= :entityId and journalEntry.entityType = :entityType") - List findProvisioningJournalEntriesByEntityId(@Param("entityId") Long entityId, @Param("entityType") Integer entityType) ; + List findProvisioningJournalEntriesByEntityId(@Param("entityId") Long entityId, @Param("entityType") Integer entityType); @Query("select journalEntry from JournalEntry journalEntry where journalEntry.transactionId= :transactionId and journalEntry.reversed=false and journalEntry.entityType = :entityType") List findJournalEntries(@Param("transactionId") String transactionId, @Param("entityType") Integer entityType); - /*@Query("select journalEntry from JournalEntry journalEntry where glAccount.id= :accountId and transactionId= :transactionId and transactionDate= :transactionDate" - + " and type= :journalEntryType and entityType=1 and entityId= :loanId and loanTransaction.id= :loanTransactionId") - JournalEntry findLOANJournalEntryWith(@Param("accountId") Long accountId, @Param("transactionId") String transactionId, - @Param("transactionDate") Date transactionDate, @Param("journalEntryType") Integer journalEntryType, - @Param("loanId") Long loanId, @Param("loanTransactionId") Long loanTransactionId);*/ + /* + * @Query("select journalEntry from JournalEntry journalEntry where glAccount.id= :accountId and transactionId= :transactionId and transactionDate= :transactionDate" + * + + * " and type= :journalEntryType and entityType=1 and entityId= :loanId and loanTransaction.id= :loanTransactionId" + * ) JournalEntry findLOANJournalEntryWith(@Param("accountId") Long + * accountId, @Param("transactionId") String transactionId, + * + * @Param("transactionDate") Date + * transactionDate, @Param("journalEntryType") Integer journalEntryType, + * + * @Param("loanId") Long loanId, @Param("loanTransactionId") Long + * loanTransactionId); + */ } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntriesNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntriesNotFoundException.java old mode 100755 new mode 100644 index 5918a8dba..44778e71e --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntriesNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntriesNotFoundException.java @@ -26,11 +26,12 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class JournalEntriesNotFoundException extends AbstractPlatformResourceNotFoundException { public JournalEntriesNotFoundException(final String transactionId) { - super("error.msg.journalEntries.transactionId.invalid", "Journal Entries with transaction Identifier " + transactionId - + " does not exist or are not system generated/reversible ", transactionId); + super("error.msg.journalEntries.transactionId.invalid", + "Journal Entries with transaction Identifier " + transactionId + " does not exist or are not system generated/reversible ", + transactionId); } public JournalEntriesNotFoundException(final Long entryId) { super("error.msg.journalEntries.id.invalid", "Journal Entry with entry Id " + entryId + " does not exist ", entryId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryInvalidException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryInvalidException.java old mode 100755 new mode 100644 index 7cbba1798..94b93b89e --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryInvalidException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryInvalidException.java @@ -28,6 +28,7 @@ public class JournalEntryInvalidException extends AbstractPlatformDomainRuleExce /*** enum of reasons for invalid Journal Entry **/ public static enum GlJournalEntryInvalidReason { + FUTURE_DATE, ACCOUNTING_CLOSED, NO_DEBITS_OR_CREDITS, DEBIT_CREDIT_SUM_MISMATCH_WITH_AMOUNT, DEBIT_CREDIT_SUM_MISMATCH, DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, GL_ACCOUNT_DISABLED, GL_ACCOUNT_MANUAL_ENTRIES_NOT_PERMITTED, INVALID_DEBIT_OR_CREDIT_ACCOUNTS; public String errorMessage() { @@ -47,7 +48,9 @@ public class JournalEntryInvalidException extends AbstractPlatformDomainRuleExce return "Target account has been disabled"; } else if (name().toString().equalsIgnoreCase("INVALID_DEBIT_OR_CREDIT_ACCOUNTS")) { return "Invalid debit or credit accounts are passed"; - } else if (name().toString().equalsIgnoreCase("GL_ACCOUNT_MANUAL_ENTRIES_NOT_PERMITTED")) { return "Target account does not allow maual adjustments"; } + } else if (name().toString().equalsIgnoreCase("GL_ACCOUNT_MANUAL_ENTRIES_NOT_PERMITTED")) { + return "Target account does not allow maual adjustments"; + } return name().toString(); } @@ -66,7 +69,9 @@ public class JournalEntryInvalidException extends AbstractPlatformDomainRuleExce return "error.msg.glJournalEntry.invalid.account.disabled"; } else if (name().toString().equalsIgnoreCase("INVALID_DEBIT_OR_CREDIT_ACCOUNTS")) { return "error.msg.glJournalEntry.invalid.debit.or.credit.accounts"; - } else if (name().toString().equalsIgnoreCase("GL_ACCOUNT_MANUAL_ENTRIES_NOT_PERMITTED")) { return "error.msg.glJournalEntry.invalid.account.manual.adjustments.not.permitted"; } + } else if (name().toString().equalsIgnoreCase("GL_ACCOUNT_MANUAL_ENTRIES_NOT_PERMITTED")) { + return "error.msg.glJournalEntry.invalid.account.manual.adjustments.not.permitted"; + } return name().toString(); } } @@ -75,4 +80,4 @@ public class JournalEntryInvalidException extends AbstractPlatformDomainRuleExce final String accountGLCode) { super(reason.errorCode(), reason.errorMessage(), date, accountName, accountGLCode); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryNotFoundException.java old mode 100755 new mode 100644 index 7a9ddf7c0..5a0086f9e --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryNotFoundException.java @@ -26,11 +26,12 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class JournalEntryNotFoundException extends AbstractPlatformResourceNotFoundException { public JournalEntryNotFoundException(final String transactionId) { - super("error.msg.journalEntries.transactionId.invalid", "Journal Entries with transaction Identifier " + transactionId - + " does not exist or are not system generated/reversible ", transactionId); + super("error.msg.journalEntries.transactionId.invalid", + "Journal Entries with transaction Identifier " + transactionId + " does not exist or are not system generated/reversible ", + transactionId); } public JournalEntryNotFoundException(final Long entryId) { super("error.msg.journalEntries.id.invalid", "Journal Entry with entry Id " + entryId + " does not exist ", entryId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryRuntimeException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryRuntimeException.java index a0fa0a724..28aac3263 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryRuntimeException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/exception/JournalEntryRuntimeException.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.accounting.journalentry.exception; - import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; public class JournalEntryRuntimeException extends AbstractPlatformDomainRuleException { diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/handler/CreateJournalEntryCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/handler/CreateJournalEntryCommandHandler.java old mode 100755 new mode 100644 index 93f5e294e..a5fd88e4e --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/handler/CreateJournalEntryCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/handler/CreateJournalEntryCommandHandler.java @@ -44,4 +44,4 @@ public class CreateJournalEntryCommandHandler implements NewCommandSourceHandler return this.writePlatformService.createJournalEntry(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/handler/ReverseJournalEntryCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/handler/ReverseJournalEntryCommandHandler.java old mode 100755 new mode 100644 index 38a745e8b..b74821c8c --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/handler/ReverseJournalEntryCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/handler/ReverseJournalEntryCommandHandler.java @@ -43,4 +43,4 @@ public class ReverseJournalEntryCommandHandler implements NewCommandSourceHandle public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.revertJournalEntry(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/serialization/JournalEntryCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/serialization/JournalEntryCommandFromApiJsonDeserializer.java old mode 100755 new mode 100644 index 9a89a941b..478473cd9 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/serialization/JournalEntryCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/serialization/JournalEntryCommandFromApiJsonDeserializer.java @@ -65,11 +65,11 @@ public final class JournalEntryCommandFromApiJsonDeserializer extends AbstractFr final JsonElement element = this.fromApiJsonHelper.parse(json); final Long officeId = this.fromApiJsonHelper.extractLongNamed(JournalEntryJsonInputParams.OFFICE_ID.getValue(), element); - final String currencyCode = this.fromApiJsonHelper - .extractStringNamed(JournalEntryJsonInputParams.CURRENCY_CODE.getValue(), element); + final String currencyCode = this.fromApiJsonHelper.extractStringNamed(JournalEntryJsonInputParams.CURRENCY_CODE.getValue(), + element); final String comments = this.fromApiJsonHelper.extractStringNamed(JournalEntryJsonInputParams.COMMENTS.getValue(), element); - final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed( - JournalEntryJsonInputParams.TRANSACTION_DATE.getValue(), element); + final LocalDate transactionDate = this.fromApiJsonHelper + .extractLocalDateNamed(JournalEntryJsonInputParams.TRANSACTION_DATE.getValue(), element); final String referenceNumber = this.fromApiJsonHelper.extractStringNamed(JournalEntryJsonInputParams.REFERENCE_NUMBER.getValue(), element); final Long accountingRuleId = this.fromApiJsonHelper.extractLongNamed(JournalEntryJsonInputParams.ACCOUNTING_RULE.getValue(), @@ -93,7 +93,8 @@ public final class JournalEntryCommandFromApiJsonDeserializer extends AbstractFr if (element.isJsonObject()) { if (topLevelJsonElement.has(JournalEntryJsonInputParams.CREDITS.getValue()) && topLevelJsonElement.get(JournalEntryJsonInputParams.CREDITS.getValue()).isJsonArray()) { - credits = populateCreditsOrDebitsArray(topLevelJsonElement, locale, credits, JournalEntryJsonInputParams.CREDITS.getValue()); + credits = populateCreditsOrDebitsArray(topLevelJsonElement, locale, credits, + JournalEntryJsonInputParams.CREDITS.getValue()); } if (topLevelJsonElement.has(JournalEntryJsonInputParams.DEBITS.getValue()) && topLevelJsonElement.get(JournalEntryJsonInputParams.DEBITS.getValue()).isJsonArray()) { @@ -126,4 +127,4 @@ public final class JournalEntryCommandFromApiJsonDeserializer extends AbstractFr } return debitOrCredits; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/AccountingProcessorHelper.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/AccountingProcessorHelper.java old mode 100755 new mode 100644 index ab44a191b..700668e3a --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/AccountingProcessorHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/AccountingProcessorHelper.java @@ -170,7 +170,7 @@ public class AccountingProcessorHelper { transactionDate, transactionType, amount, principal, interest, fees, penalties, overPayments, reversed, feePaymentDetails, penaltyPaymentDetails, isAccountTransfer); Boolean isLoanToLoanTransfer = (Boolean) accountingBridgeData.get("isLoanToLoanTransfer"); - if(isLoanToLoanTransfer != null && isLoanToLoanTransfer){ + if (isLoanToLoanTransfer != null && isLoanToLoanTransfer) { transaction.setIsLoanToLoanTransfer(true); } else { transaction.setIsLoanToLoanTransfer(false); @@ -323,14 +323,15 @@ public class AccountingProcessorHelper { final boolean isPenalty = (Boolean) clientChargePaid.get("isPenalty"); final BigDecimal chargeAmountPaid = (BigDecimal) clientChargePaid.get("amount"); final Long incomeAccountId = (Long) clientChargePaid.get("incomeAccountId"); - final ClientChargePaymentDTO clientChargePaymentDTO = new ClientChargePaymentDTO(chargeId, chargeAmountPaid, - clientChargeId, isPenalty, incomeAccountId); + final ClientChargePaymentDTO clientChargePaymentDTO = new ClientChargePaymentDTO(chargeId, chargeAmountPaid, clientChargeId, + isPenalty, incomeAccountId); clientChargePaymentDTOs.add(clientChargePaymentDTO); } } final ClientTransactionDTO clientTransactionDTO = new ClientTransactionDTO(clientId, transactionOfficeId, paymentTypeId, - transactionId, transactionDate, transactionType, currencyCode, amount, reversed, accountingEnabled, clientChargePaymentDTOs); + transactionId, transactionDate, transactionType, currencyCode, amount, reversed, accountingEnabled, + clientChargePaymentDTOs); return clientTransactionDTO; @@ -357,9 +358,8 @@ public class AccountingProcessorHelper { * @param isReversal */ public void createAccrualBasedJournalEntriesAndReversalsForLoan(final Office office, final String currencyCode, - final Integer accountTypeToBeDebited, final Integer accountTypeToBeCredited, final Long loanProductId, - final Long paymentTypeId, final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, - final Boolean isReversal) { + final Integer accountTypeToBeDebited, final Integer accountTypeToBeCredited, final Long loanProductId, final Long paymentTypeId, + final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, final Boolean isReversal) { int accountTypeToDebitId = accountTypeToBeDebited; int accountTypeToCreditId = accountTypeToBeCredited; // reverse debits and credits for reversals @@ -367,8 +367,8 @@ public class AccountingProcessorHelper { accountTypeToDebitId = accountTypeToBeCredited; accountTypeToCreditId = accountTypeToBeDebited; } - createJournalEntriesForLoan(office, currencyCode, accountTypeToDebitId, accountTypeToCreditId, loanProductId, paymentTypeId, - loanId, transactionId, transactionDate, amount); + createJournalEntriesForLoan(office, currencyCode, accountTypeToDebitId, accountTypeToCreditId, loanProductId, paymentTypeId, loanId, + transactionId, transactionDate, amount); } /** @@ -378,17 +378,28 @@ public class AccountingProcessorHelper { * The target accounts for debits and credits are switched in case of a * reversal * - * @param office office - * @param currencyCode currencyCode - * @param accountTypeToBeDebited Enum of the placeholder GLAccount to be debited - * @param accountTypeToBeCredited Enum of the placeholder of the GLAccount to be credited - * @param loanProductId loanProductId - * @param loanId loanId - * @param transactionId transactionId - * @param transactionDate transactionDate - * @param totalAmount totalAmount - * @param isReversal isReversal - * @param chargePaymentDTOs chargePaymentDTOs + * @param office + * office + * @param currencyCode + * currencyCode + * @param accountTypeToBeDebited + * Enum of the placeholder GLAccount to be debited + * @param accountTypeToBeCredited + * Enum of the placeholder of the GLAccount to be credited + * @param loanProductId + * loanProductId + * @param loanId + * loanId + * @param transactionId + * transactionId + * @param transactionDate + * transactionDate + * @param totalAmount + * totalAmount + * @param isReversal + * isReversal + * @param chargePaymentDTOs + * chargePaymentDTOs */ public void createAccrualBasedJournalEntriesAndReversalsForLoanCharges(final Office office, final String currencyCode, final Integer accountTypeToBeDebited, final Integer accountTypeToBeCredited, final Long loanProductId, final Long loanId, @@ -425,10 +436,12 @@ public class AccountingProcessorHelper { } } - if (totalAmount.compareTo(totalCreditedAmount) != 0) { throw new PlatformDataIntegrityException( - "Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction", - "Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction", - totalCreditedAmount, totalAmount); } + if (totalAmount.compareTo(totalCreditedAmount) != 0) { + throw new PlatformDataIntegrityException( + "Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction", + "Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction", + totalCreditedAmount, totalAmount); + } } /** @@ -487,9 +500,8 @@ public class AccountingProcessorHelper { * @param isReversal */ public void createCashBasedJournalEntriesAndReversalsForLoan(final Office office, final String currencyCode, - final Integer accountTypeToBeDebited, final Integer accountTypeToBeCredited, final Long loanProductId, - final Long paymentTypeId, final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, - final Boolean isReversal) { + final Integer accountTypeToBeDebited, final Integer accountTypeToBeCredited, final Long loanProductId, final Long paymentTypeId, + final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, final Boolean isReversal) { int accountTypeToDebitId = accountTypeToBeDebited; int accountTypeToCreditId = accountTypeToBeCredited; // reverse debits and credits for reversals @@ -497,8 +509,8 @@ public class AccountingProcessorHelper { accountTypeToDebitId = accountTypeToBeCredited; accountTypeToCreditId = accountTypeToBeDebited; } - createJournalEntriesForLoan(office, currencyCode, accountTypeToDebitId, accountTypeToCreditId, loanProductId, paymentTypeId, - loanId, transactionId, transactionDate, amount); + createJournalEntriesForLoan(office, currencyCode, accountTypeToDebitId, accountTypeToCreditId, loanProductId, paymentTypeId, loanId, + transactionId, transactionDate, amount); } public void createCreditJournalEntryOrReversalForLoan(final Office office, final String currencyCode, @@ -527,8 +539,10 @@ public class AccountingProcessorHelper { * transaction Date **/ if (latestGLClosure != null) { - if (latestGLClosure.getClosingDate().after(transactionDate) || latestGLClosure.getClosingDate().equals(transactionDate)) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate(), null, null); } + if (latestGLClosure.getClosingDate().after(transactionDate) || latestGLClosure.getClosingDate().equals(transactionDate)) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate(), + null, null); + } } } @@ -567,8 +581,10 @@ public class AccountingProcessorHelper { * * @param office * @param currencyCode - * @param accountTypeToBeDebited Enum of the placeholder GLAccount to be debited - * @param accountTypeToBeCredited Enum of the placeholder of the GLAccount to be credited + * @param accountTypeToBeDebited + * Enum of the placeholder GLAccount to be debited + * @param accountTypeToBeCredited + * Enum of the placeholder of the GLAccount to be credited * @param savingsProductId * @param paymentTypeId * @param savingsId @@ -711,10 +727,12 @@ public class AccountingProcessorHelper { // TODO: Vishwas Temporary validation to be removed before moving to // release branch - if (totalAmount.compareTo(totalCreditedAmount) != 0) { throw new PlatformDataIntegrityException( - "Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction", - "Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction", - totalCreditedAmount, totalAmount); } + if (totalAmount.compareTo(totalCreditedAmount) != 0) { + throw new PlatformDataIntegrityException( + "Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction", + "Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction", + totalCreditedAmount, totalAmount); + } } /** @@ -724,18 +742,30 @@ public class AccountingProcessorHelper { * The target accounts for debits and credits are switched in case of a * reversal * - * @param office office - * @param currencyCode currencyCode - * @param accountTypeToBeDebited Enum of the placeholder GLAccount to be debited - * @param accountTypeToBeCredited Enum of the placeholder of the GLAccount to be credited - * @param savingsProductId savingsProductId - * @param paymentTypeId paymentTypeId - * @param loanId loanId - * @param transactionId transactionId - * @param transactionDate transactionDate - * @param totalAmount totalAmount - * @param isReversal isReversal - * @param chargePaymentDTOs chargePaymentDTOs + * @param office + * office + * @param currencyCode + * currencyCode + * @param accountTypeToBeDebited + * Enum of the placeholder GLAccount to be debited + * @param accountTypeToBeCredited + * Enum of the placeholder of the GLAccount to be credited + * @param savingsProductId + * savingsProductId + * @param paymentTypeId + * paymentTypeId + * @param loanId + * loanId + * @param transactionId + * transactionId + * @param transactionDate + * transactionDate + * @param totalAmount + * totalAmount + * @param isReversal + * isReversal + * @param chargePaymentDTOs + * chargePaymentDTOs */ public void createCashBasedJournalEntriesAndReversalsForSavingsCharges(final Office office, final String currencyCode, final CashAccountsForSavings accountTypeToBeDebited, final CashAccountsForSavings accountTypeToBeCredited, @@ -750,9 +780,10 @@ public class AccountingProcessorHelper { * changing the expected portfolio behavior would also take care of * modifying the accounting code appropriately **/ - if (chargePaymentDTOs.size() != 1) { throw new PlatformDataIntegrityException( - "Recent Portfolio changes w.r.t Charges for Savings have Broken the accounting code", - "Recent Portfolio changes w.r.t Charges for Savings have Broken the accounting code"); } + if (chargePaymentDTOs.size() != 1) { + throw new PlatformDataIntegrityException("Recent Portfolio changes w.r.t Charges for Savings have Broken the accounting code", + "Recent Portfolio changes w.r.t Charges for Savings have Broken the accounting code"); + } ChargePaymentDTO chargePaymentDTO = chargePaymentDTOs.get(0); final GLAccount chargeSpecificAccount = getLinkedGLAccountForSavingsCharges(savingsProductId, accountTypeToBeCredited.getValue(), @@ -784,7 +815,8 @@ public class AccountingProcessorHelper { final Long loanProductId, final Long paymentTypeId, final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, final Boolean isReversal) { final GLAccount account = getLinkedGLAccountForLoanProduct(loanProductId, accountMappingTypeId, paymentTypeId); - createCreditJournalEntryOrReversalForLoan(office, currencyCode, loanId, transactionId, transactionDate, amount, isReversal, account); + createCreditJournalEntryOrReversalForLoan(office, currencyCode, loanId, transactionId, transactionDate, amount, isReversal, + account); } public void createCreditJournalEntryOrReversalForLoan(final Office office, final String currencyCode, final Long loanId, @@ -811,8 +843,8 @@ public class AccountingProcessorHelper { String modifiedTransactionId = transactionId.toString(); modifiedTransactionId = CLIENT_TRANSACTION_IDENTIFIER + transactionId; final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId, - manualEntry, transactionDate, JournalEntryType.CREDIT, amount, null, PortfolioProductType.CLIENT.getValue(), clientId, - null, loanTransaction, savingsAccountTransaction, clientTransaction, shareTransactionId); + manualEntry, transactionDate, JournalEntryType.CREDIT, amount, null, PortfolioProductType.CLIENT.getValue(), clientId, null, + loanTransaction, savingsAccountTransaction, clientTransaction, shareTransactionId); this.glJournalEntryRepository.saveAndFlush(journalEntry); } @@ -836,8 +868,8 @@ public class AccountingProcessorHelper { this.glJournalEntryRepository.saveAndFlush(journalEntry); } - private void createCreditJournalEntryForLoan(final Office office, final String currencyCode, final GLAccount account, - final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount) { + private void createCreditJournalEntryForLoan(final Office office, final String currencyCode, final GLAccount account, final Long loanId, + final String transactionId, final Date transactionDate, final BigDecimal amount) { final boolean manualEntry = false; LoanTransaction loanTransaction = null; SavingsAccountTransaction savingsAccountTransaction = null; @@ -921,8 +953,8 @@ public class AccountingProcessorHelper { modifiedTransactionId = SAVINGS_TRANSACTION_IDENTIFIER + transactionId; } final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId, - manualEntry, transactionDate, JournalEntryType.DEBIT, amount, null, PortfolioProductType.SAVING.getValue(), savingsId, - null, loanTransaction, savingsAccountTransaction, clientTransaction, shareTransactionId); + manualEntry, transactionDate, JournalEntryType.DEBIT, amount, null, PortfolioProductType.SAVING.getValue(), savingsId, null, + loanTransaction, savingsAccountTransaction, clientTransaction, shareTransactionId); this.glJournalEntryRepository.saveAndFlush(journalEntry); } @@ -1005,9 +1037,10 @@ public class AccountingProcessorHelper { totalCreditedAmount = totalCreditedAmount.add(amount); createCreditJournalEntryForShares(office, currencyCode, account, shareAccountId, transactionId, transactionDate, amount); } - if (totalAmount.compareTo(totalCreditedAmount) != 0) { throw new PlatformDataIntegrityException( - "Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code", - "Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code"); } + if (totalAmount.compareTo(totalCreditedAmount) != 0) { + throw new PlatformDataIntegrityException("Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code", + "Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code"); + } } public void revertCashBasedJournalEntryForSharesCharges(final Office office, final String currencyCode, @@ -1036,9 +1069,10 @@ public class AccountingProcessorHelper { totalCreditedAmount = totalCreditedAmount.add(amount); createDebitJournalEntryForShares(office, currencyCode, account, shareAccountId, transactionId, transactionDate, amount); } - if (totalAmount.compareTo(totalCreditedAmount) != 0) { throw new PlatformDataIntegrityException( - "Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code", - "Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code"); } + if (totalAmount.compareTo(totalCreditedAmount) != 0) { + throw new PlatformDataIntegrityException("Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code", + "Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code"); + } } private void createDebitJournalEntryForShares(final Office office, final String currencyCode, final GLAccount account, @@ -1074,8 +1108,8 @@ public class AccountingProcessorHelper { modifiedTransactionId = SHARE_TRANSACTION_IDENTIFIER + transactionId; } final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId, - manualEntry, transactionDate, JournalEntryType.CREDIT, amount, null, PortfolioProductType.SHARES.getValue(), - shareAccountId, null, loanTransaction, savingsAccountTransaction, clientTransaction, shareTransactionId); + manualEntry, transactionDate, JournalEntryType.CREDIT, amount, null, PortfolioProductType.SHARES.getValue(), shareAccountId, + null, loanTransaction, savingsAccountTransaction, clientTransaction, shareTransactionId); this.glJournalEntryRepository.save(journalEntry); } @@ -1103,8 +1137,10 @@ public class AccountingProcessorHelper { } } - if (accountMapping == null) { throw new ProductToGLAccountMappingNotFoundException(PortfolioProductType.LOAN, loanProductId, - AccrualAccountsForLoan.OVERPAYMENT.toString()); } + if (accountMapping == null) { + throw new ProductToGLAccountMappingNotFoundException(PortfolioProductType.LOAN, loanProductId, + AccrualAccountsForLoan.OVERPAYMENT.toString()); + } glAccount = accountMapping.getGlAccount(); } return glAccount; @@ -1133,7 +1169,8 @@ public class AccountingProcessorHelper { return accountMapping.getGlAccount(); } - private GLAccount getLinkedGLAccountForSavingsCharges(final Long savingsProductId, final int accountMappingTypeId, final Long chargeId) { + private GLAccount getLinkedGLAccountForSavingsCharges(final Long savingsProductId, final int accountMappingTypeId, + final Long chargeId) { ProductToGLAccountMapping accountMapping = this.accountMappingRepository.findCoreProductToFinAccountMapping(savingsProductId, PortfolioProductType.SAVING.getValue(), accountMappingTypeId); /***** @@ -1147,8 +1184,8 @@ public class AccountingProcessorHelper { if (accountMappingTypeId == CashAccountsForSavings.INCOME_FROM_FEES.getValue() || accountMappingTypeId == CashAccountsForLoan.INCOME_FROM_PENALTIES.getValue()) { final ProductToGLAccountMapping chargeSpecificIncomeAccountMapping = this.accountMappingRepository - .findProductIdAndProductTypeAndFinancialAccountTypeAndChargeId(savingsProductId, - PortfolioProductType.SAVING.getValue(), accountMappingTypeId, chargeId); + .findProductIdAndProductTypeAndFinancialAccountTypeAndChargeId(savingsProductId, PortfolioProductType.SAVING.getValue(), + accountMappingTypeId, chargeId); if (chargeSpecificIncomeAccountMapping != null) { accountMapping = chargeSpecificIncomeAccountMapping; } @@ -1184,7 +1221,8 @@ public class AccountingProcessorHelper { return glAccount; } - private GLAccount getLinkedGLAccountForShareProduct(final Long shareProductId, final int accountMappingTypeId, final Long paymentTypeId) { + private GLAccount getLinkedGLAccountForShareProduct(final Long shareProductId, final int accountMappingTypeId, + final Long paymentTypeId) { GLAccount glAccount = null; if (isOrganizationAccount(accountMappingTypeId)) { FinancialActivityAccount financialActivityAccount = this.financialActivityAccountRepository @@ -1273,8 +1311,8 @@ public class AccountingProcessorHelper { public void createDebitJournalEntryOrReversalForClientChargePayments(final Office office, final String currencyCode, final Long clientId, final Long transactionId, final Date transactionDate, final BigDecimal amount, final Boolean isReversal) { - final GLAccount account = financialActivityAccountRepository.findByFinancialActivityTypeWithNotFoundDetection( - FinancialActivity.ASSET_FUND_SOURCE.getValue()).getGlAccount(); + final GLAccount account = financialActivityAccountRepository + .findByFinancialActivityTypeWithNotFoundDetection(FinancialActivity.ASSET_FUND_SOURCE.getValue()).getGlAccount(); if (isReversal) { createCreditJournalEntryForClientPayments(office, currencyCode, account, clientId, transactionId, transactionDate, amount); } else { diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/AccrualBasedAccountingProcessorForLoan.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/AccrualBasedAccountingProcessorForLoan.java old mode 100755 new mode 100644 index 778af31b5..0556ddadf --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/AccrualBasedAccountingProcessorForLoan.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/AccrualBasedAccountingProcessorForLoan.java @@ -72,8 +72,8 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess else if (loanTransactionDTO.getTransactionType().isRepayment() || loanTransactionDTO.getTransactionType().isRepaymentAtDisbursement() || loanTransactionDTO.getTransactionType().isChargePayment()) { - createJournalEntriesForRepaymentsAndWriteOffs(loanDTO, loanTransactionDTO, office, false, loanTransactionDTO - .getTransactionType().isRepaymentAtDisbursement()); + createJournalEntriesForRepaymentsAndWriteOffs(loanDTO, loanTransactionDTO, office, false, + loanTransactionDTO.getTransactionType().isRepaymentAtDisbursement()); } /** Logic for handling recovery payments **/ @@ -87,8 +87,8 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess } /** Handle Write Offs, waivers and their reversals **/ - else if ((loanTransactionDTO.getTransactionType().isWriteOff() || loanTransactionDTO.getTransactionType().isWaiveInterest() || loanTransactionDTO - .getTransactionType().isWaiveCharges())) { + else if ((loanTransactionDTO.getTransactionType().isWriteOff() || loanTransactionDTO.getTransactionType().isWaiveInterest() + || loanTransactionDTO.getTransactionType().isWaiveCharges())) { createJournalEntriesForRepaymentsAndWriteOffs(loanDTO, loanTransactionDTO, office, true, false); } @@ -123,7 +123,7 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess // create journal entries for the disbursement (or disbursement // reversal) - if(loanTransactionDTO.isLoanToLoanTransfer()){ + if (loanTransactionDTO.isLoanToLoanTransfer()) { this.helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, AccrualAccountsForLoan.LOAN_PORTFOLIO.getValue(), FinancialActivity.ASSET_TRANSFER.getValue(), loanProductId, paymentTypeId, loanId, transactionId, transactionDate, disbursalAmount, isReversed); @@ -145,8 +145,8 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess *
*
* - * Principal Repayment: Debits "Fund Source" and Credits - * "Loan Portfolio"
+ * Principal Repayment: Debits "Fund Source" and Credits "Loan + * Portfolio"
* * Interest Repayment:Debits "Fund Source" and and Credits * "Receivable Interest"
@@ -159,8 +159,8 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess *
* Handles write offs using the following posting rules
*
- * Principal Write off: Debits "Losses Written Off" and Credits - * "Loan Portfolio"
+ * Principal Write off: Debits "Losses Written Off" and Credits "Loan + * Portfolio"
* * Interest Write off:Debits "Losses Written off" and and Credits * "Receivable Interest"
@@ -274,8 +274,8 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess if (overPaymentAmount != null && !(overPaymentAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(overPaymentAmount); - GLAccount account = this.helper.getLinkedGLAccountForLoanProduct(loanProductId, - AccrualAccountsForLoan.OVERPAYMENT.getValue(), paymentTypeId); + GLAccount account = this.helper.getLinkedGLAccountForLoanProduct(loanProductId, AccrualAccountsForLoan.OVERPAYMENT.getValue(), + paymentTypeId); if (accountMap.containsKey(account)) { BigDecimal amount = accountMap.get(account).add(overPaymentAmount); accountMap.put(account, amount); @@ -299,10 +299,9 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess AccrualAccountsForLoan.LOSSES_WRITTEN_OFF.getValue(), loanProductId, paymentTypeId, loanId, transactionId, transactionDate, totalDebitAmount, isReversal); } else { - if(loanTransactionDTO.isLoanToLoanTransfer()){ - this.helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, - FinancialActivity.ASSET_TRANSFER.getValue(), loanProductId, paymentTypeId, loanId, transactionId, - transactionDate, totalDebitAmount, isReversal); + if (loanTransactionDTO.isLoanToLoanTransfer()) { + this.helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, FinancialActivity.ASSET_TRANSFER.getValue(), + loanProductId, paymentTypeId, loanId, transactionId, transactionDate, totalDebitAmount, isReversal); } else if (loanTransactionDTO.isAccountTransfer()) { this.helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, FinancialActivity.LIABILITY_TRANSFER.getValue(), loanProductId, paymentTypeId, loanId, transactionId, @@ -317,8 +316,8 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess } /** - * Create a single Debit to fund source and a single credit to - * "Income from Recovery" + * Create a single Debit to fund source and a single credit to "Income from + * Recovery" * * In case the loan transaction is a reversal, all debits are turned into * credits and vice versa @@ -337,9 +336,9 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess final boolean isReversal = loanTransactionDTO.isReversed(); final Long paymentTypeId = loanTransactionDTO.getPaymentTypeId(); - this.helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, - AccrualAccountsForLoan.FUND_SOURCE.getValue(), AccrualAccountsForLoan.INCOME_FROM_RECOVERY.getValue(), loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, amount, isReversal); + this.helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, AccrualAccountsForLoan.FUND_SOURCE.getValue(), + AccrualAccountsForLoan.INCOME_FROM_RECOVERY.getValue(), loanProductId, paymentTypeId, loanId, transactionId, + transactionDate, amount, isReversal); } @@ -384,8 +383,8 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess // create journal entries for the fees application (or reversal) if (feesAmount != null && !(feesAmount.compareTo(BigDecimal.ZERO) == 0)) { this.helper.createAccrualBasedJournalEntriesAndReversalsForLoanCharges(office, currencyCode, - AccrualAccountsForLoan.FEES_RECEIVABLE.getValue(), AccrualAccountsForLoan.INCOME_FROM_FEES.getValue(), - loanProductId, loanId, transactionId, transactionDate, feesAmount, isReversed, loanTransactionDTO.getFeePayments()); + AccrualAccountsForLoan.FEES_RECEIVABLE.getValue(), AccrualAccountsForLoan.INCOME_FROM_FEES.getValue(), loanProductId, + loanId, transactionId, transactionDate, feesAmount, isReversed, loanTransactionDTO.getFeePayments()); } // create journal entries for the penalties application (or reversal) if (penaltiesAmount != null && !(penaltiesAmount.compareTo(BigDecimal.ZERO) == 0)) { @@ -411,13 +410,13 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess final Long paymentTypeId = loanTransactionDTO.getPaymentTypeId(); if (loanTransactionDTO.isAccountTransfer()) { - this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, - CashAccountsForLoan.OVERPAYMENT.getValue(), FinancialActivity.LIABILITY_TRANSFER.getValue(), loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, refundAmount, isReversal); + this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CashAccountsForLoan.OVERPAYMENT.getValue(), + FinancialActivity.LIABILITY_TRANSFER.getValue(), loanProductId, paymentTypeId, loanId, transactionId, transactionDate, + refundAmount, isReversal); } else { - this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, - CashAccountsForLoan.OVERPAYMENT.getValue(), CashAccountsForLoan.FUND_SOURCE.getValue(), loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, refundAmount, isReversal); + this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CashAccountsForLoan.OVERPAYMENT.getValue(), + CashAccountsForLoan.FUND_SOURCE.getValue(), loanProductId, paymentTypeId, loanId, transactionId, transactionDate, + refundAmount, isReversal); } } @@ -443,8 +442,8 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess if (principalAmount != null && !(principalAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(principalAmount); - this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, CashAccountsForLoan.LOAN_PORTFOLIO, - loanProductId, paymentTypeId, loanId, transactionId, transactionDate, principalAmount, !isReversal); + this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, CashAccountsForLoan.LOAN_PORTFOLIO, loanProductId, + paymentTypeId, loanId, transactionId, transactionDate, principalAmount, !isReversal); } if (interestAmount != null && !(interestAmount.compareTo(BigDecimal.ZERO) == 0)) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForLoan.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForLoan.java old mode 100755 new mode 100644 index c916567c1..22c42d246 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForLoan.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForLoan.java @@ -90,9 +90,8 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF final BigDecimal principalAmount = loanTransactionDTO.getPrincipal(); if (principalAmount != null && !(principalAmount.compareTo(BigDecimal.ZERO) == 0)) { this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, - CashAccountsForLoan.LOSSES_WRITTEN_OFF.getValue(), CashAccountsForLoan.LOAN_PORTFOLIO.getValue(), - loanProductId, paymentTypeId, loanId, transactionId, transactionDate, principalAmount, - loanTransactionDTO.isReversed()); + CashAccountsForLoan.LOSSES_WRITTEN_OFF.getValue(), CashAccountsForLoan.LOAN_PORTFOLIO.getValue(), loanProductId, + paymentTypeId, loanId, transactionId, transactionDate, principalAmount, loanTransactionDTO.isReversed()); } } else if (loanTransactionDTO.getTransactionType().isInitiateTransfer() @@ -131,7 +130,7 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF final BigDecimal disbursalAmount = loanTransactionDTO.getAmount(); final boolean isReversal = loanTransactionDTO.isReversed(); final Long paymentTypeId = loanTransactionDTO.getPaymentTypeId(); - if(loanTransactionDTO.isLoanToLoanTransfer()){ + if (loanTransactionDTO.isLoanToLoanTransfer()) { this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CashAccountsForLoan.LOAN_PORTFOLIO.getValue(), FinancialActivity.ASSET_TRANSFER.getValue(), loanProductId, paymentTypeId, loanId, transactionId, transactionDate, disbursalAmount, isReversal); @@ -141,8 +140,8 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF paymentTypeId, loanId, transactionId, transactionDate, disbursalAmount, isReversal); } else { this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, - CashAccountsForLoan.LOAN_PORTFOLIO.getValue(), CashAccountsForLoan.FUND_SOURCE.getValue(), loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, disbursalAmount, isReversal); + CashAccountsForLoan.LOAN_PORTFOLIO.getValue(), CashAccountsForLoan.FUND_SOURCE.getValue(), loanProductId, paymentTypeId, + loanId, transactionId, transactionDate, disbursalAmount, isReversal); } } @@ -172,13 +171,13 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF final Long paymentTypeId = loanTransactionDTO.getPaymentTypeId(); if (loanTransactionDTO.isAccountTransfer()) { - this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, - CashAccountsForLoan.OVERPAYMENT.getValue(), FinancialActivity.LIABILITY_TRANSFER.getValue(), loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, refundAmount, isReversal); + this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CashAccountsForLoan.OVERPAYMENT.getValue(), + FinancialActivity.LIABILITY_TRANSFER.getValue(), loanProductId, paymentTypeId, loanId, transactionId, transactionDate, + refundAmount, isReversal); } else { - this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, - CashAccountsForLoan.OVERPAYMENT.getValue(), CashAccountsForLoan.FUND_SOURCE.getValue(), loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, refundAmount, isReversal); + this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CashAccountsForLoan.OVERPAYMENT.getValue(), + CashAccountsForLoan.FUND_SOURCE.getValue(), loanProductId, paymentTypeId, loanId, transactionId, transactionDate, + refundAmount, isReversal); } } @@ -191,7 +190,8 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF * In case the loan transaction is a reversal, all debits are turned into * credits and vice versa */ - private void createJournalEntriesForRepayments(final LoanDTO loanDTO, final LoanTransactionDTO loanTransactionDTO, final Office office) { + private void createJournalEntriesForRepayments(final LoanDTO loanDTO, final LoanTransactionDTO loanTransactionDTO, + final Office office) { // loan properties final Long loanProductId = loanDTO.getLoanProductId(); final Long loanId = loanDTO.getLoanId(); @@ -212,8 +212,8 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF if (principalAmount != null && !(principalAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(principalAmount); - this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, CashAccountsForLoan.LOAN_PORTFOLIO, - loanProductId, paymentTypeId, loanId, transactionId, transactionDate, principalAmount, isReversal); + this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, CashAccountsForLoan.LOAN_PORTFOLIO, loanProductId, + paymentTypeId, loanId, transactionId, transactionDate, principalAmount, isReversal); } if (interestAmount != null && !(interestAmount.compareTo(BigDecimal.ZERO) == 0)) { @@ -243,7 +243,7 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF } /*** create a single debit entry (or reversal) for the entire amount **/ - if(loanTransactionDTO.isLoanToLoanTransfer()){ + if (loanTransactionDTO.isLoanToLoanTransfer()) { this.helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, FinancialActivity.ASSET_TRANSFER.getValue(), loanProductId, paymentTypeId, loanId, transactionId, transactionDate, totalDebitAmount, isReversal); } else if (loanTransactionDTO.isAccountTransfer()) { @@ -256,8 +256,8 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF } /** - * Create a single Debit to fund source and a single credit to - * "Income from Recovery" + * Create a single Debit to fund source and a single credit to "Income from + * Recovery" * * In case the loan transaction is a reversal, all debits are turned into * credits and vice versa @@ -277,8 +277,8 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF final Long paymentTypeId = loanTransactionDTO.getPaymentTypeId(); this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CashAccountsForLoan.FUND_SOURCE.getValue(), - CashAccountsForLoan.INCOME_FROM_RECOVERY.getValue(), loanProductId, paymentTypeId, loanId, transactionId, - transactionDate, amount, isReversal); + CashAccountsForLoan.INCOME_FROM_RECOVERY.getValue(), loanProductId, paymentTypeId, loanId, transactionId, transactionDate, + amount, isReversal); } @@ -310,13 +310,13 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF if (loanTransactionDTO.getTransactionType().isInitiateTransfer()) { this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, - CashAccountsForLoan.TRANSFERS_SUSPENSE.getValue(), CashAccountsForLoan.LOAN_PORTFOLIO.getValue(), loanProductId, - null, loanId, transactionId, transactionDate, principalAmount, isReversal); + CashAccountsForLoan.TRANSFERS_SUSPENSE.getValue(), CashAccountsForLoan.LOAN_PORTFOLIO.getValue(), loanProductId, null, + loanId, transactionId, transactionDate, principalAmount, isReversal); } else if (loanTransactionDTO.getTransactionType().isApproveTransfer() || loanTransactionDTO.getTransactionType().isWithdrawTransfer()) { this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, - CashAccountsForLoan.LOAN_PORTFOLIO.getValue(), CashAccountsForLoan.TRANSFERS_SUSPENSE.getValue(), loanProductId, - null, loanId, transactionId, transactionDate, principalAmount, isReversal); + CashAccountsForLoan.LOAN_PORTFOLIO.getValue(), CashAccountsForLoan.TRANSFERS_SUSPENSE.getValue(), loanProductId, null, + loanId, transactionId, transactionDate, principalAmount, isReversal); } } @@ -341,8 +341,8 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF if (principalAmount != null && !(principalAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(principalAmount); - this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, CashAccountsForLoan.LOAN_PORTFOLIO, - loanProductId, paymentTypeId, loanId, transactionId, transactionDate, principalAmount, !isReversal); + this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, CashAccountsForLoan.LOAN_PORTFOLIO, loanProductId, + paymentTypeId, loanId, transactionId, transactionDate, principalAmount, !isReversal); } if (interestAmount != null && !(interestAmount.compareTo(BigDecimal.ZERO) == 0)) { @@ -356,9 +356,10 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF List chargePaymentDTOs = new ArrayList<>(); - for(ChargePaymentDTO chargePaymentDTO : loanTransactionDTO.getFeePayments()) { + for (ChargePaymentDTO chargePaymentDTO : loanTransactionDTO.getFeePayments()) { chargePaymentDTOs.add(new ChargePaymentDTO(chargePaymentDTO.getChargeId(), chargePaymentDTO.getLoanChargeId(), - chargePaymentDTO.getAmount().floatValue() < 0 ? chargePaymentDTO.getAmount().multiply(new BigDecimal(-1)):chargePaymentDTO.getAmount() )); + chargePaymentDTO.getAmount().floatValue() < 0 ? chargePaymentDTO.getAmount().multiply(new BigDecimal(-1)) + : chargePaymentDTO.getAmount())); } this.helper.createCreditJournalEntryOrReversalForLoanCharges(office, currencyCode, CashAccountsForLoan.INCOME_FROM_FEES.getValue(), loanProductId, loanId, transactionId, transactionDate, feesAmount, @@ -369,9 +370,10 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF totalDebitAmount = totalDebitAmount.add(penaltiesAmount); List chargePaymentDTOs = new ArrayList<>(); - for(ChargePaymentDTO chargePaymentDTO : loanTransactionDTO.getPenaltyPayments()) { + for (ChargePaymentDTO chargePaymentDTO : loanTransactionDTO.getPenaltyPayments()) { chargePaymentDTOs.add(new ChargePaymentDTO(chargePaymentDTO.getChargeId(), chargePaymentDTO.getLoanChargeId(), - chargePaymentDTO.getAmount().floatValue() < 0 ? chargePaymentDTO.getAmount().multiply(new BigDecimal(-1)):chargePaymentDTO.getAmount() )); + chargePaymentDTO.getAmount().floatValue() < 0 ? chargePaymentDTO.getAmount().multiply(new BigDecimal(-1)) + : chargePaymentDTO.getAmount())); } this.helper.createCreditJournalEntryOrReversalForLoanCharges(office, currencyCode, @@ -386,8 +388,8 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF } /*** create a single debit entry (or reversal) for the entire amount **/ - this.helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, CashAccountsForLoan.FUND_SOURCE.getValue(), loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, totalDebitAmount, !isReversal); + this.helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, CashAccountsForLoan.FUND_SOURCE.getValue(), + loanProductId, paymentTypeId, loanId, transactionId, transactionDate, totalDebitAmount, !isReversal); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForSavings.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForSavings.java old mode 100755 new mode 100644 index 0f60062d7..6d57f7a6b --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForSavings.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForSavings.java @@ -63,9 +63,8 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess if (savingsTransactionDTO.getTransactionType().isWithdrawal() && savingsTransactionDTO.isOverdraftTransaction()) { if (savingsTransactionDTO.isAccountTransfer()) { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, - CashAccountsForSavings.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), - FinancialActivity.LIABILITY_TRANSFER.getValue(), savingsProductId, paymentTypeId, savingsId, transactionId, - transactionDate, overdraftAmount, isReversal); + CashAccountsForSavings.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), FinancialActivity.LIABILITY_TRANSFER.getValue(), + savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, overdraftAmount, isReversal); if (amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) > 0) { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, CashAccountsForSavings.SAVINGS_CONTROL.getValue(), FinancialActivity.LIABILITY_TRANSFER.getValue(), @@ -75,21 +74,20 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess } else { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, CashAccountsForSavings.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), - CashAccountsForSavings.SAVINGS_REFERENCE.getValue(), savingsProductId, paymentTypeId, savingsId, - transactionId, transactionDate, overdraftAmount, isReversal); + CashAccountsForSavings.SAVINGS_REFERENCE.getValue(), savingsProductId, paymentTypeId, savingsId, transactionId, + transactionDate, overdraftAmount, isReversal); if (amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) > 0) { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, - CashAccountsForSavings.SAVINGS_CONTROL.getValue(), - CashAccountsForSavings.SAVINGS_REFERENCE.getValue(), savingsProductId, paymentTypeId, savingsId, - transactionId, transactionDate, amount.subtract(overdraftAmount), isReversal); + CashAccountsForSavings.SAVINGS_CONTROL.getValue(), CashAccountsForSavings.SAVINGS_REFERENCE.getValue(), + savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, + amount.subtract(overdraftAmount), isReversal); } } } else if (savingsTransactionDTO.getTransactionType().isDeposit() && savingsTransactionDTO.isOverdraftTransaction()) { if (savingsTransactionDTO.isAccountTransfer()) { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, - FinancialActivity.LIABILITY_TRANSFER.getValue(), - CashAccountsForSavings.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), savingsProductId, paymentTypeId, savingsId, - transactionId, transactionDate, overdraftAmount, isReversal); + FinancialActivity.LIABILITY_TRANSFER.getValue(), CashAccountsForSavings.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), + savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, overdraftAmount, isReversal); if (amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) > 0) { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, FinancialActivity.LIABILITY_TRANSFER.getValue(), CashAccountsForSavings.SAVINGS_CONTROL.getValue(), @@ -103,9 +101,9 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess transactionId, transactionDate, overdraftAmount, isReversal); if (amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) > 0) { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, - CashAccountsForSavings.SAVINGS_REFERENCE.getValue(), - CashAccountsForSavings.SAVINGS_CONTROL.getValue(), savingsProductId, paymentTypeId, savingsId, - transactionId, transactionDate, amount.subtract(overdraftAmount), isReversal); + CashAccountsForSavings.SAVINGS_REFERENCE.getValue(), CashAccountsForSavings.SAVINGS_CONTROL.getValue(), + savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, + amount.subtract(overdraftAmount), isReversal); } } } @@ -126,8 +124,8 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess /** Handle Deposits and reversals of Dividend pay outs **/ else if (savingsTransactionDTO.getTransactionType().isDividendPayout()) { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, - FinancialActivity.PAYABLE_DIVIDENDS.getValue(), CashAccountsForSavings.SAVINGS_CONTROL.getValue(), - savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); + FinancialActivity.PAYABLE_DIVIDENDS.getValue(), CashAccountsForSavings.SAVINGS_CONTROL.getValue(), savingsProductId, + paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); } /** Handle withdrawals and reversals of withdrawals **/ else if (savingsTransactionDTO.getTransactionType().isWithdrawal()) { @@ -161,9 +159,9 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess transactionId, transactionDate, overdraftAmount, isReversal); if (amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) > 0) { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, - CashAccountsForSavings.INTEREST_ON_SAVINGS.getValue(), - CashAccountsForSavings.SAVINGS_CONTROL.getValue(), savingsProductId, paymentTypeId, savingsId, - transactionId, transactionDate, amount.subtract(overdraftAmount), isReversal); + CashAccountsForSavings.INTEREST_ON_SAVINGS.getValue(), CashAccountsForSavings.SAVINGS_CONTROL.getValue(), + savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, + amount.subtract(overdraftAmount), isReversal); } } } @@ -180,9 +178,8 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess else if (savingsTransactionDTO.getTransactionType().isWithholdTax()) { this.helper.createCashBasedJournalEntriesAndReversalsForSavingsTax(office, currencyCode, - CashAccountsForSavings.SAVINGS_CONTROL, CashAccountsForSavings.SAVINGS_REFERENCE, savingsProductId, - paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal, - savingsTransactionDTO.getTaxPayments()); + CashAccountsForSavings.SAVINGS_CONTROL, CashAccountsForSavings.SAVINGS_REFERENCE, savingsProductId, paymentTypeId, + savingsId, transactionId, transactionDate, amount, isReversal, savingsTransactionDTO.getTaxPayments()); } /** Handle Fees Deductions and reversals of Fees Deductions **/ @@ -195,15 +192,14 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess penaltyPayments); if (amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) > 0) { this.helper.createCashBasedJournalEntriesAndReversalsForSavingsCharges(office, currencyCode, - CashAccountsForSavings.SAVINGS_CONTROL, CashAccountsForSavings.INCOME_FROM_PENALTIES, - savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, - amount.subtract(overdraftAmount), isReversal, penaltyPayments); + CashAccountsForSavings.SAVINGS_CONTROL, CashAccountsForSavings.INCOME_FROM_PENALTIES, savingsProductId, + paymentTypeId, savingsId, transactionId, transactionDate, amount.subtract(overdraftAmount), isReversal, + penaltyPayments); } } else { this.helper.createCashBasedJournalEntriesAndReversalsForSavingsCharges(office, currencyCode, - CashAccountsForSavings.OVERDRAFT_PORTFOLIO_CONTROL, CashAccountsForSavings.INCOME_FROM_FEES, - savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, overdraftAmount, isReversal, - feePayments); + CashAccountsForSavings.OVERDRAFT_PORTFOLIO_CONTROL, CashAccountsForSavings.INCOME_FROM_FEES, savingsProductId, + paymentTypeId, savingsId, transactionId, transactionDate, overdraftAmount, isReversal, feePayments); if (amount.subtract(overdraftAmount).compareTo(BigDecimal.ZERO) > 0) { this.helper.createCashBasedJournalEntriesAndReversalsForSavingsCharges(office, currencyCode, CashAccountsForSavings.SAVINGS_CONTROL, CashAccountsForSavings.INCOME_FROM_FEES, savingsProductId, @@ -248,13 +244,12 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); } else if (savingsTransactionDTO.getTransactionType().isWrittenoff()) { this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, - CashAccountsForSavings.LOSSES_WRITTEN_OFF.getValue(), - CashAccountsForSavings.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), savingsProductId, paymentTypeId, savingsId, - transactionId, transactionDate, amount, isReversal); + CashAccountsForSavings.LOSSES_WRITTEN_OFF.getValue(), CashAccountsForSavings.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), + savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); } else if (savingsTransactionDTO.getTransactionType().isOverdraftFee()) { this.helper.createCashBasedJournalEntriesAndReversalsForSavingsCharges(office, currencyCode, - CashAccountsForSavings.SAVINGS_REFERENCE, CashAccountsForSavings.INCOME_FROM_FEES, savingsProductId, - paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal, feePayments); + CashAccountsForSavings.SAVINGS_REFERENCE, CashAccountsForSavings.INCOME_FROM_FEES, savingsProductId, paymentTypeId, + savingsId, transactionId, transactionDate, amount, isReversal, feePayments); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForShares.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForShares.java index be8bbb82a..ec0de1f3b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForShares.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/CashBasedAccountingProcessorForShares.java @@ -118,12 +118,12 @@ public class CashBasedAccountingProcessorForShares implements AccountingProcesso if (chargeAmount != null && chargeAmount.compareTo(BigDecimal.ZERO) > 0) { this.helper.revertCashBasedJournalEntryForSharesCharges(office, currencyCode, CashAccountsForShares.INCOME_FROM_FEES, shareProductId, shareAccountId, transactionId, transactionDate, chargeAmount, feePayments); - this.helper.createDebitJournalEntryForShares(office, currencyCode, CashAccountsForShares.SHARES_SUSPENSE.getValue(), shareProductId, paymentTypeId, shareAccountId, - transactionId, transactionDate, amount.subtract(chargeAmount)); - this.helper.createCreditJournalEntryForShares(office, currencyCode, CashAccountsForShares.SHARES_REFERENCE.getValue(), shareProductId, paymentTypeId, shareAccountId, - transactionId, transactionDate, amount); + this.helper.createDebitJournalEntryForShares(office, currencyCode, CashAccountsForShares.SHARES_SUSPENSE.getValue(), + shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amount.subtract(chargeAmount)); + this.helper.createCreditJournalEntryForShares(office, currencyCode, CashAccountsForShares.SHARES_REFERENCE.getValue(), + shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amount); - }else{ + } else { this.helper.createJournalEntriesForShares(office, currencyCode, CashAccountsForShares.SHARES_SUSPENSE.getValue(), CashAccountsForShares.SHARES_REFERENCE.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amount); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryReadPlatformService.java old mode 100755 new mode 100644 index 9ba0631ac..94a4afb9d --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryReadPlatformService.java @@ -34,5 +34,5 @@ public interface JournalEntryReadPlatformService { OfficeOpeningBalancesData retrieveOfficeOpeningBalances(Long officeId, String currencyCode); - Page retrieveJournalEntriesByEntityId(String transactionId, Long entityId, Integer entityType) ; + Page retrieveJournalEntriesByEntityId(String transactionId, Long entityId, Integer entityType); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryReadPlatformServiceImpl.java old mode 100755 new mode 100644 index c7ea5b9c8..56e322123 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryReadPlatformServiceImpl.java @@ -81,8 +81,7 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat @Autowired public JournalEntryReadPlatformServiceImpl(final RoutingDataSource dataSource, - final GLAccountReadPlatformService glAccountReadPlatformService, - final ColumnValidator columnValidator, + final GLAccountReadPlatformService glAccountReadPlatformService, final ColumnValidator columnValidator, final OfficeReadPlatformService officeReadPlatformService, final FinancialActivityAccountRepositoryWrapper financialActivityAccountRepositoryWrapper) { this.jdbcTemplate = new JdbcTemplate(dataSource); @@ -106,8 +105,7 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat public String schema() { StringBuilder sb = new StringBuilder(); - sb.append(" journalEntry.id as id, glAccount.classification_enum as classification ,") - .append("journalEntry.transaction_id,") + sb.append(" journalEntry.id as id, glAccount.classification_enum as classification ,").append("journalEntry.transaction_id,") .append(" glAccount.name as glAccountName, glAccount.gl_code as glAccountCode,glAccount.id as glAccountId, ") .append(" journalEntry.office_id as officeId, office.name as officeName, journalEntry.ref_num as referenceNumber, ") .append(" journalEntry.manual_entry as manualEntry,journalEntry.entry_date as transactionDate, ") @@ -187,8 +185,8 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); if (associationParametersData.isRunningBalanceRequired()) { officeRunningBalance = rs.getBigDecimal("officeRunningBalance"); @@ -225,13 +223,13 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat TransactionTypeEnumData transactionTypeEnumData = null; if (PortfolioAccountType.fromInt(entityTypeId).isLoanAccount()) { - final LoanTransactionEnumData loanTransactionType = LoanEnumerations.transactionType(JdbcSupport.getInteger(rs, - "loanTransactionType")); + final LoanTransactionEnumData loanTransactionType = LoanEnumerations + .transactionType(JdbcSupport.getInteger(rs, "loanTransactionType")); transactionTypeEnumData = new TransactionTypeEnumData(loanTransactionType.id(), loanTransactionType.getCode(), loanTransactionType.getValue()); } else if (PortfolioAccountType.fromInt(entityTypeId).isSavingsAccount()) { - final SavingsAccountTransactionEnumData savingsTransactionType = SavingsEnumerations.transactionType(JdbcSupport - .getInteger(rs, "savingsTransactionType")); + final SavingsAccountTransactionEnumData savingsTransactionType = SavingsEnumerations + .transactionType(JdbcSupport.getInteger(rs, "savingsTransactionType")); transactionTypeEnumData = new TransactionTypeEnumData(savingsTransactionType.getId(), savingsTransactionType.getCode(), savingsTransactionType.getValue()); } @@ -349,9 +347,8 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat whereClose = " and "; } if (searchParameters.isSavingsIdPassed()) { - sqlBuilder - .append(whereClose - + " journalEntry.savings_transaction_id in (select id from m_savings_account_transaction where savings_account_id = ?)"); + sqlBuilder.append(whereClose + + " journalEntry.savings_transaction_id in (select id from m_savings_account_transaction where savings_account_id = ?)"); objectArray[arrayPos] = searchParameters.getSavingsId(); arrayPos = arrayPos + 1; @@ -404,15 +401,19 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat final FinancialActivityAccount financialActivityAccountId = this.financialActivityAccountRepositoryWrapper .findByFinancialActivityTypeWithNotFoundDetection(300); final Long contraId = financialActivityAccountId.getGlAccount().getId(); - if (contraId == null) { throw new GeneralPlatformDomainRuleException( - "error.msg.financial.activity.mapping.opening.balance.contra.account.cannot.be.null", - "office-opening-balances-contra-account value can not be null", "office-opening-balances-contra-account"); } + if (contraId == null) { + throw new GeneralPlatformDomainRuleException( + "error.msg.financial.activity.mapping.opening.balance.contra.account.cannot.be.null", + "office-opening-balances-contra-account value can not be null", "office-opening-balances-contra-account"); + } final JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(); final GLAccountData contraAccount = this.glAccountReadPlatformService.retrieveGLAccountById(contraId, associationParametersData); - if (!GLAccountType.fromInt(contraAccount.getTypeId()).isEquityType()) { throw new GeneralPlatformDomainRuleException( - "error.msg.configuration.opening.balance.contra.account.value.is.invalid.account.type", - "Global configuration 'office-opening-balances-contra-account' value is not an equity type account", contraId); } + if (!GLAccountType.fromInt(contraAccount.getTypeId()).isEquityType()) { + throw new GeneralPlatformDomainRuleException( + "error.msg.configuration.opening.balance.contra.account.value.is.invalid.account.type", + "Global configuration 'office-opening-balances-contra-account' value is not an equity type account", contraId); + } final OfficeData officeData = this.officeReadPlatformService.retrieveOffice(officeId); final List allOpeningTransactions = populateAllTransactionsFromGLAccounts(contraId); @@ -494,8 +495,8 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat final String transactionId = ""; final Page contraJournalEntries = retrieveContraTransactions(officeId, contraId, transactionId, currencyCode); if (!CollectionUtils.isEmpty(contraJournalEntries.getPageItems())) { - final JournalEntryData contraTransaction = contraJournalEntries.getPageItems().get( - contraJournalEntries.getPageItems().size() - 1); + final JournalEntryData contraTransaction = contraJournalEntries.getPageItems() + .get(contraJournalEntries.getPageItems().size() - 1); return contraTransaction.getTransactionId(); } return transactionId; @@ -524,13 +525,13 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat @Override public Page retrieveJournalEntriesByEntityId(String transactionId, Long entityId, Integer entityType) { - JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(true, - true); + JournalEntryAssociationParametersData associationParametersData = new JournalEntryAssociationParametersData(true, true); try { final GLJournalEntryMapper rm = new GLJournalEntryMapper(associationParametersData); - final String sql = "select " + rm.schema() + " where journalEntry.transaction_id = ? and journalEntry.entity_id = ? and journalEntry.entity_type_enum = ?"; + final String sql = "select " + rm.schema() + + " where journalEntry.transaction_id = ? and journalEntry.entity_id = ? and journalEntry.entity_type_enum = ?"; final String sqlCountRows = "SELECT FOUND_ROWS()"; - Object[] data = {transactionId, entityId, entityType} ; + Object[] data = { transactionId, entityId, entityType }; return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sql, data, rm); } catch (final EmptyResultDataAccessException e) { throw new JournalEntriesNotFoundException(entityId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryRunningBalanceUpdateServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryRunningBalanceUpdateServiceImpl.java old mode 100755 new mode 100644 index 493cdc8dd..be6e2d075 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryRunningBalanceUpdateServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryRunningBalanceUpdateServiceImpl.java @@ -65,29 +65,34 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry private final GLJournalEntryMapper entryMapper = new GLJournalEntryMapper(); - // if a limit is not added to the running balance select statements below and the resultset is more than 400,000, + // if a limit is not added to the running balance select statements below + // and the resultset is more than 400,000, // the script will eat up all of the server memory private final String selectRunningBalanceSqlLimit = "limit 0, 10000"; private final String officeRunningBalanceSql = "select je.office_running_balance as runningBalance,je.account_id as accountId from acc_gl_journal_entry je " + "inner join (select max(id) as id from acc_gl_journal_entry where office_id=? and entry_date < ? group by account_id,entry_date) je2 " + "inner join (select max(entry_date) as date from acc_gl_journal_entry where office_id=? and entry_date < ? group by account_id) je3 " - + "where je2.id = je.id and je.entry_date = je3.date group by je.id order by je.entry_date DESC " + selectRunningBalanceSqlLimit; + + "where je2.id = je.id and je.entry_date = je3.date group by je.id order by je.entry_date DESC " + + selectRunningBalanceSqlLimit; private final String organizationRunningBalanceSql = "select je.organization_running_balance as runningBalance,je.account_id as accountId from acc_gl_journal_entry je " + "inner join (select max(id) as id from acc_gl_journal_entry where entry_date < ? group by account_id,entry_date) je2 " + "inner join (select max(entry_date) as date from acc_gl_journal_entry where entry_date < ? group by account_id) je3 " - + "where je2.id = je.id and je.entry_date = je3.date group by je.id order by je.entry_date DESC " + selectRunningBalanceSqlLimit; + + "where je2.id = je.id and je.entry_date = je3.date group by je.id order by je.entry_date DESC " + + selectRunningBalanceSqlLimit; private final String officesRunningBalanceSql = "select je.office_running_balance as runningBalance,je.account_id as accountId,je.office_id as officeId " + "from acc_gl_journal_entry je " + "inner join (select max(id) as id from acc_gl_journal_entry where entry_date < ? group by office_id,account_id,entry_date) je2 " + "inner join (select max(entry_date) as date from acc_gl_journal_entry where entry_date < ? group by office_id,account_id) je3 " - + "where je2.id = je.id and je.entry_date = je3.date group by je.id order by je.entry_date DESC " + selectRunningBalanceSqlLimit; + + "where je2.id = je.id and je.entry_date = je3.date group by je.id order by je.entry_date DESC " + + selectRunningBalanceSqlLimit; @Autowired - public JournalEntryRunningBalanceUpdateServiceImpl(final RoutingDataSource dataSource, final OfficeRepositoryWrapper officeRepositoryWrapper, - final JournalEntryDataValidator dataValidator, final FromJsonHelper fromApiJsonHelper) { + public JournalEntryRunningBalanceUpdateServiceImpl(final RoutingDataSource dataSource, + final OfficeRepositoryWrapper officeRepositoryWrapper, final JournalEntryDataValidator dataValidator, + final FromJsonHelper fromApiJsonHelper) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.officeRepositoryWrapper = officeRepositoryWrapper; this.dataValidator = dataValidator; @@ -112,8 +117,8 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry this.dataValidator.validateForUpdateRunningbalance(command); final Long officeId = this.fromApiJsonHelper.extractLongNamed(JournalEntryJsonInputParams.OFFICE_ID.getValue(), command.parsedJson()); - CommandProcessingResultBuilder commandProcessingResultBuilder = new CommandProcessingResultBuilder().withCommandId(command - .commandId()); + CommandProcessingResultBuilder commandProcessingResultBuilder = new CommandProcessingResultBuilder() + .withCommandId(command.commandId()); if (officeId == null) { updateRunningBalance(); } else { @@ -137,7 +142,16 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry List> list = jdbcTemplate.queryForList(organizationRunningBalanceSql, entityDate, entityDate); for (Map entries : list) { - Long accountId = Long.parseLong(entries.get("accountId").toString()); //Drizzle is returning Big Integer where as MySQL returns Long. + Long accountId = Long.parseLong(entries.get("accountId").toString()); // Drizzle + // is + // returning + // Big + // Integer + // where + // as + // MySQL + // returns + // Long. if (!runningBalanceMap.containsKey(accountId)) { runningBalanceMap.put(accountId, (BigDecimal) entries.get("runningBalance")); } @@ -166,8 +180,8 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry final Integer batchUpdateSize = 1000; ArrayList updateSql = new ArrayList<>(); int batchIndex = 0; - for (int index = 0 ; index < entryDatas.size() ; index++) { - JournalEntryData entryData = entryDatas.get(index) ; + for (int index = 0; index < entryDatas.size(); index++) { + JournalEntryData entryData = entryDatas.get(index); Map officeRunningBalanceMap = null; if (officesRunningBalance.containsKey(entryData.getOfficeId())) { officeRunningBalanceMap = officesRunningBalance.get(entryData.getOfficeId()); @@ -179,12 +193,12 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry BigDecimal runningBalance = calculateRunningBalance(entryData, runningBalanceMap); String sql = "UPDATE acc_gl_journal_entry je SET je.is_running_balance_calculated=1, je.organization_running_balance=" + runningBalance + ",je.office_running_balance=" + officeRunningBalance + " WHERE je.id=" + entryData.getId(); - updateSql.add(sql) ; - batchIndex++ ; - if (batchIndex == batchUpdateSize || index == entryDatas.size()-1) { + updateSql.add(sql); + batchIndex++; + if (batchIndex == batchUpdateSize || index == entryDatas.size() - 1) { // run a batch update of the 1000 update SQL statements - String[] batch = new String[updateSql.size()] ; - updateSql.toArray(batch) ; + String[] batch = new String[updateSql.size()]; + updateSql.toArray(batch); this.jdbcTemplate.batchUpdate(batch); // reset counter and string array batchIndex = 0; @@ -205,8 +219,8 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry runningBalanceMap.put(accountId, (BigDecimal) entries.get("runningBalance")); } } - List entryDatas = jdbcTemplate.query(entryMapper.officeRunningBalanceSchema(), entryMapper, new Object[] { - officeId, entityDate }); + List entryDatas = jdbcTemplate.query(entryMapper.officeRunningBalanceSchema(), entryMapper, + new Object[] { officeId, entityDate }); String[] updateSql = new String[entryDatas.size()]; int i = 0; for (JournalEntryData entryData : entryDatas) { @@ -290,8 +304,8 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry final int entryTypeId = JdbcSupport.getInteger(rs, "entryType"); final EnumOptionData entryType = AccountingEnumerations.journalEntryType(entryTypeId); - return new JournalEntryData(id, officeId, null, null, glAccountId, null, accountType, null, entryType, amount, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, null); + return new JournalEntryData(id, officeId, null, null, glAccountId, null, accountType, null, entryType, amount, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryWritePlatformService.java old mode 100755 new mode 100644 index 4ed5fcf64..297d32e01 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryWritePlatformService.java @@ -39,9 +39,9 @@ public interface JournalEntryWritePlatformService { CommandProcessingResult defineOpeningBalance(JsonCommand command); - public String revertProvisioningJournalEntries(final Date reversalTransactionDate, final Long entityId, final Integer entityType) ; + public String revertProvisioningJournalEntries(final Date reversalTransactionDate, final Long entityId, final Integer entityType); - public String createProvisioningJournalEntries(ProvisioningEntry entry) ; + public String createProvisioningJournalEntries(ProvisioningEntry entry); void createJournalEntriesForShares(Map accountingBridgeData); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index f4e9db800..75daa1f43 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/journalentry/service/JournalEntryWritePlatformServiceJpaRepositoryImpl.java @@ -168,8 +168,9 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa .orElseThrow(() -> new AccountingRuleNotFoundException(accountRuleId)); if (accountingRule.getAccountToCredit() == null) { - if (journalEntryCommand.getCredits() == null) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.NO_DEBITS_OR_CREDITS, null, null, null); } + if (journalEntryCommand.getCredits() == null) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.NO_DEBITS_OR_CREDITS, null, null, null); + } if (journalEntryCommand.getDebits() != null) { checkDebitOrCreditAccountsAreValid(accountingRule, journalEntryCommand.getCredits(), journalEntryCommand.getDebits()); @@ -187,8 +188,9 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa } if (accountingRule.getAccountToDebit() == null) { - if (journalEntryCommand.getDebits() == null) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.NO_DEBITS_OR_CREDITS, null, null, null); } + if (journalEntryCommand.getDebits() == null) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.NO_DEBITS_OR_CREDITS, null, null, null); + } if (journalEntryCommand.getCredits() != null) { checkDebitOrCreditAccountsAreValid(accountingRule, journalEntryCommand.getCredits(), journalEntryCommand.getDebits()); @@ -227,11 +229,13 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa * If a glaccount is assigned for a rule the credits or debits array * should have only one entry and it must be same as existing account */ - if (creditOrDebits.length != 1) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.INVALID_DEBIT_OR_CREDIT_ACCOUNTS, null, null, null); } + if (creditOrDebits.length != 1) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.INVALID_DEBIT_OR_CREDIT_ACCOUNTS, null, null, null); + } for (final SingleDebitOrCreditEntryCommand creditOrDebit : creditOrDebits) { - if (!glaccount.getId().equals(creditOrDebit.getGlAccountId())) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.INVALID_DEBIT_OR_CREDIT_ACCOUNTS, null, null, null); } + if (!glaccount.getId().equals(creditOrDebit.getGlAccountId())) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.INVALID_DEBIT_OR_CREDIT_ACCOUNTS, null, null, null); + } } } @@ -272,27 +276,31 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa } } if (debits.length != validDebits.length) { - throw new JournalEntryRuntimeException("error.msg.glJournalEntry.invalid.debits","Invalid Debits"); + throw new JournalEntryRuntimeException("error.msg.glJournalEntry.invalid.debits", "Invalid Debits"); } } } - private void checkDebitAndCreditAmounts(final SingleDebitOrCreditEntryCommand[] credits, final SingleDebitOrCreditEntryCommand[] debits) { + private void checkDebitAndCreditAmounts(final SingleDebitOrCreditEntryCommand[] credits, + final SingleDebitOrCreditEntryCommand[] debits) { // sum of all debits must be = sum of all credits BigDecimal creditsSum = BigDecimal.ZERO; BigDecimal debitsSum = BigDecimal.ZERO; for (final SingleDebitOrCreditEntryCommand creditEntryCommand : credits) { - if (creditEntryCommand.getAmount() == null || creditEntryCommand.getGlAccountId() == null) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null); } + if (creditEntryCommand.getAmount() == null || creditEntryCommand.getGlAccountId() == null) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null); + } creditsSum = creditsSum.add(creditEntryCommand.getAmount()); } for (final SingleDebitOrCreditEntryCommand debitEntryCommand : debits) { - if (debitEntryCommand.getAmount() == null || debitEntryCommand.getGlAccountId() == null) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null); } + if (debitEntryCommand.getAmount() == null || debitEntryCommand.getGlAccountId() == null) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null); + } debitsSum = debitsSum.add(debitEntryCommand.getAmount()); } - if (creditsSum.compareTo(debitsSum) != 0) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.DEBIT_CREDIT_SUM_MISMATCH, null, null, null); } + if (creditsSum.compareTo(debitsSum) != 0) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.DEBIT_CREDIT_SUM_MISMATCH, null, null, null); + } } private void validateGLAccountForTransaction(final GLAccount creditOrDebitAccountHead) { @@ -303,17 +311,18 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa if (creditOrDebitAccountHead.isDisabled()) { throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.GL_ACCOUNT_DISABLED, null, creditOrDebitAccountHead.getName(), creditOrDebitAccountHead.getGlCode()); - } else if (!creditOrDebitAccountHead.isManualEntriesAllowed()) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.GL_ACCOUNT_MANUAL_ENTRIES_NOT_PERMITTED, null, creditOrDebitAccountHead.getName(), - creditOrDebitAccountHead.getGlCode()); } + } else if (!creditOrDebitAccountHead.isManualEntriesAllowed()) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.GL_ACCOUNT_MANUAL_ENTRIES_NOT_PERMITTED, null, + creditOrDebitAccountHead.getName(), creditOrDebitAccountHead.getGlCode()); + } } @Transactional @Override public CommandProcessingResult revertJournalEntry(final JsonCommand command) { // is the transaction Id valid - final List journalEntries = this.glJournalEntryRepository.findUnReversedManualJournalEntriesByTransactionId(command - .getTransactionId()); + final List journalEntries = this.glJournalEntryRepository + .findUnReversedManualJournalEntriesByTransactionId(command.getTransactionId()); String reversalComment = command.stringValueOfParameterNamed("comments"); if (journalEntries.size() <= 1) { throw new JournalEntriesNotFoundException(command.getTransactionId()); } @@ -330,7 +339,8 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa validateCommentForReversal(reversalComment); - //Before reversal validate accounting closure is done for that branch or not. + // Before reversal validate accounting closure is done for that branch + // or not. final Date journalEntriesTransactionDate = journalEntries.get(0).getTransactionDate(); final GLClosure latestGLClosureByBranch = this.glClosureRepository.getLatestGLClosureByBranch(officeId); if (latestGLClosureByBranch != null) { @@ -477,8 +487,10 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa baseDataValidator.reset().parameter("comments").value(reversalComment).notExceedingLengthOf(500); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } @Transactional @@ -578,13 +590,16 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa final Date transactionDate = entryLocalDate.toDateTimeAtStartOfDay().toDate(); // shouldn't be in the future final Date todaysDate = new Date(); - if (transactionDate.after(todaysDate)) { throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.FUTURE_DATE, - transactionDate, null, null); } + if (transactionDate.after(todaysDate)) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.FUTURE_DATE, transactionDate, null, null); + } // shouldn't be before an accounting closure final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(command.getOfficeId()); if (latestGLClosure != null) { - if (latestGLClosure.getClosingDate().after(transactionDate) || latestGLClosure.getClosingDate().equals(transactionDate)) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate(), null, null); } + if (latestGLClosure.getClosingDate().after(transactionDate) || latestGLClosure.getClosingDate().equals(transactionDate)) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate(), + null, null); + } } /*** check if credits and debits are valid **/ @@ -592,16 +607,16 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa final SingleDebitOrCreditEntryCommand[] debits = command.getDebits(); // atleast one debit or credit must be present - if (credits == null || credits.length <= 0 || debits == null || debits.length <= 0) { throw new JournalEntryInvalidException( - GlJournalEntryInvalidReason.NO_DEBITS_OR_CREDITS, null, null, null); } + if (credits == null || credits.length <= 0 || debits == null || debits.length <= 0) { + throw new JournalEntryInvalidException(GlJournalEntryInvalidReason.NO_DEBITS_OR_CREDITS, null, null, null); + } checkDebitAndCreditAmounts(credits, debits); } private void saveAllDebitOrCreditEntries(final JournalEntryCommand command, final Office office, final PaymentDetail paymentDetail, - final String currencyCode, final Date transactionDate, - final SingleDebitOrCreditEntryCommand[] singleDebitOrCreditEntryCommands, final String transactionId, - final JournalEntryType type, final String referenceNumber) { + final String currencyCode, final Date transactionDate, final SingleDebitOrCreditEntryCommand[] singleDebitOrCreditEntryCommands, + final String transactionId, final JournalEntryType type, final String referenceNumber) { final boolean manualEntry = true; for (final SingleDebitOrCreditEntryCommand singleDebitOrCreditEntryCommand : singleDebitOrCreditEntryCommands) { final GLAccount glAccount = this.glAccountRepository.findById(singleDebitOrCreditEntryCommand.getGlAccountId()) @@ -655,9 +670,11 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa final FinancialActivityAccount financialActivityAccountId = this.financialActivityAccountRepositoryWrapper .findByFinancialActivityTypeWithNotFoundDetection(300); final Long contraId = financialActivityAccountId.getGlAccount().getId(); - if (contraId == null) { throw new GeneralPlatformDomainRuleException( - "error.msg.financial.activity.mapping.opening.balance.contra.account.cannot.be.null", - "office-opening-balances-contra-account value can not be null", "office-opening-balances-contra-account"); } + if (contraId == null) { + throw new GeneralPlatformDomainRuleException( + "error.msg.financial.activity.mapping.opening.balance.contra.account.cannot.be.null", + "office-opening-balances-contra-account value can not be null", "office-opening-balances-contra-account"); + } validateJournalEntriesArePostedBefore(contraId); @@ -697,16 +714,17 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa } private void saveAllDebitOrCreditOpeningBalanceEntries(final JournalEntryCommand command, final Office office, - final String currencyCode, final Date transactionDate, - final SingleDebitOrCreditEntryCommand[] singleDebitOrCreditEntryCommands, final String transactionId, - final JournalEntryType type, final Long contraAccountId) { + final String currencyCode, final Date transactionDate, final SingleDebitOrCreditEntryCommand[] singleDebitOrCreditEntryCommands, + final String transactionId, final JournalEntryType type, final Long contraAccountId) { final boolean manualEntry = true; final GLAccount contraAccount = this.glAccountRepository.findById(contraAccountId) .orElseThrow(() -> new GLAccountNotFoundException(contraAccountId)); - if (!GLAccountType.fromInt(contraAccount.getType()).isEquityType()) { throw new GeneralPlatformDomainRuleException( - "error.msg.configuration.opening.balance.contra.account.value.is.invalid.account.type", - "Global configuration 'office-opening-balances-contra-account' value is not an equity type account", contraAccountId); } + if (!GLAccountType.fromInt(contraAccount.getType()).isEquityType()) { + throw new GeneralPlatformDomainRuleException( + "error.msg.configuration.opening.balance.contra.account.value.is.invalid.account.type", + "Global configuration 'office-opening-balances-contra-account' value is not an equity type account", contraAccountId); + } validateGLAccountForTransaction(contraAccount); final JournalEntryType contraType = getContraType(type); String comments = command.getComments(); @@ -750,9 +768,10 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa private void validateJournalEntriesArePostedBefore(final Long contraId) { final List transactionIds = this.glJournalEntryRepository.findNonContraTansactionIds(contraId); - if (!CollectionUtils.isEmpty(transactionIds)) { throw new GeneralPlatformDomainRuleException( - "error.msg.journalentry.defining.openingbalance.not.allowed", - "Defining Opening balances not allowed after journal entries posted", transactionIds); } + if (!CollectionUtils.isEmpty(transactionIds)) { + throw new GeneralPlatformDomainRuleException("error.msg.journalentry.defining.openingbalance.not.allowed", + "Defining Opening balances not allowed after journal entries posted", transactionIds); + } } @Override @@ -773,9 +792,7 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa @Override public boolean equals(Object obj) { - if (!(obj instanceof OfficeCurrencyKey)) { - return false; - } + if (!(obj instanceof OfficeCurrencyKey)) { return false; } OfficeCurrencyKey copy = (OfficeCurrencyKey) obj; return Objects.equals(this.office.getId(), copy.office.getId()) && this.currency.equals(copy.currency); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/PortfolioProductType.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/PortfolioProductType.java old mode 100755 new mode 100644 index d7817a69e..31a50b865 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/PortfolioProductType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/PortfolioProductType.java @@ -22,6 +22,7 @@ import java.util.HashMap; import java.util.Map; public enum PortfolioProductType { + LOAN(1, "productType.loan"), SAVING(2, "productType.saving"), CLIENT(5, "productType.client"), PROVISIONING(3, "productType.provisioning"), SHARES(4, "productType.shares"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/ProductToGLAccountMapping.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/ProductToGLAccountMapping.java old mode 100755 new mode 100644 index 14a9762e7..82b4faaa2 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/ProductToGLAccountMapping.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/ProductToGLAccountMapping.java @@ -34,7 +34,7 @@ import org.apache.fineract.portfolio.paymenttype.domain.PaymentType; "financial_account_type", "payment_type" }, name = "financial_action") }) public class ProductToGLAccountMapping extends AbstractPersistableCustom { - @ManyToOne(optional=true) + @ManyToOne(optional = true) @JoinColumn(name = "gl_account_id") private GLAccount glAccount; @@ -64,17 +64,18 @@ public class ProductToGLAccountMapping extends AbstractPersistableCustom { // } - public ProductToGLAccountMapping(final GLAccount glAccount, final Long productId, final int productType, final int financialAccountType) { + public ProductToGLAccountMapping(final GLAccount glAccount, final Long productId, final int productType, + final int financialAccountType) { this(glAccount, productId, productType, financialAccountType, null, null); } - public ProductToGLAccountMapping(final GLAccount glAccount, final Long productId, final int productType, - final int financialAccountType, final Charge charge) { + public ProductToGLAccountMapping(final GLAccount glAccount, final Long productId, final int productType, final int financialAccountType, + final Charge charge) { this(glAccount, productId, productType, financialAccountType, null, charge); } - public ProductToGLAccountMapping(final GLAccount glAccount, final Long productId, final int productType, - final int financialAccountType, final PaymentType paymentType) { + public ProductToGLAccountMapping(final GLAccount glAccount, final Long productId, final int productType, final int financialAccountType, + final PaymentType paymentType) { this(glAccount, productId, productType, financialAccountType, paymentType, null); } @@ -136,4 +137,4 @@ public class ProductToGLAccountMapping extends AbstractPersistableCustom { this.charge = charge; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/ProductToGLAccountMappingRepository.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/ProductToGLAccountMappingRepository.java old mode 100755 new mode 100644 index 39fde10ca..1a7ecc8df --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/ProductToGLAccountMappingRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/domain/ProductToGLAccountMappingRepository.java @@ -24,31 +24,38 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface ProductToGLAccountMappingRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface ProductToGLAccountMappingRepository + extends JpaRepository, JpaSpecificationExecutor { ProductToGLAccountMapping findByProductIdAndProductTypeAndFinancialAccountTypeAndPaymentTypeId(Long productId, int productType, int financialAccountType, Long paymentType); @Query("select mapping from ProductToGLAccountMapping mapping where mapping.productId= :productId and mapping.productType= :productType and mapping.financialAccountType= :financialAccountType and mapping.charge.id= :chargeId") - ProductToGLAccountMapping findProductIdAndProductTypeAndFinancialAccountTypeAndChargeId(@Param("productId") Long productId, @Param("productType") int productType, - @Param("financialAccountType") int financialAccountType, @Param("chargeId") Long ChargeId); + ProductToGLAccountMapping findProductIdAndProductTypeAndFinancialAccountTypeAndChargeId(@Param("productId") Long productId, + @Param("productType") int productType, @Param("financialAccountType") int financialAccountType, + @Param("chargeId") Long ChargeId); @Query("select mapping from ProductToGLAccountMapping mapping where mapping.productId =:productId and mapping.productType =:productType and mapping.financialAccountType=:financialAccountType and mapping.paymentType is NULL and mapping.charge is NULL") ProductToGLAccountMapping findCoreProductToFinAccountMapping(@Param("productId") Long productId, @Param("productType") int productType, @Param("financialAccountType") int financialAccountType); - /*** The financial Account Type for a fund source will always be an asset (1) ***/ + /*** + * The financial Account Type for a fund source will always be an asset (1) + ***/ @Query("select mapping from ProductToGLAccountMapping mapping where mapping.productId =:productId and mapping.productType =:productType and mapping.financialAccountType=1 and mapping.paymentType is not NULL") List findAllPaymentTypeToFundSourceMappings(@Param("productId") Long productId, @Param("productType") int productType); - /*** The financial Account Type for income from interest will always be 4 ***/ + /*** + * The financial Account Type for income from interest will always be 4 + ***/ @Query("select mapping from ProductToGLAccountMapping mapping where mapping.productId =:productId and mapping.productType =:productType and mapping.financialAccountType=4 and mapping.charge is not NULL") List findAllFeeToIncomeAccountMappings(@Param("productId") Long productId, @Param("productType") int productType); - /*** The financial Account Type for income from interest will always be 5 ***/ + /*** + * The financial Account Type for income from interest will always be 5 + ***/ @Query("select mapping from ProductToGLAccountMapping mapping where mapping.productId =:productId and mapping.productType =:productType and mapping.financialAccountType=5 and mapping.charge is not NULL") List findAllPenaltyToIncomeAccountMappings(@Param("productId") Long productId, @Param("productType") int productType); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/exception/ProductToGLAccountMappingInvalidException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/exception/ProductToGLAccountMappingInvalidException.java old mode 100755 new mode 100644 index 2b3c1f783..acc074034 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/exception/ProductToGLAccountMappingInvalidException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/exception/ProductToGLAccountMappingInvalidException.java @@ -28,8 +28,9 @@ public class ProductToGLAccountMappingInvalidException extends AbstractPlatformD public ProductToGLAccountMappingInvalidException(final String paramName, final String accountName, final Long accountId, final String actualAccountCategory, final String expectedAccountCategory) { - super("error.msg." + paramName + ".invalid.account.type", "Passed in GLAccount " + paramName + " with Id " + accountId - + "maps to the account " + accountName + " of type " + actualAccountCategory + ", the expected account type was one among" - + expectedAccountCategory, paramName, accountId, accountName, actualAccountCategory, expectedAccountCategory); + super("error.msg." + paramName + ".invalid.account.type", + "Passed in GLAccount " + paramName + " with Id " + accountId + "maps to the account " + accountName + " of type " + + actualAccountCategory + ", the expected account type was one among" + expectedAccountCategory, + paramName, accountId, accountName, actualAccountCategory, expectedAccountCategory); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/exception/ProductToGLAccountMappingNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/exception/ProductToGLAccountMappingNotFoundException.java old mode 100755 new mode 100644 index 04c3a16d8..35541be0d --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/exception/ProductToGLAccountMappingNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/exception/ProductToGLAccountMappingNotFoundException.java @@ -31,4 +31,4 @@ public class ProductToGLAccountMappingNotFoundException extends AbstractPlatform super("error.msg.productToAccountMapping.not.found", "Mapping for product of type " + type.toString() + " with Id " + productId + " does not exist for an account of type " + accountType, type.toString(), productId, accountType); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/serialization/ProductToGLAccountMappingFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/serialization/ProductToGLAccountMappingFromApiJsonDeserializer.java old mode 100755 new mode 100644 index 62b3298e6..c262facba --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/serialization/ProductToGLAccountMappingFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/serialization/ProductToGLAccountMappingFromApiJsonDeserializer.java @@ -92,48 +92,47 @@ public final class ProductToGLAccountMappingFromApiJsonDeserializer { if (isCashBasedAccounting(accountingRuleType) || isAccrualBasedAccounting(accountingRuleType)) { - final Long fundAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.FUND_SOURCE.getValue(), - element); + final Long fundAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.FUND_SOURCE.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.FUND_SOURCE.getValue()).value(fundAccountId).notNull() .integerGreaterThanZero(); - final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.LOAN_PORTFOLIO.getValue(), element); + final Long loanPortfolioAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.LOAN_PORTFOLIO.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.LOAN_PORTFOLIO.getValue()).value(loanPortfolioAccountId) .notNull().integerGreaterThanZero(); - final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INTEREST_ON_LOANS.getValue(), element); + final Long incomeFromInterestId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INTEREST_ON_LOANS.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.INTEREST_ON_LOANS.getValue()).value(incomeFromInterestId) .notNull().integerGreaterThanZero(); - final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_FROM_FEES.getValue(), element); - baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) - .notNull().integerGreaterThanZero(); + final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.INCOME_FROM_FEES.getValue(), + element); + baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId).notNull() + .integerGreaterThanZero(); - final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); + final Long incomeFromPenaltyId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .notNull().integerGreaterThanZero(); - final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), element); + final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue()) .value(incomeFromRecoveryAccountId).notNull().integerGreaterThanZero(); - final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), element); + final Long writeOffAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue()).value(writeOffAccountId) .notNull().integerGreaterThanZero(); - final Long overpaymentAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.OVERPAYMENT.getValue(), element); - baseDataValidator.reset().parameter(LoanProductAccountingParams.OVERPAYMENT.getValue()).value(overpaymentAccountId) - .notNull().integerGreaterThanZero(); + final Long overpaymentAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.OVERPAYMENT.getValue(), + element); + baseDataValidator.reset().parameter(LoanProductAccountingParams.OVERPAYMENT.getValue()).value(overpaymentAccountId).notNull() + .integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero(); @@ -141,18 +140,18 @@ public final class ProductToGLAccountMappingFromApiJsonDeserializer { if (isAccrualBasedAccounting(accountingRuleType)) { - final Long receivableInterestAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), element); + final Long receivableInterestAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue()) .value(receivableInterestAccountId).notNull().integerGreaterThanZero(); - final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.FEES_RECEIVABLE.getValue(), element); + final Long receivableFeeAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.FEES_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.FEES_RECEIVABLE.getValue()).value(receivableFeeAccountId) .notNull().integerGreaterThanZero(); - final Long receivablePenaltyAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), element); + final Long receivablePenaltyAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue()) .value(receivablePenaltyAccountId).notNull().integerGreaterThanZero(); } @@ -170,65 +169,65 @@ public final class ProductToGLAccountMappingFromApiJsonDeserializer { final JsonElement element = this.fromApiJsonHelper.parse(json); // accounting related data validation - final Integer accountingRuleType = this.fromApiJsonHelper - .extractIntegerNamed(accountingRuleParamName, element, Locale.getDefault()); + final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed(accountingRuleParamName, element, + Locale.getDefault()); baseDataValidator.reset().parameter(accountingRuleParamName).value(accountingRuleType).notNull().inMinMaxRange(1, 3); if (isCashBasedAccounting(accountingRuleType)) { - final Long savingsControlAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_CONTROL.getValue()) - .value(savingsControlAccountId).notNull().integerGreaterThanZero(); + final Long savingsControlAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) + .notNull().integerGreaterThanZero(); - final Long savingsReferenceAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue()) - .value(savingsReferenceAccountId).notNull().integerGreaterThanZero(); + final Long savingsReferenceAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue()).value(savingsReferenceAccountId) + .notNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero(); - final Long interestOnSavingsAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); + final Long interestOnSavingsAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).notNull().integerGreaterThanZero(); - final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) + final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), + element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId).notNull() + .integerGreaterThanZero(); + + final Long incomeFromPenaltyId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .notNull().integerGreaterThanZero(); - final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue()) - .value(incomeFromPenaltyId).notNull().integerGreaterThanZero(); - final Boolean isDormancyTrackingActive = this.fromApiJsonHelper.extractBooleanNamed(isDormancyTrackingActiveParamName, element); - if(null != isDormancyTrackingActive && isDormancyTrackingActive){ - final Long escheatLiabilityId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue()) - .value(escheatLiabilityId).notNull().integerGreaterThanZero(); + if (null != isDormancyTrackingActive && isDormancyTrackingActive) { + final Long escheatLiabilityId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue()).value(escheatLiabilityId) + .notNull().integerGreaterThanZero(); } if (!accountType.equals(DepositAccountType.RECURRING_DEPOSIT) && !accountType.equals(DepositAccountType.FIXED_DEPOSIT)) { - final Long overdraftAccount = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), element); + final Long overdraftAccount = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue()) .value(overdraftAccount).notNull().integerGreaterThanZero(); - final Long incomeFromInterest = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue()) - .value(incomeFromInterest).notNull().integerGreaterThanZero(); - - final Long writtenOff = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue()).value(writtenOff) + final Long incomeFromInterest = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue()).value(incomeFromInterest) .notNull().integerGreaterThanZero(); + + final Long writtenOff = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), + element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue()).value(writtenOff).notNull() + .integerGreaterThanZero(); } } @@ -246,31 +245,31 @@ public final class ProductToGLAccountMappingFromApiJsonDeserializer { final JsonElement element = this.fromApiJsonHelper.parse(json); // accounting related data validation - final Integer accountingRuleType = this.fromApiJsonHelper - .extractIntegerNamed(accountingRuleParamName, element, Locale.getDefault()); + final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed(accountingRuleParamName, element, + Locale.getDefault()); baseDataValidator.reset().parameter(accountingRuleParamName).value(accountingRuleType).notNull().inMinMaxRange(1, 3); if (isCashBasedAccounting(accountingRuleType)) { - final Long shareReferenceId = this.fromApiJsonHelper.extractLongNamed( - SharesProductAccountingParams.SHARES_REFERENCE.getValue(), element); - baseDataValidator.reset().parameter(SharesProductAccountingParams.SHARES_REFERENCE.getValue()) - .value(shareReferenceId).notNull().integerGreaterThanZero(); + final Long shareReferenceId = this.fromApiJsonHelper.extractLongNamed(SharesProductAccountingParams.SHARES_REFERENCE.getValue(), + element); + baseDataValidator.reset().parameter(SharesProductAccountingParams.SHARES_REFERENCE.getValue()).value(shareReferenceId).notNull() + .integerGreaterThanZero(); - final Long shareSuspenseId = this.fromApiJsonHelper.extractLongNamed( - SharesProductAccountingParams.SHARES_SUSPENSE.getValue(), element); - baseDataValidator.reset().parameter(SharesProductAccountingParams.SHARES_SUSPENSE.getValue()) - .value(shareSuspenseId).notNull().integerGreaterThanZero(); + final Long shareSuspenseId = this.fromApiJsonHelper.extractLongNamed(SharesProductAccountingParams.SHARES_SUSPENSE.getValue(), + element); + baseDataValidator.reset().parameter(SharesProductAccountingParams.SHARES_SUSPENSE.getValue()).value(shareSuspenseId).notNull() + .integerGreaterThanZero(); - final Long incomeFromFeeAccountId = this.fromApiJsonHelper.extractLongNamed( - SharesProductAccountingParams.INCOME_FROM_FEES.getValue(), element); - baseDataValidator.reset().parameter(SharesProductAccountingParams.INCOME_FROM_FEES.getValue()) - .value(incomeFromFeeAccountId).notNull().integerGreaterThanZero(); + final Long incomeFromFeeAccountId = this.fromApiJsonHelper + .extractLongNamed(SharesProductAccountingParams.INCOME_FROM_FEES.getValue(), element); + baseDataValidator.reset().parameter(SharesProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeAccountId) + .notNull().integerGreaterThanZero(); - final Long shareEquityId = this.fromApiJsonHelper.extractLongNamed( - SharesProductAccountingParams.SHARES_EQUITY.getValue(), element); - baseDataValidator.reset().parameter(SharesProductAccountingParams.SHARES_EQUITY.getValue()) - .value(shareEquityId).notNull().integerGreaterThanZero(); + final Long shareEquityId = this.fromApiJsonHelper.extractLongNamed(SharesProductAccountingParams.SHARES_EQUITY.getValue(), + element); + baseDataValidator.reset().parameter(SharesProductAccountingParams.SHARES_EQUITY.getValue()).value(shareEquityId).notNull() + .integerGreaterThanZero(); } @@ -287,7 +286,9 @@ public final class ProductToGLAccountMappingFromApiJsonDeserializer { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/LoanProductToGLAccountMappingHelper.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/LoanProductToGLAccountMappingHelper.java old mode 100755 new mode 100644 index 04fbb6516..8e6f2f59b --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/LoanProductToGLAccountMappingHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/LoanProductToGLAccountMappingHelper.java @@ -49,7 +49,9 @@ public class LoanProductToGLAccountMappingHelper extends ProductToGLAccountMappi paymentTypeRepositoryWrapper); } - /*** Set of abstractions for saving Loan Products to GL Account Mappings ***/ + /*** + * Set of abstractions for saving Loan Products to GL Account Mappings + ***/ public void saveLoanToAssetAccountMapping(final JsonElement element, final String paramName, final Long productId, final int placeHolderTypeId) { @@ -71,7 +73,9 @@ public class LoanProductToGLAccountMappingHelper extends ProductToGLAccountMappi saveProductToAccountMapping(element, paramName, productId, placeHolderTypeId, GLAccountType.LIABILITY, PortfolioProductType.LOAN); } - /*** Set of abstractions for merging Savings Products to GL Account Mappings ***/ + /*** + * Set of abstractions for merging Savings Products to GL Account Mappings + ***/ public void mergeLoanToAssetAccountMappingChanges(final JsonElement element, final String paramName, final Long productId, final int accountTypeId, final String accountTypeName, final Map changes) { mergeProductToAccountMappingChanges(element, paramName, productId, accountTypeId, accountTypeName, changes, GLAccountType.ASSET, @@ -92,8 +96,8 @@ public class LoanProductToGLAccountMappingHelper extends ProductToGLAccountMappi public void mergeLoanToLiabilityAccountMappingChanges(final JsonElement element, final String paramName, final Long productId, final int accountTypeId, final String accountTypeName, final Map changes) { - mergeProductToAccountMappingChanges(element, paramName, productId, accountTypeId, accountTypeName, changes, - GLAccountType.LIABILITY, PortfolioProductType.LOAN); + mergeProductToAccountMappingChanges(element, paramName, productId, accountTypeId, accountTypeName, changes, GLAccountType.LIABILITY, + PortfolioProductType.LOAN); } /*** Abstractions for payments channel related to loan products ***/ @@ -127,38 +131,38 @@ public class LoanProductToGLAccountMappingHelper extends ProductToGLAccountMappi final Map changes = new HashMap<>(); final Long fundAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.FUND_SOURCE.getValue(), element); - final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.LOAN_PORTFOLIO.getValue(), element); - final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INTEREST_ON_LOANS.getValue(), element); + final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.LOAN_PORTFOLIO.getValue(), + element); + final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.INTEREST_ON_LOANS.getValue(), + element); final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.INCOME_FROM_FEES.getValue(), element); - final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); + final Long incomeFromPenaltyId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); - final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), element); + final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), element); - final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), element); + final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), + element); final Long overPaymentAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.OVERPAYMENT.getValue(), element); - final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); - final Long receivableInterestAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), element); - final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.FEES_RECEIVABLE.getValue(), element); - final Long receivablePenaltyAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), element); + final Long receivableInterestAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), element); + final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.FEES_RECEIVABLE.getValue(), + element); + final Long receivablePenaltyAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), element); switch (accountingRuleType) { case NONE: break; case CASH_BASED: - populateChangesForCashBasedAccounting(changes, fundAccountId, loanPortfolioAccountId, incomeFromInterestId, - incomeFromFeeId, incomeFromPenaltyId, writeOffAccountId, overPaymentAccountId, transfersInSuspenseAccountId, + populateChangesForCashBasedAccounting(changes, fundAccountId, loanPortfolioAccountId, incomeFromInterestId, incomeFromFeeId, + incomeFromPenaltyId, writeOffAccountId, overPaymentAccountId, transfersInSuspenseAccountId, incomeFromRecoveryAccountId); break; case ACCRUAL_PERIODIC: @@ -235,17 +239,15 @@ public class LoanProductToGLAccountMappingHelper extends ProductToGLAccountMappi CashAccountsForLoan.INTEREST_ON_LOANS.getValue(), CashAccountsForLoan.INTEREST_ON_LOANS.toString(), changes); mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INCOME_FROM_FEES.getValue(), loanProductId, CashAccountsForLoan.INCOME_FROM_FEES.getValue(), CashAccountsForLoan.INCOME_FROM_FEES.toString(), changes); - mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), - loanProductId, CashAccountsForLoan.INCOME_FROM_PENALTIES.getValue(), - CashAccountsForLoan.INCOME_FROM_PENALTIES.toString(), changes); - mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), - loanProductId, CashAccountsForLoan.INCOME_FROM_RECOVERY.getValue(), - CashAccountsForLoan.INCOME_FROM_RECOVERY.toString(), changes); + mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), loanProductId, + CashAccountsForLoan.INCOME_FROM_PENALTIES.getValue(), CashAccountsForLoan.INCOME_FROM_PENALTIES.toString(), + changes); + mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), loanProductId, + CashAccountsForLoan.INCOME_FROM_RECOVERY.getValue(), CashAccountsForLoan.INCOME_FROM_RECOVERY.toString(), changes); // expenses - mergeLoanToExpenseAccountMappingChanges(element, LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), - loanProductId, CashAccountsForLoan.LOSSES_WRITTEN_OFF.getValue(), - CashAccountsForLoan.LOSSES_WRITTEN_OFF.toString(), changes); + mergeLoanToExpenseAccountMappingChanges(element, LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), loanProductId, + CashAccountsForLoan.LOSSES_WRITTEN_OFF.getValue(), CashAccountsForLoan.LOSSES_WRITTEN_OFF.toString(), changes); // liabilities mergeLoanToLiabilityAccountMappingChanges(element, LoanProductAccountingParams.OVERPAYMENT.getValue(), loanProductId, @@ -262,33 +264,31 @@ public class LoanProductToGLAccountMappingHelper extends ProductToGLAccountMappi mergeLoanToAssetAccountMappingChanges(element, LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), loanProductId, AccrualAccountsForLoan.TRANSFERS_SUSPENSE.getValue(), AccrualAccountsForLoan.TRANSFERS_SUSPENSE.toString(), changes); - mergeLoanToAssetAccountMappingChanges(element, LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), - loanProductId, AccrualAccountsForLoan.INTEREST_RECEIVABLE.getValue(), - AccrualAccountsForLoan.INTEREST_RECEIVABLE.toString(), changes); + mergeLoanToAssetAccountMappingChanges(element, LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), loanProductId, + AccrualAccountsForLoan.INTEREST_RECEIVABLE.getValue(), AccrualAccountsForLoan.INTEREST_RECEIVABLE.toString(), + changes); mergeLoanToAssetAccountMappingChanges(element, LoanProductAccountingParams.FEES_RECEIVABLE.getValue(), loanProductId, AccrualAccountsForLoan.FEES_RECEIVABLE.getValue(), AccrualAccountsForLoan.FEES_RECEIVABLE.toString(), changes); - mergeLoanToAssetAccountMappingChanges(element, LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), - loanProductId, AccrualAccountsForLoan.PENALTIES_RECEIVABLE.getValue(), - AccrualAccountsForLoan.PENALTIES_RECEIVABLE.toString(), changes); + mergeLoanToAssetAccountMappingChanges(element, LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), loanProductId, + AccrualAccountsForLoan.PENALTIES_RECEIVABLE.getValue(), AccrualAccountsForLoan.PENALTIES_RECEIVABLE.toString(), + changes); // income mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INTEREST_ON_LOANS.getValue(), loanProductId, - AccrualAccountsForLoan.INTEREST_ON_LOANS.getValue(), AccrualAccountsForLoan.INTEREST_ON_LOANS.toString(), - changes); + AccrualAccountsForLoan.INTEREST_ON_LOANS.getValue(), AccrualAccountsForLoan.INTEREST_ON_LOANS.toString(), changes); mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INCOME_FROM_FEES.getValue(), loanProductId, - AccrualAccountsForLoan.INCOME_FROM_FEES.getValue(), AccrualAccountsForLoan.INCOME_FROM_FEES.toString(), + AccrualAccountsForLoan.INCOME_FROM_FEES.getValue(), AccrualAccountsForLoan.INCOME_FROM_FEES.toString(), changes); + mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), loanProductId, + AccrualAccountsForLoan.INCOME_FROM_PENALTIES.getValue(), AccrualAccountsForLoan.INCOME_FROM_PENALTIES.toString(), + changes); + mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), loanProductId, + AccrualAccountsForLoan.INCOME_FROM_RECOVERY.getValue(), AccrualAccountsForLoan.INCOME_FROM_RECOVERY.toString(), changes); - mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), - loanProductId, AccrualAccountsForLoan.INCOME_FROM_PENALTIES.getValue(), - AccrualAccountsForLoan.INCOME_FROM_PENALTIES.toString(), changes); - mergeLoanToIncomeAccountMappingChanges(element, LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), - loanProductId, AccrualAccountsForLoan.INCOME_FROM_RECOVERY.getValue(), - AccrualAccountsForLoan.INCOME_FROM_RECOVERY.toString(), changes); // expenses - mergeLoanToExpenseAccountMappingChanges(element, LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), - loanProductId, AccrualAccountsForLoan.LOSSES_WRITTEN_OFF.getValue(), - AccrualAccountsForLoan.LOSSES_WRITTEN_OFF.toString(), changes); + mergeLoanToExpenseAccountMappingChanges(element, LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), loanProductId, + AccrualAccountsForLoan.LOSSES_WRITTEN_OFF.getValue(), AccrualAccountsForLoan.LOSSES_WRITTEN_OFF.toString(), + changes); // liabilities mergeLoanToLiabilityAccountMappingChanges(element, LoanProductAccountingParams.OVERPAYMENT.getValue(), loanProductId, diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingHelper.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingHelper.java old mode 100755 new mode 100644 index 4e22bce23..d8c9fba3a --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingHelper.java @@ -90,8 +90,9 @@ public class ProductToGLAccountMappingHelper { if (accountId != null) { final ProductToGLAccountMapping accountMapping = this.accountMappingRepository.findCoreProductToFinAccountMapping(productId, portfolioProductType.getValue(), accountTypeId); - if (accountMapping == null) { throw new ProductToGLAccountMappingNotFoundException(portfolioProductType, productId, - accountTypeName); } + if (accountMapping == null) { + throw new ProductToGLAccountMappingNotFoundException(portfolioProductType, productId, accountTypeName); + } if (!accountMapping.getGlAccount().getId().equals(accountId)) { final GLAccount glAccount = getAccountByIdAndType(paramName, expectedAccountType, accountId); changes.put(paramName, accountId); @@ -102,21 +103,21 @@ public class ProductToGLAccountMappingHelper { } public void createOrmergeProductToAccountMappingChanges(final JsonElement element, final String paramName, final Long productId, - final int accountTypeId, final Map changes, - final GLAccountType expectedAccountType, final PortfolioProductType portfolioProductType) { + final int accountTypeId, final Map changes, final GLAccountType expectedAccountType, + final PortfolioProductType portfolioProductType) { final Long accountId = this.fromApiJsonHelper.extractLongNamed(paramName, element); // get the existing product if (accountId != null) { final ProductToGLAccountMapping accountMapping = this.accountMappingRepository.findCoreProductToFinAccountMapping(productId, portfolioProductType.getValue(), accountTypeId); - if(accountMapping == null) { + if (accountMapping == null) { final GLAccount glAccount = getAccountByIdAndType(paramName, expectedAccountType, accountId); changes.put(paramName, accountId); - ProductToGLAccountMapping newAccountMapping = new ProductToGLAccountMapping(glAccount, productId, - portfolioProductType.getValue(), accountTypeId) ; + ProductToGLAccountMapping newAccountMapping = new ProductToGLAccountMapping(glAccount, productId, + portfolioProductType.getValue(), accountTypeId); this.accountMappingRepository.save(newAccountMapping); - }else if (!accountMapping.getGlAccount().getId().equals(accountId)) { + } else if (!accountMapping.getGlAccount().getId().equals(accountId)) { final GLAccount glAccount = getAccountByIdAndType(paramName, expectedAccountType, accountId); changes.put(paramName, accountId); accountMapping.setGlAccount(glAccount); @@ -124,6 +125,7 @@ public class ProductToGLAccountMappingHelper { } } } + /** * Saves the payment type to Fund source mappings for a particular * product/product type (also populates the changes array if passed in) @@ -135,8 +137,8 @@ public class ProductToGLAccountMappingHelper { */ public void savePaymentChannelToFundSourceMappings(final JsonCommand command, final JsonElement element, final Long productId, final Map changes, final PortfolioProductType portfolioProductType) { - final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( - LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); + final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper + .extractJsonArrayNamed(LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); if (paymentChannelMappingArray != null) { if (changes != null) { changes.put(LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), @@ -233,15 +235,15 @@ public class ProductToGLAccountMappingHelper { // If input map is empty, delete all existing mappings if (inputChargeToIncomeAccountMap.size() == 0) { this.accountMappingRepository.deleteInBatch(existingChargeToIncomeAccountMappings); - }/** - * Else,
- * update existing mappings OR
- * delete old mappings (which are already present, but not passed in - * as a part of Jsoncommand)
- * Create new mappings for charges that are passed in as a part of - * the Jsoncommand but not already present - * - **/ + } /** + * Else,
+ * update existing mappings OR
+ * delete old mappings (which are already present, but not passed + * in as a part of Jsoncommand)
+ * Create new mappings for charges that are passed in as a part of + * the Jsoncommand but not already present + * + **/ else { for (final ProductToGLAccountMapping chargeToIncomeAccountMapping : existingChargeToIncomeAccountMappings) { final Long currentCharge = chargeToIncomeAccountMapping.getCharge().getId(); @@ -262,7 +264,7 @@ public class ProductToGLAccountMappingHelper { chargeToIncomeAccountMapping.setGlAccount(glAccount); this.accountMappingRepository.save(chargeToIncomeAccountMapping); } - }// deleted payment type + } // deleted payment type else { this.accountMappingRepository.delete(chargeToIncomeAccountMapping); } @@ -291,8 +293,8 @@ public class ProductToGLAccountMappingHelper { // find all existing payment Channel to Fund source Mappings final List existingPaymentChannelToFundSourceMappings = this.accountMappingRepository .findAllPaymentTypeToFundSourceMappings(productId, portfolioProductType.getValue()); - final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( - LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); + final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper + .extractJsonArrayNamed(LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); /** * Variable stores a map representation of Payment channels (key) and * their fund sources (value) extracted from the passed in Jsoncommand @@ -319,15 +321,15 @@ public class ProductToGLAccountMappingHelper { // If input map is empty, delete all existing mappings if (inputPaymentChannelFundSourceMap.size() == 0) { this.accountMappingRepository.deleteInBatch(existingPaymentChannelToFundSourceMappings); - }/** - * Else,
- * update existing mappings OR
- * delete old mappings (which re already present, but not passed in - * as a part of Jsoncommand)
- * Create new mappings for payment types that are passed in as a - * part of the Jsoncommand but not already present - * - **/ + } /** + * Else,
+ * update existing mappings OR
+ * delete old mappings (which re already present, but not passed + * in as a part of Jsoncommand)
+ * Create new mappings for payment types that are passed in as a + * part of the Jsoncommand but not already present + * + **/ else { for (final ProductToGLAccountMapping existingPaymentChannelToFundSourceMapping : existingPaymentChannelToFundSourceMappings) { final Long currentPaymentChannelId = existingPaymentChannelToFundSourceMapping.getPaymentType().getId(); @@ -341,7 +343,7 @@ public class ProductToGLAccountMappingHelper { existingPaymentChannelToFundSourceMapping.setGlAccount(glAccount); this.accountMappingRepository.save(existingPaymentChannelToFundSourceMapping); } - }// deleted payment type + } // deleted payment type else { this.accountMappingRepository.delete(existingPaymentChannelToFundSourceMapping); } @@ -425,9 +427,10 @@ public class ProductToGLAccountMappingHelper { final GLAccount glAccount = this.accountRepositoryWrapper.findOneWithNotFoundDetection(accountId); // validate account is of the expected Type - if (glAccount.getType().intValue() != expectedAccountType.getValue()) { throw new ProductToGLAccountMappingInvalidException( - paramName, glAccount.getName(), accountId, GLAccountType.fromInt(glAccount.getType()).toString(), - expectedAccountType.toString()); } + if (glAccount.getType().intValue() != expectedAccountType.getValue()) { + throw new ProductToGLAccountMappingInvalidException(paramName, glAccount.getName(), accountId, + GLAccountType.fromInt(glAccount.getType()).toString(), expectedAccountType.toString()); + } return glAccount; } @@ -438,14 +441,16 @@ public class ProductToGLAccountMappingHelper { for (GLAccountType glAccountType : expectedAccountTypes) { glAccountTypeValues.add(glAccountType.getValue()); } - if (!glAccountTypeValues.contains(glAccount.getType())) { throw new ProductToGLAccountMappingInvalidException(paramName, - glAccount.getName(), accountId, GLAccountType.fromInt(glAccount.getType()).toString(), glAccountTypeValues.toString()); } + if (!glAccountTypeValues.contains(glAccount.getType())) { + throw new ProductToGLAccountMappingInvalidException(paramName, glAccount.getName(), accountId, + GLAccountType.fromInt(glAccount.getType()).toString(), glAccountTypeValues.toString()); + } return glAccount; } public void deleteProductToGLAccountMapping(final Long loanProductId, final PortfolioProductType portfolioProductType) { - final List productToGLAccountMappings = this.accountMappingRepository.findByProductIdAndProductType( - loanProductId, portfolioProductType.getValue()); + final List productToGLAccountMappings = this.accountMappingRepository + .findByProductIdAndProductType(loanProductId, portfolioProductType.getValue()); if (productToGLAccountMappings != null && productToGLAccountMappings.size() > 0) { this.accountMappingRepository.deleteInBatch(productToGLAccountMappings); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformService.java old mode 100755 new mode 100644 index f1d422904..dfd58159d --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformService.java @@ -47,4 +47,4 @@ public interface ProductToGLAccountMappingReadPlatformService { public List fetchFeeToIncomeAccountMappingsForShareProduct(final Long productId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformServiceImpl.java old mode 100755 new mode 100644 index ad23f06f8..85718d93f --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformServiceImpl.java @@ -108,8 +108,8 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product final ProductToGLAccountMappingMapper rm = new ProductToGLAccountMappingMapper(); final String sql = "select " + rm.schema() + " and product_id = ? and payment_type is null and mapping.charge_id is null"; - final List> listOfProductToGLAccountMaps = this.jdbcTemplate.query(sql, rm, new Object[] { - PortfolioProductType.LOAN.getValue(), loanProductId }); + final List> listOfProductToGLAccountMaps = this.jdbcTemplate.query(sql, rm, + new Object[] { PortfolioProductType.LOAN.getValue(), loanProductId }); if (AccountingRuleType.CASH_BASED.getValue().equals(accountingType)) { @@ -194,8 +194,8 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product final ProductToGLAccountMappingMapper rm = new ProductToGLAccountMappingMapper(); final String sql = "select " + rm.schema() + " and product_id = ? and payment_type is null and mapping.charge_id is null "; - final List> listOfProductToGLAccountMaps = this.jdbcTemplate.query(sql, rm, new Object[] { - PortfolioProductType.SAVING.getValue(), savingsProductId }); + final List> listOfProductToGLAccountMaps = this.jdbcTemplate.query(sql, rm, + new Object[] { PortfolioProductType.SAVING.getValue(), savingsProductId }); if (AccountingRuleType.CASH_BASED.getValue().equals(accountingType)) { @@ -255,8 +255,8 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product final ProductToGLAccountMappingMapper rm = new ProductToGLAccountMappingMapper(); final String sql = "select " + rm.schema() + " and product_id = ? and payment_type is not null"; - final List> paymentTypeToFundSourceMappingsList = this.jdbcTemplate.query(sql, rm, new Object[] { - portfolioProductType.getValue(), loanProductId }); + final List> paymentTypeToFundSourceMappingsList = this.jdbcTemplate.query(sql, rm, + new Object[] { portfolioProductType.getValue(), loanProductId }); List paymentTypeToGLAccountMappers = null; for (final Map productToGLAccountMap : paymentTypeToFundSourceMappingsList) { @@ -308,8 +308,8 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product sql = sql + " 0"; } - final List> chargeToFundSourceMappingsList = this.jdbcTemplate.query(sql, rm, new Object[] { - portfolioProductType.getValue(), loanProductId }); + final List> chargeToFundSourceMappingsList = this.jdbcTemplate.query(sql, rm, + new Object[] { portfolioProductType.getValue(), loanProductId }); List chargeToGLAccountMappers = null; for (final Map chargeToIncomeAccountMap : chargeToFundSourceMappingsList) { if (chargeToGLAccountMappers == null) { @@ -337,8 +337,8 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product final ProductToGLAccountMappingMapper rm = new ProductToGLAccountMappingMapper(); final String sql = "select " + rm.schema() + " and product_id = ? and payment_type is null and mapping.charge_id is null "; - final List> listOfProductToGLAccountMaps = this.jdbcTemplate.query(sql, rm, new Object[] { - PortfolioProductType.SHARES.getValue(), productId }); + final List> listOfProductToGLAccountMaps = this.jdbcTemplate.query(sql, rm, + new Object[] { PortfolioProductType.SHARES.getValue(), productId }); if (AccountingRuleType.CASH_BASED.getValue().equals(accountingType)) { for (final Map productToGLAccountMap : listOfProductToGLAccountMaps) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformService.java old mode 100755 new mode 100644 index 5b0f58fb8..1b11d4d06 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformService.java @@ -39,4 +39,4 @@ public interface ProductToGLAccountMappingWritePlatformService { Map updateShareProductToGLAccountMapping(Long shareProductId, JsonCommand command, boolean accountingRuleChanged, int accountingRuleTypeId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformServiceImpl.java old mode 100755 new mode 100644 index 044f20c71..8d87f3f81 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformServiceImpl.java @@ -75,9 +75,8 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc break; case CASH_BASED: // asset - this.loanProductToGLAccountMappingHelper - .saveLoanToAssetAccountMapping(element, LoanProductAccountingParams.FUND_SOURCE.getValue(), loanProductId, - CashAccountsForLoan.FUND_SOURCE.getValue()); + this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, + LoanProductAccountingParams.FUND_SOURCE.getValue(), loanProductId, CashAccountsForLoan.FUND_SOURCE.getValue()); this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, LoanProductAccountingParams.LOAN_PORTFOLIO.getValue(), loanProductId, CashAccountsForLoan.LOAN_PORTFOLIO.getValue()); @@ -105,9 +104,8 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc CashAccountsForLoan.LOSSES_WRITTEN_OFF.getValue()); // liabilities - this.loanProductToGLAccountMappingHelper - .saveLoanToLiabilityAccountMapping(element, LoanProductAccountingParams.OVERPAYMENT.getValue(), loanProductId, - CashAccountsForLoan.OVERPAYMENT.getValue()); + this.loanProductToGLAccountMappingHelper.saveLoanToLiabilityAccountMapping(element, + LoanProductAccountingParams.OVERPAYMENT.getValue(), loanProductId, CashAccountsForLoan.OVERPAYMENT.getValue()); // advanced accounting mappings this.loanProductToGLAccountMappingHelper.savePaymentChannelToFundSourceMappings(command, element, loanProductId, null); @@ -118,8 +116,7 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc case ACCRUAL_PERIODIC: // assets (including receivables) this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, - LoanProductAccountingParams.FUND_SOURCE.getValue(), loanProductId, - AccrualAccountsForLoan.FUND_SOURCE.getValue()); + LoanProductAccountingParams.FUND_SOURCE.getValue(), loanProductId, AccrualAccountsForLoan.FUND_SOURCE.getValue()); this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, LoanProductAccountingParams.LOAN_PORTFOLIO.getValue(), loanProductId, AccrualAccountsForLoan.LOAN_PORTFOLIO.getValue()); @@ -157,8 +154,7 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc // liabilities this.loanProductToGLAccountMappingHelper.saveLoanToLiabilityAccountMapping(element, - LoanProductAccountingParams.OVERPAYMENT.getValue(), loanProductId, - AccrualAccountsForLoan.OVERPAYMENT.getValue()); + LoanProductAccountingParams.OVERPAYMENT.getValue(), loanProductId, AccrualAccountsForLoan.OVERPAYMENT.getValue()); // advanced accounting mappings this.loanProductToGLAccountMappingHelper.savePaymentChannelToFundSourceMappings(command, element, loanProductId, null); @@ -169,7 +165,8 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc @Override @Transactional - public void createSavingProductToGLAccountMapping(final Long savingProductId, final JsonCommand command, DepositAccountType accountType) { + public void createSavingProductToGLAccountMapping(final Long savingProductId, final JsonCommand command, + DepositAccountType accountType) { final JsonElement element = this.fromApiJsonHelper.parse(command.json()); final Integer accountingRuleTypeId = this.fromApiJsonHelper.extractIntegerNamed(accountingRuleParamName, element, Locale.getDefault()); @@ -224,8 +221,9 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), savingProductId, CashAccountsForSavings.TRANSFERS_SUSPENSE.getValue()); - final Boolean isDormancyTrackingActive = this.fromApiJsonHelper.extractBooleanNamed(isDormancyTrackingActiveParamName, element); - if(null != isDormancyTrackingActive && isDormancyTrackingActive){ + final Boolean isDormancyTrackingActive = this.fromApiJsonHelper.extractBooleanNamed(isDormancyTrackingActiveParamName, + element); + if (null != isDormancyTrackingActive && isDormancyTrackingActive) { this.savingsProductToGLAccountMappingHelper.saveSavingsToLiabilityAccountMapping(element, SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), savingProductId, CashAccountsForSavings.ESCHEAT_LIABILITY.getValue()); @@ -307,7 +305,7 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc createLoanProductToGLAccountMapping(loanProductId, command); changes = this.loanProductToGLAccountMappingHelper.populateChangesForNewLoanProductToGLAccountMappingCreation(element, accountingRuleType); - }/*** else examine and update individual changes ***/ + } /*** else examine and update individual changes ***/ else { this.loanProductToGLAccountMappingHelper.handleChangesToLoanProductToGLAccountMappings(loanProductId, changes, element, accountingRuleType); @@ -338,10 +336,10 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc createSavingProductToGLAccountMapping(savingsProductId, command, accountType); changes = this.savingsProductToGLAccountMappingHelper.populateChangesForNewSavingsProductToGLAccountMappingCreation(element, accountingRuleType); - }/*** else examine and update individual changes ***/ + } /*** else examine and update individual changes ***/ else { - this.savingsProductToGLAccountMappingHelper.handleChangesToSavingsProductToGLAccountMappings(savingsProductId, changes, - element, accountingRuleType); + this.savingsProductToGLAccountMappingHelper.handleChangesToSavingsProductToGLAccountMappings(savingsProductId, changes, element, + accountingRuleType); this.savingsProductToGLAccountMappingHelper.updatePaymentChannelToFundSourceMappings(command, element, savingsProductId, changes); this.savingsProductToGLAccountMappingHelper.updateChargesToIncomeAccountMappings(command, element, savingsProductId, changes); @@ -369,7 +367,7 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc createShareProductToGLAccountMapping(shareProductId, command); changes = this.shareProductToGLAccountMappingHelper.populateChangesForNewSharesProductToGLAccountMappingCreation(element, accountingRuleType); - }/*** else examine and update individual changes ***/ + } /*** else examine and update individual changes ***/ else { this.shareProductToGLAccountMappingHelper.handleChangesToSharesProductToGLAccountMappings(shareProductId, changes, element, accountingRuleType); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/SavingsProductToGLAccountMappingHelper.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/SavingsProductToGLAccountMappingHelper.java old mode 100755 new mode 100644 index c8c0b7f94..4ce519f7e --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/SavingsProductToGLAccountMappingHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/SavingsProductToGLAccountMappingHelper.java @@ -48,7 +48,9 @@ public class SavingsProductToGLAccountMappingHelper extends ProductToGLAccountMa paymentTypeRepositoryWrapper); } - /*** Set of abstractions for saving Saving Products to GL Account Mappings ***/ + /*** + * Set of abstractions for saving Saving Products to GL Account Mappings + ***/ public void saveSavingsToAssetAccountMapping(final JsonElement element, final String paramName, final Long productId, final int placeHolderTypeId) { @@ -70,7 +72,9 @@ public class SavingsProductToGLAccountMappingHelper extends ProductToGLAccountMa saveProductToAccountMapping(element, paramName, productId, placeHolderTypeId, GLAccountType.LIABILITY, PortfolioProductType.SAVING); } - /*** Set of abstractions for merging Savings Products to GL Account Mappings ***/ + /*** + * Set of abstractions for merging Savings Products to GL Account Mappings + ***/ public void mergeSavingsToAssetAccountMappingChanges(final JsonElement element, final String paramName, final Long productId, final int accountTypeId, final String accountTypeName, final Map changes) { @@ -92,14 +96,14 @@ public class SavingsProductToGLAccountMappingHelper extends ProductToGLAccountMa public void mergeSavingsToLiabilityAccountMappingChanges(final JsonElement element, final String paramName, final Long productId, final int accountTypeId, final String accountTypeName, final Map changes) { - mergeProductToAccountMappingChanges(element, paramName, productId, accountTypeId, accountTypeName, changes, - GLAccountType.LIABILITY, PortfolioProductType.SAVING); + mergeProductToAccountMappingChanges(element, paramName, productId, accountTypeId, accountTypeName, changes, GLAccountType.LIABILITY, + PortfolioProductType.SAVING); } - public void createOrmergeSavingsToLiabilityAccountMappingChanges(final JsonElement element, final String paramName, final Long productId, - final int accountTypeId, final Map changes) { - createOrmergeProductToAccountMappingChanges(element, paramName, productId, accountTypeId, changes, - GLAccountType.LIABILITY, PortfolioProductType.SAVING); + public void createOrmergeSavingsToLiabilityAccountMappingChanges(final JsonElement element, final String paramName, + final Long productId, final int accountTypeId, final Map changes) { + createOrmergeProductToAccountMappingChanges(element, paramName, productId, accountTypeId, changes, GLAccountType.LIABILITY, + PortfolioProductType.SAVING); } /*** Abstractions for payments channel related to savings products ***/ @@ -132,22 +136,22 @@ public class SavingsProductToGLAccountMappingHelper extends ProductToGLAccountMa final AccountingRuleType accountingRuleType) { final Map changes = new HashMap<>(); - final Long savingsReferenceId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); - final Long incomeFromFeesId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), element); - final Long incomeFromPenaltiesId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); - final Long interestOnSavingsId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); + final Long savingsReferenceId = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), + element); + final Long incomeFromFeesId = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), + element); + final Long incomeFromPenaltiesId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); + final Long interestOnSavingsId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); final Long savingsControlId = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), element); - final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); - final Long overdraftControlId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), element); - final Long incomeFromInterest = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue(), element); + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); + final Long overdraftControlId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), element); + final Long incomeFromInterest = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue(), element); final Long writeOffId = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), element); switch (accountingRuleType) { @@ -227,8 +231,7 @@ public class SavingsProductToGLAccountMappingHelper extends ProductToGLAccountMa savingsProductId, CashAccountsForSavings.TRANSFERS_SUSPENSE.getValue(), CashAccountsForSavings.TRANSFERS_SUSPENSE.toString(), changes); createOrmergeSavingsToLiabilityAccountMappingChanges(element, SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), - savingsProductId, CashAccountsForSavings.ESCHEAT_LIABILITY.getValue(), - changes); + savingsProductId, CashAccountsForSavings.ESCHEAT_LIABILITY.getValue(), changes); break; case ACCRUAL_PERIODIC: break; diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ShareProductToGLAccountMappingHelper.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ShareProductToGLAccountMappingHelper.java index 93a414cfa..b162eee9e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ShareProductToGLAccountMappingHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/producttoaccountmapping/service/ShareProductToGLAccountMappingHelper.java @@ -48,7 +48,9 @@ public class ShareProductToGLAccountMappingHelper extends ProductToGLAccountMapp paymentTypeRepositoryWrapper); } - /*** Set of abstractions for saving Share Products to GL Account Mappings ***/ + /*** + * Set of abstractions for saving Share Products to GL Account Mappings + ***/ public void saveSharesToAssetAccountMapping(final JsonElement element, final String paramName, final Long productId, final int placeHolderTypeId) { @@ -70,7 +72,9 @@ public class ShareProductToGLAccountMappingHelper extends ProductToGLAccountMapp saveProductToAccountMapping(element, paramName, productId, placeHolderTypeId, GLAccountType.LIABILITY, PortfolioProductType.SHARES); } - /*** Set of abstractions for merging Shares Products to GL Account Mappings ***/ + /*** + * Set of abstractions for merging Shares Products to GL Account Mappings + ***/ public void mergeSharesToAssetAccountMappingChanges(final JsonElement element, final String paramName, final Long productId, final int accountTypeId, final String accountTypeName, final Map changes) { @@ -92,8 +96,8 @@ public class ShareProductToGLAccountMappingHelper extends ProductToGLAccountMapp public void mergeSharesToLiabilityAccountMappingChanges(final JsonElement element, final String paramName, final Long productId, final int accountTypeId, final String accountTypeName, final Map changes) { - mergeProductToAccountMappingChanges(element, paramName, productId, accountTypeId, accountTypeName, changes, - GLAccountType.LIABILITY, PortfolioProductType.SHARES); + mergeProductToAccountMappingChanges(element, paramName, productId, accountTypeId, accountTypeName, changes, GLAccountType.LIABILITY, + PortfolioProductType.SHARES); } /*** Abstractions for payments channel related to Shares products ***/ @@ -126,12 +130,11 @@ public class ShareProductToGLAccountMappingHelper extends ProductToGLAccountMapp final Long shareReferenceId = this.fromApiJsonHelper.extractLongNamed(SharesProductAccountingParams.SHARES_REFERENCE.getValue(), element); - final Long incomeFromFeeAccountId = this.fromApiJsonHelper.extractLongNamed( - SharesProductAccountingParams.INCOME_FROM_FEES.getValue(), element); + final Long incomeFromFeeAccountId = this.fromApiJsonHelper + .extractLongNamed(SharesProductAccountingParams.INCOME_FROM_FEES.getValue(), element); final Long shareSuspenseId = this.fromApiJsonHelper.extractLongNamed(SharesProductAccountingParams.SHARES_SUSPENSE.getValue(), element); - final Long shareEquityId = this.fromApiJsonHelper.extractLongNamed(SharesProductAccountingParams.SHARES_EQUITY.getValue(), - element); + final Long shareEquityId = this.fromApiJsonHelper.extractLongNamed(SharesProductAccountingParams.SHARES_EQUITY.getValue(), element); switch (accountingRuleType) { case NONE: @@ -168,9 +171,8 @@ public class ShareProductToGLAccountMappingHelper extends ProductToGLAccountMapp break; case CASH_BASED: // asset - mergeSharesToAssetAccountMappingChanges(element, SharesProductAccountingParams.SHARES_REFERENCE.getValue(), - sharesProductId, CashAccountsForShares.SHARES_REFERENCE.getValue(), - CashAccountsForShares.SHARES_REFERENCE.toString(), changes); + mergeSharesToAssetAccountMappingChanges(element, SharesProductAccountingParams.SHARES_REFERENCE.getValue(), sharesProductId, + CashAccountsForShares.SHARES_REFERENCE.getValue(), CashAccountsForShares.SHARES_REFERENCE.toString(), changes); // income mergeSharesToIncomeAccountMappingChanges(element, SharesProductAccountingParams.INCOME_FROM_FEES.getValue(), @@ -179,13 +181,12 @@ public class ShareProductToGLAccountMappingHelper extends ProductToGLAccountMapp // liability mergeSharesToLiabilityAccountMappingChanges(element, SharesProductAccountingParams.SHARES_SUSPENSE.getValue(), - sharesProductId, CashAccountsForShares.SHARES_SUSPENSE.getValue(), - CashAccountsForShares.SHARES_SUSPENSE.toString(), changes); + sharesProductId, CashAccountsForShares.SHARES_SUSPENSE.getValue(), CashAccountsForShares.SHARES_SUSPENSE.toString(), + changes); // equity - mergeSharesToEquityAccountMappingChanges(element, SharesProductAccountingParams.SHARES_EQUITY.getValue(), - sharesProductId, CashAccountsForShares.SHARES_EQUITY.getValue(), - CashAccountsForShares.SHARES_EQUITY.toString(), changes); + mergeSharesToEquityAccountMappingChanges(element, SharesProductAccountingParams.SHARES_EQUITY.getValue(), sharesProductId, + CashAccountsForShares.SHARES_EQUITY.getValue(), CashAccountsForShares.SHARES_EQUITY.toString(), changes); break; case ACCRUAL_PERIODIC: break; diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/api/ProvisioningEntriesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/api/ProvisioningEntriesApiResource.java index 7a408d545..205254422 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/api/ProvisioningEntriesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/api/ProvisioningEntriesApiResource.java @@ -62,10 +62,11 @@ import org.springframework.stereotype.Component; @Path("/provisioningentries") @Component @Scope("singleton") -@Api(tags = {"Provisioning Entries"}) +@Api(tags = { "Provisioning Entries" }) @SwaggerDefinition(tags = { - @Tag(name = "Provisioning Entries", description = "This defines the Provisioning Entries for all active loan products\n" + "\n" + "Field Descriptions\n" + "date\n" + "Date on which day provisioning entries should be created\n" + "createjournalentries\n" + "Boolean variable whether to add journal entries for generated provisioning entries\n") -}) + @Tag(name = "Provisioning Entries", description = "This defines the Provisioning Entries for all active loan products\n" + "\n" + + "Field Descriptions\n" + "date\n" + "Date on which day provisioning entries should be created\n" + + "createjournalentries\n" + "Boolean variable whether to add journal entries for generated provisioning entries\n") }) public class ProvisioningEntriesApiResource { private final PlatformSecurityContext platformSecurityContext; @@ -74,10 +75,11 @@ public class ProvisioningEntriesApiResource { private final DefaultToApiJsonSerializer entriesApiJsonSerializer; private final ProvisioningEntriesReadPlatformService provisioningEntriesReadPlatformService; private final ApiRequestParameterHelper apiRequestParameterHelper; - private static final Set PROVISIONING_ENTRY_PARAMETERS = new HashSet<>(Arrays.asList( - ProvisioningEntriesApiConstants.PROVISIONINGENTRY_PARAM, ProvisioningEntriesApiConstants.ENTRIES_PARAM)); - private static final Set ALL_PROVISIONING_ENTRIES = new HashSet<>(Arrays.asList - (ProvisioningEntriesApiConstants.PROVISIONINGENTRY_PARAM)); + private static final Set PROVISIONING_ENTRY_PARAMETERS = new HashSet<>( + Arrays.asList(ProvisioningEntriesApiConstants.PROVISIONINGENTRY_PARAM, ProvisioningEntriesApiConstants.ENTRIES_PARAM)); + private static final Set ALL_PROVISIONING_ENTRIES = new HashSet<>( + Arrays.asList(ProvisioningEntriesApiConstants.PROVISIONINGENTRY_PARAM)); + @Autowired public ProvisioningEntriesApiResource(final PlatformSecurityContext platformSecurityContext, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, @@ -95,9 +97,12 @@ public class ProvisioningEntriesApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create new Provisioning Entries", notes = "Creates a new Provisioning Entries\n" + "\n" + "Mandatory Fields\n" + "date\n" + "dateFormat\n" + "locale\n" + "Optional Fields\n" + "createjournalentries") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = ProvisioningEntriesApiResourceSwagger.PostProvisioningEntriesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ProvisioningEntriesApiResourceSwagger.PostProvisioningEntriesResponse.class)}) + @ApiOperation(value = "Create new Provisioning Entries", notes = "Creates a new Provisioning Entries\n" + "\n" + "Mandatory Fields\n" + + "date\n" + "dateFormat\n" + "locale\n" + "Optional Fields\n" + "createjournalentries") + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = ProvisioningEntriesApiResourceSwagger.PostProvisioningEntriesRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ProvisioningEntriesApiResourceSwagger.PostProvisioningEntriesResponse.class) }) public String createProvisioningEntries(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { CommandWrapper commandWrapper = null; this.platformSecurityContext.authenticatedUser(); @@ -111,10 +116,13 @@ public class ProvisioningEntriesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Recreates Provisioning Entry", notes = "Recreates Provisioning Entry | createjournalentry.") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = ProvisioningEntriesApiResourceSwagger.PutProvisioningEntriesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ProvisioningEntriesApiResourceSwagger.PutProvisioningEntriesResponse.class)}) - public String modifyProvisioningEntry(@PathParam("entryId") @ApiParam(value = "entryId") final Long entryId, @QueryParam("command") @ApiParam(value = "command=createjournalentry\ncommand=recreateprovisioningentry") final String commandParam, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = ProvisioningEntriesApiResourceSwagger.PutProvisioningEntriesRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ProvisioningEntriesApiResourceSwagger.PutProvisioningEntriesResponse.class) }) + public String modifyProvisioningEntry(@PathParam("entryId") @ApiParam(value = "entryId") final Long entryId, + @QueryParam("command") @ApiParam(value = "command=createjournalentry\ncommand=recreateprovisioningentry") final String commandParam, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { CommandWrapper commandWrapper = null; this.platformSecurityContext.authenticatedUser(); if ("createjournalentry".equals(commandParam)) { @@ -136,8 +144,9 @@ public class ProvisioningEntriesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieves a Provisioning Entry", notes = "Returns the details of a generated Provisioning Entry.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ProvisioningEntryData.class)}) - public String retrieveProvisioningEntry(@PathParam("entryId") @ApiParam(value = "entryId") final Long entryId, @Context final UriInfo uriInfo) { + @ApiResponses({ @ApiResponse(code = 200, message = "", response = ProvisioningEntryData.class) }) + public String retrieveProvisioningEntry(@PathParam("entryId") @ApiParam(value = "entryId") final Long entryId, + @Context final UriInfo uriInfo) { platformSecurityContext.authenticatedUser(); ProvisioningEntryData data = this.provisioningEntriesReadPlatformService.retrieveProvisioningEntryData(entryId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -148,10 +157,11 @@ public class ProvisioningEntriesApiResource { @Path("entries") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiResponses({@ApiResponse(code = 200, message = "", response = LoanProductProvisioningEntryData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = LoanProductProvisioningEntryData.class) }) public String retrieveProviioningEntries(@QueryParam("entryId") final Long entryId, @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, @QueryParam("officeId") final Long officeId, - @QueryParam("productId") final Long productId, @QueryParam("categoryId") final Long categoryId, @Context final UriInfo uriInfo) { + @QueryParam("productId") final Long productId, @QueryParam("categoryId") final Long categoryId, + @Context final UriInfo uriInfo) { this.platformSecurityContext.authenticatedUser(); SearchParameters params = SearchParameters.forProvisioningEntries(entryId, officeId, productId, categoryId, offset, limit); Page entries = this.provisioningEntriesReadPlatformService.retrieveProvisioningEntries(params); @@ -163,9 +173,9 @@ public class ProvisioningEntriesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "List all Provisioning Entries") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ProvisioningEntryData.class, responseContainer = "list")}) - public String retrieveAllProvisioningEntries(@QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @Context final UriInfo uriInfo) { + @ApiResponses({ @ApiResponse(code = 200, message = "", response = ProvisioningEntryData.class, responseContainer = "list") }) + public String retrieveAllProvisioningEntries(@QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, @Context final UriInfo uriInfo) { platformSecurityContext.authenticatedUser(); Page data = this.provisioningEntriesReadPlatformService.retrieveAllProvisioningEntries(offset, limit); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/api/ProvisioningEntriesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/api/ProvisioningEntriesApiResourceSwagger.java index 8b77bfbd8..1b413563a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/api/ProvisioningEntriesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/api/ProvisioningEntriesApiResourceSwagger.java @@ -25,15 +25,18 @@ import io.swagger.annotations.ApiModelProperty; * Created by sanyam on 25/7/17. */ final class ProvisioningEntriesApiResourceSwagger { + private ProvisioningEntriesApiResourceSwagger() { // only for Swagger Documentation } @ApiModel(value = "PostProvisioningEntriesRequest") public static final class PostProvisioningEntriesRequest { + private PostProvisioningEntriesRequest() { } + @ApiModelProperty(example = "16 October 2015") public String date; @@ -52,28 +55,34 @@ final class ProvisioningEntriesApiResourceSwagger { } @ApiModel(value = "PostProvisioningEntriesResponse") - public static final class PostProvisioningEntriesResponse{ + public static final class PostProvisioningEntriesResponse { + private PostProvisioningEntriesResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "PutProvisioningEntriesRequest") - public static final class PutProvisioningEntriesRequest{ + public static final class PutProvisioningEntriesRequest { + private PutProvisioningEntriesRequest() { } + @ApiModelProperty(example = "recreateprovisioningentry") public String command; } @ApiModel(value = "PutProvisioningEntriesResponse") - public static final class PutProvisioningEntriesResponse{ + public static final class PutProvisioningEntriesResponse { + private PutProvisioningEntriesResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/constant/ProvisioningEntriesApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/constant/ProvisioningEntriesApiConstants.java index 80d2be672..a9126d3a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/constant/ProvisioningEntriesApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/constant/ProvisioningEntriesApiConstants.java @@ -20,13 +20,13 @@ package org.apache.fineract.accounting.provisioning.constant; public interface ProvisioningEntriesApiConstants { - public final static String JSON_DATE_PARAM = "date" ; + public final static String JSON_DATE_PARAM = "date"; - public final static String JSON_DATEFORMAT_PARAM = "dateFormat" ; + public final static String JSON_DATEFORMAT_PARAM = "dateFormat"; - public final static String JSON_LOCALE_PARAM = "locale" ; + public final static String JSON_LOCALE_PARAM = "locale"; - public final static String JSON_CREATEJOURNALENTRIES_PARAM = "createjournalentries" ; + public final static String JSON_CREATEJOURNALENTRIES_PARAM = "createjournalentries"; public final static String PROVISIONINGENTRY_PARAM = "provisioningentry"; diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/data/LoanProductProvisioningEntryData.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/data/LoanProductProvisioningEntryData.java index 8eee0c300..cd3f0498a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/data/LoanProductProvisioningEntryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/data/LoanProductProvisioningEntryData.java @@ -26,17 +26,17 @@ public class LoanProductProvisioningEntryData { private final Long officeId; - private final String officeName ; + private final String officeName; private final String currencyCode; private final Long productId; - private final String productName ; + private final String productName; private final Long categoryId; - private final String categoryName ; + private final String categoryName; private final Long overdueInDays; @@ -44,21 +44,21 @@ public class LoanProductProvisioningEntryData { private final BigDecimal balance; - private final BigDecimal amountreserved ; + private final BigDecimal amountreserved; private final Long liablityAccount; - private final String liabilityAccountCode ; + private final String liabilityAccountCode; - private final String liabilityAccountName ; + private final String liabilityAccountName; private final Long expenseAccount; - private final String expenseAccountCode ; + private final String expenseAccountCode; - private final String expenseAccountName ; + private final String expenseAccountName; - private final Long criteriaId ; + private final Long criteriaId; public LoanProductProvisioningEntryData(final Long historyId, final Long officeId, final String currencyCode, final Long productId, final Long categoryId, final Long overdueInDays, final BigDecimal percentage, final BigDecimal balance, Long liablityAccount, @@ -73,40 +73,42 @@ public class LoanProductProvisioningEntryData { this.balance = balance; this.liablityAccount = liablityAccount; this.expenseAccount = expenseAccount; - this.amountreserved = null ; - this.officeName = null ; - this.productName = null ; - this.categoryName = null ; - this.liabilityAccountCode = null ; - this.liabilityAccountName = null ; - this.expenseAccountCode = null ; - this.expenseAccountName = null ; - this.criteriaId = criteriaId ; + this.amountreserved = null; + this.officeName = null; + this.productName = null; + this.categoryName = null; + this.liabilityAccountCode = null; + this.liabilityAccountName = null; + this.expenseAccountCode = null; + this.expenseAccountName = null; + this.criteriaId = criteriaId; } - public LoanProductProvisioningEntryData(final Long historyId, final Long officeId, final String officeName, final String currencyCode, final Long productId, - final String productName, final Long categoryId, final String categoryName, final Long overdueInDays, final BigDecimal amountreserved, - Long liablityAccount, String liabilityAccountglCode, String liabilityAccountName, Long expenseAccount, String expenseAccountglCode, String expenseAccountName, final Long criteriaId) { + public LoanProductProvisioningEntryData(final Long historyId, final Long officeId, final String officeName, final String currencyCode, + final Long productId, final String productName, final Long categoryId, final String categoryName, final Long overdueInDays, + final BigDecimal amountreserved, Long liablityAccount, String liabilityAccountglCode, String liabilityAccountName, + Long expenseAccount, String expenseAccountglCode, String expenseAccountName, final Long criteriaId) { this.historyId = historyId; this.officeId = officeId; this.currencyCode = currencyCode; this.productId = productId; this.categoryId = categoryId; - this.categoryName = categoryName ; + this.categoryName = categoryName; this.overdueInDays = overdueInDays; this.percentage = null; this.balance = null; this.liablityAccount = liablityAccount; this.expenseAccount = expenseAccount; - this.officeName = officeName ; - this.productName = productName ; - this.amountreserved = amountreserved ; - this.liabilityAccountCode = liabilityAccountglCode ; - this.liabilityAccountName = liabilityAccountName ; - this.expenseAccountCode = expenseAccountglCode ; - this.expenseAccountName = expenseAccountName ; - this.criteriaId = criteriaId ; + this.officeName = officeName; + this.productName = productName; + this.amountreserved = amountreserved; + this.liabilityAccountCode = liabilityAccountglCode; + this.liabilityAccountName = liabilityAccountName; + this.expenseAccountCode = expenseAccountglCode; + this.expenseAccountName = expenseAccountName; + this.criteriaId = criteriaId; } + public Long getHistoryId() { return this.historyId; } @@ -148,7 +150,7 @@ public class LoanProductProvisioningEntryData { } public Long getCriteriaId() { - return this.criteriaId ; + return this.criteriaId; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/data/ProvisioningEntryData.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/data/ProvisioningEntryData.java index df16b938f..f03628af2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/data/ProvisioningEntryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/data/ProvisioningEntryData.java @@ -25,50 +25,50 @@ import java.util.Date; @SuppressWarnings("unused") public class ProvisioningEntryData { - private Long id ; + private Long id; - private Boolean journalEntry ; + private Boolean journalEntry; - private Long createdById ; + private Long createdById; - private String createdUser ; + private String createdUser; - Date createdDate ; + Date createdDate; - Long modifiedById ; + Long modifiedById; - private String modifiedUser ; + private String modifiedUser; - private BigDecimal reservedAmount ; + private BigDecimal reservedAmount; - private Collection provisioningEntries ; + private Collection provisioningEntries; public ProvisioningEntryData(final Long id, final Collection provisioningEntries) { - this.provisioningEntries = provisioningEntries ; - this.id = id ; + this.provisioningEntries = provisioningEntries; + this.id = id; } - public ProvisioningEntryData(Long id, Boolean journalEntry, Long createdById, - String createdUser, Date createdDate, Long modifiedById, String modifiedUser, BigDecimal totalReservedAmount) { - this.id = id ; - this.journalEntry = journalEntry ; - this.createdById = createdById ; - this.createdUser = createdUser ; - this.modifiedById = modifiedById ; - this.modifiedUser = modifiedUser ; - this.createdDate = createdDate ; - this.reservedAmount = totalReservedAmount ; + public ProvisioningEntryData(Long id, Boolean journalEntry, Long createdById, String createdUser, Date createdDate, Long modifiedById, + String modifiedUser, BigDecimal totalReservedAmount) { + this.id = id; + this.journalEntry = journalEntry; + this.createdById = createdById; + this.createdUser = createdUser; + this.modifiedById = modifiedById; + this.modifiedUser = modifiedUser; + this.createdDate = createdDate; + this.reservedAmount = totalReservedAmount; } public void setEntries(Collection provisioningEntries) { - this.provisioningEntries = provisioningEntries ; + this.provisioningEntries = provisioningEntries; } public Long getId() { - return this.id ; + return this.id; } public Date getCreatedDate() { - return this.createdDate ; + return this.createdDate; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/LoanProductProvisioningEntry.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/LoanProductProvisioningEntry.java index fd3458e58..21706b917 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/LoanProductProvisioningEntry.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/LoanProductProvisioningEntry.java @@ -71,8 +71,7 @@ public class LoanProductProvisioningEntry extends AbstractPersistableCustom { @JoinColumn(name = "expense_account", nullable = false) private GLAccount expenseAccount; - protected LoanProductProvisioningEntry() { - } + protected LoanProductProvisioningEntry() {} public LoanProductProvisioningEntry(final LoanProduct loanProduct, final Office office, final String currencyCode, final ProvisioningCategory provisioningCategory, final Long overdueInDays, final BigDecimal reservedAmount, @@ -85,7 +84,7 @@ public class LoanProductProvisioningEntry extends AbstractPersistableCustom { this.reservedAmount = reservedAmount; this.liabilityAccount = liabilityAccount; this.expenseAccount = expenseAccount; - this.criteriaId = criteriaId ; + this.criteriaId = criteriaId; } public void setProvisioningEntry(ProvisioningEntry provisioningEntry) { @@ -93,52 +92,53 @@ public class LoanProductProvisioningEntry extends AbstractPersistableCustom { } public BigDecimal getReservedAmount() { - return this.reservedAmount; + return this.reservedAmount; } + public void addReservedAmount(BigDecimal value) { - this.reservedAmount = this.reservedAmount.add(value); + this.reservedAmount = this.reservedAmount.add(value); } public Office getOffice() { - return this.office; - } + return this.office; + } - public GLAccount getLiabilityAccount() { - return this.liabilityAccount; - } + public GLAccount getLiabilityAccount() { + return this.liabilityAccount; + } - public String getCurrencyCode() { - return this.currencyCode; - } + public String getCurrencyCode() { + return this.currencyCode; + } - public GLAccount getExpenseAccount() { - return this.expenseAccount; - } + public GLAccount getExpenseAccount() { + return this.expenseAccount; + } - // TODO Note that this domain class does equals() & hashCode() on getId() for @JoinColumn attributes, which not all other classes do... + // TODO Note that this domain class does equals() & hashCode() on getId() + // for @JoinColumn attributes, which not all other classes do... @Override public boolean equals(Object obj) { - if (!(obj instanceof LoanProductProvisioningEntry)) { - return false; - } + if (!(obj instanceof LoanProductProvisioningEntry)) { return false; } LoanProductProvisioningEntry other = (LoanProductProvisioningEntry) obj; - return Objects.equals(other.entry.getId(), this.entry.getId()) - && Objects.equals(other.criteriaId, this.criteriaId) - && Objects.equals(other.office.getId(), this.office.getId()) - && Objects.equals(other.currencyCode, this.currencyCode) - && Objects.equals(other.loanProduct.getId(), this.loanProduct.getId()) - && Objects.equals(other.provisioningCategory.getId(), this.provisioningCategory.getId()) - && Objects.equals(other.overdueInDays, this.overdueInDays) - && Objects.equals(other.reservedAmount, this.reservedAmount) - && Objects.equals(other.liabilityAccount.getId(), this.liabilityAccount.getId()) - && Objects.equals(other.expenseAccount.getId(), this.expenseAccount.getId()); + return Objects.equals(other.entry.getId(), this.entry.getId()) && Objects.equals(other.criteriaId, this.criteriaId) + && Objects.equals(other.office.getId(), this.office.getId()) && Objects.equals(other.currencyCode, this.currencyCode) + && Objects.equals(other.loanProduct.getId(), this.loanProduct.getId()) + && Objects.equals(other.provisioningCategory.getId(), this.provisioningCategory.getId()) + && Objects.equals(other.overdueInDays, this.overdueInDays) && Objects.equals(other.reservedAmount, this.reservedAmount) + && Objects.equals(other.liabilityAccount.getId(), this.liabilityAccount.getId()) + && Objects.equals(other.expenseAccount.getId(), this.expenseAccount.getId()); } @Override public int hashCode() { - // NOT return Objects.hash(entry, criteriaId, office, currencyCode, loanProduct, provisioningCategory, overdueInDays, reservedAmount, liabilityAccount, expenseAccount); - // to remain consistent with the implementation in equals(), also use getId() here. - return Objects.hash(entry.getId(), criteriaId, office.getId(), currencyCode, loanProduct.getId(), provisioningCategory.getId(), overdueInDays, reservedAmount, liabilityAccount.getId(), expenseAccount.getId()); + // NOT return Objects.hash(entry, criteriaId, office, currencyCode, + // loanProduct, provisioningCategory, overdueInDays, reservedAmount, + // liabilityAccount, expenseAccount); + // to remain consistent with the implementation in equals(), also use + // getId() here. + return Objects.hash(entry.getId(), criteriaId, office.getId(), currencyCode, loanProduct.getId(), provisioningCategory.getId(), + overdueInDays, reservedAmount, liabilityAccount.getId(), expenseAccount.getId()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/ProvisioningEntry.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/ProvisioningEntry.java index 4178b1c09..c981cbb4c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/ProvisioningEntry.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/ProvisioningEntry.java @@ -42,7 +42,7 @@ public class ProvisioningEntry extends AbstractPersistableCustom { @Column(name = "journal_entry_created") private Boolean isJournalEntryCreated; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", orphanRemoval = true, fetch = FetchType.EAGER) private Set provisioningEntries = new HashSet<>(); @OneToOne @@ -65,31 +65,32 @@ public class ProvisioningEntry extends AbstractPersistableCustom { } - public ProvisioningEntry(AppUser createdBy, Date createdDate, AppUser lastModifiedBy, Date lastModifiedDate, Set provisioningEntries ) { - this.provisioningEntries = provisioningEntries ; - this.createdBy = createdBy ; - this.createdDate = createdDate ; - this.lastModifiedBy = lastModifiedBy ; - this.lastModifiedDate = lastModifiedDate ; + public ProvisioningEntry(AppUser createdBy, Date createdDate, AppUser lastModifiedBy, Date lastModifiedDate, + Set provisioningEntries) { + this.provisioningEntries = provisioningEntries; + this.createdBy = createdBy; + this.createdDate = createdDate; + this.lastModifiedBy = lastModifiedBy; + this.lastModifiedDate = lastModifiedDate; } public void setProvisioningEntries(Collection provisioningEntries) { - if(this.provisioningEntries == null) { + if (this.provisioningEntries == null) { this.provisioningEntries = new HashSet<>(); } - this.provisioningEntries.addAll(provisioningEntries) ; + this.provisioningEntries.addAll(provisioningEntries); } public Collection getLoanProductProvisioningEntries() { - return this.provisioningEntries ; + return this.provisioningEntries; } public void setJournalEntryCreated(Boolean bool) { - this.isJournalEntryCreated = bool ; + this.isJournalEntryCreated = bool; } public Date getCreatedDate() { - return this.createdDate ; + return this.createdDate; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/ProvisioningEntryRepository.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/ProvisioningEntryRepository.java index cd4395e74..c76eb07e7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/ProvisioningEntryRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/domain/ProvisioningEntryRepository.java @@ -26,10 +26,10 @@ import org.springframework.data.repository.query.Param; public interface ProvisioningEntryRepository extends JpaRepository, JpaSpecificationExecutor { - //OPENJPA throws error if we use entry + // OPENJPA throws error if we use entry @Query("select entry1 from ProvisioningEntry entry1 where entry1.createdDate = :createdDate") ProvisioningEntry findByProvisioningEntryDate(@Param("createdDate") Date createdDate); @Query("select entry1 from ProvisioningEntry entry1 where entry1.createdDate = (select max(entry2.createdDate) from ProvisioningEntry entry2 where entry2.isJournalEntryCreated=true)") - ProvisioningEntry findExistingProvisioningEntryWithJournalEntries() ; + ProvisioningEntry findExistingProvisioningEntryWithJournalEntries(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/NoProvisioningCriteriaDefinitionFound.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/NoProvisioningCriteriaDefinitionFound.java index 796f02efc..202e63806 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/NoProvisioningCriteriaDefinitionFound.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/NoProvisioningCriteriaDefinitionFound.java @@ -20,7 +20,6 @@ package org.apache.fineract.accounting.provisioning.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - public class NoProvisioningCriteriaDefinitionFound extends AbstractPlatformResourceNotFoundException { public NoProvisioningCriteriaDefinitionFound() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/ProvisioningEntryAlreadyCreatedException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/ProvisioningEntryAlreadyCreatedException.java index ff16cdba7..b916b7f9c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/ProvisioningEntryAlreadyCreatedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/ProvisioningEntryAlreadyCreatedException.java @@ -21,10 +21,10 @@ package org.apache.fineract.accounting.provisioning.exception; import java.util.Date; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - public class ProvisioningEntryAlreadyCreatedException extends AbstractPlatformResourceNotFoundException { public ProvisioningEntryAlreadyCreatedException(Long id, Date date) { - super("error.msg.provisioningentry.already.exists.for.this.date", "ProvisioningEntry with identifier " + id + " exists for given date" + date, id); + super("error.msg.provisioningentry.already.exists.for.this.date", + "ProvisioningEntry with identifier " + id + " exists for given date" + date, id); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/ProvisioningEntryNotfoundException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/ProvisioningEntryNotfoundException.java index 0f9ac45e2..163f3fc54 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/ProvisioningEntryNotfoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/exception/ProvisioningEntryNotfoundException.java @@ -20,7 +20,6 @@ package org.apache.fineract.accounting.provisioning.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - public class ProvisioningEntryNotfoundException extends AbstractPlatformResourceNotFoundException { public ProvisioningEntryNotfoundException(Long id) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/CreateProvisioningEntriesRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/CreateProvisioningEntriesRequestCommandHandler.java index 354a3d167..492680131 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/CreateProvisioningEntriesRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/CreateProvisioningEntriesRequestCommandHandler.java @@ -31,7 +31,8 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "PROVISIONENTRIES", action = "CREATE") public class CreateProvisioningEntriesRequestCommandHandler implements NewCommandSourceHandler { - private final ProvisioningEntriesWritePlatformService provisioningEntriesWritePlatformService ; + private final ProvisioningEntriesWritePlatformService provisioningEntriesWritePlatformService; + @Autowired public CreateProvisioningEntriesRequestCommandHandler( final ProvisioningEntriesWritePlatformService provisioningEntriesWritePlatformService) { @@ -41,7 +42,7 @@ public class CreateProvisioningEntriesRequestCommandHandler implements NewComman @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { - return this.provisioningEntriesWritePlatformService.createProvisioningEntries(jsonCommand) ; + return this.provisioningEntriesWritePlatformService.createProvisioningEntries(jsonCommand); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/CreateProvisioningJournalEntriesRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/CreateProvisioningJournalEntriesRequestCommandHandler.java index b94053497..a42e25e98 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/CreateProvisioningJournalEntriesRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/CreateProvisioningJournalEntriesRequestCommandHandler.java @@ -31,7 +31,8 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "PROVISIONJOURNALENTRIES", action = "CREATE") public class CreateProvisioningJournalEntriesRequestCommandHandler implements NewCommandSourceHandler { - private final ProvisioningEntriesWritePlatformService provisioningEntriesWritePlatformService ; + private final ProvisioningEntriesWritePlatformService provisioningEntriesWritePlatformService; + @Autowired public CreateProvisioningJournalEntriesRequestCommandHandler( final ProvisioningEntriesWritePlatformService provisioningEntriesWritePlatformService) { @@ -41,7 +42,7 @@ public class CreateProvisioningJournalEntriesRequestCommandHandler implements Ne @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { - return this.provisioningEntriesWritePlatformService.createProvisioningJournalEntries(jsonCommand.entityId(), jsonCommand) ; + return this.provisioningEntriesWritePlatformService.createProvisioningJournalEntries(jsonCommand.entityId(), jsonCommand); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/ReCreateProvisioningEntryRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/ReCreateProvisioningEntryRequestCommandHandler.java index 1fe504fb9..24b23ce79 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/ReCreateProvisioningEntryRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/handler/ReCreateProvisioningEntryRequestCommandHandler.java @@ -29,9 +29,9 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "PROVISIONENTRIES", action = "RECREATE") -public class ReCreateProvisioningEntryRequestCommandHandler implements NewCommandSourceHandler { +public class ReCreateProvisioningEntryRequestCommandHandler implements NewCommandSourceHandler { - private final ProvisioningEntriesWritePlatformService provisioningEntriesWritePlatformService ; + private final ProvisioningEntriesWritePlatformService provisioningEntriesWritePlatformService; @Autowired public ReCreateProvisioningEntryRequestCommandHandler( @@ -42,8 +42,7 @@ public class ReCreateProvisioningEntryRequestCommandHandler implements NewComma @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { - return this.provisioningEntriesWritePlatformService.reCreateProvisioningEntries(jsonCommand.entityId(), jsonCommand) ; + return this.provisioningEntriesWritePlatformService.reCreateProvisioningEntries(jsonCommand.entityId(), jsonCommand); } } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/serialization/ProvisioningEntriesDefinitionJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/serialization/ProvisioningEntriesDefinitionJsonDeserializer.java index 016e4f536..19ffdc7a9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/serialization/ProvisioningEntriesDefinitionJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/serialization/ProvisioningEntriesDefinitionJsonDeserializer.java @@ -47,16 +47,15 @@ public class ProvisioningEntriesDefinitionJsonDeserializer implements Provisioni private static final Set supportedParameters = new HashSet<>( Arrays.asList(JSON_DATE_PARAM, JSON_DATEFORMAT_PARAM, JSON_LOCALE_PARAM, JSON_CREATEJOURNALENTRIES_PARAM)); - @Autowired public ProvisioningEntriesDefinitionJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { this.fromApiJsonHelper = fromApiJsonHelper; } public void validateForCreate(final String json) { - if (StringUtils.isBlank(json)) { throw new ProvisioningCriteriaCannotBeCreatedException( - "error.msg.provisioningentry.cannot.be.created", - "locale, dateformat, date, createjournalentries params are missing in the request"); + if (StringUtils.isBlank(json)) { + throw new ProvisioningCriteriaCannotBeCreatedException("error.msg.provisioningentry.cannot.be.created", + "locale, dateformat, date, createjournalentries params are missing in the request"); } final Type typeOfMap = new TypeToken>() {}.getType(); @@ -68,12 +67,12 @@ public class ProvisioningEntriesDefinitionJsonDeserializer implements Provisioni baseDataValidator.reset().parameter(JSON_DATEFORMAT_PARAM).value(locale).notNull(); final String dateformat = this.fromApiJsonHelper.extractDateFormatParameter(element.getAsJsonObject()); baseDataValidator.reset().parameter(JSON_DATEFORMAT_PARAM).value(dateformat).notBlank(); - LocalDate localDate = this.fromApiJsonHelper.extractLocalDateNamed(JSON_DATE_PARAM, element) ; + LocalDate localDate = this.fromApiJsonHelper.extractLocalDateNamed(JSON_DATE_PARAM, element); baseDataValidator.reset().parameter(JSON_DATE_PARAM).value(localDate).notBlank(); - baseDataValidator.reset().parameter(JSON_DATE_PARAM).value(localDate).validateDateBeforeOrEqual(DateUtils.getLocalDateOfTenant()) ; - if(this.fromApiJsonHelper.parameterExists(JSON_CREATEJOURNALENTRIES_PARAM, element)) { - Boolean bool = this.fromApiJsonHelper.extractBooleanNamed(JSON_CREATEJOURNALENTRIES_PARAM, element) ; - baseDataValidator.reset().parameter(JSON_CREATEJOURNALENTRIES_PARAM).value(bool).validateForBooleanValue() ; + baseDataValidator.reset().parameter(JSON_DATE_PARAM).value(localDate).validateDateBeforeOrEqual(DateUtils.getLocalDateOfTenant()); + if (this.fromApiJsonHelper.parameterExists(JSON_CREATEJOURNALENTRIES_PARAM, element)) { + Boolean bool = this.fromApiJsonHelper.extractBooleanNamed(JSON_CREATEJOURNALENTRIES_PARAM, element); + baseDataValidator.reset().parameter(JSON_CREATEJOURNALENTRIES_PARAM).value(bool).validateForBooleanValue(); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesReadPlatformService.java index 8a568a76d..552b5e06e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesReadPlatformService.java @@ -25,20 +25,19 @@ import org.apache.fineract.accounting.provisioning.data.ProvisioningEntryData; import org.apache.fineract.infrastructure.core.service.Page; import org.apache.fineract.infrastructure.core.service.SearchParameters; - public interface ProvisioningEntriesReadPlatformService { - public Collection retrieveLoanProductsProvisioningData(Date date) ; + public Collection retrieveLoanProductsProvisioningData(Date date); - public ProvisioningEntryData retrieveProvisioningEntryData(Long entryId) ; + public ProvisioningEntryData retrieveProvisioningEntryData(Long entryId); - public Page retrieveAllProvisioningEntries(Integer offset, Integer limit) ; + public Page retrieveAllProvisioningEntries(Integer offset, Integer limit); - public ProvisioningEntryData retrieveProvisioningEntryData(String date) ; + public ProvisioningEntryData retrieveProvisioningEntryData(String date); - public ProvisioningEntryData retrieveProvisioningEntryDataByCriteriaId(Long criteriaId) ; + public ProvisioningEntryData retrieveProvisioningEntryDataByCriteriaId(Long criteriaId); - public ProvisioningEntryData retrieveExistingProvisioningIdDateWithJournals() ; + public ProvisioningEntryData retrieveExistingProvisioningIdDateWithJournals(); - public Page retrieveProvisioningEntries(SearchParameters searchParams) ; + public Page retrieveProvisioningEntries(SearchParameters searchParams); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesReadPlatformServiceImpl.java index db6443619..39522b841 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesReadPlatformServiceImpl.java @@ -42,6 +42,7 @@ import org.springframework.stereotype.Service; @Service public class ProvisioningEntriesReadPlatformServiceImpl implements ProvisioningEntriesReadPlatformService { + private final static Logger LOG = LoggerFactory.getLogger(ProvisioningEntriesReadPlatformServiceImpl.class); private final JdbcTemplate jdbcTemplate; @@ -67,10 +68,9 @@ public class ProvisioningEntriesReadPlatformServiceImpl implements ProvisioningE private final StringBuilder sqlQuery; protected LoanProductProvisioningEntryMapper(String formattedDate) { - sqlQuery = new StringBuilder() - .append("select if(loan.loan_type_enum=1, mclient.office_id, mgroup.office_id) as office_id, loan.loan_type_enum, pcd.criteria_id as criteriaid, loan.product_id,loan.currency_code,") - .append("GREATEST(datediff(") - .append(formattedDate) + sqlQuery = new StringBuilder().append( + "select if(loan.loan_type_enum=1, mclient.office_id, mgroup.office_id) as office_id, loan.loan_type_enum, pcd.criteria_id as criteriaid, loan.product_id,loan.currency_code,") + .append("GREATEST(datediff(").append(formattedDate) .append(",sch.duedate),0) as numberofdaysoverdue,sch.duedate, pcd.category_id, pcd.provision_percentage,") .append("loan.total_outstanding_derived as outstandingbalance, pcd.liability_account, pcd.expense_account from m_loan_repayment_schedule sch") .append(" LEFT JOIN m_loan loan on sch.loan_id = loan.id") @@ -147,8 +147,8 @@ public class ProvisioningEntriesReadPlatformServiceImpl implements ProvisioningE private static final class LoanProductProvisioningEntryRowMapper implements RowMapper { - private final StringBuilder sqlQuery = new StringBuilder() - .append(" entry.id, entry.history_id as historyId, office_id, entry.criteria_id as criteriaid, office.name as officename, product.name as productname, entry.product_id, ") + private final StringBuilder sqlQuery = new StringBuilder().append( + " entry.id, entry.history_id as historyId, office_id, entry.criteria_id as criteriaid, office.name as officename, product.name as productname, entry.product_id, ") .append("category_id, category.category_name, liability.id as liabilityid, liability.gl_code as liabilitycode, liability.name as liabilityname, ") .append("expense.id as expenseid, expense.gl_code as expensecode, expense.name as expensename, entry.currency_code, entry.overdue_in_days, entry.reseve_amount from m_loanproduct_provisioning_entry entry ") .append("left join m_office office ON office.id = entry.office_id ") @@ -225,10 +225,10 @@ public class ProvisioningEntriesReadPlatformServiceImpl implements ProvisioningE sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); sqlBuilder.append(mapper.getSchema()); sqlBuilder.append(" order by entry.created_date"); - if(limit != null ) { + if (limit != null) { sqlBuilder.append(" limit ").append(limit); } - if(offset != null) { + if (offset != null) { sqlBuilder.append(" offset ").append(offset); } @@ -241,13 +241,13 @@ public class ProvisioningEntriesReadPlatformServiceImpl implements ProvisioningE @Override public ProvisioningEntryData retrieveProvisioningEntryData(String date) { ProvisioningEntryDataMapper mapper1 = new ProvisioningEntryDataMapper(); - date = date+"%"; + date = date + "%"; final String sql1 = "select " + mapper1.getSchema() + " where entry.created_date like ? "; ProvisioningEntryData data = null; try { - data = this.jdbcTemplate.queryForObject(sql1, mapper1, new Object[] {date}); + data = this.jdbcTemplate.queryForObject(sql1, mapper1, new Object[] { date }); } catch (EmptyResultDataAccessException e) { - LOG.error("Problem occurred in retrieveProvisioningEntryData function",e); + LOG.error("Problem occurred in retrieveProvisioningEntryData function", e); } return data; diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesWritePlatformService.java index 196bf5b73..be97d1e36 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesWritePlatformService.java @@ -21,14 +21,13 @@ package org.apache.fineract.accounting.provisioning.service; import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; - public interface ProvisioningEntriesWritePlatformService { CommandProcessingResult createProvisioningEntries(JsonCommand command); - CommandProcessingResult reCreateProvisioningEntries(Long provisioningEntryId, JsonCommand command) ; + CommandProcessingResult reCreateProvisioningEntries(Long provisioningEntryId, JsonCommand command); CommandProcessingResult createProvisioningJournalEntries(Long provisioningEntryId, JsonCommand command); - void generateLoanLossProvisioningAmount() ; + void generateLoanLossProvisioningAmount(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl.java index 2ec2eef40..be2bfb6cd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/provisioning/service/ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl.java @@ -67,9 +67,10 @@ import org.springframework.stereotype.Service; @Service public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements ProvisioningEntriesWritePlatformService { + private final static Logger LOG = LoggerFactory.getLogger(ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl.class); private final ProvisioningEntriesReadPlatformService provisioningEntriesReadPlatformService; - private final ProvisioningCriteriaReadPlatformService provisioningCriteriaReadPlatformService ; + private final ProvisioningCriteriaReadPlatformService provisioningCriteriaReadPlatformService; private final LoanProductRepository loanProductRepository; private final GLAccountRepository glAccountRepository; private final OfficeRepositoryWrapper officeRepositoryWrapper; @@ -90,7 +91,7 @@ public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements final JournalEntryWritePlatformService journalEntryWritePlatformService, final ProvisioningEntriesDefinitionJsonDeserializer fromApiJsonDeserializer, final FromJsonHelper fromApiJsonHelper) { this.provisioningEntriesReadPlatformService = provisioningEntriesReadPlatformService; - this.provisioningCriteriaReadPlatformService = provisioningCriteriaReadPlatformService ; + this.provisioningCriteriaReadPlatformService = provisioningCriteriaReadPlatformService; this.loanProductRepository = loanProductRepository; this.glAccountRepository = glAccountRepository; this.officeRepositoryWrapper = officeRepositoryWrapper; @@ -119,9 +120,9 @@ public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements this.journalEntryWritePlatformService.revertProvisioningJournalEntries(requestedEntry.getCreatedDate(), existingEntryData.getId(), PortfolioProductType.PROVISIONING.getValue()); } - if(requestedEntry.getLoanProductProvisioningEntries() == null || requestedEntry.getLoanProductProvisioningEntries().size() == 0) { + if (requestedEntry.getLoanProductProvisioningEntries() == null || requestedEntry.getLoanProductProvisioningEntries().size() == 0) { requestedEntry.setJournalEntryCreated(Boolean.FALSE); - }else { + } else { requestedEntry.setJournalEntryCreated(Boolean.TRUE); } @@ -132,8 +133,9 @@ public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements private void validateForCreateJournalEntry(ProvisioningEntryData existingEntry, ProvisioningEntry requested) { Date existingDate = existingEntry.getCreatedDate(); Date requestedDate = requested.getCreatedDate(); - if (existingDate.after(requestedDate) || existingDate.equals(requestedDate)) { throw new ProvisioningJournalEntriesCannotbeCreatedException( - existingEntry.getCreatedDate(), requestedDate); } + if (existingDate.after(requestedDate) || existingDate.equals(requestedDate)) { + throw new ProvisioningJournalEntriesCannotbeCreatedException(existingEntry.getCreatedDate(), requestedDate); + } } private boolean isJournalEntriesRequired(JsonCommand command) { @@ -153,19 +155,21 @@ public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements @Override @CronTarget(jobName = JobName.GENERATE_LOANLOSS_PROVISIONING) public void generateLoanLossProvisioningAmount() { - Date currentDate = DateUtils.getLocalDateOfTenant().toDate() ; + Date currentDate = DateUtils.getLocalDateOfTenant().toDate(); boolean addJournalEntries = true; try { - Collection criteriaCollection = this.provisioningCriteriaReadPlatformService.retrieveAllProvisioningCriterias() ; - if(criteriaCollection == null || criteriaCollection.size() == 0){ - return ; - //FIXME: Do we need to throw NoProvisioningCriteriaDefinitionFound()? + Collection criteriaCollection = this.provisioningCriteriaReadPlatformService + .retrieveAllProvisioningCriterias(); + if (criteriaCollection == null || criteriaCollection.size() == 0) { + return; + // FIXME: Do we need to throw + // NoProvisioningCriteriaDefinitionFound()? } createProvsioningEntry(currentDate, addJournalEntries); } catch (ProvisioningEntryAlreadyCreatedException peace) { - LOG.error("{}",peace.getDefaultUserMessage()); + LOG.error("{}", peace.getDefaultUserMessage()); } catch (DataIntegrityViolationException dive) { - LOG.error("Problem occurred in generateLoanLossProvisioningAmount function",dive); + LOG.error("Problem occurred in generateLoanLossProvisioningAmount function", dive); } } @@ -175,10 +179,9 @@ public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements Date createdDate = parseDate(command); boolean addJournalEntries = isJournalEntriesRequired(command); try { - Collection criteriaCollection = this.provisioningCriteriaReadPlatformService.retrieveAllProvisioningCriterias() ; - if(criteriaCollection == null || criteriaCollection.size() == 0){ - throw new NoProvisioningCriteriaDefinitionFound() ; - } + Collection criteriaCollection = this.provisioningCriteriaReadPlatformService + .retrieveAllProvisioningCriterias(); + if (criteriaCollection == null || criteriaCollection.size() == 0) { throw new NoProvisioningCriteriaDefinitionFound(); } ProvisioningEntry requestedEntry = createProvsioningEntry(createdDate, addJournalEntries); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(requestedEntry.getId()).build(); } catch (DataIntegrityViolationException dve) { @@ -188,8 +191,9 @@ public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements private ProvisioningEntry createProvsioningEntry(Date date, boolean addJournalEntries) { ProvisioningEntry existingEntry = this.provisioningEntryRepository.findByProvisioningEntryDate(date); - if (existingEntry != null) { throw new ProvisioningEntryAlreadyCreatedException(existingEntry.getId(), - existingEntry.getCreatedDate()); } + if (existingEntry != null) { + throw new ProvisioningEntryAlreadyCreatedException(existingEntry.getId(), existingEntry.getCreatedDate()); + } AppUser currentUser = this.platformSecurityContext.authenticatedUser(); AppUser lastModifiedBy = null; Date lastModifiedDate = null; @@ -234,7 +238,8 @@ public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements Money amountToReserve = money.percentageOf(data.getPercentage(), MoneyHelper.getRoundingMode()); Long criteraId = data.getCriteriaId(); LoanProductProvisioningEntry entry = new LoanProductProvisioningEntry(loanProduct, office, data.getCurrencyCode(), - provisioningCategory, data.getOverdueInDays(), amountToReserve.getAmount(), liabilityAccount, expenseAccount, criteraId); + provisioningCategory, data.getOverdueInDays(), amountToReserve.getAmount(), liabilityAccount, expenseAccount, + criteraId); entry.setProvisioningEntry(parent); if (!provisioningEntries.containsKey(entry)) { provisioningEntries.put(entry, entry); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleApiResource.java old mode 100755 new mode 100644 index 366457908..3f9570e66 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleApiResource.java @@ -73,16 +73,21 @@ import org.springframework.stereotype.Component; @Path("/accountingrules") @Component @Scope("singleton") -@Api(tags = {"Accounting Rules"}) +@Api(tags = { "Accounting Rules" }) @SwaggerDefinition(tags = { - @Tag(name = "Accounting Rules", description = "It is typical scenario in MFI's that non accountants pass journal entries on a regular basis. For Ex: A branch office might deposit their entire cash at hand to their Bank account at the end of a working day. The branch office users might not understand enough of accounting to figure out which account needs to get credited and which account needs to be debited to represent this transaction.\n" + "\n" + "Enter accounting rules, an abstraction on top of manual Journal entires for enabling simpler data entry. An accounting rule can define any of the following abstractions\n" + "\n" + "A Simple journal entry where both the credit and debit account have been preselected\n" + "A Simple journal entry where either credit or debit accounts have been limited to a pre-selected list of accounts (Ex: Debit account should be one of \"Bank of America\" of \"JP Morgan\" and credit account should be \"Cash\")\n" + "A Compound journal entry where multiple debits and / or multiple credits may be made amongst a set of preselected list of accounts (Ex: Credit account should be either \"Bank Of America\" or \"Cash\" and debit account can be \"Employee Salary\" and/or \"Miscellenous Expenses\")\n" + "An accounting rule can also be optionally associated with a branch, so that only a particular Branch's users have access to the rule") -}) + @Tag(name = "Accounting Rules", description = "It is typical scenario in MFI's that non accountants pass journal entries on a regular basis. For Ex: A branch office might deposit their entire cash at hand to their Bank account at the end of a working day. The branch office users might not understand enough of accounting to figure out which account needs to get credited and which account needs to be debited to represent this transaction.\n" + + "\n" + + "Enter accounting rules, an abstraction on top of manual Journal entires for enabling simpler data entry. An accounting rule can define any of the following abstractions\n" + + "\n" + "A Simple journal entry where both the credit and debit account have been preselected\n" + + "A Simple journal entry where either credit or debit accounts have been limited to a pre-selected list of accounts (Ex: Debit account should be one of \"Bank of America\" of \"JP Morgan\" and credit account should be \"Cash\")\n" + + "A Compound journal entry where multiple debits and / or multiple credits may be made amongst a set of preselected list of accounts (Ex: Credit account should be either \"Bank Of America\" or \"Cash\" and debit account can be \"Employee Salary\" and/or \"Miscellenous Expenses\")\n" + + "An accounting rule can also be optionally associated with a branch, so that only a particular Branch's users have access to the rule") }) public class AccountingRuleApiResource { - private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "officeId", "officeName", - "accountToDebitId", "accountToCreditId", "name", "description", "systemDefined", "allowedCreditTagOptions", - "allowedDebitTagOptions", "debitTags", "creditTags", "creditAccounts", "debitAccounts", "allowMultipleCreditEntries", - "allowMultipleDebitEntries", "tag")); + private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "officeId", "officeName", "accountToDebitId", "accountToCreditId", "name", "description", "systemDefined", + "allowedCreditTagOptions", "allowedDebitTagOptions", "debitTags", "creditTags", "creditAccounts", "debitAccounts", + "allowMultipleCreditEntries", "allowMultipleDebitEntries", "tag")); private final String resourceNameForPermission = "ACCOUNTINGRULE"; @@ -116,8 +121,10 @@ public class AccountingRuleApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Accounting Rule Details Template", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "accountingrules/template") - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountingRuleApiResourceSwagger.GetAccountRulesTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Accounting Rule Details Template", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "accountingrules/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = AccountingRuleApiResourceSwagger.GetAccountRulesTemplateResponse.class) }) public String retrieveTemplate(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); @@ -132,8 +139,10 @@ public class AccountingRuleApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Accounting Rules", notes = "Returns the list of defined accounting rules.\n" + "\n" + "Example Requests:\n" + "\n" + "accountingrules") - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountingRuleApiResourceSwagger.GetAccountRulesResponse.class, responseContainer = "list")}) + @ApiOperation(value = "Retrieve Accounting Rules", notes = "Returns the list of defined accounting rules.\n" + "\n" + + "Example Requests:\n" + "\n" + "accountingrules") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = AccountingRuleApiResourceSwagger.GetAccountRulesResponse.class, responseContainer = "list") }) public String retrieveAllAccountingRules(@Context final UriInfo uriInfo) { final AppUser currentUser = this.context.authenticatedUser(); @@ -151,8 +160,8 @@ public class AccountingRuleApiResource { // journal entry form. } } - final List accountingRuleDatas = this.accountingRuleReadPlatformService.retrieveAllAccountingRules( - hierarchySearchString, isAssociationParametersExists); + final List accountingRuleDatas = this.accountingRuleReadPlatformService + .retrieveAllAccountingRules(hierarchySearchString, isAssociationParametersExists); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.apiJsonSerializerService.serialize(settings, accountingRuleDatas, RESPONSE_DATA_PARAMETERS); @@ -162,9 +171,11 @@ public class AccountingRuleApiResource { @Path("{accountingRuleId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Accounting rule", notes = "Returns the details of a defined Accounting rule.\n" + "\n" + "Example Requests:\n" + "\n" + "accountingrules/1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountingRuleData.class)}) - public String retreiveAccountingRule(@PathParam("accountingRuleId") @ApiParam(value = "accountingRuleId") final Long accountingRuleId, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Accounting rule", notes = "Returns the details of a defined Accounting rule.\n" + "\n" + + "Example Requests:\n" + "\n" + "accountingrules/1") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = AccountingRuleData.class) }) + public String retreiveAccountingRule(@PathParam("accountingRuleId") @ApiParam(value = "accountingRuleId") final Long accountingRuleId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -180,9 +191,12 @@ public class AccountingRuleApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create/Define a Accounting rule", notes = "Define a new Accounting rule.\n" + "\n" + "Mandatory Fields\n" + "name, officeId,\n" + "accountToDebit OR debitTags,\n" + "accountToCredit OR creditTags.\n" + "\n" + "Optional Fields\n" + "description") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = AccountingRuleApiResourceSwagger.PostAccountingRulesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountingRuleApiResourceSwagger.PostAccountingRulesResponse.class)}) + @ApiOperation(value = "Create/Define a Accounting rule", notes = "Define a new Accounting rule.\n" + "\n" + "Mandatory Fields\n" + + "name, officeId,\n" + "accountToDebit OR debitTags,\n" + "accountToCredit OR creditTags.\n" + "\n" + "Optional Fields\n" + + "description") + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = AccountingRuleApiResourceSwagger.PostAccountingRulesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = AccountingRuleApiResourceSwagger.PostAccountingRulesResponse.class) }) public String createAccountingRule(@ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createAccountingRule().withJson(jsonRequestBody).build(); @@ -197,9 +211,11 @@ public class AccountingRuleApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Accounting Rule", notes = "Updates the details of a Accounting rule.") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = AccountingRuleApiResourceSwagger.PutAccountingRulesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountingRuleApiResourceSwagger.PutAccountingRulesResponse.class)}) - public String updateAccountingRule(@PathParam("accountingRuleId") @ApiParam(value = "accountingRuleId") final Long accountingRuleId,@ApiParam(hidden = true) final String jsonRequestBody) { + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", value = "body", dataType = "body", dataTypeClass = AccountingRuleApiResourceSwagger.PutAccountingRulesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = AccountingRuleApiResourceSwagger.PutAccountingRulesResponse.class) }) + public String updateAccountingRule(@PathParam("accountingRuleId") @ApiParam(value = "accountingRuleId") final Long accountingRuleId, + @ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateAccountingRule(accountingRuleId).withJson(jsonRequestBody) .build(); @@ -213,7 +229,8 @@ public class AccountingRuleApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Accounting Rule", notes = "Deletes a Accounting rule.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountingRuleApiResourceSwagger.DeleteAccountingRulesResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = AccountingRuleApiResourceSwagger.DeleteAccountingRulesResponse.class) }) public String deleteAccountingRule(@PathParam("accountingRuleId") @ApiParam(value = "accountingRuleId") final Long accountingRuleId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteAccountingRule(accountingRuleId).build(); @@ -229,14 +246,14 @@ public class AccountingRuleApiResource { final Collection allowedTagOptions = this.codeValueReadPlatformService .retrieveCodeValuesByCode(AccountingConstants.ASSESTS_TAG_OPTION_CODE_NAME); - allowedTagOptions.addAll(this.codeValueReadPlatformService - .retrieveCodeValuesByCode(AccountingConstants.LIABILITIES_TAG_OPTION_CODE_NAME)); - allowedTagOptions.addAll(this.codeValueReadPlatformService - .retrieveCodeValuesByCode(AccountingConstants.EQUITY_TAG_OPTION_CODE_NAME)); - allowedTagOptions.addAll(this.codeValueReadPlatformService - .retrieveCodeValuesByCode(AccountingConstants.INCOME_TAG_OPTION_CODE_NAME)); - allowedTagOptions.addAll(this.codeValueReadPlatformService - .retrieveCodeValuesByCode(AccountingConstants.EXPENSES_TAG_OPTION_CODE_NAME)); + allowedTagOptions + .addAll(this.codeValueReadPlatformService.retrieveCodeValuesByCode(AccountingConstants.LIABILITIES_TAG_OPTION_CODE_NAME)); + allowedTagOptions + .addAll(this.codeValueReadPlatformService.retrieveCodeValuesByCode(AccountingConstants.EQUITY_TAG_OPTION_CODE_NAME)); + allowedTagOptions + .addAll(this.codeValueReadPlatformService.retrieveCodeValuesByCode(AccountingConstants.INCOME_TAG_OPTION_CODE_NAME)); + allowedTagOptions + .addAll(this.codeValueReadPlatformService.retrieveCodeValuesByCode(AccountingConstants.EXPENSES_TAG_OPTION_CODE_NAME)); if (accountingRuleData == null) { @@ -282,4 +299,4 @@ public class AccountingRuleApiResource { tempOptions.removeAll(selectedTags.values()); return tempOptions; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleApiResourceSwagger.java index dba659cc9..6fb084119 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleApiResourceSwagger.java @@ -30,12 +30,14 @@ import org.apache.fineract.organisation.office.data.OfficeData; * Created by sanyam on 26/7/17. */ final class AccountingRuleApiResourceSwagger { + private AccountingRuleApiResourceSwagger() { // For Swagger Documentation } @ApiModel(value = "GetAccountRulesResponse") public static final class GetAccountRulesResponse { + private GetAccountRulesResponse() { } @@ -54,6 +56,7 @@ final class AccountingRuleApiResourceSwagger { @ApiModel(value = "GetAccountRulesTemplateResponse") public static final class GetAccountRulesTemplateResponse { + private GetAccountRulesTemplateResponse() { } @@ -66,6 +69,7 @@ final class AccountingRuleApiResourceSwagger { @ApiModel(value = "PostAccountingRulesRequest") public static final class PostAccountingRulesRequest { + private PostAccountingRulesRequest() { } @@ -84,9 +88,11 @@ final class AccountingRuleApiResourceSwagger { @ApiModel(value = "PostAccountingRulesResponse") public static final class PostAccountingRulesResponse { + private PostAccountingRulesResponse() { } + @ApiModelProperty(example = "1") public Long officeId; @ApiModelProperty(example = "1") @@ -95,24 +101,30 @@ final class AccountingRuleApiResourceSwagger { @ApiModel(value = "PutAccountingRulesRequest") public static final class PutAccountingRulesRequest { + private PutAccountingRulesRequest() { } + @ApiModelProperty(example = "Employee Salary posting rule") public String name; } @ApiModel(value = "PutAccountingRulesResponse") public static final class PutAccountingRulesResponse { - private PutAccountingRulesResponse () { + + private PutAccountingRulesResponse() { } public class PutAccountingRulesResponsechangesSwagger { - public PutAccountingRulesResponsechangesSwagger(){} + + public PutAccountingRulesResponsechangesSwagger() {} + @ApiModelProperty(example = "Employee Salary posting rule") public String name; } + @ApiModelProperty(example = "1") public Long resourceId; public PutAccountingRulesResponsechangesSwagger changes; @@ -120,9 +132,11 @@ final class AccountingRuleApiResourceSwagger { @ApiModel(value = "DeleteAccountingRulesResponse") public static final class DeleteAccountingRulesResponse { + private DeleteAccountingRulesResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleJsonInputParams.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleJsonInputParams.java old mode 100755 new mode 100644 index 92099490b..2e56de911 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleJsonInputParams.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/api/AccountingRuleJsonInputParams.java @@ -25,9 +25,11 @@ import java.util.Set; * Enum of all parameters passed in while creating/updating a loan product ***/ public enum AccountingRuleJsonInputParams { + ID("id"), OFFICE_ID("officeId"), ACCOUNT_TO_DEBIT("accountToDebit"), ACCOUNT_TO_CREDIT("accountToCredit"), NAME("name"), DESCRIPTION( - "description"), SYSTEM_DEFINED("systemDefined"), DEBIT_ACCOUNT_TAGS("debitTags"), CREDIT_ACCOUNT_TAGS("creditTags"), ALLOW_MULTIPLE_CREDIT_ENTRIES( - "allowMultipleCreditEntries"), ALLOW_MULTIPLE_DEBIT_ENTRIES("allowMultipleDebitEntries"); + "description"), SYSTEM_DEFINED("systemDefined"), DEBIT_ACCOUNT_TAGS("debitTags"), CREDIT_ACCOUNT_TAGS( + "creditTags"), ALLOW_MULTIPLE_CREDIT_ENTRIES( + "allowMultipleCreditEntries"), ALLOW_MULTIPLE_DEBIT_ENTRIES("allowMultipleDebitEntries"); private final String value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/data/AccountingRuleData.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/data/AccountingRuleData.java old mode 100755 new mode 100644 index 0c6c155ee..655e60888 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/data/AccountingRuleData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/data/AccountingRuleData.java @@ -128,4 +128,4 @@ public class AccountingRuleData { return this.debitTags; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/domain/AccountingRule.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/domain/AccountingRule.java old mode 100755 new mode 100644 index 9d04a6a45..eb03e655a --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/domain/AccountingRule.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/domain/AccountingRule.java @@ -42,7 +42,8 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; import org.apache.fineract.organisation.office.domain.Office; @Entity -@Table(name = "acc_accounting_rule", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "accounting_rule_name_unique") }) +@Table(name = "acc_accounting_rule", uniqueConstraints = { + @UniqueConstraint(columnNames = { "name" }, name = "accounting_rule_name_unique") }) public class AccountingRule extends AbstractPersistableCustom { @Column(name = "name", nullable = false, length = 500) @@ -66,7 +67,7 @@ public class AccountingRule extends AbstractPersistableCustom { @Column(name = "system_defined", nullable = false) private Boolean systemDefined; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "accountingRule", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "accountingRule", orphanRemoval = true, fetch = FetchType.EAGER) private List accountingTagRules = new ArrayList<>(); @Column(name = "allow_multiple_credits", nullable = false) @@ -104,8 +105,8 @@ public class AccountingRule extends AbstractPersistableCustom { public Map update(final JsonCommand command) { final Map actualChanges = new LinkedHashMap<>(10); - handlePropertyUpdate(command, actualChanges, AccountingRuleJsonInputParams.OFFICE_ID.getValue(), this.office == null ? 0L - : this.office.getId()); + handlePropertyUpdate(command, actualChanges, AccountingRuleJsonInputParams.OFFICE_ID.getValue(), + this.office == null ? 0L : this.office.getId()); handlePropertyUpdate(command, actualChanges, AccountingRuleJsonInputParams.ACCOUNT_TO_DEBIT.getValue(), this.accountToDebit == null ? 0L : this.accountToDebit.getId()); handlePropertyUpdate(command, actualChanges, AccountingRuleJsonInputParams.ACCOUNT_TO_CREDIT.getValue(), @@ -260,4 +261,4 @@ public class AccountingRule extends AbstractPersistableCustom { this.accountingTagRules.removeAll(accountsToRemove); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/domain/AccountingTagRule.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/domain/AccountingTagRule.java index 6af091e3d..d429004b2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/domain/AccountingTagRule.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/domain/AccountingTagRule.java @@ -29,7 +29,8 @@ import org.apache.fineract.infrastructure.codes.domain.CodeValue; import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity -@Table(name = "acc_rule_tags", uniqueConstraints = { @UniqueConstraint(columnNames = { "acc_rule_id", "tag_id", "acc_type_enum" }, name = "UNIQUE_ACCOUNT_RULE_TAGS") }) +@Table(name = "acc_rule_tags", uniqueConstraints = { + @UniqueConstraint(columnNames = { "acc_rule_id", "tag_id", "acc_type_enum" }, name = "UNIQUE_ACCOUNT_RULE_TAGS") }) public class AccountingTagRule extends AbstractPersistableCustom { @ManyToOne diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleDataException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleDataException.java index 1082fd523..551ffdeb3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleDataException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleDataException.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class AccountingRuleDataException extends AbstractPlatformDomainRuleException { public AccountingRuleDataException(final String debitOrCreditAccount, final String debitOrCreditTags) { - super("error.msg.accounting.rule." + debitOrCreditAccount + ".or." + debitOrCreditTags + ".required", debitOrCreditAccount + " or " - + debitOrCreditTags + " required", debitOrCreditAccount, debitOrCreditTags); + super("error.msg.accounting.rule." + debitOrCreditAccount + ".or." + debitOrCreditTags + ".required", + debitOrCreditAccount + " or " + debitOrCreditTags + " required", debitOrCreditAccount, debitOrCreditTags); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleDuplicateException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleDuplicateException.java old mode 100755 new mode 100644 index 3f34d870e..7cd76a28f --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleDuplicateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleDuplicateException.java @@ -34,4 +34,4 @@ public class AccountingRuleDuplicateException extends AbstractPlatformDomainRule super("error.msg.accounting.rule.tag.duplicate", "The accounting rule already have the tags which you defined"); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleInvalidDeleteException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleInvalidDeleteException.java old mode 100755 new mode 100644 index 4cb428fac..4c64dd034 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleInvalidDeleteException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleInvalidDeleteException.java @@ -30,4 +30,4 @@ public class AccountingRuleInvalidDeleteException extends AbstractPlatformDomain super("error.msg.glclosure.invalid.delete", "The latest closure for office with Id " + officeId + " and name " + officeName + " is on " + latestclosureDate.toString() + ", please delete this closure first", latestclosureDate); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleInvalidException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleInvalidException.java old mode 100755 new mode 100644 index eb2fee7df..1caa78d2a --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleInvalidException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleInvalidException.java @@ -28,12 +28,15 @@ public class AccountingRuleInvalidException extends AbstractPlatformDomainRuleEx /*** enum of reasons for invalid Accounting Closure **/ public static enum GlClosureInvalidReason { + FUTURE_DATE, ACCOUNTING_CLOSED; public String errorMessage() { if (name().toString().equalsIgnoreCase("FUTURE_DATE")) { return "Accounting closures cannot be made for a future date"; - } else if (name().toString().equalsIgnoreCase("ACCOUNTING_CLOSED")) { return "Accounting Closure for this branch has already been defined for a greater date"; } + } else if (name().toString().equalsIgnoreCase("ACCOUNTING_CLOSED")) { + return "Accounting Closure for this branch has already been defined for a greater date"; + } return name().toString(); } @@ -48,4 +51,4 @@ public class AccountingRuleInvalidException extends AbstractPlatformDomainRuleEx public AccountingRuleInvalidException(final GlClosureInvalidReason reason, final Date date) { super(reason.errorCode(), reason.errorMessage(), date); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleNotFoundException.java old mode 100755 new mode 100644 index 121d6a358..293679931 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/exception/AccountingRuleNotFoundException.java @@ -29,4 +29,4 @@ public class AccountingRuleNotFoundException extends AbstractPlatformResourceNot public AccountingRuleNotFoundException(final Long id) { super("error.msg.accounting.rule.id.invalid", "Accounting Rule with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/CreateAccountingRuleCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/CreateAccountingRuleCommandHandler.java old mode 100755 new mode 100644 index 8b69cdc32..f90ca890d --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/CreateAccountingRuleCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/CreateAccountingRuleCommandHandler.java @@ -43,4 +43,4 @@ public class CreateAccountingRuleCommandHandler implements NewCommandSourceHandl public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.createAccountingRule(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/DeleteAccountingRuleCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/DeleteAccountingRuleCommandHandler.java old mode 100755 new mode 100644 index 190be8552..ec61507c5 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/DeleteAccountingRuleCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/DeleteAccountingRuleCommandHandler.java @@ -43,4 +43,4 @@ public class DeleteAccountingRuleCommandHandler implements NewCommandSourceHandl public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.deleteAccountingRule(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/UpdateAccountingRuleCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/UpdateAccountingRuleCommandHandler.java old mode 100755 new mode 100644 index ad9b5e38f..82ab71f6f --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/UpdateAccountingRuleCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/handler/UpdateAccountingRuleCommandHandler.java @@ -43,4 +43,4 @@ public class UpdateAccountingRuleCommandHandler implements NewCommandSourceHandl public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.updateAccountingRule(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/serialization/AccountingRuleCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/serialization/AccountingRuleCommandFromApiJsonDeserializer.java old mode 100755 new mode 100644 index 0b14ac3e4..9adb9b7f1 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/serialization/AccountingRuleCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/serialization/AccountingRuleCommandFromApiJsonDeserializer.java @@ -113,27 +113,27 @@ public class AccountingRuleCommandFromApiJsonDeserializer { final String debitAccount = AccountingRuleJsonInputParams.ACCOUNT_TO_DEBIT.getValue(); final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(debitAccount).append(".or.") .append(debitTag).append(".required"); - final StringBuilder defaultUserMessage = new StringBuilder("The parameter ").append(debitAccount).append(" or") - .append(debitTag).append(" required"); + final StringBuilder defaultUserMessage = new StringBuilder("The parameter ").append(debitAccount).append(" or").append(debitTag) + .append(" required"); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultUserMessage.toString(), debitAccount + "," + debitTag, new Object[] { debitAccount, debitTag }); dataValidationErrors.add(error); } - final String allowMultipleCredits = this.fromApiJsonHelper.extractStringNamed( - AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue(), element); + final String allowMultipleCredits = this.fromApiJsonHelper + .extractStringNamed(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue(), element); baseDataValidator.reset().parameter(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue()) .value(allowMultipleCredits).ignoreIfNull().notBlank(); - final Boolean allowMultipleCreditEntries = this.fromApiJsonHelper.extractBooleanNamed( - AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue(), element); + final Boolean allowMultipleCreditEntries = this.fromApiJsonHelper + .extractBooleanNamed(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue(), element); baseDataValidator.reset().parameter(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue()) .value(allowMultipleCreditEntries).ignoreIfNull(); - final String allowMultipleDebits = this.fromApiJsonHelper.extractStringNamed( - AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue(), element); + final String allowMultipleDebits = this.fromApiJsonHelper + .extractStringNamed(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue(), element); baseDataValidator.reset().parameter(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue()) .value(allowMultipleDebits).ignoreIfNull().notBlank(); - final Boolean allowMultipleDebitEntries = this.fromApiJsonHelper.extractBooleanNamed( - AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue(), element); + final Boolean allowMultipleDebitEntries = this.fromApiJsonHelper + .extractBooleanNamed(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue(), element); baseDataValidator.reset().parameter(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue()) .value(allowMultipleDebitEntries).ignoreIfNull(); @@ -200,20 +200,20 @@ public class AccountingRuleCommandFromApiJsonDeserializer { .arrayNotEmpty(); validateCreditOrDebitTagArray(debitTags, baseDataValidator, AccountingRuleJsonInputParams.DEBIT_ACCOUNT_TAGS.getValue()); - final String allowMultipleCredits = this.fromApiJsonHelper.extractStringNamed( - AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue(), element); + final String allowMultipleCredits = this.fromApiJsonHelper + .extractStringNamed(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue(), element); baseDataValidator.reset().parameter(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue()) .value(allowMultipleCredits).ignoreIfNull().notBlank(); - final Boolean allowMultipleCreditEntries = this.fromApiJsonHelper.extractBooleanNamed( - AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue(), element); + final Boolean allowMultipleCreditEntries = this.fromApiJsonHelper + .extractBooleanNamed(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue(), element); baseDataValidator.reset().parameter(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue()) .value(allowMultipleCreditEntries).ignoreIfNull(); - final String allowMultipleDebits = this.fromApiJsonHelper.extractStringNamed( - AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue(), element); + final String allowMultipleDebits = this.fromApiJsonHelper + .extractStringNamed(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue(), element); baseDataValidator.reset().parameter(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue()) .value(allowMultipleDebits).ignoreIfNull().notBlank(); - final Boolean allowMultipleDebitEntries = this.fromApiJsonHelper.extractBooleanNamed( - AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue(), element); + final Boolean allowMultipleDebitEntries = this.fromApiJsonHelper + .extractBooleanNamed(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue(), element); baseDataValidator.reset().parameter(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_DEBIT_ENTRIES.getValue()) .value(allowMultipleDebitEntries).ignoreIfNull(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/service/AccountingRuleReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/service/AccountingRuleReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 90d9f1fde..0ceedac8b --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/service/AccountingRuleReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/service/AccountingRuleReadPlatformServiceImpl.java @@ -64,15 +64,14 @@ public class AccountingRuleReadPlatformServiceImpl implements AccountingRuleRead private final GLAccountReadPlatformService glAccountReadPlatformService; private final boolean isAssociationParametersExists; - public AccountingRuleDataExtractor(final JdbcTemplate jdbcTemplate, - final GLAccountReadPlatformService glAccountReadPlatformService, final boolean isAssociationParametersExists) { + public AccountingRuleDataExtractor(final JdbcTemplate jdbcTemplate, final GLAccountReadPlatformService glAccountReadPlatformService, + final boolean isAssociationParametersExists) { this.jdbcTemplate = jdbcTemplate; this.glAccountReadPlatformService = glAccountReadPlatformService; this.isAssociationParametersExists = isAssociationParametersExists; final StringBuilder sqlBuilder = new StringBuilder(400); - sqlBuilder - .append(" rule.id as id,rule.name as name, rule.office_id as officeId,office.name as officeName,") - .append(" rule.description as description, rule.system_defined as systemDefined, rule.allow_multiple_debits as allowMultipleDebitEntries, rule.allow_multiple_credits as allowMultipleCreditEntries, ") + sqlBuilder.append(" rule.id as id,rule.name as name, rule.office_id as officeId,office.name as officeName,").append( + " rule.description as description, rule.system_defined as systemDefined, rule.allow_multiple_debits as allowMultipleDebitEntries, rule.allow_multiple_credits as allowMultipleCreditEntries, ") .append("debitAccount.id AS debitAccountId, debitAccount.name as debitAccountName, debitAccount.gl_code as debitAccountGLCode, ") .append("creditAccount.id AS creditAccountId, creditAccount.name as creditAccountName, creditAccount.gl_code as creditAccountGLCode") .append(" from m_office AS office, acc_accounting_rule AS rule ") @@ -116,8 +115,9 @@ public class AccountingRuleReadPlatformServiceImpl implements AccountingRuleRead if (accountToCreditId == null) { creditTags = !this.isAssociationParametersExists ? getCreditOrDebitTags(id, JournalEntryType.CREDIT.getValue()) : null; - creditAccounts = this.isAssociationParametersExists ? this.glAccountReadPlatformService.retrieveAccountsByTagId(id, - JournalEntryType.CREDIT.getValue()) : null; + creditAccounts = this.isAssociationParametersExists + ? this.glAccountReadPlatformService.retrieveAccountsByTagId(id, JournalEntryType.CREDIT.getValue()) + : null; } else { creditTags = null; final GLAccountDataForLookup creditAccount = new GLAccountDataForLookup(accountToCreditId, creditAccountName, @@ -127,8 +127,9 @@ public class AccountingRuleReadPlatformServiceImpl implements AccountingRuleRead if (accountToDebitId == null) { debitTags = !this.isAssociationParametersExists ? getCreditOrDebitTags(id, JournalEntryType.DEBIT.getValue()) : null; - debitAccounts = this.isAssociationParametersExists ? this.glAccountReadPlatformService.retrieveAccountsByTagId(id, - JournalEntryType.DEBIT.getValue()) : null; + debitAccounts = this.isAssociationParametersExists + ? this.glAccountReadPlatformService.retrieveAccountsByTagId(id, JournalEntryType.DEBIT.getValue()) + : null; } else { debitTags = null; final GLAccountDataForLookup debitAccount = new GLAccountDataForLookup(accountToDebitId, debitAccountName, diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/service/AccountingRuleWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/service/AccountingRuleWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index 8a7ed6463..fac283f9e --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/service/AccountingRuleWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/rule/service/AccountingRuleWritePlatformServiceJpaRepositoryImpl.java @@ -195,12 +195,15 @@ public class AccountingRuleWritePlatformServiceJpaRepositoryImpl implements Acco creditTags = command.arrayValueOfParameterNamed(AccountingRuleJsonInputParams.CREDIT_ACCOUNT_TAGS.getValue()); } - if (accountToDebitId != null && debitTags != null) { throw new AccountingRuleDataException( - AccountingRuleJsonInputParams.ACCOUNT_TO_DEBIT.getValue(), AccountingRuleJsonInputParams.DEBIT_ACCOUNT_TAGS.getValue()); } + if (accountToDebitId != null && debitTags != null) { + throw new AccountingRuleDataException(AccountingRuleJsonInputParams.ACCOUNT_TO_DEBIT.getValue(), + AccountingRuleJsonInputParams.DEBIT_ACCOUNT_TAGS.getValue()); + } - if (accountToCreditId != null && creditTags != null) { throw new AccountingRuleDataException( - AccountingRuleJsonInputParams.ACCOUNT_TO_CREDIT.getValue(), - AccountingRuleJsonInputParams.CREDIT_ACCOUNT_TAGS.getValue()); } + if (accountToCreditId != null && creditTags != null) { + throw new AccountingRuleDataException(AccountingRuleJsonInputParams.ACCOUNT_TO_CREDIT.getValue(), + AccountingRuleJsonInputParams.CREDIT_ACCOUNT_TAGS.getValue()); + } boolean allowMultipleCreditEntries = false; if (command.parameterExists(AccountingRuleJsonInputParams.ALLOW_MULTIPLE_CREDIT_ENTRIES.getValue())) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/accounting/trialbalance/exception/TrialBalanceNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/accounting/trialbalance/exception/TrialBalanceNotFoundException.java index 9660405c1..5cda18b47 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/accounting/trialbalance/exception/TrialBalanceNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/accounting/trialbalance/exception/TrialBalanceNotFoundException.java @@ -20,9 +20,11 @@ package org.apache.fineract.accounting.trialbalance.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; -public class TrialBalanceNotFoundException extends AbstractPlatformResourceNotFoundException{ - public TrialBalanceNotFoundException(final Long officeId,final Long accountId){ - super("error.msg.trial.balance.invalid", "Trial balance with officeId " + officeId +"and accountId"+accountId+" does not exist"); +public class TrialBalanceNotFoundException extends AbstractPlatformResourceNotFoundException { + + public TrialBalanceNotFoundException(final Long officeId, final Long accountId) { + super("error.msg.trial.balance.invalid", + "Trial balance with officeId " + officeId + "and accountId" + accountId + " does not exist"); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/api/AdHocApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/api/AdHocApiResource.java index d85913b65..a642d9e71 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/api/AdHocApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/api/AdHocApiResource.java @@ -55,16 +55,16 @@ import org.springframework.stereotype.Component; @Path("/adhocquery") @Component @Scope("singleton") -@Api(tags = {"AdhocQuery Api"}) -@SwaggerDefinition(tags = { - @Tag(name = "AdhocQuery Api", description = "") -}) +@Api(tags = { "AdhocQuery Api" }) +@SwaggerDefinition(tags = { @Tag(name = "AdhocQuery Api", description = "") }) public class AdHocApiResource { /** - * The set of parameters that are supported in response for {@link AdhocData} + * The set of parameters that are supported in response for + * {@link AdhocData} */ - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "query", "tableName","tableField","isActive","createdBy","createdOn","createdById","updatedById","updatedOn","email")); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "query", "tableName", "tableField", + "isActive", "createdBy", "createdOn", "createdById", "updatedById", "updatedOn", "email")); private final PlatformSecurityContext context; private final AdHocReadPlatformService adHocReadPlatformService; @@ -74,8 +74,7 @@ public class AdHocApiResource { @Autowired public AdHocApiResource(final PlatformSecurityContext context, final AdHocReadPlatformService readPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, + final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.context = context; this.adHocReadPlatformService = readPlatformService; @@ -94,6 +93,7 @@ public class AdHocApiResource { final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, adhocs, this.RESPONSE_DATA_PARAMETERS); } + @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @@ -104,6 +104,7 @@ public class AdHocApiResource { final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, user, this.RESPONSE_DATA_PARAMETERS); } + @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @@ -123,7 +124,8 @@ public class AdHocApiResource { @Path("{adHocId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveAdHocQuery(@PathParam("adHocId") @ApiParam(value = "adHocId") final Long adHocId, @Context final UriInfo uriInfo) { + public String retrieveAdHocQuery(@PathParam("adHocId") @ApiParam(value = "adHocId") final Long adHocId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser(); @@ -133,6 +135,7 @@ public class AdHocApiResource { return this.toApiJsonSerializer.serialize(settings, adhoc, this.RESPONSE_DATA_PARAMETERS); } + @PUT @Path("{adHocId}") @Consumes({ MediaType.APPLICATION_JSON }) @@ -148,7 +151,8 @@ public class AdHocApiResource { return this.toApiJsonSerializer.serialize(result); } - /** + + /** * Delete AdHocQuery * * @param adHocId @@ -173,4 +177,4 @@ public class AdHocApiResource { return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/api/AdHocJsonInputParams.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/api/AdHocJsonInputParams.java index a20b11005..d2b45d987 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/api/AdHocJsonInputParams.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/api/AdHocJsonInputParams.java @@ -25,10 +25,9 @@ import java.util.Set; * Enum of all parameters passed in while creating/updating a AdHocQuery ***/ public enum AdHocJsonInputParams { - ID("id"), NAME("name"),QUERY("query"),TABLENAME("tableName"), TABLEFIELDS("tableFields"), ISACTIVE("isActive"), - REPORT_RUN_FREQUENCY("reportRunFrequency"), - REPORT_RUN_EVERY("reportRunEvery"), - EMAIL("email"); + + ID("id"), NAME("name"), QUERY("query"), TABLENAME("tableName"), TABLEFIELDS("tableFields"), ISACTIVE("isActive"), REPORT_RUN_FREQUENCY( + "reportRunFrequency"), REPORT_RUN_EVERY("reportRunEvery"), EMAIL("email"); private final String value; @@ -55,4 +54,4 @@ public enum AdHocJsonInputParams { public String getValue() { return this.value; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/data/AdHocData.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/data/AdHocData.java index 6a71ebff5..67129ee19 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/data/AdHocData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/data/AdHocData.java @@ -31,8 +31,6 @@ import org.joda.time.DateTime; */ public class AdHocData { - - @SuppressWarnings("unused") private final Long id; @SuppressWarnings("unused") @@ -67,80 +65,96 @@ public class AdHocData { private final DateTime lastRun; public AdHocData(final Long id, final String name, final String query, final String tableName, final String tableFields, - final boolean isActive, final DateTime createdOn, final Long createdById, final Long updatedById, - final DateTime updatedOn, final String createdBy, final String email, - final List reportRunFrequencies, final Long reportRunFrequency, final Long reportRunEvery, - final DateTime lastRun) { + final boolean isActive, final DateTime createdOn, final Long createdById, final Long updatedById, final DateTime updatedOn, + final String createdBy, final String email, final List reportRunFrequencies, final Long reportRunFrequency, + final Long reportRunEvery, final DateTime lastRun) { this.id = id; - this.name=name; - this.query=query; + this.name = name; + this.query = query; this.tableName = tableName; this.tableFields = tableFields; this.isActive = isActive; this.createdOn = createdOn; this.createdById = createdById; - this.updatedById=updatedById; - this.updatedOn=updatedOn; - this.createdBy=createdBy; - this.email=email; + this.updatedById = updatedById; + this.updatedOn = updatedOn; + this.createdBy = createdBy; + this.email = email; this.reportRunFrequencies = reportRunFrequencies; this.reportRunFrequency = reportRunFrequency; this.reportRunEvery = reportRunEvery; this.lastRun = lastRun; } - public static AdHocData template() { - List reportRunFrequencies = Arrays.stream(ReportRunFrequency.values()).map(rrf -> new EnumOptionData( - rrf.getValue(), rrf.getCode(), rrf.getCode() - )).collect(Collectors.toList()); - AdHocData adHocData = new AdHocData(null,null,null,null,null,false,null,null,null,null,null,null, reportRunFrequencies, null, null, null); + public static AdHocData template() { + List reportRunFrequencies = Arrays.stream(ReportRunFrequency.values()) + .map(rrf -> new EnumOptionData(rrf.getValue(), rrf.getCode(), rrf.getCode())).collect(Collectors.toList()); + + AdHocData adHocData = new AdHocData(null, null, null, null, null, false, null, null, null, null, null, null, reportRunFrequencies, + null, null, null); return adHocData; } + public Long getId() { return this.id; } + public String getName() { return this.name; } + public String getQuery() { return this.query; } + public String getTableName() { return this.tableName; } + public String getTableFields() { return this.tableFields; } + public String getEmail() { return this.email; } + public boolean isActive() { return this.isActive; } + public DateTime getCreatedOn() { return this.createdOn; } + public Long getCreatedById() { return this.createdById; } + public Long getUpdatedById() { return this.updatedById; } + public DateTime getUpdatedOn() { return this.updatedOn; } + public String getCreatedBy() { return this.createdBy; } + public List getReportRunFrequencies() { return this.reportRunFrequencies; } + public Long getReportRunFrequency() { return this.reportRunFrequency; } + public Long getReportRunEvery() { return this.reportRunEvery; } + public DateTime getLastRun() { return this.lastRun; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/domain/AdHoc.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/domain/AdHoc.java index 651b939a2..84838f538 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/domain/AdHoc.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/domain/AdHoc.java @@ -30,26 +30,24 @@ import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.domain.AbstractAuditableCustom; import org.apache.fineract.infrastructure.security.utils.SQLInjectionValidator; - @Entity @Table(name = "m_adhoc") public class AdHoc extends AbstractAuditableCustom { - @Column(name = "name", length = 100) - private String name; + @Column(name = "name", length = 100) + private String name; @Column(name = "query", length = 2000) - private String query; + private String query; @Column(name = "table_name", length = 100) - private String tableName; - + private String tableName; @Column(name = "table_fields", length = 2000) - private String tableFields; + private String tableFields; @Column(name = "email", length = 500) - private String email; + private String email; @Column(name = "report_run_frequency_code") private Long reportRunFrequency; @@ -62,21 +60,23 @@ public class AdHoc extends AbstractAuditableCustom { private AdHoc() {} - private AdHoc(final String name, final String query,final String tableName,final String tableFields ,final String email, final Long reportRunFrequency, final Long reportRunEvery, final boolean isActive) { + private AdHoc(final String name, final String query, final String tableName, final String tableFields, final String email, + final Long reportRunFrequency, final Long reportRunEvery, final boolean isActive) { this.name = StringUtils.defaultIfEmpty(name, null); - this.query=StringUtils.defaultIfEmpty(query,null); - this.tableName=StringUtils.defaultIfEmpty(tableName,null); - this.tableFields=StringUtils.defaultIfEmpty(tableFields,null); - this.email=StringUtils.defaultIfEmpty(email,null); + this.query = StringUtils.defaultIfEmpty(query, null); + this.tableName = StringUtils.defaultIfEmpty(tableName, null); + this.tableFields = StringUtils.defaultIfEmpty(tableFields, null); + this.email = StringUtils.defaultIfEmpty(email, null); this.reportRunFrequency = reportRunFrequency; this.reportRunEvery = reportRunEvery; this.isActive = BooleanUtils.toBooleanDefaultIfNull(isActive, false); } + public static AdHoc fromJson(final JsonCommand command) { final String name = command.stringValueOfParameterNamed(AdHocJsonInputParams.NAME.getValue()); - String commandQuery=command.stringValueOfParameterNamed(AdHocJsonInputParams.QUERY.getValue()); + String commandQuery = command.stringValueOfParameterNamed(AdHocJsonInputParams.QUERY.getValue()); SQLInjectionValidator.validateAdhocQuery(commandQuery); final String query = commandQuery; @@ -86,7 +86,7 @@ public class AdHoc extends AbstractAuditableCustom { final Long reportRunFrequency = command.longValueOfParameterNamed(AdHocJsonInputParams.REPORT_RUN_FREQUENCY.getValue()); final Long reportRunEvery = command.longValueOfParameterNamed(AdHocJsonInputParams.REPORT_RUN_EVERY.getValue()); final boolean isActive = command.booleanPrimitiveValueOfParameterNamed(AdHocJsonInputParams.ISACTIVE.getValue()); - return new AdHoc(name,query,tableName,tableFields, email, reportRunFrequency, reportRunEvery, isActive); + return new AdHoc(name, query, tableName, tableFields, email, reportRunFrequency, reportRunEvery, isActive); } public Map update(final JsonCommand command) { @@ -148,31 +148,40 @@ public class AdHoc extends AbstractAuditableCustom { public String getName() { return name; } + public String getQuery() { return query; } + public String getTableName() { return tableName; } + public String getTableFields() { return tableFields; } + public boolean isActive() { return this.isActive; } + public String getEmail() { return email; } + public void disableActive() { this.isActive = true; } + public void enableActive() { this.isActive = false; } + public Long getReportRunFrequency() { return this.reportRunFrequency; } + public Long getReportRunEvery() { return this.reportRunEvery; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/domain/ReportRunFrequency.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/domain/ReportRunFrequency.java index fc02d4bc7..8c79487f5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/domain/ReportRunFrequency.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/domain/ReportRunFrequency.java @@ -23,15 +23,12 @@ import java.util.Map; import java.util.stream.Collectors; public enum ReportRunFrequency { - DAILY(1, "reportRunFrequency.daily"), - WEEKLY(2, "reportRunFrequency.weekly"), - MONTHLY(3, "reportRunFrequency.monthly"), - YEARLY(4, "reportRunFrequency.yearly"), - CUSTOM(5, "reportRunFrequency.custom"); - private static final Map MAP = Arrays.stream(ReportRunFrequency.values()).collect(Collectors.toMap( - ReportRunFrequency::getValue, e -> e - )); + DAILY(1, "reportRunFrequency.daily"), WEEKLY(2, "reportRunFrequency.weekly"), MONTHLY(3, "reportRunFrequency.monthly"), YEARLY(4, + "reportRunFrequency.yearly"), CUSTOM(5, "reportRunFrequency.custom"); + + private static final Map MAP = Arrays.stream(ReportRunFrequency.values()) + .collect(Collectors.toMap(ReportRunFrequency::getValue, e -> e)); private final long value; private final String code; diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/exception/AdHocNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/exception/AdHocNotFoundException.java index 7de67f5c4..e30cf213f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/exception/AdHocNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/exception/AdHocNotFoundException.java @@ -21,12 +21,11 @@ package org.apache.fineract.adhocquery.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when AdHoc resources are not - * found. + * A {@link RuntimeException} thrown when AdHoc resources are not found. */ public class AdHocNotFoundException extends AbstractPlatformResourceNotFoundException { public AdHocNotFoundException(final Long id) { super("error.msg.adhocquery.adhoc.id.invalid", "Adhoc Record with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/CreateAdHocCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/CreateAdHocCommandHandler.java index 73f09dccc..1d7ec8a4f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/CreateAdHocCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/CreateAdHocCommandHandler.java @@ -44,4 +44,4 @@ public class CreateAdHocCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createAdHocQuery(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/DeleteAdHocCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/DeleteAdHocCommandHandler.java index 42c48ebdd..161d4f31c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/DeleteAdHocCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/DeleteAdHocCommandHandler.java @@ -44,4 +44,4 @@ public class DeleteAdHocCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.deleteAdHocQuery(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/UpdateAdHocCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/UpdateAdHocCommandHandler.java index c031eada6..841725d06 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/UpdateAdHocCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/handler/UpdateAdHocCommandHandler.java @@ -45,4 +45,4 @@ public class UpdateAdHocCommandHandler implements NewCommandSourceHandler { final Long adHocId = command.entityId(); return this.writePlatformService.updateAdHocQuery(adHocId, command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocDataValidator.java index 548d69445..96edbf79f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocDataValidator.java @@ -43,9 +43,8 @@ public final class AdHocDataValidator { /** * The parameters supported for this command. */ - private final Set supportedParameters = new HashSet<>(Arrays.asList( - "name","query","tableName","tableFields","email","isActive", "reportRunFrequency", "reportRunEvery" - )); + private final Set supportedParameters = new HashSet<>( + Arrays.asList("name", "query", "tableName", "tableFields", "email", "isActive", "reportRunFrequency", "reportRunEvery")); private final FromJsonHelper fromApiJsonHelper; @@ -83,7 +82,7 @@ public final class AdHocDataValidator { final Long reportRunFrequencyCode = this.fromApiJsonHelper.extractLongNamed("reportRunFrequency", element); if (reportRunFrequencyCode != null) { baseDataValidator.reset().parameter("reportRunFrequency").value(reportRunFrequencyCode) - .inMinMaxRange((int) ReportRunFrequency.DAILY.getValue(), (int) ReportRunFrequency.CUSTOM.getValue()); + .inMinMaxRange((int) ReportRunFrequency.DAILY.getValue(), (int) ReportRunFrequency.CUSTOM.getValue()); } final Long reportRunEvery = this.fromApiJsonHelper.extractLongNamed("reportRunEvery", element); @@ -129,16 +128,20 @@ public final class AdHocDataValidator { if (this.fromApiJsonHelper.parameterExists("reportRunFrequency", element)) { final Long reportRunFrequencyCode = this.fromApiJsonHelper.extractLongNamed("reportRunFrequency", element); baseDataValidator.reset().parameter("reportRunFrequency").value(reportRunFrequencyCode) - .inMinMaxRange((int) ReportRunFrequency.DAILY.getValue(), (int) ReportRunFrequency.CUSTOM.getValue()); + .inMinMaxRange((int) ReportRunFrequency.DAILY.getValue(), (int) ReportRunFrequency.CUSTOM.getValue()); } if (this.fromApiJsonHelper.parameterExists("reportRunEvery", element)) { final Long reportRunEvery = this.fromApiJsonHelper.extractLongNamed("reportRunEvery", element); baseDataValidator.reset().parameter("reportRunEvery").value(reportRunEvery).integerGreaterThanZero(); } - /*if (this.fromApiJsonHelper.parameterExists("isActive", element)) { - final Integer isActive = this.fromApiJsonHelper.extractIntegerNamed("isActive", element, Locale.getDefault()); - baseDataValidator.reset().parameter("isActive").value(isActive).notNull().inMinMaxRange(1, 2); - }*/ + /* + * if (this.fromApiJsonHelper.parameterExists("isActive", element)) { + * final Integer isActive = + * this.fromApiJsonHelper.extractIntegerNamed("isActive", element, + * Locale.getDefault()); + * baseDataValidator.reset().parameter("isActive").value(isActive). + * notNull().inMinMaxRange(1, 2); } + */ throwExceptionIfValidationWarningsExist(dataValidationErrors); } @@ -146,4 +149,4 @@ public final class AdHocDataValidator { private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocReadPlatformService.java index 3e3acad60..776e3614f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocReadPlatformService.java @@ -28,6 +28,7 @@ public interface AdHocReadPlatformService { Collection retrieveAllActiveAdHocQuery(); AdHocData retrieveOne(Long adHocId); + AdHocData retrieveNewAdHocDetails(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocReadPlatformServiceImpl.java index 1201d3248..16492b0eb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocReadPlatformServiceImpl.java @@ -78,20 +78,21 @@ public class AdHocReadPlatformServiceImpl implements AdHocReadPlatformService { final Long id = JdbcSupport.getLong(rs, "id"); final String name = rs.getString("name"); final String query = rs.getString("query"); - final String tableName=rs.getString("tableName"); - final String tableFields=rs.getString("tableField"); + final String tableName = rs.getString("tableName"); + final String tableFields = rs.getString("tableField"); final Boolean isActive = rs.getBoolean("isActive"); final DateTime createdDate = JdbcSupport.getDateTime(rs, "createdDate"); final Long createdById = JdbcSupport.getLong(rs, "createdById"); - final Long updatedById=JdbcSupport.getLong(rs, "updatedById"); - final DateTime updatedOn=JdbcSupport.getDateTime(rs, "updatedOn"); - final String createdByUsername=rs.getString("createdBy"); - final String email=rs.getString("email"); - final Long reportRunFrequency=JdbcSupport.getLong(rs, "report_run_frequency_code"); - final Long reportRunEvery=JdbcSupport.getLong(rs, "report_run_every"); + final Long updatedById = JdbcSupport.getLong(rs, "updatedById"); + final DateTime updatedOn = JdbcSupport.getDateTime(rs, "updatedOn"); + final String createdByUsername = rs.getString("createdBy"); + final String email = rs.getString("email"); + final Long reportRunFrequency = JdbcSupport.getLong(rs, "report_run_frequency_code"); + final Long reportRunEvery = JdbcSupport.getLong(rs, "report_run_every"); final DateTime lastRun = JdbcSupport.getDateTime(rs, "last_run"); - return new AdHocData(id,name,query, tableName,tableFields,isActive,createdDate,createdById,updatedById,updatedOn,createdByUsername,email, AdHocData.template().getReportRunFrequencies(), reportRunFrequency, reportRunEvery, lastRun); + return new AdHocData(id, name, query, tableName, tableFields, isActive, createdDate, createdById, updatedById, updatedOn, + createdByUsername, email, AdHocData.template().getReportRunFrequencies(), reportRunFrequency, reportRunEvery, lastRun); } public String schema() { @@ -105,8 +106,7 @@ public class AdHocReadPlatformServiceImpl implements AdHocReadPlatformService { @Override public AdHocData retrieveNewAdHocDetails() { - return AdHocData.template(); + return AdHocData.template(); } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocScheduledJobRunnerService.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocScheduledJobRunnerService.java index 88e24a255..4f2bc2b46 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocScheduledJobRunnerService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocScheduledJobRunnerService.java @@ -19,5 +19,6 @@ package org.apache.fineract.adhocquery.service; public interface AdHocScheduledJobRunnerService { + void generateClientSchedule(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocScheduledJobRunnerServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocScheduledJobRunnerServiceImpl.java index e44dc5fe4..2c9e0094d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocScheduledJobRunnerServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocScheduledJobRunnerServiceImpl.java @@ -46,9 +46,7 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn private final JdbcTemplate jdbcTemplate; @Autowired - public AdHocScheduledJobRunnerServiceImpl(final RoutingDataSource dataSource, - final AdHocReadPlatformService adHocReadPlatformService - ) { + public AdHocScheduledJobRunnerServiceImpl(final RoutingDataSource dataSource, final AdHocReadPlatformService adHocReadPlatformService) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.adHocReadPlatformService = adHocReadPlatformService; @@ -59,8 +57,8 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn @CronTarget(jobName = JobName.GENERATE_ADHOCCLIENT_SCEHDULE) public void generateClientSchedule() { final Collection adhocs = this.adHocReadPlatformService.retrieveAllActiveAdHocQuery(); - if(adhocs.size()>0){ - adhocs.forEach(adhoc->{ + if (adhocs.size() > 0) { + adhocs.forEach(adhoc -> { boolean run = true; LocalDate next = null; if (adhoc.getReportRunFrequency() != null) { @@ -71,23 +69,23 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn case DAILY: next = start.plusDays(1); run = Days.daysBetween(start, end).getDays() >= 1; - break; + break; case WEEKLY: next = start.plusDays(7); run = Days.daysBetween(start, end).getDays() >= 7; - break; + break; case MONTHLY: next = start.plusMonths(1); run = Months.monthsBetween(start, end).getMonths() >= 1; - break; + break; case YEARLY: next = start.plusYears(1); run = Years.yearsBetween(start, end).getYears() >= 1; - break; + break; case CUSTOM: next = start.plusDays((int) (long) adhoc.getReportRunEvery()); run = Days.daysBetween(start, end).getDays() >= adhoc.getReportRunEvery(); - break; + break; default: throw new IllegalStateException(); } @@ -96,12 +94,10 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn } if (run) { - //jdbcTemplate.execute("truncate table "+adhoc.getTableName()); + // jdbcTemplate.execute("truncate table + // "+adhoc.getTableName()); final StringBuilder insertSqlBuilder = new StringBuilder(900); - insertSqlBuilder - .append("INSERT INTO ") - .append(adhoc.getTableName()+"(") - .append(adhoc.getTableFields()+") ") + insertSqlBuilder.append("INSERT INTO ").append(adhoc.getTableName() + "(").append(adhoc.getTableFields() + ") ") .append(adhoc.getQuery()); if (insertSqlBuilder.length() > 0) { final int result = this.jdbcTemplate.update(insertSqlBuilder.toString()); @@ -111,15 +107,13 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn } } else { LOG.info("{}: Skipping execution of {}, scheduled for execution on {}", - new Object[] { ThreadLocalContextUtil.getTenant().getName(), adhoc.getName(), next }); + new Object[] { ThreadLocalContextUtil.getTenant().getName(), adhoc.getName(), next }); } }); - }else{ + } else { LOG.info("{} Nothing to update", ThreadLocalContextUtil.getTenant().getName()); } - - } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocWritePlatformService.java index ae467a1dd..0d2566611 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocWritePlatformService.java @@ -32,4 +32,4 @@ public interface AdHocWritePlatformService { CommandProcessingResult disableAdHocQuery(Long adHocId); CommandProcessingResult enableAdHocQuery(Long adHocId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocWritePlatformServiceJpaRepositoryImpl.java index fd6d1ccc0..b622c397d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/adhocquery/service/AdHocWritePlatformServiceJpaRepositoryImpl.java @@ -42,10 +42,9 @@ public class AdHocWritePlatformServiceJpaRepositoryImpl implements AdHocWritePla private final AdHocRepository adHocRepository; private final AdHocDataValidator adHocCommandFromApiJsonDeserializer; - @Autowired public AdHocWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final AdHocRepository adHocRepository, - final AdHocDataValidator adHocCommandFromApiJsonDeserializer) { + final AdHocDataValidator adHocCommandFromApiJsonDeserializer) { this.context = context; this.adHocRepository = adHocRepository; this.adHocCommandFromApiJsonDeserializer = adHocCommandFromApiJsonDeserializer; @@ -83,8 +82,8 @@ public class AdHocWritePlatformServiceJpaRepositoryImpl implements AdHocWritePla if (realCause.getMessage().contains("unq_name")) { final String name = command.stringValueOfParameterNamed("name"); - throw new PlatformDataIntegrityException("error.msg.adhocquery.duplicate.name", "AdHocQuery with name `" + name + "` already exists", - "name", name); + throw new PlatformDataIntegrityException("error.msg.adhocquery.duplicate.name", + "AdHocQuery with name `" + name + "` already exists", "name", name); } logAsErrorUnexpectedDataIntegrityException(dve); @@ -123,6 +122,7 @@ public class AdHocWritePlatformServiceJpaRepositoryImpl implements AdHocWritePla .build(); } } + /** * Method for Delete adhoc */ diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/api/BatchApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/batch/api/BatchApiResource.java index 5f2376f2f..3a7ecd668 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/api/BatchApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/api/BatchApiResource.java @@ -50,8 +50,8 @@ import org.springframework.stereotype.Component; /** * Provides a REST resource for Batch Requests. This class acts as a proxy to - * {@link org.apache.fineract.batch.service.BatchApiService} and de-serializes the - * incoming JSON string to a list of + * {@link org.apache.fineract.batch.service.BatchApiService} and de-serializes + * the incoming JSON string to a list of * {@link org.apache.fineract.batch.domain .BatchRequest} type. This list is * forwarded to BatchApiService which finally returns a list of * {@link org.apache.fineract.batch.domain.BatchResponse} type which is then @@ -66,10 +66,15 @@ import org.springframework.stereotype.Component; @Path("/batches") @Component @Scope("singleton") -@Api(tags = {"Batch API"}) +@Api(tags = { "Batch API" }) @SwaggerDefinition(tags = { - @Tag(name = "Batch API", description = "The Apache Fineract Batch API enables a consumer to access significant amounts of data in a single call or to make changes to several objects at once. Batching allows a consumer to pass instructions for several operations in a single HTTP request. A consumer can also specify dependencies between related operations. Once all operations have been completed, a consolidated response will be passed back and the HTTP connection will be closed.\n" + "\n" + "The Batch API takes in an array of logical HTTP requests represented as JSON arrays - each request has a requestId (the id of a request used to specify the sequence and as a dependency between requests), a method (corresponding to HTTP method GET/PUT/POST/DELETE etc.), a relativeUrl (the portion of the URL after https://example.org/api/v2/), optional headers array (corresponding to HTTP headers), optional reference parameter if a request is dependent on another request and an optional body (for POST and PUT requests). The Batch API returns an array of logical HTTP responses represented as JSON arrays - each response has a requestId, a status code, an optional headers array and an optional body (which is a JSON encoded string).\n" + "\n" + "Batch API uses Json Path to handle dependent parameters. For example, if request '2' is referencing request '1' and in the \"body\" or in \"relativeUrl\" of request '2', there is a dependent parameter (which will look like \"$.parameter_name\"), then Batch API will internally substitute this dependent parameter from the response body of request '1'.\n" + "\n" + "Batch API is able to handle deeply nested dependent requests as well nested parameters. As shown in the example, requests are dependent on each other as, 1<--2<--6, i.e a nested dependency, where request '6' is not directly dependent on request '1' but still it is one of the nested child of request '1'. In the same way Batch API could handle a deeply nested dependent value, such as {..[..{..,$.parameter_name,..}..]}.") -}) + @Tag(name = "Batch API", description = "The Apache Fineract Batch API enables a consumer to access significant amounts of data in a single call or to make changes to several objects at once. Batching allows a consumer to pass instructions for several operations in a single HTTP request. A consumer can also specify dependencies between related operations. Once all operations have been completed, a consolidated response will be passed back and the HTTP connection will be closed.\n" + + "\n" + + "The Batch API takes in an array of logical HTTP requests represented as JSON arrays - each request has a requestId (the id of a request used to specify the sequence and as a dependency between requests), a method (corresponding to HTTP method GET/PUT/POST/DELETE etc.), a relativeUrl (the portion of the URL after https://example.org/api/v2/), optional headers array (corresponding to HTTP headers), optional reference parameter if a request is dependent on another request and an optional body (for POST and PUT requests). The Batch API returns an array of logical HTTP responses represented as JSON arrays - each response has a requestId, a status code, an optional headers array and an optional body (which is a JSON encoded string).\n" + + "\n" + + "Batch API uses Json Path to handle dependent parameters. For example, if request '2' is referencing request '1' and in the \"body\" or in \"relativeUrl\" of request '2', there is a dependent parameter (which will look like \"$.parameter_name\"), then Batch API will internally substitute this dependent parameter from the response body of request '1'.\n" + + "\n" + + "Batch API is able to handle deeply nested dependent requests as well nested parameters. As shown in the example, requests are dependent on each other as, 1<--2<--6, i.e a nested dependency, where request '6' is not directly dependent on request '1' but still it is one of the nested child of request '1'. In the same way Batch API could handle a deeply nested dependent value, such as {..[..{..,$.parameter_name,..}..]}.") }) public class BatchApiResource { private final PlatformSecurityContext context; @@ -108,11 +113,15 @@ public class BatchApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Batch requests in a single transaction", httpMethod = "POST", notes = "The Apache Fineract Batch API is also capable of executing all the requests in a single transaction, by setting a Query Parameter, \"enclosingTransaction=true\". So, if one or more of the requests in a batch returns an erroneous response all of the Data base transactions made by other successful requests will be rolled back.\n" + "\n" + "If there has been a rollback in a transaction then a single response will be provided, with a '400' status code and a body consisting of the error details of the first failed request.") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "BatchRequest", required = true, type = "body", dataTypeClass = BatchApiResourceSwagger.PostBatchesRequest.class, value = "request body")}) - @ApiResponses({@ApiResponse(code = 200, message = "Success", response = BatchResponse.class)}) - public String handleBatchRequests(@DefaultValue("false") @QueryParam("enclosingTransaction") @ApiParam(value = "enclosingTransaction", defaultValue = "false") final boolean enclosingTransaction, - @ApiParam(hidden = true) final String jsonRequestString, @Context UriInfo uriInfo) { + @ApiOperation(value = "Batch requests in a single transaction", httpMethod = "POST", notes = "The Apache Fineract Batch API is also capable of executing all the requests in a single transaction, by setting a Query Parameter, \"enclosingTransaction=true\". So, if one or more of the requests in a batch returns an erroneous response all of the Data base transactions made by other successful requests will be rolled back.\n" + + "\n" + + "If there has been a rollback in a transaction then a single response will be provided, with a '400' status code and a body consisting of the error details of the first failed request.") + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", dataType = "BatchRequest", required = true, type = "body", dataTypeClass = BatchApiResourceSwagger.PostBatchesRequest.class, value = "request body") }) + @ApiResponses({ @ApiResponse(code = 200, message = "Success", response = BatchResponse.class) }) + public String handleBatchRequests( + @DefaultValue("false") @QueryParam("enclosingTransaction") @ApiParam(value = "enclosingTransaction", defaultValue = "false") final boolean enclosingTransaction, + @ApiParam(hidden = true) final String jsonRequestString, @Context UriInfo uriInfo) { // Handles user authentication this.context.authenticatedUser(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/api/BatchApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/batch/api/BatchApiResourceSwagger.java index d2ce0bfc9..c016c3bcc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/api/BatchApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/api/BatchApiResourceSwagger.java @@ -27,17 +27,20 @@ import org.apache.fineract.batch.domain.Header; * Created by sanyam on 26/7/17. */ final class BatchApiResourceSwagger { + private BatchApiResourceSwagger() { } @ApiModel(value = "PostBatchesRequest") - public static final class PostBatchesRequest{ + public static final class PostBatchesRequest { + private PostBatchesRequest() { } - public static final class PostBodyRequestSwagger{ + public static final class PostBodyRequestSwagger { + private PostBodyRequestSwagger() { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/CommandContext.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/CommandContext.java index 4016fa5e9..da6635ce8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/CommandContext.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/CommandContext.java @@ -19,9 +19,10 @@ package org.apache.fineract.batch.command; /** - * Provides an object to {@link org.apache.fineract.batch.service.BatchApiService} - * to get the proper commandStrategy for each request in BatchRequest. It uses - * Builder pattern to create object of this type. + * Provides an object to + * {@link org.apache.fineract.batch.service.BatchApiService} to get the proper + * commandStrategy for each request in BatchRequest. It uses Builder pattern to + * create object of this type. * * @author Rishabh Shukla * @@ -92,30 +93,16 @@ public class CommandContext { @Override public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof CommandContext)) { - return false; - } + if (this == obj) { return true; } + if (obj == null) { return false; } + if (!(obj instanceof CommandContext)) { return false; } CommandContext other = (CommandContext) obj; if (this.method == null) { - if (other.method != null) { - return false; - } - } else if (!this.method.equals(other.method)) { - return false; - } + if (other.method != null) { return false; } + } else if (!this.method.equals(other.method)) { return false; } if (this.resource == null) { - if (other.resource != null) { - return false; - } - } else if (!this.resource.equals(other.resource)) { - return false; - } + if (other.resource != null) { return false; } + } else if (!this.resource.equals(other.resource)) { return false; } return true; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/CommandStrategyProvider.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/CommandStrategyProvider.java index 96254c956..4aa4301cd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/CommandStrategyProvider.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/CommandStrategyProvider.java @@ -66,12 +66,14 @@ public class CommandStrategyProvider { */ public CommandStrategy getCommandStrategy(final CommandContext commandContext) { - if (this.commandStrategies.containsKey(commandContext)) { return (CommandStrategy) this.applicationContext - .getBean(this.commandStrategies.get(commandContext)); } + if (this.commandStrategies.containsKey(commandContext)) { + return (CommandStrategy) this.applicationContext.getBean(this.commandStrategies.get(commandContext)); + } for (ConcurrentHashMap.Entry entry : this.commandStrategies.entrySet()) { - if (commandContext.matcher(entry.getKey())) { return (CommandStrategy) this.applicationContext.getBean(this.commandStrategies - .get(entry.getKey())); } + if (commandContext.matcher(entry.getKey())) { + return (CommandStrategy) this.applicationContext.getBean(this.commandStrategies.get(entry.getKey())); + } } return new UnknownCommandStrategy(); @@ -89,10 +91,10 @@ public class CommandStrategyProvider { this.commandStrategies.put(CommandContext.resource("loans").method("POST").build(), "applyLoanCommandStrategy"); this.commandStrategies.put(CommandContext.resource("savingsaccounts").method("POST").build(), "applySavingsCommandStrategy"); this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges").method("POST").build(), "createChargeCommandStrategy"); - this.commandStrategies - .put(CommandContext.resource("loans\\/\\d+\\/charges").method("GET").build(), "collectChargesCommandStrategy"); - this.commandStrategies - .put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=repayment").method("POST").build(), "repayLoanCommandStrategy"); + this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges").method("GET").build(), + "collectChargesCommandStrategy"); + this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=repayment").method("POST").build(), + "repayLoanCommandStrategy"); this.commandStrategies.put(CommandContext.resource("clients\\/\\d+\\?command=activate").method("POST").build(), "activateClientCommandStrategy"); this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\?command=approve").method("POST").build(), @@ -103,4 +105,4 @@ public class CommandStrategyProvider { "approveLoanRescheduleCommandStrategy"); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ActivateClientCommandStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ActivateClientCommandStrategy.java index f9de92837..ba465dc5a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ActivateClientCommandStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ActivateClientCommandStrategy.java @@ -29,9 +29,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * Implements {@link org.apache.fineract.batch.command.CommandStrategy} to handle - * activation of a pending client. It passes the contents of the body from the - * BatchRequest to + * Implements {@link org.apache.fineract.batch.command.CommandStrategy} to + * handle activation of a pending client. It passes the contents of the body + * from the BatchRequest to * {@link org.apache.fineract.portfolio.client.api.ClientsApiResource} and gets * back the response. This class will also catch any errors raised by * {@link org.apache.fineract.portfolio.client.api.ClientsApiResource} and map @@ -68,7 +68,8 @@ public class ActivateClientCommandStrategy implements CommandStrategy { // Try-catch blocks to map exceptions to appropriate status codes try { - // Calls 'activate' function from 'ClientsApiResource' to activate a client + // Calls 'activate' function from 'ClientsApiResource' to activate a + // client responseBody = clientsApiResource.activate(clientId, "activate", request.getBody()); response.setStatusCode(200); diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApplyLoanCommandStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApplyLoanCommandStrategy.java index 0304aa5d3..49142b2de 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApplyLoanCommandStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApplyLoanCommandStrategy.java @@ -32,10 +32,10 @@ import org.springframework.stereotype.Component; * Implements {@link org.apache.fineract.batch.command.CommandStrategy} and * applies a new loan on an existing client. It passes the contents of the body * from the BatchRequest to - * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and gets back - * the response. This class will also catch any errors raised by - * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and map those - * errors to appropriate status codes in BatchResponse. + * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and + * gets back the response. This class will also catch any errors raised by + * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and + * map those errors to appropriate status codes in BatchResponse. * * @author Rishabh Shukla * diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApplySavingsCommandStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApplySavingsCommandStrategy.java index e0f01075a..042a5e9a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApplySavingsCommandStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApplySavingsCommandStrategy.java @@ -32,10 +32,10 @@ import org.springframework.stereotype.Component; * Implements {@link org.apache.fineract.batch.command.CommandStrategy} and * applies a new savings on an existing client. It passes the contents of the * body from the BatchRequest to - * {@link org.apache.fineract.portfolio.savings.api.SavingsAccountsApiResource} and - * gets back the response. This class will also catch any errors raised by - * {@link org.apache.fineract.portfolio.savings.api.SavingsAccountsApiResource} and - * map those errors to appropriate status codes in BatchResponse. + * {@link org.apache.fineract.portfolio.savings.api.SavingsAccountsApiResource} + * and gets back the response. This class will also catch any errors raised by + * {@link org.apache.fineract.portfolio.savings.api.SavingsAccountsApiResource} + * and map those errors to appropriate status codes in BatchResponse. * * @author Rishabh Shukla * @@ -87,4 +87,4 @@ public class ApplySavingsCommandStrategy implements CommandStrategy { return response; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApproveLoanCommandStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApproveLoanCommandStrategy.java index ab976b1ca..fbf010ab6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApproveLoanCommandStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApproveLoanCommandStrategy.java @@ -29,13 +29,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * Implements {@link org.apache.fineract.batch.command.CommandStrategy} to handle - * approval of a pending loan. It passes the contents of the body from the - * BatchRequest to - * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and gets - * back the response. This class will also catch any errors raised by - * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and map - * those errors to appropriate status codes in BatchResponse. + * Implements {@link org.apache.fineract.batch.command.CommandStrategy} to + * handle approval of a pending loan. It passes the contents of the body from + * the BatchRequest to + * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and + * gets back the response. This class will also catch any errors raised by + * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and + * map those errors to appropriate status codes in BatchResponse. * * @author Rishabh Shukla * @@ -68,11 +68,13 @@ public class ApproveLoanCommandStrategy implements CommandStrategy { // Try-catch blocks to map exceptions to appropriate status codes try { - // Calls 'approve' function from 'LoansApiResource' to approve a loan + // Calls 'approve' function from 'LoansApiResource' to approve a + // loan responseBody = loansApiResource.stateTransitions(loanId, "approve", request.getBody()); response.setStatusCode(200); - // Sets the body of the response after the successful approval of a loan + // Sets the body of the response after the successful approval of a + // loan response.setBody(responseBody); } catch (RuntimeException e) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApproveLoanRescheduleCommandStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApproveLoanRescheduleCommandStrategy.java index 7e1a7bd78..0bfc764bf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApproveLoanRescheduleCommandStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/ApproveLoanRescheduleCommandStrategy.java @@ -52,7 +52,8 @@ public class ApproveLoanRescheduleCommandStrategy implements CommandStrategy { // Try-catch blocks to map exceptions to appropriate status codes try { - // Calls 'approve' function from 'Loans reschedule Request' to approve a + // Calls 'approve' function from 'Loans reschedule Request' to + // approve a // loan responseBody = rescheduleLoansApiResource.updateLoanRescheduleRequest(scheduleId, "approve", request.getBody()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CollectChargesCommandStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CollectChargesCommandStrategy.java index cd9b29636..3f8cdb489 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CollectChargesCommandStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CollectChargesCommandStrategy.java @@ -32,10 +32,10 @@ import org.springframework.stereotype.Component; * Implements {@link org.apache.fineract.batch.command.CommandStrategy} and * Collect Charges for a Loan. It passes the contents of the body from the * BatchRequest to - * {@link org.apache.fineract.portfolio.loanaccount.api.LoanChargesApiResource} and - * gets back the response. This class will also catch any errors raised by - * {@link org.apache.fineract.portfolio.loanaccount.api.LoanChargesApiResource} and map - * those errors to appropriate status codes in BatchResponse. + * {@link org.apache.fineract.portfolio.loanaccount.api.LoanChargesApiResource} + * and gets back the response. This class will also catch any errors raised by + * {@link org.apache.fineract.portfolio.loanaccount.api.LoanChargesApiResource} + * and map those errors to appropriate status codes in BatchResponse. * * @author Rishabh Shukla * diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CreateChargeCommandStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CreateChargeCommandStrategy.java index 6bbb0abd8..94b02dcbe 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CreateChargeCommandStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CreateChargeCommandStrategy.java @@ -29,12 +29,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * Implements {@link org.apache.fineract.batch.command.CommandStrategy} and Create - * Charge for a Loan. It passes the contents of the body from the BatchRequest - * to {@link org.apache.fineract.portfolio.loanaccount.api.LoanChargesApiResource} and - * gets back the response. This class will also catch any errors raised by - * {@link org.apache.fineract.portfolio.loanaccount.api.LoanChargesApiResource} and map - * those errors to appropriate status codes in BatchResponse. + * Implements {@link org.apache.fineract.batch.command.CommandStrategy} and + * Create Charge for a Loan. It passes the contents of the body from the + * BatchRequest to + * {@link org.apache.fineract.portfolio.loanaccount.api.LoanChargesApiResource} + * and gets back the response. This class will also catch any errors raised by + * {@link org.apache.fineract.portfolio.loanaccount.api.LoanChargesApiResource} + * and map those errors to appropriate status codes in BatchResponse. * * @author Rishabh Shukla * diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CreateClientCommandStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CreateClientCommandStrategy.java index 9bcd8829c..d599212d7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CreateClientCommandStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/CreateClientCommandStrategy.java @@ -29,8 +29,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * Implements {@link org.apache.fineract.batch.command.CommandStrategy} to handle - * creation of a new client. It passes the contents of the body from the + * Implements {@link org.apache.fineract.batch.command.CommandStrategy} to + * handle creation of a new client. It passes the contents of the body from the * BatchRequest to * {@link org.apache.fineract.portfolio.client.api.ClientsApiResource} and gets * back the response. This class will also catch any errors raised by diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/DisburseLoanCommandStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/DisburseLoanCommandStrategy.java index 93c213dda..c6027ce98 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/DisburseLoanCommandStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/DisburseLoanCommandStrategy.java @@ -29,13 +29,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * Implements {@link org.apache.fineract.batch.command.CommandStrategy} to handle - * disburse of a loan. It passes the contents of the body from the + * Implements {@link org.apache.fineract.batch.command.CommandStrategy} to + * handle disburse of a loan. It passes the contents of the body from the * BatchRequest to - * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and gets - * back the response. This class will also catch any errors raised by - * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and map - * those errors to appropriate status codes in BatchResponse. + * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and + * gets back the response. This class will also catch any errors raised by + * {@link org.apache.fineract.portfolio.loanaccount.api.LoansApiResource} and + * map those errors to appropriate status codes in BatchResponse. * * @author Rishabh Shukla * @@ -68,12 +68,14 @@ public class DisburseLoanCommandStrategy implements CommandStrategy { // Try-catch blocks to map exceptions to appropriate status codes try { - // Calls 'disburse' function from 'LoansApiResource' to disburse a loan + // Calls 'disburse' function from 'LoansApiResource' to disburse a + // loan responseBody = loansApiResource.stateTransitions(loanId, "disburse", request.getBody()); response.setStatusCode(200); - // Sets the body of the response after the successful disbursal of the loan + // Sets the body of the response after the successful disbursal of + // the loan response.setBody(responseBody); } catch (RuntimeException e) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/RepayLoanCommandStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/RepayLoanCommandStrategy.java index 6e681fad1..a3250e034 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/RepayLoanCommandStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/command/internal/RepayLoanCommandStrategy.java @@ -29,12 +29,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * Implements {@link CommandStrategy} and handles - * repayment for a Loan. It passes the contents of the body from the BatchRequest - * to {@link LoanTransactionsApiResource} and - * gets back the response. This class will also catch any errors raised by - * {@link LoanTransactionsApiResource} and map - * those errors to appropriate status codes in BatchResponse. + * Implements {@link CommandStrategy} and handles repayment for a Loan. It + * passes the contents of the body from the BatchRequest to + * {@link LoanTransactionsApiResource} and gets back the response. This class + * will also catch any errors raised by {@link LoanTransactionsApiResource} and + * map those errors to appropriate status codes in BatchResponse. * * @author Mohit Sinha * diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/exception/ClientDetailsNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/batch/exception/ClientDetailsNotFoundException.java index f1e52fe21..b0885f521 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/exception/ClientDetailsNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/exception/ClientDetailsNotFoundException.java @@ -20,7 +20,7 @@ package org.apache.fineract.batch.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; -public class ClientDetailsNotFoundException extends AbstractPlatformDomainRuleException{ +public class ClientDetailsNotFoundException extends AbstractPlatformDomainRuleException { public ClientDetailsNotFoundException() { super("validation.msg.batch.jlg.no.clients.defined", "No Client details found", ""); diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/exception/ErrorHandler.java b/fineract-provider/src/main/java/org/apache/fineract/batch/exception/ErrorHandler.java index a33114d0f..9bf21ea61 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/exception/ErrorHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/exception/ErrorHandler.java @@ -69,12 +69,11 @@ public class ErrorHandler extends RuntimeException { */ public static ErrorInfo handler(final RuntimeException exception) { - if(exception instanceof AbstractPlatformDomainRuleException) { - PlatformDomainRuleExceptionMapper mapper = new PlatformDomainRuleExceptionMapper() ; - final String errorBody = jsonHelper - .toJson(mapper.toResponse((AbstractPlatformDomainRuleException) exception).getEntity()); + if (exception instanceof AbstractPlatformDomainRuleException) { + PlatformDomainRuleExceptionMapper mapper = new PlatformDomainRuleExceptionMapper(); + final String errorBody = jsonHelper.toJson(mapper.toResponse((AbstractPlatformDomainRuleException) exception).getEntity()); return new ErrorInfo(500, 9999, errorBody); - }else if (exception instanceof AbstractPlatformResourceNotFoundException) { + } else if (exception instanceof AbstractPlatformResourceNotFoundException) { final PlatformResourceNotFoundExceptionMapper mapper = new PlatformResourceNotFoundExceptionMapper(); final String errorBody = jsonHelper @@ -118,7 +117,7 @@ public class ErrorHandler extends RuntimeException { return new ErrorInfo(403, 3003, errorBody); } else if (exception instanceof TransactionException) { - return new ErrorInfo(400, 4001, "{\"Exception\": " + exception.getMessage()+"}"); + return new ErrorInfo(400, 4001, "{\"Exception\": " + exception.getMessage() + "}"); } else if (exception instanceof PlatformInternalServerException) { @@ -126,8 +125,8 @@ public class ErrorHandler extends RuntimeException { final String errorBody = jsonHelper.toJson(mapper.toResponse((PlatformInternalServerException) exception).getEntity()); return new ErrorInfo(500, 5001, errorBody); - }else if(exception instanceof NonTransientDataAccessException) { - return new ErrorInfo(400, 4001, "{\"Exception\": " + exception.getMessage()+"}"); + } else if (exception instanceof NonTransientDataAccessException) { + return new ErrorInfo(400, 4001, "{\"Exception\": " + exception.getMessage() + "}"); } return new ErrorInfo(500, 9999, "{\"Exception\": " + exception.toString() + "}"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/serialization/BatchRequestJsonHelper.java b/fineract-provider/src/main/java/org/apache/fineract/batch/serialization/BatchRequestJsonHelper.java index 06579b617..d2067650b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/serialization/BatchRequestJsonHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/serialization/BatchRequestJsonHelper.java @@ -27,8 +27,8 @@ import org.springframework.stereotype.Component; /** * Extends - * {@link org.apache.fineract.infrastructure.core.serialization.FromJsonHelper} to - * de-serialize the incoming String into a JSON List of type + * {@link org.apache.fineract.infrastructure.core.serialization.FromJsonHelper} + * to de-serialize the incoming String into a JSON List of type * {@link org.apache.fineract.batch.domain.BatchRequest} * * @author Rishabh Shukla diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/service/BatchApiService.java b/fineract-provider/src/main/java/org/apache/fineract/batch/service/BatchApiService.java index e78b61b6f..e9d83f88f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/service/BatchApiService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/service/BatchApiService.java @@ -38,8 +38,8 @@ public interface BatchApiService { /** * Returns a list of {@link org.apache.fineract.batch.domain.BatchResponse}s * by getting the appropriate CommandStrategy for every - * {@link org.apache.fineract.batch.domain.BatchRequest}. It will be used when - * the Query Parameter "enclosingTransaction "is set to 'false'. + * {@link org.apache.fineract.batch.domain.BatchRequest}. It will be used + * when the Query Parameter "enclosingTransaction "is set to 'false'. * * @param requestList * @param uriInfo @@ -50,9 +50,9 @@ public interface BatchApiService { /** * returns a list of {@link org.apache.fineract.batch.domain.BatchResponse}s * by getting the appropriate CommandStrategy for every - * {@link org.apache.fineract.batch.domain.BatchRequest}. It will be used when - * the Query Parameter "enclosingTransaction "is set to 'true'. If one or - * more of the requests are not completed properly then whole of the + * {@link org.apache.fineract.batch.domain.BatchRequest}. It will be used + * when the Query Parameter "enclosingTransaction "is set to 'true'. If one + * or more of the requests are not completed properly then whole of the * transaction will be rolled back properly. * * @param requestList diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/service/BatchApiServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/batch/service/BatchApiServiceImpl.java index 5071dcc61..c6b0378af 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/service/BatchApiServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/service/BatchApiServiceImpl.java @@ -79,8 +79,9 @@ public class BatchApiServiceImpl implements BatchApiService { /** * Returns the response list by getting a proper - * {@link org.apache.fineract.batch.command.CommandStrategy}. execute() method - * of acquired commandStrategy is then provided with the separate Request. + * {@link org.apache.fineract.batch.command.CommandStrategy}. execute() + * method of acquired commandStrategy is then provided with the separate + * Request. * * @param requestList * @param uriInfo @@ -91,18 +92,18 @@ public class BatchApiServiceImpl implements BatchApiService { final List responseList = new ArrayList<>(requestList.size()); final List batchRequestNodes = this.resolutionHelper.getDependingRequests(requestList); - if(batchRequestNodes.isEmpty()) { - final BatchResponse response = new BatchResponse(); - ErrorInfo ex = ErrorHandler.handler(new ClientDetailsNotFoundException()); - response.setStatusCode(500); - response.setBody(ex.getMessage()); - responseList.add(response) ; - return responseList ; + if (batchRequestNodes.isEmpty()) { + final BatchResponse response = new BatchResponse(); + ErrorInfo ex = ErrorHandler.handler(new ClientDetailsNotFoundException()); + response.setStatusCode(500); + response.setBody(ex.getMessage()); + responseList.add(response); + return responseList; } for (BatchRequestNode rootNode : batchRequestNodes) { final BatchRequest rootRequest = rootNode.getRequest(); - final CommandStrategy commandStrategy = this.strategyProvider.getCommandStrategy(CommandContext - .resource(rootRequest.getRelativeUrl()).method(rootRequest.getMethod()).build()); + final CommandStrategy commandStrategy = this.strategyProvider + .getCommandStrategy(CommandContext.resource(rootRequest.getRelativeUrl()).method(rootRequest.getMethod()).build()); final BatchResponse rootResponse = commandStrategy.execute(rootRequest, uriInfo); responseList.add(rootResponse); @@ -135,8 +136,8 @@ public class BatchApiServiceImpl implements BatchApiService { if (rootResponse.getStatusCode().equals(200)) { childRequest = this.resolutionHelper.resoluteRequest(childRequest, rootResponse); - final CommandStrategy commandStrategy = this.strategyProvider.getCommandStrategy(CommandContext - .resource(childRequest.getRelativeUrl()).method(childRequest.getMethod()).build()); + final CommandStrategy commandStrategy = this.strategyProvider.getCommandStrategy( + CommandContext.resource(childRequest.getRelativeUrl()).method(childRequest.getMethod()).build()); childResponse = commandStrategy.execute(childRequest, uriInfo); @@ -148,8 +149,8 @@ public class BatchApiServiceImpl implements BatchApiService { childResponse.setStatusCode(Status.CONFLICT.getStatusCode()); // Some detail information about the error - final ErrorInfo conflictError = new ErrorInfo(Status.CONFLICT.getStatusCode(), 8001, "Parent request with id " - + rootResponse.getRequestId() + " was erroneous!"); + final ErrorInfo conflictError = new ErrorInfo(Status.CONFLICT.getStatusCode(), 8001, + "Parent request with id " + rootResponse.getRequestId() + " was erroneous!"); childResponse.setBody(conflictError.getMessage()); } childResponses.addAll(this.processChildRequests(childNode, childResponse, uriInfo)); @@ -218,21 +219,21 @@ public class BatchApiServiceImpl implements BatchApiService { errResponseList.add(errResponse); return errResponseList; - }catch (final NonTransientDataAccessException ex) { - ErrorInfo e = ErrorHandler.handler(ex); - BatchResponse errResponse = new BatchResponse(); - errResponse.setStatusCode(e.getStatusCode()); + } catch (final NonTransientDataAccessException ex) { + ErrorInfo e = ErrorHandler.handler(ex); + BatchResponse errResponse = new BatchResponse(); + errResponse.setStatusCode(e.getStatusCode()); - for (BatchResponse res : responseList) { - if (!res.getStatusCode().equals(200)) { - errResponse.setBody("Transaction is being rolled back. First erroneous request: \n" + new Gson().toJson(res)); - break; - } - } - List errResponseList = new ArrayList<>(); - errResponseList.add(errResponse); + for (BatchResponse res : responseList) { + if (!res.getStatusCode().equals(200)) { + errResponse.setBody("Transaction is being rolled back. First erroneous request: \n" + new Gson().toJson(res)); + break; + } + } + List errResponseList = new ArrayList<>(); + errResponseList.add(errResponse); - return errResponseList; + return errResponseList; } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/batch/service/ResolutionHelper.java b/fineract-provider/src/main/java/org/apache/fineract/batch/service/ResolutionHelper.java index 0ed763bf7..ec43caa15 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/batch/service/ResolutionHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/batch/service/ResolutionHelper.java @@ -159,7 +159,7 @@ public class ResolutionHelper { if (relativeUrl.contains("$.")) { String queryParams = ""; - if(relativeUrl.contains("?")) { + if (relativeUrl.contains("?")) { queryParams = relativeUrl.substring(relativeUrl.indexOf("?")); relativeUrl = relativeUrl.substring(0, relativeUrl.indexOf("?")); } @@ -170,7 +170,7 @@ public class ResolutionHelper { if (parameter.contains("$.")) { final String resParamValue = responseCtx.read(parameter).toString(); relativeUrl = relativeUrl.replace(parameter, resParamValue); - br.setRelativeUrl(relativeUrl+queryParams); + br.setRelativeUrl(relativeUrl + queryParams); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/annotation/CommandType.java b/fineract-provider/src/main/java/org/apache/fineract/commands/annotation/CommandType.java index 96a2919fb..351c07fb3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/annotation/CommandType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/annotation/CommandType.java @@ -27,7 +27,8 @@ import java.lang.annotation.Target; /** * Specifies the command type for the annotated class.
*
- * The entity name (e.g. CLIENT, SAVINGSACCOUNT, LOANPRODUCT) and the action (e.g. CREATE, DELETE) must be given. + * The entity name (e.g. CLIENT, SAVINGSACCOUNT, LOANPRODUCT) and the action + * (e.g. CREATE, DELETE) must be given. * * @author Markus Geiss * @version 1.0 diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/api/AuditsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/commands/api/AuditsApiResource.java index b1f7f4e8e..f5934b934 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/api/AuditsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/api/AuditsApiResource.java @@ -55,10 +55,13 @@ import org.springframework.stereotype.Component; @Path("/audits") @Component @Scope("singleton") -@Api(tags = {"Audits"}) +@Api(tags = { "Audits" }) @SwaggerDefinition(tags = { - @Tag(name = "Audits", description = "Every non-read Mifos API request is audited. A fully processed request can not be changed or deleted. See maker checker api for situations where an audit is not fully processed.\n" + "\n" + "Permissions: To search and look at audit entries a user needs to be attached to a role that has one of the ALL_FUNCTIONS, ALL_FUNCTIONS_READ or READ_AUDIT permissions.\n" + "\n" + "Data Scope: A user can only see audits that are within their data scope. However, 'head office' users can see all audits including those that aren't office/branch related e.g. Loan Product changes.\")") -}) + @Tag(name = "Audits", description = "Every non-read Mifos API request is audited. A fully processed request can not be changed or deleted. See maker checker api for situations where an audit is not fully processed.\n" + + "\n" + + "Permissions: To search and look at audit entries a user needs to be attached to a role that has one of the ALL_FUNCTIONS, ALL_FUNCTIONS_READ or READ_AUDIT permissions.\n" + + "\n" + + "Data Scope: A user can only see audits that are within their data scope. However, 'head office' users can see all audits including those that aren't office/branch related e.g. Loan Product changes.\")") }) public class AuditsApiResource { private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "actionName", "entityName", "resourceId", @@ -87,19 +90,33 @@ public class AuditsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Audits", notes = "Get a 200 list of audits that match the criteria supplied and sorted by audit id in descending order, and are within the requestors' data scope. Also it supports pagination and sorting\n" + "\n" + "Example Requests:\n" + "\n" + "audits\n" + "\n" + "audits?fields=madeOnDate,maker,processingResult\n" + "\n" + "audits?makerDateTimeFrom=2013-03-25 08:00:00&makerDateTimeTo=2013-04-04 18:00:00\n" + "\n" + "audits?officeId=1\n" + "\n" + "audits?officeId=1&includeJson=true") - @ApiResponses({@ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.GetMakerCheckerResponse.class, responseContainer = "list")}) - public String retrieveAuditEntries(@Context final UriInfo uriInfo, @QueryParam("actionName") @ApiParam(value = "actionName") final String actionName, - @QueryParam("entityName") @ApiParam(value = "entityName") final String entityName, @QueryParam("resourceId") @ApiParam(value = "resourceId") final Long resourceId, - @QueryParam("makerId") @ApiParam(value = "makerId") final Long makerId, @QueryParam("makerDateTimeFrom") @ApiParam(value = "makerDateTimeFrom") final String makerDateTimeFrom, - @QueryParam("makerDateTimeTo") @ApiParam(value = "makerDateTimeTo") final String makerDateTimeTo, @QueryParam("checkerId") @ApiParam(value = "checkerId") final Long checkerId, + @ApiOperation(value = "List Audits", notes = "Get a 200 list of audits that match the criteria supplied and sorted by audit id in descending order, and are within the requestors' data scope. Also it supports pagination and sorting\n" + + "\n" + "Example Requests:\n" + "\n" + "audits\n" + "\n" + "audits?fields=madeOnDate,maker,processingResult\n" + "\n" + + "audits?makerDateTimeFrom=2013-03-25 08:00:00&makerDateTimeTo=2013-04-04 18:00:00\n" + "\n" + "audits?officeId=1\n" + "\n" + + "audits?officeId=1&includeJson=true") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.GetMakerCheckerResponse.class, responseContainer = "list") }) + public String retrieveAuditEntries(@Context final UriInfo uriInfo, + @QueryParam("actionName") @ApiParam(value = "actionName") final String actionName, + @QueryParam("entityName") @ApiParam(value = "entityName") final String entityName, + @QueryParam("resourceId") @ApiParam(value = "resourceId") final Long resourceId, + @QueryParam("makerId") @ApiParam(value = "makerId") final Long makerId, + @QueryParam("makerDateTimeFrom") @ApiParam(value = "makerDateTimeFrom") final String makerDateTimeFrom, + @QueryParam("makerDateTimeTo") @ApiParam(value = "makerDateTimeTo") final String makerDateTimeTo, + @QueryParam("checkerId") @ApiParam(value = "checkerId") final Long checkerId, @QueryParam("checkerDateTimeFrom") @ApiParam(value = "checkerDateTimeFrom") final String checkerDateTimeFrom, @QueryParam("checkerDateTimeTo") @ApiParam(value = "checkerDateTimeTo") final String checkerDateTimeTo, - @QueryParam("processingResult") @ApiParam(value = "processingResult") final Integer processingResult, @QueryParam("officeId") @ApiParam(value = "officeId") final Integer officeId, - @QueryParam("groupId") @ApiParam(value = "groupId") final Integer groupId, @QueryParam("clientId") @ApiParam(value = "clientId") final Integer clientId, - @QueryParam("loanid") @ApiParam(value = "loanid") final Integer loanId, @QueryParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Integer savingsAccountId, - @QueryParam("paged") @ApiParam(value = "paged") final Boolean paged, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { + @QueryParam("processingResult") @ApiParam(value = "processingResult") final Integer processingResult, + @QueryParam("officeId") @ApiParam(value = "officeId") final Integer officeId, + @QueryParam("groupId") @ApiParam(value = "groupId") final Integer groupId, + @QueryParam("clientId") @ApiParam(value = "clientId") final Integer clientId, + @QueryParam("loanid") @ApiParam(value = "loanid") final Integer loanId, + @QueryParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Integer savingsAccountId, + @QueryParam("paged") @ApiParam(value = "paged") final Boolean paged, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final PaginationParameters parameters = PaginationParameters.instance(paged, offset, limit, orderBy, sortOrder); @@ -124,9 +141,11 @@ public class AuditsApiResource { @Path("{auditId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve an Audit Entry", notes = "Example Requests:\n" + "\n" + "audits/20\n" + "audits/20?fields=madeOnDate,maker,processingResult") - @ApiResponses({@ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.GetMakerCheckerResponse.class)}) - public String retrieveAuditEntry(@PathParam("auditId") @ApiParam(value = "auditId") final Long auditId, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve an Audit Entry", notes = "Example Requests:\n" + "\n" + "audits/20\n" + + "audits/20?fields=madeOnDate,maker,processingResult") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.GetMakerCheckerResponse.class) }) + public String retrieveAuditEntry(@PathParam("auditId") @ApiParam(value = "auditId") final Long auditId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -140,8 +159,10 @@ public class AuditsApiResource { @Path("/searchtemplate") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Audit Search Template", notes = "This is a convenience resource. It can be useful when building an Audit Search UI. \"appUsers\" are data scoped to the office/branch the requestor is associated with.\n" + "\n" + "Example Requests:\n" + "\n" + "audits/searchtemplate\n" + "audits/searchtemplate?fields=actionNames") - @ApiResponses({@ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.GetMakerCheckersSearchTemplateResponse.class)}) + @ApiOperation(value = "Audit Search Template", notes = "This is a convenience resource. It can be useful when building an Audit Search UI. \"appUsers\" are data scoped to the office/branch the requestor is associated with.\n" + + "\n" + "Example Requests:\n" + "\n" + "audits/searchtemplate\n" + "audits/searchtemplate?fields=actionNames") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.GetMakerCheckersSearchTemplateResponse.class) }) public String retrieveAuditSearchTemplate(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -150,8 +171,8 @@ public class AuditsApiResource { final AuditSearchData auditSearchData = this.auditReadPlatformService.retrieveSearchTemplate("audit"); - final Set RESPONSE_DATA_PARAMETERS_SEARCH_TEMPLATE = new HashSet<>(Arrays.asList("appUsers", "actionNames", - "entityNames", "processingResults")); + final Set RESPONSE_DATA_PARAMETERS_SEARCH_TEMPLATE = new HashSet<>( + Arrays.asList("appUsers", "actionNames", "entityNames", "processingResults")); return this.toApiJsonSerializerSearchTemplate.serialize(settings, auditSearchData, RESPONSE_DATA_PARAMETERS_SEARCH_TEMPLATE); } @@ -182,4 +203,4 @@ public class AuditsApiResource { return extraCriteria; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/api/MakercheckersApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/commands/api/MakercheckersApiResource.java old mode 100755 new mode 100644 index b96460577..14edbc945 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/api/MakercheckersApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/api/MakercheckersApiResource.java @@ -58,10 +58,8 @@ import org.springframework.stereotype.Component; @Path("/makercheckers") @Component @Scope("singleton") -@Api(tags = {"Maker Checker (or 4-eye) functionality"}) -@SwaggerDefinition(tags = { - @Tag(name = "Maker Checker (or 4-eye) functionality") -}) +@Api(tags = { "Maker Checker (or 4-eye) functionality" }) +@SwaggerDefinition(tags = { @Tag(name = "Maker Checker (or 4-eye) functionality") }) public class MakercheckersApiResource { private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "actionName", "entityName", "resourceId", @@ -78,7 +76,8 @@ public class MakercheckersApiResource { public MakercheckersApiResource(final AuditReadPlatformService readPlatformService, final DefaultToApiJsonSerializer toApiJsonSerializerAudit, final DefaultToApiJsonSerializer toApiJsonSerializerSearchTemplate, - final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService writePlatformService) { + final ApiRequestParameterHelper apiRequestParameterHelper, + final PortfolioCommandSourceWritePlatformService writePlatformService) { this.readPlatformService = readPlatformService; this.apiRequestParameterHelper = apiRequestParameterHelper; this.toApiJsonSerializerAudit = toApiJsonSerializerAudit; @@ -89,14 +88,24 @@ public class MakercheckersApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Maker Checker Entries", notes = "Get a list of entries that can be checked by the requestor that match the criteria supplied.\n" + "\n" + "Example Requests:\n" + "\n" + "makercheckers\n" + "\n" + "makercheckers?fields=madeOnDate,maker,processingResult\n" + "\n" + "makercheckers?makerDateTimeFrom=2013-03-25 08:00:00&makerDateTimeTo=2013-04-04 18:00:00\n" + "\n" + "makercheckers?officeId=1\n" + "\n" + "makercheckers?officeId=1&includeJson=true") - @ApiResponses({@ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.GetMakerCheckerResponse.class, responseContainer = "list")}) - public String retrieveCommands(@Context final UriInfo uriInfo, @QueryParam("actionName") @ApiParam(value = "actionName") final String actionName, - @QueryParam("entityName") @ApiParam(value = "entityName") final String entityName, @QueryParam("resourceId") @ApiParam(value = "resourceId") final Long resourceId, - @QueryParam("makerId") @ApiParam(value = "makerId") final Long makerId, @QueryParam("makerDateTimeFrom") @ApiParam(value = "makerDateTimeFrom") final String makerDateTimeFrom, - @QueryParam("makerDateTimeTo") @ApiParam(value = "makerDateTimeTo") final String makerDateTimeTo, @QueryParam("officeId") @ApiParam(value = "officeId") final Integer officeId, - @QueryParam("groupId") @ApiParam(value = "groupId") final Integer groupId, @QueryParam("clientId") @ApiParam(value = "clientId") final Integer clientId, - @QueryParam("loanid") @ApiParam(value = "loanid") final Integer loanId, @QueryParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Integer savingsAccountId) { + @ApiOperation(value = "List Maker Checker Entries", notes = "Get a list of entries that can be checked by the requestor that match the criteria supplied.\n" + + "\n" + "Example Requests:\n" + "\n" + "makercheckers\n" + "\n" + "makercheckers?fields=madeOnDate,maker,processingResult\n" + + "\n" + "makercheckers?makerDateTimeFrom=2013-03-25 08:00:00&makerDateTimeTo=2013-04-04 18:00:00\n" + "\n" + + "makercheckers?officeId=1\n" + "\n" + "makercheckers?officeId=1&includeJson=true") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.GetMakerCheckerResponse.class, responseContainer = "list") }) + public String retrieveCommands(@Context final UriInfo uriInfo, + @QueryParam("actionName") @ApiParam(value = "actionName") final String actionName, + @QueryParam("entityName") @ApiParam(value = "entityName") final String entityName, + @QueryParam("resourceId") @ApiParam(value = "resourceId") final Long resourceId, + @QueryParam("makerId") @ApiParam(value = "makerId") final Long makerId, + @QueryParam("makerDateTimeFrom") @ApiParam(value = "makerDateTimeFrom") final String makerDateTimeFrom, + @QueryParam("makerDateTimeTo") @ApiParam(value = "makerDateTimeTo") final String makerDateTimeTo, + @QueryParam("officeId") @ApiParam(value = "officeId") final Integer officeId, + @QueryParam("groupId") @ApiParam(value = "groupId") final Integer groupId, + @QueryParam("clientId") @ApiParam(value = "clientId") final Integer clientId, + @QueryParam("loanid") @ApiParam(value = "loanid") final Integer loanId, + @QueryParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Integer savingsAccountId) { final SQLBuilder extraCriteria = getExtraCriteria(actionName, entityName, resourceId, makerId, makerDateTimeFrom, makerDateTimeTo, officeId, groupId, clientId, loanId, savingsAccountId); @@ -113,16 +122,17 @@ public class MakercheckersApiResource { @Path("/searchtemplate") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Maker Checker Search Template", notes = "This is a convenience resource. It can be useful when building a Checker Inbox UI. \"appUsers\" are data scoped to the office/branch the requestor is associated with. \"actionNames\" and \"entityNames\" returned are those that the requestor has Checker approval permissions for.\n" + "\n" + "Example Requests:\n" + "\n" + "makercheckers/searchtemplate\n" + "makercheckers/searchtemplate?fields=entityNames") - @ApiResponses({@ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.GetMakerCheckersSearchTemplateResponse.class)}) + @ApiOperation(value = "Maker Checker Search Template", notes = "This is a convenience resource. It can be useful when building a Checker Inbox UI. \"appUsers\" are data scoped to the office/branch the requestor is associated with. \"actionNames\" and \"entityNames\" returned are those that the requestor has Checker approval permissions for.\n" + + "\n" + "Example Requests:\n" + "\n" + "makercheckers/searchtemplate\n" + "makercheckers/searchtemplate?fields=entityNames") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.GetMakerCheckersSearchTemplateResponse.class) }) public String retrieveAuditSearchTemplate(@Context final UriInfo uriInfo) { final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final AuditSearchData auditSearchData = this.readPlatformService.retrieveSearchTemplate("makerchecker"); - final Set RESPONSE_DATA_PARAMETERS_SEARCH_TEMPLATE = new HashSet<>(Arrays.asList("appUsers", "actionNames", - "entityNames")); + final Set RESPONSE_DATA_PARAMETERS_SEARCH_TEMPLATE = new HashSet<>(Arrays.asList("appUsers", "actionNames", "entityNames")); return this.toApiJsonSerializerSearchTemplate.serialize(settings, auditSearchData, RESPONSE_DATA_PARAMETERS_SEARCH_TEMPLATE); } @@ -132,8 +142,9 @@ public class MakercheckersApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Approve Maker Checker Entry | Reject Maker Checker Entry") - @ApiResponses({@ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.PostMakerCheckersResponse.class)}) - public String approveMakerCheckerEntry(@PathParam("auditId") @ApiParam(value = "auditId") final Long auditId, @QueryParam("command") @ApiParam(value = "command") final String commandParam) { + @ApiResponses({ @ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.PostMakerCheckersResponse.class) }) + public String approveMakerCheckerEntry(@PathParam("auditId") @ApiParam(value = "auditId") final Long auditId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam) { CommandProcessingResult result = null; if (is(commandParam, "approve")) { @@ -156,7 +167,7 @@ public class MakercheckersApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete Maker Checker Entry") - @ApiResponses({@ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.PostMakerCheckersResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = MakercheckersApiResourceSwagger.PostMakerCheckersResponse.class) }) public String deleteMakerCheckerEntry(@PathParam("auditId") @ApiParam(value = "auditId") final Long auditId) { final Long id = this.writePlatformService.deleteEntry(auditId); @@ -185,4 +196,4 @@ public class MakercheckersApiResource { return extraCriteria; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/api/MakercheckersApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/commands/api/MakercheckersApiResourceSwagger.java index 1f68e27ba..39b8c9d86 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/api/MakercheckersApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/api/MakercheckersApiResourceSwagger.java @@ -30,15 +30,18 @@ import org.joda.time.DateTime; * Created by sanyam on 27/7/17. */ final class MakercheckersApiResourceSwagger { + private MakercheckersApiResourceSwagger() { // only to initialize swagger documentation } @ApiModel(value = "GetMakerCheckerResponse") - public static final class GetMakerCheckerResponse{ + public static final class GetMakerCheckerResponse { + private GetMakerCheckerResponse() { } + public Long id; public String actionName; public String entityName; @@ -60,14 +63,15 @@ final class MakercheckersApiResourceSwagger { public Long loanId; public String url; - } @ApiModel(value = "GetMakerCheckersSearchTemplateResponse") - public static final class GetMakerCheckersSearchTemplateResponse{ + public static final class GetMakerCheckersSearchTemplateResponse { + private GetMakerCheckersSearchTemplateResponse() { } + public Collection appUsers; public List actionNames; public List entityNames; @@ -75,10 +79,12 @@ final class MakercheckersApiResourceSwagger { } @ApiModel(value = "PostMakerCheckersResponse") - public static final class PostMakerCheckersResponse{ + public static final class PostMakerCheckersResponse { + private PostMakerCheckersResponse() { } + @ApiModelProperty(example = "1") public Long auditId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/data/AuditData.java b/fineract-provider/src/main/java/org/apache/fineract/commands/data/AuditData.java old mode 100755 new mode 100644 index af53b55b3..5f7b44af9 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/data/AuditData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/data/AuditData.java @@ -67,8 +67,8 @@ public final class AuditData { public AuditData(final Long id, final String actionName, final String entityName, final Long resourceId, final Long subresourceId, final String maker, final DateTime madeOnDate, final String checker, final DateTime checkedOnDate, final String processingResult, final String commandAsJson, final String officeName, final String groupLevelName, - final String groupName, final String clientName, final String loanAccountNo, final String savingsAccountNo, - final Long clientId, final Long loanId, final String url) { + final String groupName, final String clientName, final String loanAccountNo, final String savingsAccountNo, final Long clientId, + final Long loanId, final String url) { this.id = id; this.actionName = actionName; @@ -103,4 +103,4 @@ public final class AuditData { public String getEntityName() { return this.entityName; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/data/AuditSearchData.java b/fineract-provider/src/main/java/org/apache/fineract/commands/data/AuditSearchData.java index c417f2871..d0ecd1a75 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/data/AuditSearchData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/data/AuditSearchData.java @@ -43,4 +43,4 @@ public final class AuditSearchData { this.entityNames = resources; this.processingResults = processingResults; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/data/ProcessingResultLookup.java b/fineract-provider/src/main/java/org/apache/fineract/commands/data/ProcessingResultLookup.java index 18dac4257..e8e8db2a2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/data/ProcessingResultLookup.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/data/ProcessingResultLookup.java @@ -39,4 +39,4 @@ public class ProcessingResultLookup { return this.processingResult; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandProcessingResultType.java b/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandProcessingResultType.java index 0e75ec863..e30d8c599 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandProcessingResultType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandProcessingResultType.java @@ -56,4 +56,4 @@ public enum CommandProcessingResultType { } return type; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandSource.java b/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandSource.java old mode 100755 new mode 100644 index 561300a36..553833479 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandSource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandSource.java @@ -94,10 +94,10 @@ public class CommandSource extends AbstractPersistableCustom { @Column(name = "transaction_id", length = 100) private String transactionId; - @Column(name="creditbureau_id") + @Column(name = "creditbureau_id") private Long creditBureauId; - @Column(name="organisation_creditbureau_id") + @Column(name = "organisation_creditbureau_id") private Long organisationCreditBureauId; public static CommandSource fullEntryFrom(final CommandWrapper wrapper, final JsonCommand command, final AppUser maker) { @@ -120,21 +120,20 @@ public class CommandSource extends AbstractPersistableCustom { this.maker = maker; this.madeOnDate = madeOnDateTime.toDate(); this.processingResult = CommandProcessingResultType.PROCESSED.getValue(); - } public Long getCreditBureauId() { - return this.creditBureauId; } + public Long getCreditBureauId() { + return this.creditBureauId; + } public void setCreditBureauId(Long creditBureauId) { this.creditBureauId = creditBureauId; } - public Long getOrganisationCreditBureauId() { return this.organisationCreditBureauId; } - public void setOrganisationCreditBureauId(Long organisationCreditBureauId) { this.organisationCreditBureauId = organisationCreditBureauId; } @@ -145,7 +144,7 @@ public class CommandSource extends AbstractPersistableCustom { this.processingResult = CommandProcessingResultType.PROCESSED.getValue(); } - public void markAsRejected(final AppUser checker, final DateTime checkedOnDate){ + public void markAsRejected(final AppUser checker, final DateTime checkedOnDate) { this.checker = checker; this.checkedOnDate = checkedOnDate.toDate(); this.processingResult = CommandProcessingResultType.REJECTED.getValue(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandSourceRepository.java b/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandSourceRepository.java index 4ecd01362..158ce0a1a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandSourceRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandSourceRepository.java @@ -23,4 +23,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface CommandSourceRepository extends JpaRepository, JpaSpecificationExecutor { // no added behaviour -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandWrapper.java old mode 100755 new mode 100644 index 128ef5bb3..7dac6ee67 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/domain/CommandWrapper.java @@ -56,9 +56,9 @@ public class CommandWrapper { public static CommandWrapper fromExistingCommand(final Long commandId, final String actionName, final String entityName, final Long resourceId, final Long subresourceId, final String resourceGetUrl, final Long productId, final Long officeId, final Long groupId, final Long clientId, final Long loanId, final Long savingsId, final String transactionId, - final Long creditBureauId,final Long organisationCreditBureauId) { + final Long creditBureauId, final Long organisationCreditBureauId) { return new CommandWrapper(commandId, actionName, entityName, resourceId, subresourceId, resourceGetUrl, productId, officeId, - groupId, clientId, loanId, savingsId, transactionId,creditBureauId,organisationCreditBureauId); + groupId, clientId, loanId, savingsId, transactionId, creditBureauId, organisationCreditBureauId); } private CommandWrapper(final Long commandId, final String actionName, final String entityName, final Long resourceId, @@ -78,14 +78,14 @@ public class CommandWrapper { this.json = null; this.transactionId = null; this.productId = productId; - this.creditBureauId=null; - this.organisationCreditBureauId=null; + this.creditBureauId = null; + this.organisationCreditBureauId = null; } public CommandWrapper(final Long officeId, final Long groupId, final Long clientId, final Long loanId, final Long savingsId, final String actionName, final String entityName, final Long entityId, final Long subentityId, final String href, - final String json, final String transactionId, final Long productId, final Long templateId, - final Long creditBureauId,final Long organisationCreditBureauId) { + final String json, final String transactionId, final Long productId, final Long templateId, final Long creditBureauId, + final Long organisationCreditBureauId) { this.commandId = null; this.officeId = officeId; @@ -103,14 +103,14 @@ public class CommandWrapper { this.transactionId = transactionId; this.productId = productId; this.templateId = templateId; - this.creditBureauId=creditBureauId; - this.organisationCreditBureauId=organisationCreditBureauId; + this.creditBureauId = creditBureauId; + this.organisationCreditBureauId = organisationCreditBureauId; } private CommandWrapper(final Long commandId, final String actionName, final String entityName, final Long resourceId, final Long subresourceId, final String resourceGetUrl, final Long productId, final Long officeId, final Long groupId, - final Long clientId, final Long loanId, final Long savingsId, final String transactionId, - final Long creditBureauId,final Long organisationCreditBureauId) { + final Long clientId, final Long loanId, final Long savingsId, final String transactionId, final Long creditBureauId, + final Long organisationCreditBureauId) { this.commandId = commandId; this.officeId = officeId; @@ -127,8 +127,8 @@ public class CommandWrapper { this.json = null; this.transactionId = transactionId; this.productId = productId; - this.creditBureauId=creditBureauId; - this.organisationCreditBureauId=organisationCreditBureauId; + this.creditBureauId = creditBureauId; + this.organisationCreditBureauId = organisationCreditBureauId; } public Long getCreditBureauId() { @@ -204,9 +204,9 @@ public class CommandWrapper { public boolean isUpdate() { // permissions resource has special update which involves no resource. - return (isPermissionResource() && isUpdateOperation()) || (isCurrencyResource() && isUpdateOperation()) || (isCacheResource() - && isUpdateOperation()) || (isWorkingDaysResource() && isUpdateOperation()) || (isPasswordPreferencesResource() - && isUpdateOperation()) || (isUpdateOperation() && (this.entityId != null)); + return (isPermissionResource() && isUpdateOperation()) || (isCurrencyResource() && isUpdateOperation()) + || (isCacheResource() && isUpdateOperation()) || (isWorkingDaysResource() && isUpdateOperation()) + || (isPasswordPreferencesResource() && isUpdateOperation()) || (isUpdateOperation() && (this.entityId != null)); } public boolean isCacheResource() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/exception/CommandNotAwaitingApprovalException.java b/fineract-provider/src/main/java/org/apache/fineract/commands/exception/CommandNotAwaitingApprovalException.java index 3fcff4d30..26a28ffdd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/exception/CommandNotAwaitingApprovalException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/exception/CommandNotAwaitingApprovalException.java @@ -28,4 +28,4 @@ public class CommandNotAwaitingApprovalException extends AbstractPlatformResourc public CommandNotAwaitingApprovalException(final Long id) { super("error.msg.command.id.not.awaiting.approval", "Audit with identifier " + id + " is Not Awaiting Approval", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/exception/CommandNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/commands/exception/CommandNotFoundException.java index edf80b2c4..09a3ed856 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/exception/CommandNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/exception/CommandNotFoundException.java @@ -28,4 +28,4 @@ public class CommandNotFoundException extends AbstractPlatformResourceNotFoundEx public CommandNotFoundException(final Long id) { super("error.msg.command.id.invalid", "Audit with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/exception/UnsupportedCommandException.java b/fineract-provider/src/main/java/org/apache/fineract/commands/exception/UnsupportedCommandException.java index 010844f69..67e8c8cbd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/exception/UnsupportedCommandException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/exception/UnsupportedCommandException.java @@ -33,4 +33,4 @@ public class UnsupportedCommandException extends RuntimeException { public String getUnsupportedCommandName() { return this.unsupportedCommandName; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/handler/NewCommandSourceHandler.java b/fineract-provider/src/main/java/org/apache/fineract/commands/handler/NewCommandSourceHandler.java index a8e914d74..d2fd82ce1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/handler/NewCommandSourceHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/handler/NewCommandSourceHandler.java @@ -24,4 +24,4 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public interface NewCommandSourceHandler { CommandProcessingResult processCommand(JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/provider/CommandHandlerProvider.java b/fineract-provider/src/main/java/org/apache/fineract/commands/provider/CommandHandlerProvider.java index 58d452ebf..05740cf4a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/provider/CommandHandlerProvider.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/provider/CommandHandlerProvider.java @@ -34,11 +34,12 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; /** - * {@link CommandHandlerProvider} provides {@link NewCommandSourceHandler}s for a given entity and action. + * {@link CommandHandlerProvider} provides {@link NewCommandSourceHandler}s for + * a given entity and action.
*
- *
- * A {@link NewCommandSourceHandler} can be registered and the annotation {@link CommandType} is used to determine - * the entity and the action the handler is capable to process. + * A {@link NewCommandSourceHandler} can be registered and the annotation + * {@link CommandType} is used to determine the entity and the action the + * handler is capable to process. * * @author Markus Geiss * @version 1.0 @@ -62,20 +63,21 @@ public class CommandHandlerProvider implements ApplicationContextAware { /** * Returns a handler for the given entity and action.
*
- * Throws an {@link UnsupportedCommandException} if no handler - * for the given entity, action combination can be found. - * @param entity the entity to lookup the handler, must be given. - * @param action the action to lookup the handler, must be given. + * Throws an {@link UnsupportedCommandException} if no handler for the given + * entity, action combination can be found. + * + * @param entity + * the entity to lookup the handler, must be given. + * @param action + * the action to lookup the handler, must be given. */ - public NewCommandSourceHandler getHandler (final String entity, final String action) { + public NewCommandSourceHandler getHandler(final String entity, final String action) { Preconditions.checkArgument(StringUtils.isNoneEmpty(entity), "An entity must be given!"); Preconditions.checkArgument(StringUtils.isNoneEmpty(action), "An action must be given!"); - final String key = entity + "|" + action; - if (!this.registeredHandlers.containsKey(key)) { - throw new UnsupportedCommandException(key); - } - return (NewCommandSourceHandler)this.applicationContext.getBean(this.registeredHandlers.get(key)); + final String key = entity + "|" + action; + if (!this.registeredHandlers.containsKey(key)) { throw new UnsupportedCommandException(key); } + return (NewCommandSourceHandler) this.applicationContext.getBean(this.registeredHandlers.get(key)); } private void initializeHandlerRegistry() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/service/AuditReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/commands/service/AuditReadPlatformService.java index c3d71c5a6..f7c90e4c4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/service/AuditReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/service/AuditReadPlatformService.java @@ -36,4 +36,4 @@ public interface AuditReadPlatformService { AuditData retrieveAuditEntry(Long auditId); AuditSearchData retrieveSearchTemplate(String useType); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/service/AuditReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/commands/service/AuditReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 2f2c7b7da..235b9e386 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/service/AuditReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/service/AuditReadPlatformServiceImpl.java @@ -100,8 +100,7 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { final LoanProductReadPlatformService loanProductReadPlatformService, final StaffReadPlatformService staffReadPlatformService, final PaginationParametersDataValidator paginationParametersDataValidator, final SavingsProductReadPlatformService savingsProductReadPlatformService, - final DepositProductReadPlatformService depositProductReadPlatformService, - final ColumnValidator columnValidator) { + final DepositProductReadPlatformService depositProductReadPlatformService, final ColumnValidator columnValidator) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); this.fromApiJsonHelper = fromApiJsonHelper; @@ -186,7 +185,8 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { @Override public Collection retrieveAuditEntries(final SQLBuilder extraCriteria, final boolean includeJson) { - return retrieveEntries("audit", extraCriteria, " order by aud.id DESC limit " + PaginationParameters.getCheckedLimit(null), includeJson); + return retrieveEntries("audit", extraCriteria, " order by aud.id DESC limit " + PaginationParameters.getCheckedLimit(null), + includeJson); } @Override @@ -226,10 +226,13 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { return retrieveEntries("makerchecker", extraCriteria, " group by aud.id order by aud.id", includeJson); } - private Collection retrieveEntries(final String useType, final SQLBuilder extraCriteria, final String groupAndOrderBySQL, final boolean includeJson) { + private Collection retrieveEntries(final String useType, final SQLBuilder extraCriteria, final String groupAndOrderBySQL, + final boolean includeJson) { - if ((!useType.equals("audit") && !useType.equals("makerchecker"))) { throw new PlatformDataIntegrityException( - "error.msg.invalid.auditSearchTemplate.useType", "Invalid Audit Search Template UseType: " + useType); } + if ((!useType.equals("audit") && !useType.equals("makerchecker"))) { + throw new PlatformDataIntegrityException("error.msg.invalid.auditSearchTemplate.useType", + "Invalid Audit Search Template UseType: " + useType); + } final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); @@ -427,8 +430,10 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { @Override public AuditSearchData retrieveSearchTemplate(final String useType) { - if (!(useType.equals("audit") || useType.equals("makerchecker"))) { throw new PlatformDataIntegrityException( - "error.msg.invalid.auditSearchTemplate.useType", "Invalid Audit Search Template UseType: " + useType); } + if (!(useType.equals("audit") || useType.equals("makerchecker"))) { + throw new PlatformDataIntegrityException("error.msg.invalid.auditSearchTemplate.useType", + "Invalid Audit Search Template UseType: " + useType); + } final AppUser currentUser = this.context.authenticatedUser(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/service/CommandProcessingService.java b/fineract-provider/src/main/java/org/apache/fineract/commands/service/CommandProcessingService.java index e510cbc87..19033a13d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/service/CommandProcessingService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/service/CommandProcessingService.java @@ -30,6 +30,6 @@ public interface CommandProcessingService { CommandProcessingResult logCommand(CommandSource commandSourceResult); - boolean validateCommand(final CommandWrapper commandWrapper,final AppUser user); + boolean validateCommand(final CommandWrapper commandWrapper, final AppUser user); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/service/CommandWrapperBuilder.java b/fineract-provider/src/main/java/org/apache/fineract/commands/service/CommandWrapperBuilder.java old mode 100755 new mode 100644 index 60fa5f65e..6226c265e --- a/fineract-provider/src/main/java/org/apache/fineract/commands/service/CommandWrapperBuilder.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/service/CommandWrapperBuilder.java @@ -45,11 +45,10 @@ public class CommandWrapperBuilder { private Long creditBureauId; private Long organisationCreditBureauId; - public CommandWrapper build() { - return new CommandWrapper(this.officeId, this.groupId, this.clientId, this.loanId, this.savingsId, this.actionName, - this.entityName, this.entityId, this.subentityId, this.href, this.json, this.transactionId, this.productId, - this.templateId,this.creditBureauId,this.organisationCreditBureauId); + return new CommandWrapper(this.officeId, this.groupId, this.clientId, this.loanId, this.savingsId, this.actionName, this.entityName, + this.entityId, this.subentityId, this.href, this.json, this.transactionId, this.productId, this.templateId, + this.creditBureauId, this.organisationCreditBureauId); } public CommandWrapperBuilder updateCreditBureau() { @@ -73,7 +72,7 @@ public class CommandWrapperBuilder { this.entityName = "ORGANISATIONCREDITBUREAU"; this.entityId = organisationCreditBureauId; this.href = "/creditBureauConfiguration/organizationCreditBureau/template"; - this.organisationCreditBureauId=organisationCreditBureauId; + this.organisationCreditBureauId = organisationCreditBureauId; return this; } @@ -82,49 +81,48 @@ public class CommandWrapperBuilder { this.entityName = "CREDITBUREAU_LOANPRODUCT_MAPPING"; this.entityId = creditBureauId; this.href = "/creditBureauConfiguration/template"; - this.creditBureauId=creditBureauId; + this.creditBureauId = creditBureauId; return this; } - public CommandWrapperBuilder addClientAddress(final long clientId,final long addressTypeId) { + public CommandWrapperBuilder addClientAddress(final long clientId, final long addressTypeId) { this.actionName = "CREATE"; this.entityName = "ADDRESS"; this.entityId = addressTypeId; - this.href = "/clients/"+clientId+"/addresses"; - this.clientId=clientId; + this.href = "/clients/" + clientId + "/addresses"; + this.clientId = clientId; return this; } public CommandWrapperBuilder updateClientAddress(final long clientId) { this.actionName = "UPDATE"; this.entityName = "ADDRESS"; - this.href = "/clients/"+clientId+"/addresses"; - this.clientId=clientId; + this.href = "/clients/" + clientId + "/addresses"; + this.clientId = clientId; return this; } - public CommandWrapperBuilder addFamilyMembers(final long clientId) { this.actionName = "CREATE"; this.entityName = "FAMILYMEMBERS"; - this.href = "/clients/"+clientId+"/familymembers"; - this.clientId=clientId; + this.href = "/clients/" + clientId + "/familymembers"; + this.clientId = clientId; return this; } public CommandWrapperBuilder updateFamilyMembers(final long familyMemberId) { this.actionName = "UPDATE"; this.entityName = "FAMILYMEMBERS"; - this.href = "/clients/"+clientId+"/familymembers"; - this.entityId=familyMemberId; + this.href = "/clients/" + clientId + "/familymembers"; + this.entityId = familyMemberId; return this; } public CommandWrapperBuilder deleteFamilyMembers(final long familyMemberId) { this.actionName = "DELETE"; this.entityName = "FAMILYMEMBERS"; - this.href = "/clients/"+clientId+"/familymembers"; - this.entityId=familyMemberId; + this.href = "/clients/" + clientId + "/familymembers"; + this.entityId = familyMemberId; return this; } @@ -644,6 +642,7 @@ public class CommandWrapperBuilder { this.json = json; return this; } + public CommandWrapperBuilder undoRejection(final Long clientId) { this.actionName = "UNDOREJECT"; this.entityName = "CLIENT"; @@ -652,6 +651,7 @@ public class CommandWrapperBuilder { this.href = "/clients/" + clientId + "?command=undoRejection"; return this; } + public CommandWrapperBuilder undoWithdrawal(final Long clientId) { this.actionName = "UNDOWITHDRAWAL"; this.entityName = "CLIENT"; @@ -936,6 +936,7 @@ public class CommandWrapperBuilder { this.href = "/loans/" + glimId; return this; } + public CommandWrapperBuilder undoGLIMLoanDisbursal(final Long glimId) { this.actionName = "UNDODISBURSAL"; this.entityName = "GLIMLOAN"; @@ -2066,7 +2067,8 @@ public class CommandWrapperBuilder { return this; } - public CommandWrapperBuilder saveOrUpdateAttendance(final Long entityId, final String supportedEntityType, final Long supportedEntityId) { + public CommandWrapperBuilder saveOrUpdateAttendance(final Long entityId, final String supportedEntityType, + final Long supportedEntityId) { this.actionName = "SAVEORUPDATEATTENDANCE"; this.entityName = "MEETING"; this.entityId = entityId; @@ -2894,10 +2896,10 @@ public class CommandWrapperBuilder { } public CommandWrapperBuilder createAccountCommand(String accountType, final Long accountId, String command) { - this.entityName = accountType.toUpperCase()+"ACCOUNT" ; + this.entityName = accountType.toUpperCase() + "ACCOUNT"; this.actionName = command.toUpperCase(); this.entityId = accountId; - this.href = "/accounts/" + accountType+"/"+accountId+"?command="+command; + this.href = "/accounts/" + accountType + "/" + accountId + "?command=" + command; return this; } @@ -2971,7 +2973,7 @@ public class CommandWrapperBuilder { this.actionName = "UPDATE"; this.entityName = "SSBENEFICIARYTPT"; this.entityId = beneficiaryId; - this.href = "/self/beneficiaries/tpt/"+beneficiaryId; + this.href = "/self/beneficiaries/tpt/" + beneficiaryId; return this; } @@ -2979,7 +2981,7 @@ public class CommandWrapperBuilder { this.actionName = "DELETE"; this.entityName = "SSBENEFICIARYTPT"; this.entityId = beneficiaryId; - this.href = "/self/beneficiaries/tpt/"+beneficiaryId; + this.href = "/self/beneficiaries/tpt/" + beneficiaryId; return this; } @@ -3019,7 +3021,7 @@ public class CommandWrapperBuilder { this.actionName = "UPDATE"; this.entityName = "SMSCAMPAIGN"; this.entityId = resourceId; - this.href = "/smscampaigns/"+resourceId; + this.href = "/smscampaigns/" + resourceId; return this; } @@ -3027,7 +3029,7 @@ public class CommandWrapperBuilder { this.actionName = "ACTIVATE"; this.entityName = "SMSCAMPAIGN"; this.entityId = resourceId; - this.href = "/smscampaigns/"+resourceId + "?command=activate"; + this.href = "/smscampaigns/" + resourceId + "?command=activate"; return this; } @@ -3035,14 +3037,15 @@ public class CommandWrapperBuilder { this.actionName = "CLOSE"; this.entityName = "SMSCAMPAIGN"; this.entityId = resourceId; - this.href = "/smscampaigns/"+resourceId + "?command=close"; + this.href = "/smscampaigns/" + resourceId + "?command=close"; return this; } + public CommandWrapperBuilder reactivateSmsCampaign(final Long resourceId) { this.actionName = "REACTIVATE"; this.entityName = "SMSCAMPAIGN"; this.entityId = resourceId; - this.href = "/smscampaigns/"+resourceId + "?command=reactivate"; + this.href = "/smscampaigns/" + resourceId + "?command=reactivate"; return this; } @@ -3050,7 +3053,7 @@ public class CommandWrapperBuilder { this.actionName = "DELETE"; this.entityName = "SMSCAMPAIGN"; this.entityId = resourceId; - this.href = "/smscampaigns/"+resourceId; + this.href = "/smscampaigns/" + resourceId; return this; } @@ -3126,6 +3129,7 @@ public class CommandWrapperBuilder { this.href = "/savingsaccounts/" + accountId + "?command=unblock"; return this; } + public CommandWrapperBuilder disableAdHoc(Long adHocId) { this.actionName = "DISABLE"; this.entityName = "ADHOC"; @@ -3143,12 +3147,14 @@ public class CommandWrapperBuilder { this.json = "{}"; return this; } + public CommandWrapperBuilder createAdHoc() { this.actionName = "CREATE"; this.entityName = "ADHOC"; this.href = "/adhocquery/template"; return this; } + public CommandWrapperBuilder updateAdHoc(final Long adHocId) { this.actionName = "UPDATE"; this.entityName = "ADHOC"; @@ -3163,8 +3169,9 @@ public class CommandWrapperBuilder { this.entityId = adHocId; this.href = "/adhocquery/" + adHocId; this.json = "{}"; - return this ; + return this; } + public CommandWrapperBuilder createEmail() { this.actionName = "CREATE"; this.entityName = "EMAIL"; @@ -3177,7 +3184,7 @@ public class CommandWrapperBuilder { this.actionName = "UPDATE"; this.entityName = "EMAIL"; this.entityId = resourceId; - this.href = "/emailcampaigns/"+resourceId; + this.href = "/emailcampaigns/" + resourceId; return this; } @@ -3185,7 +3192,7 @@ public class CommandWrapperBuilder { this.actionName = "DELETE"; this.entityName = "EMAIL"; this.entityId = resourceId; - this.href = "/emailcampaigns/"+resourceId; + this.href = "/emailcampaigns/" + resourceId; return this; } @@ -3201,7 +3208,7 @@ public class CommandWrapperBuilder { this.actionName = "UPDATE"; this.entityName = "EMAIL_CAMPAIGN"; this.entityId = resourceId; - this.href = "/emailcampaigns/"+resourceId; + this.href = "/emailcampaigns/" + resourceId; return this; } @@ -3209,7 +3216,7 @@ public class CommandWrapperBuilder { this.actionName = "DELETE"; this.entityName = "EMAIL_CAMPAIGN"; this.entityId = resourceId; - this.href = "/emailcampaigns/"+resourceId; + this.href = "/emailcampaigns/" + resourceId; return this; } @@ -3217,7 +3224,7 @@ public class CommandWrapperBuilder { this.actionName = "ACTIVATE"; this.entityName = "EMAIL_CAMPAIGN"; this.entityId = resourceId; - this.href = "/emailcampaigns/"+resourceId + "?command=activate"; + this.href = "/emailcampaigns/" + resourceId + "?command=activate"; return this; } @@ -3225,14 +3232,15 @@ public class CommandWrapperBuilder { this.actionName = "CLOSE"; this.entityName = "EMAIL_CAMPAIGN"; this.entityId = resourceId; - this.href = "/emailcampaigns/"+resourceId + "?command=close"; + this.href = "/emailcampaigns/" + resourceId + "?command=close"; return this; } + public CommandWrapperBuilder reactivateEmailCampaign(final Long resourceId) { this.actionName = "REACTIVATE"; this.entityName = "EMAIL_CAMPAIGN"; this.entityId = resourceId; - this.href = "/emailcampaigns/"+resourceId + "?command=reactivate"; + this.href = "/emailcampaigns/" + resourceId + "?command=reactivate"; return this; } @@ -3260,14 +3268,14 @@ public class CommandWrapperBuilder { public CommandWrapperBuilder linkAccountsToPocket() { this.actionName = PocketApiConstants.linkAccountsActionName; this.entityName = PocketApiConstants.pocketEntityName; - this.href = "/self/pocket?command="+PocketApiConstants.linkAccountsToPocketCommandParam; + this.href = "/self/pocket?command=" + PocketApiConstants.linkAccountsToPocketCommandParam; return this; } public CommandWrapperBuilder delinkAccountsFromPocket() { this.actionName = PocketApiConstants.delinkAccountsActionName; this.entityName = PocketApiConstants.pocketEntityName; - this.href = "/self/pocket?command="+PocketApiConstants.delinkAccountsFromPocketCommandParam; + this.href = "/self/pocket?command=" + PocketApiConstants.delinkAccountsFromPocketCommandParam; return this; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/service/PortfolioCommandSourceWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/commands/service/PortfolioCommandSourceWritePlatformService.java old mode 100755 new mode 100644 index 8fa858710..7a897c547 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/service/PortfolioCommandSourceWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/service/PortfolioCommandSourceWritePlatformService.java @@ -30,4 +30,4 @@ public interface PortfolioCommandSourceWritePlatformService { Long rejectEntry(Long id); Long deleteEntry(Long makerCheckerId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java old mode 100755 new mode 100644 index 5e74845e9..7b35dc3c3 --- a/fineract-provider/src/main/java/org/apache/fineract/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java @@ -90,7 +90,8 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio final JsonElement parsedCommand = this.fromApiJsonHelper.parse(json); command = JsonCommand.from(json, parsedCommand, this.fromApiJsonHelper, wrapper.getEntityName(), wrapper.getEntityId(), wrapper.getSubentityId(), wrapper.getGroupId(), wrapper.getClientId(), wrapper.getLoanId(), wrapper.getSavingsId(), - wrapper.getTransactionId(), wrapper.getHref(), wrapper.getProductId(),wrapper.getCreditBureauId(),wrapper.getOrganisationCreditBureauId()); + wrapper.getTransactionId(), wrapper.getHref(), wrapper.getProductId(), wrapper.getCreditBureauId(), + wrapper.getOrganisationCreditBureauId()); while (numberOfRetries <= maxNumberOfRetries) { try { result = this.processAndLogCommandService.processAndLogCommand(wrapper, command, isApprovedByChecker); @@ -103,7 +104,7 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio **/ if (numberOfRetries >= maxNumberOfRetries) { LOG.warn("The following command {} has been retried for the max allowed attempts of {} and will be rolled back", - command.json(), numberOfRetries); + command.json(), numberOfRetries); throw (exception); } /*** @@ -137,13 +138,14 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio commandSourceInput.getEntityName(), commandSourceInput.resourceId(), commandSourceInput.subresourceId(), commandSourceInput.getResourceGetUrl(), commandSourceInput.getProductId(), commandSourceInput.getOfficeId(), commandSourceInput.getGroupId(), commandSourceInput.getClientId(), commandSourceInput.getLoanId(), - commandSourceInput.getSavingsId(), commandSourceInput.getTransactionId(),commandSourceInput.getCreditBureauId(),commandSourceInput.getOrganisationCreditBureauId()); + commandSourceInput.getSavingsId(), commandSourceInput.getTransactionId(), commandSourceInput.getCreditBureauId(), + commandSourceInput.getOrganisationCreditBureauId()); final JsonElement parsedCommand = this.fromApiJsonHelper.parse(commandSourceInput.json()); final JsonCommand command = JsonCommand.fromExistingCommand(makerCheckerId, commandSourceInput.json(), parsedCommand, this.fromApiJsonHelper, commandSourceInput.getEntityName(), commandSourceInput.resourceId(), commandSourceInput.subresourceId(), commandSourceInput.getGroupId(), commandSourceInput.getClientId(), commandSourceInput.getLoanId(), commandSourceInput.getSavingsId(), commandSourceInput.getTransactionId(), - commandSourceInput.getResourceGetUrl(), commandSourceInput.getProductId(),commandSourceInput.getCreditBureauId(), + commandSourceInput.getResourceGetUrl(), commandSourceInput.getProductId(), commandSourceInput.getCreditBureauId(), commandSourceInput.getOrganisationCreditBureauId()); final boolean makerCheckerApproval = true; diff --git a/fineract-provider/src/main/java/org/apache/fineract/commands/service/SynchronousCommandProcessingService.java b/fineract-provider/src/main/java/org/apache/fineract/commands/service/SynchronousCommandProcessingService.java old mode 100755 new mode 100644 index 3be69b3c7..f0334107a --- a/fineract-provider/src/main/java/org/apache/fineract/commands/service/SynchronousCommandProcessingService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/commands/service/SynchronousCommandProcessingService.java @@ -75,7 +75,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer public CommandProcessingResult processAndLogCommand(final CommandWrapper wrapper, final JsonCommand command, final boolean isApprovedByChecker) { - final boolean rollbackTransaction = this.configurationDomainService.isMakerCheckerEnabledForTask(wrapper.taskPermissionName()); + final boolean rollbackTransaction = this.configurationDomainService.isMakerCheckerEnabledForTask(wrapper.taskPermissionName()); final NewCommandSourceHandler handler = findCommandHandler(wrapper); @@ -95,7 +95,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer result.getSavingsId(), result.getProductId(), result.getTransactionId()); String changesOnlyJson = null; - boolean rollBack = (rollbackTransaction || result.isRollbackTransaction()) && !isApprovedByChecker ; + boolean rollBack = (rollbackTransaction || result.isRollbackTransaction()) && !isApprovedByChecker; if (result.hasChanges() && !rollBack) { changesOnlyJson = this.toApiJsonSerializer.serializeResult(result.getChanges()); commandSourceResult.updateJsonTo(changesOnlyJson); @@ -211,8 +211,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer final String authToken = ThreadLocalContextUtil.getAuthToken(); final String tenantIdentifier = ThreadLocalContextUtil.getTenant().getTenantIdentifier(); - final AppUser appUser = this.context.authenticatedUser(CommandWrapper.wrap(actionName, - entityName, null, null)); + final AppUser appUser = this.context.authenticatedUser(CommandWrapper.wrap(actionName, entityName, null, null)); final HookEventSource hookEventSource = new HookEventSource(entityName, actionName); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/api/AccountNumberFormatsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/api/AccountNumberFormatsApiResource.java index 3d2c2d34e..b8cda753e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/api/AccountNumberFormatsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/api/AccountNumberFormatsApiResource.java @@ -61,10 +61,9 @@ import org.springframework.stereotype.Component; @Path(AccountNumberFormatConstants.resourceRelativeURL) @Component @Scope("singleton") -@Api(tags = {"Account number format"}) +@Api(tags = { "Account number format" }) @SwaggerDefinition(tags = { - @Tag(name = "Account number format", description = "Account number preferences are used to describe custom formats for account numbers associated with Customer, Loan and Savings accounts." ) -}) + @Tag(name = "Account number format", description = "Account number preferences are used to describe custom formats for account numbers associated with Customer, Loan and Savings accounts.") }) public class AccountNumberFormatsApiResource { private final PlatformSecurityContext context; @@ -72,10 +71,10 @@ public class AccountNumberFormatsApiResource { private final ToApiJsonSerializer toApiJsonSerializer; private final ApiRequestParameterHelper apiRequestParameterHelper; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - private static final Set ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - AccountNumberFormatConstants.idParamName, AccountNumberFormatConstants.accountTypeParamName, - AccountNumberFormatConstants.prefixTypeParamName, AccountNumberFormatConstants.accountTypeOptionsParamName, - AccountNumberFormatConstants.prefixTypeOptionsParamName)); + private static final Set ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(AccountNumberFormatConstants.idParamName, AccountNumberFormatConstants.accountTypeParamName, + AccountNumberFormatConstants.prefixTypeParamName, AccountNumberFormatConstants.accountTypeOptionsParamName, + AccountNumberFormatConstants.prefixTypeOptionsParamName)); @Autowired public AccountNumberFormatsApiResource(final PlatformSecurityContext context, @@ -94,8 +93,10 @@ public class AccountNumberFormatsApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Account number format Template", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "\n" + "Example Request:\n" + "\n" + "accountnumberformats/template") - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.GetAccountNumberFormatsResponseTemplate.class)}) + @ApiOperation(value = "Retrieve Account number format Template", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "\n" + "Example Request:\n" + "\n" + "accountnumberformats/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.GetAccountNumberFormatsResponseTemplate.class) }) public String retrieveTemplate(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(AccountNumberFormatConstants.ENTITY_NAME); @@ -104,15 +105,16 @@ public class AccountNumberFormatsApiResource { AccountNumberFormatData accountNumberFormatData = this.accountNumberFormatReadPlatformService.retrieveTemplate(accountType); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData, - ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData, ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS); } @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Account number formats", notes = "Example Requests:\n" + "\n" + "accountnumberformats\n" + "\n" + "\n" + "accountnumberformats?fields=accountType,prefixType", responseContainer = "List") - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.GetAccountNumberFormatsIdResponse.class, responseContainer = "List")}) + @ApiOperation(value = "List Account number formats", notes = "Example Requests:\n" + "\n" + "accountnumberformats\n" + "\n" + "\n" + + "accountnumberformats?fields=accountType,prefixType", responseContainer = "List") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.GetAccountNumberFormatsIdResponse.class, responseContainer = "List") }) public String retrieveAll(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(AccountNumberFormatConstants.ENTITY_NAME); @@ -121,17 +123,19 @@ public class AccountNumberFormatsApiResource { .getAllAccountNumberFormats(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData, - ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData, ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS); } @GET @Path("{accountNumberFormatId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve an Account number format", notes = "Example Requests:\n" + "\n" + "accountnumberformats/1\n" + "\n" + "\n" + "accountnumberformats/1?template=true\n" + "\n" + "\n" + "accountnumberformats/1?fields=accountType,prefixType") - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.GetAccountNumberFormatsIdResponse.class)}) - public String retrieveOne(@Context final UriInfo uriInfo, @PathParam("accountNumberFormatId") @ApiParam(value = "accountNumberFormatId") final Long accountNumberFormatId) { + @ApiOperation(value = "Retrieve an Account number format", notes = "Example Requests:\n" + "\n" + "accountnumberformats/1\n" + "\n" + + "\n" + "accountnumberformats/1?template=true\n" + "\n" + "\n" + "accountnumberformats/1?fields=accountType,prefixType") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.GetAccountNumberFormatsIdResponse.class) }) + public String retrieveOne(@Context final UriInfo uriInfo, + @PathParam("accountNumberFormatId") @ApiParam(value = "accountNumberFormatId") final Long accountNumberFormatId) { this.context.authenticatedUser().validateHasReadPermission(AccountNumberFormatConstants.ENTITY_NAME); @@ -140,21 +144,23 @@ public class AccountNumberFormatsApiResource { AccountNumberFormatData accountNumberFormatData = this.accountNumberFormatReadPlatformService .getAccountNumberFormat(accountNumberFormatId); if (settings.isTemplate()) { - final AccountNumberFormatData templateData = this.accountNumberFormatReadPlatformService.retrieveTemplate(EntityAccountType - .fromInt(accountNumberFormatData.getAccountType().getId().intValue())); + final AccountNumberFormatData templateData = this.accountNumberFormatReadPlatformService + .retrieveTemplate(EntityAccountType.fromInt(accountNumberFormatData.getAccountType().getId().intValue())); accountNumberFormatData.templateOnTop(templateData.getAccountTypeOptions(), templateData.getPrefixTypeOptions()); } - return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData, - ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData, ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS); } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create an Account number format", notes = "Note: You may associate a single Account number format for a given account type\n" + "Mandatory Fields for Account number formats\n" + "accountType") - @ApiImplicitParams({@ApiImplicitParam(value = "body", paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountNumberFormatsApiResourceSwagger.PostAccountNumberFormatsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.PostAccountNumberFormatsResponse.class)}) + @ApiOperation(value = "Create an Account number format", notes = "Note: You may associate a single Account number format for a given account type\n" + + "Mandatory Fields for Account number formats\n" + "accountType") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountNumberFormatsApiResourceSwagger.PostAccountNumberFormatsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.PostAccountNumberFormatsResponse.class) }) public String create(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -172,9 +178,12 @@ public class AccountNumberFormatsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update an Account number format") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true,paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountNumberFormatsApiResourceSwagger.PutAccountNumberFormatsRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.PutAccountNumberFormatsResponse.class)}) - public String update(@PathParam("accountNumberFormatId") @ApiParam(value = "accountNumberFormatId") final Long accountNumberFormatId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountNumberFormatsApiResourceSwagger.PutAccountNumberFormatsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.PutAccountNumberFormatsResponse.class) }) + public String update(@PathParam("accountNumberFormatId") @ApiParam(value = "accountNumberFormatId") final Long accountNumberFormatId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .updateAccountNumberFormat(accountNumberFormatId) // @@ -191,7 +200,8 @@ public class AccountNumberFormatsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete an Account number format", notes = "Note: Account numbers created while this format was active would remain unchanged.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.DeleteAccountNumberFormatsResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = AccountNumberFormatsApiResourceSwagger.DeleteAccountNumberFormatsResponse.class) }) public String delete(@PathParam("accountNumberFormatId") @ApiParam(value = "accountNumberFormatId") final Long accountNumberFormatId) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/api/AccountNumberFormatsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/api/AccountNumberFormatsApiResourceSwagger.java index 628f46265..2de81f9cf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/api/AccountNumberFormatsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/api/AccountNumberFormatsApiResourceSwagger.java @@ -28,24 +28,28 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; * Created by sanyam on 28/7/17. */ final class AccountNumberFormatsApiResourceSwagger { + private AccountNumberFormatsApiResourceSwagger() { // this class is only for Swagger implementation for Live Documentation } @ApiModel(value = "GetAccountNumberFormatsResponse") public static final class GetAccountNumberFormatsResponse { + private GetAccountNumberFormatsResponse() { } -// public List _; + // public List _; } @ApiModel(value = "GetAccountNumberFormatsIdResponse") public static final class GetAccountNumberFormatsIdResponse { + private GetAccountNumberFormatsIdResponse() { } + @ApiModelProperty(example = "2") public Long id; public EnumOptionData accountType; @@ -56,9 +60,11 @@ final class AccountNumberFormatsApiResourceSwagger { @ApiModel(value = "GetAccountNumberFormatsResponseTemplate") public static final class GetAccountNumberFormatsResponseTemplate { + private GetAccountNumberFormatsResponseTemplate() { } + public List accountTypeOptions; public Map> prefixTypeOptions; @@ -66,9 +72,11 @@ final class AccountNumberFormatsApiResourceSwagger { @ApiModel(value = "PostAccountNumberFormatsRequest") public static final class PostAccountNumberFormatsRequest { + private PostAccountNumberFormatsRequest() { } + @ApiModelProperty(example = "1") public Long accountType; @ApiModelProperty(example = "101") @@ -78,9 +86,11 @@ final class AccountNumberFormatsApiResourceSwagger { @ApiModel(value = "PostAccountNumberFormatsResponse") public static final class PostAccountNumberFormatsResponse { + private PostAccountNumberFormatsResponse() { } + @ApiModelProperty(example = "4") public Long resourceId; @@ -88,9 +98,11 @@ final class AccountNumberFormatsApiResourceSwagger { @ApiModel(value = "PutAccountNumberFormatsRequest") public static final class PutAccountNumberFormatsRequest { + private PutAccountNumberFormatsRequest() { } + @ApiModelProperty(example = "1") public Long prefixType; @@ -98,13 +110,17 @@ final class AccountNumberFormatsApiResourceSwagger { @ApiModel(value = "PutAccountNumberFormatsResponse") public static final class PutAccountNumberFormatsResponse { + private PutAccountNumberFormatsResponse() { } + public static final class PutAccountNumberFormatschangesSwagger { + private PutAccountNumberFormatschangesSwagger() { } + @ApiModelProperty(example = "OFFICE_NAME") public Long prefixType; } @@ -117,9 +133,11 @@ final class AccountNumberFormatsApiResourceSwagger { @ApiModel(value = "DeleteAccountNumberFormatsResponse") public static final class DeleteAccountNumberFormatsResponse { + private DeleteAccountNumberFormatsResponse() { } + @ApiModelProperty(example = "2") public Long resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/data/AccountNumberFormatDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/data/AccountNumberFormatDataValidator.java index 601b7564c..bd624ba95 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/data/AccountNumberFormatDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/data/AccountNumberFormatDataValidator.java @@ -44,8 +44,8 @@ import org.springframework.stereotype.Component; public class AccountNumberFormatDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set ACCOUNT_NUMBER_FORMAT_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - AccountNumberFormatConstants.accountTypeParamName, AccountNumberFormatConstants.prefixTypeParamName)); + private static final Set ACCOUNT_NUMBER_FORMAT_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(AccountNumberFormatConstants.accountTypeParamName, AccountNumberFormatConstants.prefixTypeParamName)); private static final Set ACCOUNT_NUMBER_FORMAT_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(AccountNumberFormatConstants.prefixTypeParamName)); @@ -59,8 +59,7 @@ public class AccountNumberFormatDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - ACCOUNT_NUMBER_FORMAT_CREATE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, ACCOUNT_NUMBER_FORMAT_CREATE_REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); final List dataValidationErrors = new ArrayList<>(); @@ -73,8 +72,8 @@ public class AccountNumberFormatDataValidator { .integerGreaterThanZero().inMinMaxRange(EntityAccountType.getMinValue(), EntityAccountType.getMaxValue()); if (this.fromApiJsonHelper.parameterExists(AccountNumberFormatConstants.prefixTypeParamName, element)) { - final Integer prefixType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - AccountNumberFormatConstants.prefixTypeParamName, element); + final Integer prefixType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(AccountNumberFormatConstants.prefixTypeParamName, element); DataValidatorBuilder dataValidatorForValidatingPrefixType = baseDataValidator.reset() .parameter(AccountNumberFormatConstants.prefixTypeParamName).value(prefixType).notNull().integerGreaterThanZero(); @@ -103,31 +102,30 @@ public class AccountNumberFormatDataValidator { } - public Set determineValidAccountNumberPrefixes( - EntityAccountType entityAccountType) { + public Set determineValidAccountNumberPrefixes(EntityAccountType entityAccountType) { Set validAccountNumberPrefixes = new HashSet<>(); switch (entityAccountType) { - case CLIENT: - validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForClientAccounts; + case CLIENT: + validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForClientAccounts; break; - case LOAN: - validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForLoanAccounts; + case LOAN: + validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForLoanAccounts; break; - case SAVINGS: - validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForSavingsAccounts; + case SAVINGS: + validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForSavingsAccounts; break; - case CENTER: - validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForCenters; + case CENTER: + validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForCenters; break; - case GROUP: - validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForGroups; + case GROUP: + validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForGroups; break; - default: + default: } Set validAccountNumberPrefixValues = new HashSet<>(); @@ -142,8 +140,7 @@ public class AccountNumberFormatDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - ACCOUNT_NUMBER_FORMAT_UPDATE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, ACCOUNT_NUMBER_FORMAT_UPDATE_REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); final List dataValidationErrors = new ArrayList<>(); @@ -155,8 +152,8 @@ public class AccountNumberFormatDataValidator { if (this.fromApiJsonHelper.parameterExists(AccountNumberFormatConstants.prefixTypeParamName, element)) { atLeastOneParameterPassedForUpdate = true; Set validAccountNumberPrefixes = determineValidAccountNumberPrefixes(entityAccountType); - final Integer prefixType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - AccountNumberFormatConstants.prefixTypeParamName, element); + final Integer prefixType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(AccountNumberFormatConstants.prefixTypeParamName, element); baseDataValidator.reset().parameter(AccountNumberFormatConstants.prefixTypeParamName).value(prefixType).notNull() .integerGreaterThanZero().isOneOfTheseValues(validAccountNumberPrefixes.toArray()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormat.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormat.java index 58d6a87f2..fa4025383 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormat.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormat.java @@ -27,7 +27,8 @@ import org.apache.fineract.infrastructure.accountnumberformat.service.AccountNum import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity -@Table(name = AccountNumberFormatConstants.ACCOUNT_NUMBER_FORMAT_TABLE_NAME, uniqueConstraints = { @UniqueConstraint(columnNames = { AccountNumberFormatConstants.ACCOUNT_TYPE_ENUM_COLUMN_NAME }, name = AccountNumberFormatConstants.ACCOUNT_TYPE_UNIQUE_CONSTRAINT_NAME) }) +@Table(name = AccountNumberFormatConstants.ACCOUNT_NUMBER_FORMAT_TABLE_NAME, uniqueConstraints = { @UniqueConstraint(columnNames = { + AccountNumberFormatConstants.ACCOUNT_TYPE_ENUM_COLUMN_NAME }, name = AccountNumberFormatConstants.ACCOUNT_TYPE_UNIQUE_CONSTRAINT_NAME) }) public class AccountNumberFormat extends AbstractPersistableCustom { @Column(name = AccountNumberFormatConstants.ACCOUNT_TYPE_ENUM_COLUMN_NAME, nullable = false) @@ -74,4 +75,4 @@ public class AccountNumberFormat extends AbstractPersistableCustom { public void setPrefix(AccountNumberPrefixType accountNumberPrefixType) { setPrefixEnum(accountNumberPrefixType.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatEnumerations.java index 7545f55cd..d66bf1898 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatEnumerations.java @@ -30,28 +30,27 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; public class AccountNumberFormatEnumerations { - public final static Set accountNumberPrefixesForClientAccounts = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(AccountNumberPrefixType.OFFICE_NAME, - AccountNumberPrefixType.CLIENT_TYPE))); + public final static Set accountNumberPrefixesForClientAccounts = Collections + .unmodifiableSet(new HashSet<>(Arrays.asList(AccountNumberPrefixType.OFFICE_NAME, AccountNumberPrefixType.CLIENT_TYPE))); - public final static Set accountNumberPrefixesForLoanAccounts = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(AccountNumberPrefixType.OFFICE_NAME, - AccountNumberPrefixType.LOAN_PRODUCT_SHORT_NAME))); + public final static Set accountNumberPrefixesForLoanAccounts = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList(AccountNumberPrefixType.OFFICE_NAME, AccountNumberPrefixType.LOAN_PRODUCT_SHORT_NAME))); - public final static Set accountNumberPrefixesForSavingsAccounts = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(AccountNumberPrefixType.OFFICE_NAME, - AccountNumberPrefixType.SAVINGS_PRODUCT_SHORT_NAME))); + public final static Set accountNumberPrefixesForSavingsAccounts = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList(AccountNumberPrefixType.OFFICE_NAME, AccountNumberPrefixType.SAVINGS_PRODUCT_SHORT_NAME))); - public final static Set accountNumberPrefixesForCenters = - Collections.unmodifiableSet(new HashSet<>(Collections.singletonList(AccountNumberPrefixType.OFFICE_NAME))); + public final static Set accountNumberPrefixesForCenters = Collections + .unmodifiableSet(new HashSet<>(Collections.singletonList(AccountNumberPrefixType.OFFICE_NAME))); - public final static Set accountNumberPrefixesForGroups = - Collections.unmodifiableSet(new HashSet<>(Collections.singletonList(AccountNumberPrefixType.OFFICE_NAME))); + public final static Set accountNumberPrefixesForGroups = Collections + .unmodifiableSet(new HashSet<>(Collections.singletonList(AccountNumberPrefixType.OFFICE_NAME))); public enum AccountNumberPrefixType { - OFFICE_NAME(1, "accountNumberPrefixType.officeName"), CLIENT_TYPE(101, "accountNumberPrefixType.clientType"), LOAN_PRODUCT_SHORT_NAME( - 201, "accountNumberPrefixType.loanProductShortName"), SAVINGS_PRODUCT_SHORT_NAME(301, - "accountNumberPrefixType.savingsProductShortName"); + + OFFICE_NAME(1, "accountNumberPrefixType.officeName"), CLIENT_TYPE(101, + "accountNumberPrefixType.clientType"), LOAN_PRODUCT_SHORT_NAME(201, + "accountNumberPrefixType.loanProductShortName"), SAVINGS_PRODUCT_SHORT_NAME(301, + "accountNumberPrefixType.savingsProductShortName"); private final Integer value; private final String code; @@ -145,4 +144,4 @@ public class AccountNumberFormatEnumerations { return accountNumberPrefixType(accountNumberPrefixTypes); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatRepository.java index 12396abe5..bed8e900d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatRepository.java @@ -23,8 +23,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface AccountNumberFormatRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface AccountNumberFormatRepository + extends JpaRepository, JpaSpecificationExecutor { public static final String FIND_ACCOUNT_NUMBER_FORMAT_FOR_ENTITY = "select anf from AccountNumberFormat anf where anf.accountTypeEnum = :accountTypeEnum"; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatRepositoryWrapper.java index 593599986..35ccda056 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/AccountNumberFormatRepositoryWrapper.java @@ -33,8 +33,7 @@ public class AccountNumberFormatRepositoryWrapper { } public AccountNumberFormat findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new AccountNumberFormatNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new AccountNumberFormatNotFoundException(id)); } public void save(final AccountNumberFormat accountNumberFormat) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/EntityAccountType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/EntityAccountType.java index de58ecb5c..1df0217ce 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/EntityAccountType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/domain/EntityAccountType.java @@ -22,8 +22,9 @@ import java.util.HashMap; import java.util.Map; public enum EntityAccountType { - CLIENT(1, "accountType.client"), LOAN(2, "accountType.loan"), SAVINGS(3, "accountType.savings"), CENTER(4, "accountType.center"), - GROUP(5, "accountType.group"), SHARES(6, "accountType.shares"); + + CLIENT(1, "accountType.client"), LOAN(2, "accountType.loan"), SAVINGS(3, "accountType.savings"), CENTER(4, + "accountType.center"), GROUP(5, "accountType.group"), SHARES(6, "accountType.shares"); private final Integer value; private final String code; @@ -91,11 +92,11 @@ public enum EntityAccountType { return this.value.equals(EntityAccountType.SAVINGS.getValue()); } - public Boolean isCenterAccount(){ + public Boolean isCenterAccount() { return this.value.equals(EntityAccountType.CENTER.getValue()); } - public Boolean isGroupAccount(){ + public Boolean isGroupAccount() { return this.value.equals(EntityAccountType.GROUP.getValue()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/exception/AccountNumberFormatNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/exception/AccountNumberFormatNotFoundException.java index 4ff275aed..45d713b92 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/exception/AccountNumberFormatNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/exception/AccountNumberFormatNotFoundException.java @@ -27,8 +27,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class AccountNumberFormatNotFoundException extends AbstractPlatformResourceNotFoundException { public AccountNumberFormatNotFoundException(final Long id) { - super(AccountNumberFormatConstants.EXCEPTION_ACCOUNT_NUMBER_FORMAT_NOT_FOUND, "AccountNumber format with identifier " + id - + " does not exist", id); + super(AccountNumberFormatConstants.EXCEPTION_ACCOUNT_NUMBER_FORMAT_NOT_FOUND, + "AccountNumber format with identifier " + id + " does not exist", id); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/service/AccountNumberFormatReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/service/AccountNumberFormatReadPlatformServiceImpl.java index f7d5e746c..b2310b5f9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/service/AccountNumberFormatReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/service/AccountNumberFormatReadPlatformServiceImpl.java @@ -139,10 +139,10 @@ public class AccountNumberFormatReadPlatformServiceImpl implements AccountNumber case SAVINGS: accountNumberPrefixTypesSet = AccountNumberFormatEnumerations.accountNumberPrefixesForSavingsAccounts; break; - case CENTER : + case CENTER: accountNumberPrefixTypesSet = AccountNumberFormatEnumerations.accountNumberPrefixesForCenters; break; - case GROUP : + case GROUP: accountNumberPrefixTypesSet = AccountNumberFormatEnumerations.accountNumberPrefixesForGroups; break; default: diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/service/AccountNumberFormatWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/service/AccountNumberFormatWritePlatformServiceJpaRepositoryImpl.java index 72ba73d60..2cb3059ad 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/service/AccountNumberFormatWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/accountnumberformat/service/AccountNumberFormatWritePlatformServiceJpaRepositoryImpl.java @@ -77,8 +77,8 @@ public class AccountNumberFormatWritePlatformServiceJpaRepositoryImpl implements } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + } catch (final PersistenceException ee) { + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()); handleDataIntegrityIssues(command, throwable, ee); return CommandProcessingResult.empty(); } @@ -118,7 +118,7 @@ public class AccountNumberFormatWritePlatformServiceJpaRepositoryImpl implements handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); } catch (final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()); handleDataIntegrityIssues(command, throwable, ee); return CommandProcessingResult.empty(); } @@ -135,7 +135,6 @@ public class AccountNumberFormatWritePlatformServiceJpaRepositoryImpl implements .build(); } - /* * Guaranteed to throw an exception no matter what the data integrity issue * is. diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/api/BulkImportApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/api/BulkImportApiResource.java index 6510cf4c0..8824432f1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/api/BulkImportApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/api/BulkImportApiResource.java @@ -55,40 +55,34 @@ public class BulkImportApiResource { private final ApiRequestParameterHelper apiRequestParameterHelper; @Autowired - public BulkImportApiResource(final PlatformSecurityContext context, - final BulkImportWorkbookService bulkImportWorkbookService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper) { + public BulkImportApiResource(final PlatformSecurityContext context, final BulkImportWorkbookService bulkImportWorkbookService, + final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper) { this.context = context; this.bulkImportWorkbookService = bulkImportWorkbookService; this.toApiJsonSerializer = toApiJsonSerializer; this.apiRequestParameterHelper = apiRequestParameterHelper; } - @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveImportDocuments(@Context final UriInfo uriInfo, - @QueryParam("entityType") final String entityType) { + public String retrieveImportDocuments(@Context final UriInfo uriInfo, @QueryParam("entityType") final String entityType) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - Collection importData=new ArrayList<>(); - if (entityType.equals(GlobalEntityType.CLIENT.getCode())){ + Collection importData = new ArrayList<>(); + if (entityType.equals(GlobalEntityType.CLIENT.getCode())) { final Collection importForClientEntity = this.bulkImportWorkbookService.getImports(GlobalEntityType.CLIENTS_ENTTTY); - final Collection importForClientPerson=this.bulkImportWorkbookService.getImports(GlobalEntityType.CLIENTS_PERSON); - if (importForClientEntity!=null) { + final Collection importForClientPerson = this.bulkImportWorkbookService.getImports(GlobalEntityType.CLIENTS_PERSON); + if (importForClientEntity != null) { importData.addAll(importForClientEntity); } - if (importForClientPerson!=null) { + if (importForClientPerson != null) { importData.addAll(importForClientPerson); } - }else { + } else { final GlobalEntityType type = GlobalEntityType.fromCode(entityType); - if (type == null) { - throw new ImportTypeNotFoundException(entityType); - } - importData = this.bulkImportWorkbookService.getImports(type); + if (type == null) { throw new ImportTypeNotFoundException(entityType); } + importData = this.bulkImportWorkbookService.getImports(type); } final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, importData); @@ -96,9 +90,9 @@ public class BulkImportApiResource { @GET @Path("getOutputTemplateLocation") - public String retriveOutputTemplateLocation(@QueryParam("importDocumentId")final String importDocumentId ){ + public String retriveOutputTemplateLocation(@QueryParam("importDocumentId") final String importDocumentId) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final DocumentData documentData =this.bulkImportWorkbookService.getOutputTemplateLocation(importDocumentId); + final DocumentData documentData = this.bulkImportWorkbookService.getOutputTemplateLocation(importDocumentId); return this.toApiJsonSerializer.serialize(documentData.fileLocation()); } @@ -109,6 +103,4 @@ public class BulkImportApiResource { return bulkImportWorkbookService.getOutputTemplate(importDocumentId); } - - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/CenterConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/CenterConstants.java index 007222118..4d973992a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/CenterConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/CenterConstants.java @@ -20,32 +20,28 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class CenterConstants { - //Column indices - public static final int CENTER_NAME_COL = 0;//A - public static final int OFFICE_NAME_COL = 1;//B - public static final int STAFF_NAME_COL = 2;//C - public static final int EXTERNAL_ID_COL = 3;//D - public static final int ACTIVE_COL = 4;//E - public static final int ACTIVATION_DATE_COL = 5;//F - public static final int SUBMITTED_ON_DATE_COL=6;//G - public static final int MEETING_START_DATE_COL = 7;//H - public static final int IS_REPEATING_COL = 8;//I - public static final int FREQUENCY_COL = 9;//J - public static final int INTERVAL_COL = 10;//K - public static final int REPEATS_ON_DAY_COL = 11;//L - public static final int STATUS_COL = 12;//M - public static final int CENTER_ID_COL = 13;//N - public static final int FAILURE_COL = 14;//O - public static final int GROUP_NAMES_STARTING_COL = 15;//P - public static final int GROUP_NAMES_ENDING_COL = 250;//IQ + // Column indices + public static final int CENTER_NAME_COL = 0;// A + public static final int OFFICE_NAME_COL = 1;// B + public static final int STAFF_NAME_COL = 2;// C + public static final int EXTERNAL_ID_COL = 3;// D + public static final int ACTIVE_COL = 4;// E + public static final int ACTIVATION_DATE_COL = 5;// F + public static final int SUBMITTED_ON_DATE_COL = 6;// G + public static final int MEETING_START_DATE_COL = 7;// H + public static final int IS_REPEATING_COL = 8;// I + public static final int FREQUENCY_COL = 9;// J + public static final int INTERVAL_COL = 10;// K + public static final int REPEATS_ON_DAY_COL = 11;// L + public static final int STATUS_COL = 12;// M + public static final int CENTER_ID_COL = 13;// N + public static final int FAILURE_COL = 14;// O + public static final int GROUP_NAMES_STARTING_COL = 15;// P + public static final int GROUP_NAMES_ENDING_COL = 250;// IQ public static final int LOOKUP_OFFICE_NAME_COL = 251; public static final int LOOKUP_OFFICE_OPENING_DATE_COL = 252; public static final int LOOKUP_REPEAT_NORMAL_COL = 253; public static final int LOOKUP_REPEAT_MONTHLY_COL = 254; public static final int LOOKUP_IF_REPEAT_WEEKLY_COL = 255; - - - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ChartOfAcountsConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ChartOfAcountsConstants.java index 02255c2b1..f13a40468 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ChartOfAcountsConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ChartOfAcountsConstants.java @@ -19,20 +19,21 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class ChartOfAcountsConstants { - public static final int ACCOUNT_TYPE_COL=0;//A - public static final int ACCOUNT_NAME_COL=1;//B - public static final int ACCOUNT_USAGE_COL=2;//C - public static final int MANUAL_ENTRIES_ALLOWED_COL=3;//D - public static final int PARENT_COL=4;//E - public static final int PARENT_ID_COL=5;//F - public static final int GL_CODE_COL=6;//G - public static final int TAG_COL=7;//H - public static final int TAG_ID_COL=8;//I - public static final int DESCRIPTION_COL=9;//J - public static final int LOOKUP_ACCOUNT_TYPE_COL=15;// P - public static final int LOOKUP_ACCOUNT_NAME_COL=16; //Q - public static final int LOOKUP_ACCOUNT_ID_COL=17;//R - public static final int LOOKUP_TAG_COL=18; //S - public static final int LOOKUP_TAG_ID_COL=19; //T - public static final int STATUS_COL=20; + + public static final int ACCOUNT_TYPE_COL = 0;// A + public static final int ACCOUNT_NAME_COL = 1;// B + public static final int ACCOUNT_USAGE_COL = 2;// C + public static final int MANUAL_ENTRIES_ALLOWED_COL = 3;// D + public static final int PARENT_COL = 4;// E + public static final int PARENT_ID_COL = 5;// F + public static final int GL_CODE_COL = 6;// G + public static final int TAG_COL = 7;// H + public static final int TAG_ID_COL = 8;// I + public static final int DESCRIPTION_COL = 9;// J + public static final int LOOKUP_ACCOUNT_TYPE_COL = 15;// P + public static final int LOOKUP_ACCOUNT_NAME_COL = 16; // Q + public static final int LOOKUP_ACCOUNT_ID_COL = 17;// R + public static final int LOOKUP_TAG_COL = 18; // S + public static final int LOOKUP_TAG_ID_COL = 19; // T + public static final int STATUS_COL = 20; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ClientEntityConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ClientEntityConstants.java index f8ec57387..430e79e15 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ClientEntityConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ClientEntityConstants.java @@ -20,42 +20,42 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class ClientEntityConstants { - public static final int NAME_COL = 0;//A - public static final int OFFICE_NAME_COL = 1;//B - public static final int STAFF_NAME_COL = 2;//C - public static final int INCOPORATION_DATE_COL = 3;//D - public static final int INCOPORATION_VALID_TILL_COL = 4; //E - public static final int MOBILE_NO_COL=5;//F - public static final int CLIENT_TYPE_COL=6;//G - public static final int CLIENT_CLASSIFICATION_COL=7;//H - public static final int INCOPORATION_NUMBER_COL=8;//I - public static final int MAIN_BUSINESS_LINE=9;//J - public static final int CONSTITUTION_COL=10;//K - public static final int REMARKS_COL=11;//L - public static final int EXTERNAL_ID_COL=12;//M - public static final int ACTIVE_COL = 13;//N - public static final int ACTIVATION_DATE_COL = 14;//O - public static final int SUBMITTED_ON_COL=15; //P - public static final int ADDRESS_ENABLED=16;//Q - public static final int ADDRESS_TYPE_COL=17;//R - public static final int STREET_COL=18;//S - public static final int ADDRESS_LINE_1_COL=19;//T - public static final int ADDRESS_LINE_2_COL=20;//U - public static final int ADDRESS_LINE_3_COL=21;//V - public static final int CITY_COL =22;//W - public static final int STATE_PROVINCE_COL=23;//X - public static final int COUNTRY_COL=24;//Y - public static final int POSTAL_CODE_COL=25;//Z - public static final int IS_ACTIVE_ADDRESS_COL=26;//AA - public static final int WARNING_COL = 26;//AA - public static final int STATUS_COL = 27;//AB - public static final int RELATIONAL_OFFICE_NAME_COL = 35;//AJ - public static final int RELATIONAL_OFFICE_OPENING_DATE_COL = 36;//AK - public static final int LOOKUP_CONSTITUTION_COL = 37;//AL - public static final int LOOKUP_CLIENT_CLASSIFICATION = 38;//AM - public static final int LOOKUP_CLIENT_TYPES = 39;//AN - public static final int LOOKUP_ADDRESS_TYPE = 40;//AO - public static final int LOOKUP_STATE_PROVINCE = 41;//AP - public static final int LOOKUP_COUNTRY = 42;//AQ - public static final int LOOKUP_MAIN_BUSINESS_LINE=43;//AR + public static final int NAME_COL = 0;// A + public static final int OFFICE_NAME_COL = 1;// B + public static final int STAFF_NAME_COL = 2;// C + public static final int INCOPORATION_DATE_COL = 3;// D + public static final int INCOPORATION_VALID_TILL_COL = 4; // E + public static final int MOBILE_NO_COL = 5;// F + public static final int CLIENT_TYPE_COL = 6;// G + public static final int CLIENT_CLASSIFICATION_COL = 7;// H + public static final int INCOPORATION_NUMBER_COL = 8;// I + public static final int MAIN_BUSINESS_LINE = 9;// J + public static final int CONSTITUTION_COL = 10;// K + public static final int REMARKS_COL = 11;// L + public static final int EXTERNAL_ID_COL = 12;// M + public static final int ACTIVE_COL = 13;// N + public static final int ACTIVATION_DATE_COL = 14;// O + public static final int SUBMITTED_ON_COL = 15; // P + public static final int ADDRESS_ENABLED = 16;// Q + public static final int ADDRESS_TYPE_COL = 17;// R + public static final int STREET_COL = 18;// S + public static final int ADDRESS_LINE_1_COL = 19;// T + public static final int ADDRESS_LINE_2_COL = 20;// U + public static final int ADDRESS_LINE_3_COL = 21;// V + public static final int CITY_COL = 22;// W + public static final int STATE_PROVINCE_COL = 23;// X + public static final int COUNTRY_COL = 24;// Y + public static final int POSTAL_CODE_COL = 25;// Z + public static final int IS_ACTIVE_ADDRESS_COL = 26;// AA + public static final int WARNING_COL = 26;// AA + public static final int STATUS_COL = 27;// AB + public static final int RELATIONAL_OFFICE_NAME_COL = 35;// AJ + public static final int RELATIONAL_OFFICE_OPENING_DATE_COL = 36;// AK + public static final int LOOKUP_CONSTITUTION_COL = 37;// AL + public static final int LOOKUP_CLIENT_CLASSIFICATION = 38;// AM + public static final int LOOKUP_CLIENT_TYPES = 39;// AN + public static final int LOOKUP_ADDRESS_TYPE = 40;// AO + public static final int LOOKUP_STATE_PROVINCE = 41;// AP + public static final int LOOKUP_COUNTRY = 42;// AQ + public static final int LOOKUP_MAIN_BUSINESS_LINE = 43;// AR } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ClientPersonConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ClientPersonConstants.java index 5da827019..8e35d801f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ClientPersonConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/ClientPersonConstants.java @@ -19,40 +19,41 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class ClientPersonConstants { - public static final int FIRST_NAME_COL = 0;//A - public static final int LAST_NAME_COL = 1;//B - public static final int MIDDLE_NAME_COL = 2;//C - public static final int OFFICE_NAME_COL = 3;//D - public static final int STAFF_NAME_COL = 4;//E - public static final int EXTERNAL_ID_COL = 5;//F - public static final int ACTIVE_COL = 6;//G - public static final int ACTIVATION_DATE_COL = 7;//H - public static final int SUBMITTED_ON_COL=8; //I - public static final int MOBILE_NO_COL=9;//J - public static final int DOB_COL=10;//K - public static final int CLIENT_TYPE_COL=11;//L - public static final int GENDER_COL=12;//M - public static final int CLIENT_CLASSIFICATION_COL=13;//N - public static final int IS_STAFF_COL=14;//O - public static final int ADDRESS_ENABLED_COL=15;// P - public static final int ADDRESS_TYPE_COL=16;//Q - public static final int STREET_COL=17;//R - public static final int ADDRESS_LINE_1_COL=18;//S - public static final int ADDRESS_LINE_2_COL=19;//T - public static final int ADDRESS_LINE_3_COL=20;//U - public static final int CITY_COL=21;//V - public static final int STATE_PROVINCE_COL=22;//W - public static final int COUNTRY_COL=23;//X - public static final int POSTAL_CODE_COL=24;//Y - public static final int IS_ACTIVE_ADDRESS_COL=25;//Z - public static final int WARNING_COL = 26;//AA - public static final int STATUS_COL = 27;//AB - public static final int RELATIONAL_OFFICE_NAME_COL = 35;//AJ - public static final int RELATIONAL_OFFICE_OPENING_DATE_COL = 36;//AK - public static final int LOOKUP_GENDER_COL = 37;//AL - public static final int LOOKUP_CLIENT_CLASSIFICATION_COL = 38;//AM - public static final int LOOKUP_CLIENT_TYPES_COL = 39;//AN - public static final int LOOKUP_ADDRESS_TYPE_COL = 40;//AO - public static final int LOOKUP_STATE_PROVINCE_COL = 41;//AP - public static final int LOOKUP_COUNTRY_COL = 42;//AQ + + public static final int FIRST_NAME_COL = 0;// A + public static final int LAST_NAME_COL = 1;// B + public static final int MIDDLE_NAME_COL = 2;// C + public static final int OFFICE_NAME_COL = 3;// D + public static final int STAFF_NAME_COL = 4;// E + public static final int EXTERNAL_ID_COL = 5;// F + public static final int ACTIVE_COL = 6;// G + public static final int ACTIVATION_DATE_COL = 7;// H + public static final int SUBMITTED_ON_COL = 8; // I + public static final int MOBILE_NO_COL = 9;// J + public static final int DOB_COL = 10;// K + public static final int CLIENT_TYPE_COL = 11;// L + public static final int GENDER_COL = 12;// M + public static final int CLIENT_CLASSIFICATION_COL = 13;// N + public static final int IS_STAFF_COL = 14;// O + public static final int ADDRESS_ENABLED_COL = 15;// P + public static final int ADDRESS_TYPE_COL = 16;// Q + public static final int STREET_COL = 17;// R + public static final int ADDRESS_LINE_1_COL = 18;// S + public static final int ADDRESS_LINE_2_COL = 19;// T + public static final int ADDRESS_LINE_3_COL = 20;// U + public static final int CITY_COL = 21;// V + public static final int STATE_PROVINCE_COL = 22;// W + public static final int COUNTRY_COL = 23;// X + public static final int POSTAL_CODE_COL = 24;// Y + public static final int IS_ACTIVE_ADDRESS_COL = 25;// Z + public static final int WARNING_COL = 26;// AA + public static final int STATUS_COL = 27;// AB + public static final int RELATIONAL_OFFICE_NAME_COL = 35;// AJ + public static final int RELATIONAL_OFFICE_OPENING_DATE_COL = 36;// AK + public static final int LOOKUP_GENDER_COL = 37;// AL + public static final int LOOKUP_CLIENT_CLASSIFICATION_COL = 38;// AM + public static final int LOOKUP_CLIENT_TYPES_COL = 39;// AN + public static final int LOOKUP_ADDRESS_TYPE_COL = 40;// AO + public static final int LOOKUP_STATE_PROVINCE_COL = 41;// AP + public static final int LOOKUP_COUNTRY_COL = 42;// AQ } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/GroupConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/GroupConstants.java index 02c03260c..8fd1f7ca5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/GroupConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/GroupConstants.java @@ -20,28 +20,28 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class GroupConstants { - public static final int NAME_COL = 0; //A - public static final int OFFICE_NAME_COL = 1; //B - public static final int STAFF_NAME_COL = 2;//C + public static final int NAME_COL = 0; // A + public static final int OFFICE_NAME_COL = 1; // B + public static final int STAFF_NAME_COL = 2;// C - public static final int CENTER_NAME_COL = 3;//D - public static final int EXTERNAL_ID_COL = 4;//E - public static final int ACTIVE_COL = 5;//F - public static final int ACTIVATION_DATE_COL = 6;//G - public static final int SUBMITTED_ON_DATE_COL=7;//H - public static final int MEETING_START_DATE_COL = 8;//I - public static final int IS_REPEATING_COL = 9;//J - public static final int FREQUENCY_COL = 10;//K - public static final int INTERVAL_COL = 11;//L - public static final int REPEATS_ON_DAY_COL = 12;//M - public static final int STATUS_COL = 13;//N - public static final int GROUP_ID_COL = 14;//O - public static final int FAILURE_COL = 15;//P - public static final int CLIENT_NAMES_STARTING_COL = 16;//Q - public static final int CLIENT_NAMES_ENDING_COL = 250;//IQ - public static final int LOOKUP_OFFICE_NAME_COL = 251;//IR - public static final int LOOKUP_OFFICE_OPENING_DATE_COL = 252;//IS - public static final int LOOKUP_REPEAT_NORMAL_COL = 253;//IT - public static final int LOOKUP_REPEAT_MONTHLY_COL = 254;//IU - public static final int LOOKUP_IF_REPEAT_WEEKLY_COL = 255;//IV + public static final int CENTER_NAME_COL = 3;// D + public static final int EXTERNAL_ID_COL = 4;// E + public static final int ACTIVE_COL = 5;// F + public static final int ACTIVATION_DATE_COL = 6;// G + public static final int SUBMITTED_ON_DATE_COL = 7;// H + public static final int MEETING_START_DATE_COL = 8;// I + public static final int IS_REPEATING_COL = 9;// J + public static final int FREQUENCY_COL = 10;// K + public static final int INTERVAL_COL = 11;// L + public static final int REPEATS_ON_DAY_COL = 12;// M + public static final int STATUS_COL = 13;// N + public static final int GROUP_ID_COL = 14;// O + public static final int FAILURE_COL = 15;// P + public static final int CLIENT_NAMES_STARTING_COL = 16;// Q + public static final int CLIENT_NAMES_ENDING_COL = 250;// IQ + public static final int LOOKUP_OFFICE_NAME_COL = 251;// IR + public static final int LOOKUP_OFFICE_OPENING_DATE_COL = 252;// IS + public static final int LOOKUP_REPEAT_NORMAL_COL = 253;// IT + public static final int LOOKUP_REPEAT_MONTHLY_COL = 254;// IU + public static final int LOOKUP_IF_REPEAT_WEEKLY_COL = 255;// IV } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/GuarantorConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/GuarantorConstants.java index b37195bd2..a28f51c93 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/GuarantorConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/GuarantorConstants.java @@ -23,23 +23,23 @@ public class GuarantorConstants { public static final int OFFICE_NAME_COL = 0; public static final int CLIENT_NAME_COL = 1; public static final int LOAN_ACCOUNT_NO_COL = 2; - public static final int GUARANTO_TYPE_COL =3; - public static final int CLIENT_RELATIONSHIP_TYPE_COL =4; + public static final int GUARANTO_TYPE_COL = 3; + public static final int CLIENT_RELATIONSHIP_TYPE_COL = 4; public static final int ENTITY_OFFICE_NAME_COL = 5; public static final int ENTITY_ID_COL = 6; public static final int FIRST_NAME_COL = 7; public static final int LAST_NAME_COL = 8; - public static final int ADDRESS_LINE_1_COL= 9; + public static final int ADDRESS_LINE_1_COL = 9; public static final int ADDRESS_LINE_2_COL = 10; public static final int CITY_COL = 11; public static final int DOB_COL = 12; public static final int ZIP_COL = 13; - public static final int SAVINGS_ID_COL=14; - public static final int AMOUNT=15; + public static final int SAVINGS_ID_COL = 14; + public static final int AMOUNT = 15; public static final int STATUS_COL = 18; - public static final int LOOKUP_CLIENT_NAME_COL=81; - public static final int LOOKUP_ACCOUNT_NO_COL=82; - public static final int LOOKUP_SAVINGS_CLIENT_NAME_COL=83; - public static final int LOOKUP_SAVINGS_ACCOUNT_NO_COL=84; - public static final int LOOKUP_GUARANTOR_RELATIONSHIPS=85; + public static final int LOOKUP_CLIENT_NAME_COL = 81; + public static final int LOOKUP_ACCOUNT_NO_COL = 82; + public static final int LOOKUP_SAVINGS_CLIENT_NAME_COL = 83; + public static final int LOOKUP_SAVINGS_ACCOUNT_NO_COL = 84; + public static final int LOOKUP_GUARANTOR_RELATIONSHIPS = 85; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/JournalEntryConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/JournalEntryConstants.java index e54f19b88..89e8c8492 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/JournalEntryConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/JournalEntryConstants.java @@ -45,5 +45,5 @@ public class JournalEntryConstants { public static final int ROUTING_CODE_COL = 12; public static final int RECEIPT_NO_COL = 13; public static final int BANK_NO_COL = 14; - public static final int COMMENTS_COL=15; + public static final int COMMENTS_COL = 15; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/LoanConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/LoanConstants.java index 2e5b38fd0..0d429812b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/LoanConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/LoanConstants.java @@ -20,56 +20,56 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class LoanConstants { - public static final int OFFICE_NAME_COL = 0;//A - public static final int LOAN_TYPE_COL = 1;//B - public static final int CLIENT_NAME_COL = 2;//C - public static final int CLIENT_EXTERNAL_ID=3;//D - public static final int PRODUCT_COL = 4;//E - public static final int LOAN_OFFICER_NAME_COL = 5;//F - public static final int SUBMITTED_ON_DATE_COL = 6;//G - public static final int APPROVED_DATE_COL = 7;//H - public static final int DISBURSED_DATE_COL = 8;//I - public static final int DISBURSED_PAYMENT_TYPE_COL = 9;//J - public static final int FUND_NAME_COL = 10;//K - public static final int PRINCIPAL_COL = 11;//L - public static final int NO_OF_REPAYMENTS_COL = 12;//M - public static final int REPAID_EVERY_COL = 13;//N - public static final int REPAID_EVERY_FREQUENCY_COL = 14;//O - public static final int LOAN_TERM_COL = 15;//P - public static final int LOAN_TERM_FREQUENCY_COL = 16;//Q - public static final int NOMINAL_INTEREST_RATE_COL = 17;//R - public static final int NOMINAL_INTEREST_RATE_FREQUENCY_COL = 18;//S - public static final int AMORTIZATION_COL = 19;//T - public static final int INTEREST_METHOD_COL = 20;//U - public static final int INTEREST_CALCULATION_PERIOD_COL = 21;//V - public static final int ARREARS_TOLERANCE_COL = 22;//W - public static final int REPAYMENT_STRATEGY_COL = 23;//X - public static final int GRACE_ON_PRINCIPAL_PAYMENT_COL = 24;//Y - public static final int GRACE_ON_INTEREST_PAYMENT_COL = 25;//Z - public static final int GRACE_ON_INTEREST_CHARGED_COL = 26;//AA - public static final int INTEREST_CHARGED_FROM_COL = 27;//AB - public static final int FIRST_REPAYMENT_COL = 28;//AC - public static final int TOTAL_AMOUNT_REPAID_COL = 29;//AD - public static final int LAST_REPAYMENT_DATE_COL = 30;//AE - public static final int REPAYMENT_TYPE_COL = 31;//AF - public static final int STATUS_COL = 32;//AG - public static final int LOAN_ID_COL = 33;//AH - public static final int FAILURE_REPORT_COL = 34;//AI - public static final int EXTERNAL_ID_COL = 35;//AJ - public static final int CHARGE_ID_1 = 36;//AK - public static final int CHARGE_AMOUNT_1 = 37;//AL - public static final int CHARGE_DUE_DATE_1 = 38;//AM - public static final int CHARGE_ID_2 = 39;//AN - public static final int CHARGE_AMOUNT_2 = 40;//AO - public static final int CHARGE_DUE_DATE_2 = 41;//AP - public static final int GROUP_ID = 42;//AQ - public static final int LOOKUP_CLIENT_NAME_COL = 43;//AR - public static final int LOOKUP_CLIENT_EXTERNAL_ID=44;//AS - public static final int LOOKUP_ACTIVATION_DATE_COL = 45;//AT - public static final int LINK_ACCOUNT_ID = 46;//AU + public static final int OFFICE_NAME_COL = 0;// A + public static final int LOAN_TYPE_COL = 1;// B + public static final int CLIENT_NAME_COL = 2;// C + public static final int CLIENT_EXTERNAL_ID = 3;// D + public static final int PRODUCT_COL = 4;// E + public static final int LOAN_OFFICER_NAME_COL = 5;// F + public static final int SUBMITTED_ON_DATE_COL = 6;// G + public static final int APPROVED_DATE_COL = 7;// H + public static final int DISBURSED_DATE_COL = 8;// I + public static final int DISBURSED_PAYMENT_TYPE_COL = 9;// J + public static final int FUND_NAME_COL = 10;// K + public static final int PRINCIPAL_COL = 11;// L + public static final int NO_OF_REPAYMENTS_COL = 12;// M + public static final int REPAID_EVERY_COL = 13;// N + public static final int REPAID_EVERY_FREQUENCY_COL = 14;// O + public static final int LOAN_TERM_COL = 15;// P + public static final int LOAN_TERM_FREQUENCY_COL = 16;// Q + public static final int NOMINAL_INTEREST_RATE_COL = 17;// R + public static final int NOMINAL_INTEREST_RATE_FREQUENCY_COL = 18;// S + public static final int AMORTIZATION_COL = 19;// T + public static final int INTEREST_METHOD_COL = 20;// U + public static final int INTEREST_CALCULATION_PERIOD_COL = 21;// V + public static final int ARREARS_TOLERANCE_COL = 22;// W + public static final int REPAYMENT_STRATEGY_COL = 23;// X + public static final int GRACE_ON_PRINCIPAL_PAYMENT_COL = 24;// Y + public static final int GRACE_ON_INTEREST_PAYMENT_COL = 25;// Z + public static final int GRACE_ON_INTEREST_CHARGED_COL = 26;// AA + public static final int INTEREST_CHARGED_FROM_COL = 27;// AB + public static final int FIRST_REPAYMENT_COL = 28;// AC + public static final int TOTAL_AMOUNT_REPAID_COL = 29;// AD + public static final int LAST_REPAYMENT_DATE_COL = 30;// AE + public static final int REPAYMENT_TYPE_COL = 31;// AF + public static final int STATUS_COL = 32;// AG + public static final int LOAN_ID_COL = 33;// AH + public static final int FAILURE_REPORT_COL = 34;// AI + public static final int EXTERNAL_ID_COL = 35;// AJ + public static final int CHARGE_ID_1 = 36;// AK + public static final int CHARGE_AMOUNT_1 = 37;// AL + public static final int CHARGE_DUE_DATE_1 = 38;// AM + public static final int CHARGE_ID_2 = 39;// AN + public static final int CHARGE_AMOUNT_2 = 40;// AO + public static final int CHARGE_DUE_DATE_2 = 41;// AP + public static final int GROUP_ID = 42;// AQ + public static final int LOOKUP_CLIENT_NAME_COL = 43;// AR + public static final int LOOKUP_CLIENT_EXTERNAL_ID = 44;// AS + public static final int LOOKUP_ACTIVATION_DATE_COL = 45;// AT + public static final int LINK_ACCOUNT_ID = 46;// AU - public static final String LOAN_TYPE_INDIVIDUAL="Individual"; - public static final String LOAN_TYPE_GROUP="Group"; - public static final String LOAN_TYPE_JLG="JLG" ; + public static final String LOAN_TYPE_INDIVIDUAL = "Individual"; + public static final String LOAN_TYPE_GROUP = "Group"; + public static final String LOAN_TYPE_JLG = "JLG"; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/LoanRepaymentConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/LoanRepaymentConstants.java index 8fe2c6f36..5aa5714cd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/LoanRepaymentConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/LoanRepaymentConstants.java @@ -20,28 +20,28 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class LoanRepaymentConstants { - public static final int OFFICE_NAME_COL = 0;//A - public static final int CLIENT_NAME_COL = 1;//B - public static final int CLIENT_EXTERNAL_ID=2;//C - public static final int LOAN_ACCOUNT_NO_COL = 3;//D - public static final int PRODUCT_COL = 4;//E - public static final int PRINCIPAL_COL = 5;//F - public static final int TOTAL_OUTSTANDING_AMOUNT_COL=6; - public static final int LOAN_DISBURSEMENT_DATE_COL=7; - public static final int AMOUNT_COL = 8;//G - public static final int REPAID_ON_DATE_COL = 9;//H - public static final int REPAYMENT_TYPE_COL = 10;//I - public static final int ACCOUNT_NO_COL = 11;//J - public static final int CHECK_NO_COL = 12;//K - public static final int ROUTING_CODE_COL = 13;//L - public static final int RECEIPT_NO_COL = 14;//M - public static final int BANK_NO_COL = 15;//N - public static final int STATUS_COL = 16;//O - public static final int LOOKUP_CLIENT_NAME_COL = 17;//P - public static final int LOOKUP_CLIENT_EXTERNAL_ID = 18;//Q - public static final int LOOKUP_ACCOUNT_NO_COL = 19;//R - public static final int LOOKUP_PRODUCT_COL = 20;//S - public static final int LOOKUP_PRINCIPAL_COL = 21;//T - public static final int LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL=22; - public static final int LOOKUP_LOAN_DISBURSEMENT_DATE_COL = 23;//U + public static final int OFFICE_NAME_COL = 0;// A + public static final int CLIENT_NAME_COL = 1;// B + public static final int CLIENT_EXTERNAL_ID = 2;// C + public static final int LOAN_ACCOUNT_NO_COL = 3;// D + public static final int PRODUCT_COL = 4;// E + public static final int PRINCIPAL_COL = 5;// F + public static final int TOTAL_OUTSTANDING_AMOUNT_COL = 6; + public static final int LOAN_DISBURSEMENT_DATE_COL = 7; + public static final int AMOUNT_COL = 8;// G + public static final int REPAID_ON_DATE_COL = 9;// H + public static final int REPAYMENT_TYPE_COL = 10;// I + public static final int ACCOUNT_NO_COL = 11;// J + public static final int CHECK_NO_COL = 12;// K + public static final int ROUTING_CODE_COL = 13;// L + public static final int RECEIPT_NO_COL = 14;// M + public static final int BANK_NO_COL = 15;// N + public static final int STATUS_COL = 16;// O + public static final int LOOKUP_CLIENT_NAME_COL = 17;// P + public static final int LOOKUP_CLIENT_EXTERNAL_ID = 18;// Q + public static final int LOOKUP_ACCOUNT_NO_COL = 19;// R + public static final int LOOKUP_PRODUCT_COL = 20;// S + public static final int LOOKUP_PRINCIPAL_COL = 21;// T + public static final int LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL = 22; + public static final int LOOKUP_LOAN_DISBURSEMENT_DATE_COL = 23;// U } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/OfficeConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/OfficeConstants.java index f1fe3a386..c320359e0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/OfficeConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/OfficeConstants.java @@ -20,14 +20,14 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class OfficeConstants { - //Column indices + // Column indices public static final int OFFICE_NAME_COL = 0; public static final int PARENT_OFFICE_NAME_COL = 1; - public static final int PARENT_OFFICE_ID_COL=2; + public static final int PARENT_OFFICE_ID_COL = 2; public static final int OPENED_ON_COL = 3; public static final int EXTERNAL_ID_COL = 4; - public static final int LOOKUP_OFFICE_COL=7; - public static final int LOOKUP_OFFICE_ID_COL=8; - public static final int STATUS_COL=10; + public static final int LOOKUP_OFFICE_COL = 7; + public static final int LOOKUP_OFFICE_ID_COL = 8; + public static final int STATUS_COL = 10; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/RecurringDepositConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/RecurringDepositConstants.java index 0cd58d087..4d0653dc0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/RecurringDepositConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/RecurringDepositConstants.java @@ -54,7 +54,6 @@ public class RecurringDepositConstants { public static final int CHARGE_AMOUNT_2 = 34; public static final int CHARGE_DUE_DATE_2 = 35; - public static final int LOOKUP_CLIENT_NAME_COL = 31; public static final int LOOKUP_ACTIVATION_DATE_COL = 32; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/SavingsConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/SavingsConstants.java index 72b544a81..86eacb3db 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/SavingsConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/SavingsConstants.java @@ -41,7 +41,7 @@ public class SavingsConstants { public static final int LOCKIN_PERIOD_FREQUENCY_COL = 18; public static final int APPLY_WITHDRAWAL_FEE_FOR_TRANSFERS = 19; public static final int ALLOW_OVER_DRAFT_COL = 20; - public static final int OVER_DRAFT_LIMIT_COL= 21; + public static final int OVER_DRAFT_LIMIT_COL = 21; public static final int EXTERNAL_ID_COL = 22; public static final int STATUS_COL = 23; public static final int SAVINGS_ID_COL = 24; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/SharedAccountsConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/SharedAccountsConstants.java index c3d8e61a3..68a7919a5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/SharedAccountsConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/SharedAccountsConstants.java @@ -20,26 +20,26 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class SharedAccountsConstants { - public static final int CLIENT_NAME_COL=0; - public static final int PRODUCT_COL=1; - public static final int SUBMITTED_ON_COL=2; - public static final int EXTERNAL_ID_COL=3; - public static final int CURRENCY_COL=4; - public static final int DECIMAL_PLACES_COL=5; - public static final int TOTAL_NO_SHARES_COL=6; - public static final int TODAYS_PRICE_COL=7; - public static final int CURRENCY_IN_MULTIPLES_COL=8; - public static final int DEFAULT_SAVINGS_AC_COL=9; - public static final int MINIMUM_ACTIVE_PERIOD_IN_DAYS_COL=10; - public static final int LOCK_IN_PERIOD_COL=11; - public static final int LOCK_IN_PERIOD_FREQUENCY_TYPE=12; - public static final int APPLICATION_DATE_COL=13; - public static final int ALLOW_DIVIDEND_CALCULATION_FOR_INACTIVE_CLIENTS_COL=14; - public static final int CHARGES_NAME_1_COL=15; - public static final int CHARGES_AMOUNT_1_COL=16; - public static final int CHARGES_NAME_2_COL=17; - public static final int CHARGES_AMOUNT_2_COL=18; - public static final int CHARGES_NAME_3_COL=19; - public static final int CHARGES_AMOUNT_3_COL=20; - public static final int STATUS_COL=25; + public static final int CLIENT_NAME_COL = 0; + public static final int PRODUCT_COL = 1; + public static final int SUBMITTED_ON_COL = 2; + public static final int EXTERNAL_ID_COL = 3; + public static final int CURRENCY_COL = 4; + public static final int DECIMAL_PLACES_COL = 5; + public static final int TOTAL_NO_SHARES_COL = 6; + public static final int TODAYS_PRICE_COL = 7; + public static final int CURRENCY_IN_MULTIPLES_COL = 8; + public static final int DEFAULT_SAVINGS_AC_COL = 9; + public static final int MINIMUM_ACTIVE_PERIOD_IN_DAYS_COL = 10; + public static final int LOCK_IN_PERIOD_COL = 11; + public static final int LOCK_IN_PERIOD_FREQUENCY_TYPE = 12; + public static final int APPLICATION_DATE_COL = 13; + public static final int ALLOW_DIVIDEND_CALCULATION_FOR_INACTIVE_CLIENTS_COL = 14; + public static final int CHARGES_NAME_1_COL = 15; + public static final int CHARGES_AMOUNT_1_COL = 16; + public static final int CHARGES_NAME_2_COL = 17; + public static final int CHARGES_AMOUNT_2_COL = 18; + public static final int CHARGES_NAME_3_COL = 19; + public static final int CHARGES_AMOUNT_3_COL = 20; + public static final int STATUS_COL = 25; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/StaffConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/StaffConstants.java index f1d7d6a3a..67cca0ad2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/StaffConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/StaffConstants.java @@ -20,13 +20,13 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class StaffConstants { - public static final int OFFICE_NAME_COL = 0;//A - public static final int FIRST_NAME_COL = 1;//B - public static final int LAST_NAME_COL = 2;//C - public static final int IS_LOAN_OFFICER = 3;//D - public static final int MOBILE_NO_COL=4;//E - public static final int JOINED_ON_COL =5;//F - public static final int EXTERNAL_ID_COL =6;//G - public static final int IS_ACTIVE_COL =7;//h - public static final int STATUS_COL=8;//H + public static final int OFFICE_NAME_COL = 0;// A + public static final int FIRST_NAME_COL = 1;// B + public static final int LAST_NAME_COL = 2;// C + public static final int IS_LOAN_OFFICER = 3;// D + public static final int MOBILE_NO_COL = 4;// E + public static final int JOINED_ON_COL = 5;// F + public static final int EXTERNAL_ID_COL = 6;// G + public static final int IS_ACTIVE_COL = 7;// h + public static final int STATUS_COL = 8;// H } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/TemplatePopulateImportConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/TemplatePopulateImportConstants.java index ba7ad96ae..03f2b4f3d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/TemplatePopulateImportConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/TemplatePopulateImportConstants.java @@ -20,124 +20,124 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class TemplatePopulateImportConstants { - //columns sizes - public final static int SMALL_COL_SIZE =4000; - public final static int MEDIUM_COL_SIZE =6000; - public final static int LARGE_COL_SIZE=8000; - public final static int EXTRALARGE_COL_SIZE=10000; + // columns sizes + public final static int SMALL_COL_SIZE = 4000; + public final static int MEDIUM_COL_SIZE = 6000; + public final static int LARGE_COL_SIZE = 8000; + public final static int EXTRALARGE_COL_SIZE = 10000; - //Sheet names - public static final String OFFICE_SHEET_NAME ="Offices"; - public static final String CENTER_SHEET_NAME="Centers"; - public static final String STAFF_SHEET_NAME="Staff"; - public static final String GROUP_SHEET_NAME="Groups"; - public static final String CHART_OF_ACCOUNTS_SHEET_NAME="ChartOfAccounts"; - public static final String CLIENT_ENTITY_SHEET_NAME="ClientEntity"; - public static final String CLIENT_PERSON_SHEET_NAME="ClientPerson"; - public static final String CLIENT_SHEET_NAME="Clients"; - public static final String FIXED_DEPOSIT_SHEET_NAME="FixedDeposit"; - public static final String FIXED_DEPOSIT_TRANSACTION_SHEET_NAME="FixedDepositTransactions"; - public static final String PRODUCT_SHEET_NAME="Products"; - public static final String GUARANTOR_SHEET_NAME="guarantor"; - public static final String EXTRAS_SHEET_NAME="Extras"; - public static final String GL_ACCOUNTS_SHEET_NAME="GlAccounts"; - public static final String SAVINGS_ACCOUNTS_SHEET_NAME="SavingsAccounts"; - public static final String SHARED_PRODUCTS_SHEET_NAME="SharedProducts"; - public static final String JOURNAL_ENTRY_SHEET_NAME="AddJournalEntries"; - public static final String LOANS_SHEET_NAME="Loans"; - public static final String LOAN_REPAYMENT_SHEET_NAME="LoanRepayment"; - public static final String RECURRING_DEPOSIT_SHEET_NAME="RecurringDeposit"; - public static final String SAVINGS_TRANSACTION_SHEET_NAME="SavingsTransaction"; - public static final String SHARED_ACCOUNTS_SHEET_NAME="SharedAccounts"; - public static final String EMPLOYEE_SHEET_NAME="Employee"; - public static final String ROLES_SHEET_NAME="Roles"; - public static final String USER_SHEET_NAME="Users"; + // Sheet names + public static final String OFFICE_SHEET_NAME = "Offices"; + public static final String CENTER_SHEET_NAME = "Centers"; + public static final String STAFF_SHEET_NAME = "Staff"; + public static final String GROUP_SHEET_NAME = "Groups"; + public static final String CHART_OF_ACCOUNTS_SHEET_NAME = "ChartOfAccounts"; + public static final String CLIENT_ENTITY_SHEET_NAME = "ClientEntity"; + public static final String CLIENT_PERSON_SHEET_NAME = "ClientPerson"; + public static final String CLIENT_SHEET_NAME = "Clients"; + public static final String FIXED_DEPOSIT_SHEET_NAME = "FixedDeposit"; + public static final String FIXED_DEPOSIT_TRANSACTION_SHEET_NAME = "FixedDepositTransactions"; + public static final String PRODUCT_SHEET_NAME = "Products"; + public static final String GUARANTOR_SHEET_NAME = "guarantor"; + public static final String EXTRAS_SHEET_NAME = "Extras"; + public static final String GL_ACCOUNTS_SHEET_NAME = "GlAccounts"; + public static final String SAVINGS_ACCOUNTS_SHEET_NAME = "SavingsAccounts"; + public static final String SHARED_PRODUCTS_SHEET_NAME = "SharedProducts"; + public static final String JOURNAL_ENTRY_SHEET_NAME = "AddJournalEntries"; + public static final String LOANS_SHEET_NAME = "Loans"; + public static final String LOAN_REPAYMENT_SHEET_NAME = "LoanRepayment"; + public static final String RECURRING_DEPOSIT_SHEET_NAME = "RecurringDeposit"; + public static final String SAVINGS_TRANSACTION_SHEET_NAME = "SavingsTransaction"; + public static final String SHARED_ACCOUNTS_SHEET_NAME = "SharedAccounts"; + public static final String EMPLOYEE_SHEET_NAME = "Employee"; + public static final String ROLES_SHEET_NAME = "Roles"; + public static final String USER_SHEET_NAME = "Users"; - public final static int ROWHEADER_INDEX=0; - public final static short ROW_HEADER_HEIGHT =500; - public final static int FIRST_COLUMN_INDEX=0; + public final static int ROWHEADER_INDEX = 0; + public final static short ROW_HEADER_HEIGHT = 500; + public final static int FIRST_COLUMN_INDEX = 0; - //Status column - public final static String STATUS_CELL_IMPORTED="Imported"; - public final static String STATUS_CREATION_FAILED="Creation failed"; - public final static String STATUS_APPROVAL_FAILED="Approval failed"; - public final static String STATUS_ACTIVATION_FAILED="Activation failed"; - public final static String STATUS_MEETING_FAILED="Meeting failed"; - public final static String STATUS_DISBURSAL_FAILED="Disbursal failed"; - public final static String STATUS_DISBURSAL_REPAYMENT_FAILED="Repayment failed"; - public final static String STATUS_COLUMN_HEADER="Status"; + // Status column + public final static String STATUS_CELL_IMPORTED = "Imported"; + public final static String STATUS_CREATION_FAILED = "Creation failed"; + public final static String STATUS_APPROVAL_FAILED = "Approval failed"; + public final static String STATUS_ACTIVATION_FAILED = "Activation failed"; + public final static String STATUS_MEETING_FAILED = "Meeting failed"; + public final static String STATUS_DISBURSAL_FAILED = "Disbursal failed"; + public final static String STATUS_DISBURSAL_REPAYMENT_FAILED = "Repayment failed"; + public final static String STATUS_COLUMN_HEADER = "Status"; - //Frequency Calender - public static final String FREQUENCY_DAILY="Daily"; - public static final String FREQUENCY_WEEKLY="Weekly"; - public static final String FREQUENCY_MONTHLY="Monthly"; - public static final String FREQUENCY_YEARLY= "Yearly"; + // Frequency Calender + public static final String FREQUENCY_DAILY = "Daily"; + public static final String FREQUENCY_WEEKLY = "Weekly"; + public static final String FREQUENCY_MONTHLY = "Monthly"; + public static final String FREQUENCY_YEARLY = "Yearly"; - //InterestCompoundingPeriod - public static final String INTEREST_COMPOUNDING_PERIOD_DAILY="Daily"; - public static final String INTEREST_COMPOUNDING_PERIOD_MONTHLY="Monthly"; - public static final String INTEREST_COMPOUNDING_PERIOD_QUARTERLY="Quarterly"; - public static final String INTEREST_COMPOUNDING_PERIOD_SEMI_ANNUALLY="Semi-Annual"; - public static final String INTEREST_COMPOUNDING_PERIOD_ANNUALLY="Annually"; + // InterestCompoundingPeriod + public static final String INTEREST_COMPOUNDING_PERIOD_DAILY = "Daily"; + public static final String INTEREST_COMPOUNDING_PERIOD_MONTHLY = "Monthly"; + public static final String INTEREST_COMPOUNDING_PERIOD_QUARTERLY = "Quarterly"; + public static final String INTEREST_COMPOUNDING_PERIOD_SEMI_ANNUALLY = "Semi-Annual"; + public static final String INTEREST_COMPOUNDING_PERIOD_ANNUALLY = "Annually"; - //InterestPostingPeriod - public static final String INTEREST_POSTING_PERIOD_MONTHLY="Monthly"; - public static final String INTEREST_POSTING_PERIOD_QUARTERLY="Quarterly"; - public static final String INTEREST_POSTING_PERIOD_BIANUALLY="BiAnnual"; - public static final String INTEREST_POSTING_PERIOD_ANNUALLY="Annually"; + // InterestPostingPeriod + public static final String INTEREST_POSTING_PERIOD_MONTHLY = "Monthly"; + public static final String INTEREST_POSTING_PERIOD_QUARTERLY = "Quarterly"; + public static final String INTEREST_POSTING_PERIOD_BIANUALLY = "BiAnnual"; + public static final String INTEREST_POSTING_PERIOD_ANNUALLY = "Annually"; - //InterestCalculation - public static final String INTEREST_CAL_DAILY_BALANCE="Daily Balance"; - public static final String INTEREST_CAL_AVG_BALANCE="Average Daily Balance"; + // InterestCalculation + public static final String INTEREST_CAL_DAILY_BALANCE = "Daily Balance"; + public static final String INTEREST_CAL_AVG_BALANCE = "Average Daily Balance"; - //InterestCalculation Day in Year - public static final String INTEREST_CAL_DAYS_IN_YEAR_360="360 Days"; - public static final String INTEREST_CAL_DAYS_IN_YEAR_365="365 Days"; + // InterestCalculation Day in Year + public static final String INTEREST_CAL_DAYS_IN_YEAR_360 = "360 Days"; + public static final String INTEREST_CAL_DAYS_IN_YEAR_365 = "365 Days"; - //Frequency - public static final String FREQUENCY_DAYS="Days"; - public static final String FREQUENCY_WEEKS="Weeks"; - public static final String FREQUENCY_MONTHS="Months"; - public static final String FREQUENCY_YEARS="Years"; + // Frequency + public static final String FREQUENCY_DAYS = "Days"; + public static final String FREQUENCY_WEEKS = "Weeks"; + public static final String FREQUENCY_MONTHS = "Months"; + public static final String FREQUENCY_YEARS = "Years"; - //Day Of Week - public static final String MONDAY ="Mon"; - public static final String TUESDAY ="Tue"; - public static final String WEDNESDAY ="Wed"; - public static final String THURSDAY ="Thu"; - public static final String FRIDAY ="Fri"; - public static final String SATURDAY ="Sat"; - public static final String SUNDAY ="Sun"; + // Day Of Week + public static final String MONDAY = "Mon"; + public static final String TUESDAY = "Tue"; + public static final String WEDNESDAY = "Wed"; + public static final String THURSDAY = "Thu"; + public static final String FRIDAY = "Fri"; + public static final String SATURDAY = "Sat"; + public static final String SUNDAY = "Sun"; - //Entity types - public static final String CENTER_ENTITY_TYPE="CENTER"; - public static final String OFFICE_ENTITY_TYPE="OFFICE"; - public static final String STAFF_ENTITY_TYPE="STAFF"; - public static final String USER_ENTITY_TYPE="USER"; - public static final String GROUP_ENTITY_TYPE="GROUP"; - public static final String CLIENT_ENTITY_TYPE="CLIENT"; - public static final String LOAN_PRODUCT_ENTITY_TYPE="LOANPRODUCT"; - public static final String FUNDS_ENTITY_TYPE="FUNDS"; - public static final String PAYMENT_TYPE_ENTITY_TYPE="PAYMENTTYPE"; - public static final String CURRENCY_ENTITY_TYPE="CURRENCY"; - public static final String GL_ACCOUNT_ENTITY_TYPE="GLACCOUNT"; - public static final String SHARED_ACCOUNT_ENTITY_TYPE="SHAREDACCOUNT"; - public static final String SAVINGS_PRODUCT_ENTITY_TYPE="SAVINGSPRODUCT"; - public static final String RECURRING_DEPOSIT_PRODUCT_ENTITY_TYPE="RECURRINGDEPOSITPRODUCT"; - public static final String FIXED_DEPOSIT_PRODUCT_ENTITY_TYPE="FIXEDDEPOSITPRODUCT"; + // Entity types + public static final String CENTER_ENTITY_TYPE = "CENTER"; + public static final String OFFICE_ENTITY_TYPE = "OFFICE"; + public static final String STAFF_ENTITY_TYPE = "STAFF"; + public static final String USER_ENTITY_TYPE = "USER"; + public static final String GROUP_ENTITY_TYPE = "GROUP"; + public static final String CLIENT_ENTITY_TYPE = "CLIENT"; + public static final String LOAN_PRODUCT_ENTITY_TYPE = "LOANPRODUCT"; + public static final String FUNDS_ENTITY_TYPE = "FUNDS"; + public static final String PAYMENT_TYPE_ENTITY_TYPE = "PAYMENTTYPE"; + public static final String CURRENCY_ENTITY_TYPE = "CURRENCY"; + public static final String GL_ACCOUNT_ENTITY_TYPE = "GLACCOUNT"; + public static final String SHARED_ACCOUNT_ENTITY_TYPE = "SHAREDACCOUNT"; + public static final String SAVINGS_PRODUCT_ENTITY_TYPE = "SAVINGSPRODUCT"; + public static final String RECURRING_DEPOSIT_PRODUCT_ENTITY_TYPE = "RECURRINGDEPOSITPRODUCT"; + public static final String FIXED_DEPOSIT_PRODUCT_ENTITY_TYPE = "FIXEDDEPOSITPRODUCT"; - //ReportHeader Values - public static final String STATUS_COL_REPORT_HEADER="Status"; - public static final String CENTERID_COL_REPORT_HEADER="Center Id"; - public static final String SAVINGS_ID_COL_REPORT_HEADER="Savings ID"; - public static final String GROUP_ID_COL_REPORT_HEADER="Group ID"; - public static final String FAILURE_COL_REPORT_HEADER="Failure Report"; + // ReportHeader Values + public static final String STATUS_COL_REPORT_HEADER = "Status"; + public static final String CENTERID_COL_REPORT_HEADER = "Center Id"; + public static final String SAVINGS_ID_COL_REPORT_HEADER = "Savings ID"; + public static final String GROUP_ID_COL_REPORT_HEADER = "Group ID"; + public static final String FAILURE_COL_REPORT_HEADER = "Failure Report"; - //Guarantor Types - public static final String GUARANTOR_INTERNAL="Internal"; - public static final String GUARANTOR_EXTERNAL="External"; + // Guarantor Types + public static final String GUARANTOR_INTERNAL = "Internal"; + public static final String GUARANTOR_EXTERNAL = "External"; - //Loan Account/Loan repayment Client External Id - public static final Boolean CONTAINS_CLIENT_EXTERNAL_ID=true; + // Loan Account/Loan repayment Client External Id + public static final Boolean CONTAINS_CLIENT_EXTERNAL_ID = true; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/UserConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/UserConstants.java index b9b6c4c51..699ab22a3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/UserConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/constants/UserConstants.java @@ -19,16 +19,17 @@ package org.apache.fineract.infrastructure.bulkimport.constants; public class UserConstants { - public static final int OFFICE_NAME_COL=0; - public static final int STAFF_NAME_COL=1; - public static final int USER_NAME_COL=2; - public static final int FIRST_NAME_COL=3; - public static final int LAST_NAME_COL=4; - public static final int EMAIL_COL=5; - public static final int AUTO_GEN_PW_COL=6; - public static final int OVERRIDE_PW_EXPIRY_POLICY_COL=7; - public static final int STATUS_COL=8; - public static final int ROLE_NAME_START_COL=9; - public static final int ROLE_NAME_END_COL=14; + + public static final int OFFICE_NAME_COL = 0; + public static final int STAFF_NAME_COL = 1; + public static final int USER_NAME_COL = 2; + public static final int FIRST_NAME_COL = 3; + public static final int LAST_NAME_COL = 4; + public static final int EMAIL_COL = 5; + public static final int AUTO_GEN_PW_COL = 6; + public static final int OVERRIDE_PW_EXPIRY_POLICY_COL = 7; + public static final int STATUS_COL = 8; + public static final int ROLE_NAME_START_COL = 9; + public static final int ROLE_NAME_END_COL = 14; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/BulkImportEvent.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/BulkImportEvent.java index 0a493663d..66dd11b46 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/BulkImportEvent.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/BulkImportEvent.java @@ -33,8 +33,8 @@ public class BulkImportEvent extends ApplicationEvent { private final String dateFormat; - private BulkImportEvent(final String tenantIdentifier, final Workbook workbook, - final Long importId, final String locale, final String dateFormat) { + private BulkImportEvent(final String tenantIdentifier, final Workbook workbook, final Long importId, final String locale, + final String dateFormat) { super(BulkImportEvent.class); this.tenantIdentifier = tenantIdentifier; this.workbook = workbook; @@ -43,8 +43,8 @@ public class BulkImportEvent extends ApplicationEvent { this.dateFormat = dateFormat; } - public static BulkImportEvent instance(final String tenantIdentifier, final Workbook workbook, - final Long importId, final String locale, final String dateFormat) { + public static BulkImportEvent instance(final String tenantIdentifier, final Workbook workbook, final Long importId, final String locale, + final String dateFormat) { return new BulkImportEvent(tenantIdentifier, workbook, importId, locale, dateFormat); } @@ -68,4 +68,4 @@ public class BulkImportEvent extends ApplicationEvent { return locale; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/Count.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/Count.java index c4926c19b..be7312320 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/Count.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/Count.java @@ -23,14 +23,12 @@ public class Count { private Integer successCount; private Integer errorCount; - public static Count instance(final Integer successCount, - final Integer errorCount) { + public static Count instance(final Integer successCount, final Integer errorCount) { return new Count(successCount, errorCount); } - private Count(final Integer successCount, - final Integer errorCount) { - this.successCount = successCount; + private Count(final Integer successCount, final Integer errorCount) { + this.successCount = successCount; this.errorCount = errorCount; } @@ -42,4 +40,4 @@ public class Count { return errorCount; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/GlobalEntityType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/GlobalEntityType.java index bb99a544a..39dc86f38 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/GlobalEntityType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/GlobalEntityType.java @@ -23,43 +23,24 @@ import java.util.Map; public enum GlobalEntityType { - - INVALID(0, "invalid"), - CLIENTS_PERSON(1, "clients.person"), - CLIENTS_ENTTTY(2,"clients.entity"), - GROUPS(3, "groups"), - CENTERS(4, "centers"), - OFFICES(5, "offices"), - STAFF(6, "staff"), - USERS(7, "users"), - SMS(8, "sms"), - DOCUMENTS(9, "documents"), - TEMPLATES(10, "templates"), - NOTES(11, "templates"), - CALENDAR(12, "calendar"), - MEETINGS(13, "meetings"), - HOLIDAYS(14, "holidays"), - LOANS(15, "loans"), - LOAN_PRODUCTS(16,"loancharges"), - LOAN_TRANSACTIONS(18, "loantransactions"), - GUARANTORS(19, "guarantors"), - COLLATERALS(20, "collaterals"), - FUNDS(21, "funds"), - CURRENCY(22, "currencies"), - SAVINGS_ACCOUNT(23, "savingsaccount"), - SAVINGS_CHARGES(24, "savingscharges"), - SAVINGS_TRANSACTIONS(25, "savingstransactions"), - SAVINGS_PRODUCTS(26, "savingsproducts"), - GL_JOURNAL_ENTRIES(27, "gljournalentries"), - CODE_VALUE(28, "codevalue"), - CODE(29, "code"), - CHART_OF_ACCOUNTS(30,"chartofaccounts"), - FIXED_DEPOSIT_ACCOUNTS(31,"fixeddepositaccounts"), - FIXED_DEPOSIT_TRANSACTIONS(32,"fixeddeposittransactions"), - SHARE_ACCOUNTS(33,"shareaccounts"), - RECURRING_DEPOSIT_ACCOUNTS(34,"recurringdeposits"), - RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS(35,"recurringdepositstransactions"), - CLIENT(36,"client"); + INVALID(0, "invalid"), CLIENTS_PERSON(1, "clients.person"), CLIENTS_ENTTTY(2, "clients.entity"), GROUPS(3, "groups"), CENTERS(4, + "centers"), OFFICES(5, "offices"), STAFF(6, "staff"), USERS(7, "users"), SMS(8, "sms"), DOCUMENTS(9, "documents"), TEMPLATES(10, + "templates"), NOTES(11, "templates"), CALENDAR(12, "calendar"), MEETINGS(13, "meetings"), HOLIDAYS(14, + "holidays"), LOANS(15, "loans"), LOAN_PRODUCTS(16, "loancharges"), LOAN_TRANSACTIONS(18, + "loantransactions"), GUARANTORS(19, "guarantors"), COLLATERALS(20, "collaterals"), FUNDS(21, + "funds"), CURRENCY(22, "currencies"), SAVINGS_ACCOUNT(23, "savingsaccount"), SAVINGS_CHARGES(24, + "savingscharges"), SAVINGS_TRANSACTIONS(25, "savingstransactions"), SAVINGS_PRODUCTS(26, + "savingsproducts"), GL_JOURNAL_ENTRIES(27, "gljournalentries"), CODE_VALUE(28, + "codevalue"), CODE(29, "code"), CHART_OF_ACCOUNTS(30, + "chartofaccounts"), FIXED_DEPOSIT_ACCOUNTS(31, + "fixeddepositaccounts"), FIXED_DEPOSIT_TRANSACTIONS(32, + "fixeddeposittransactions"), SHARE_ACCOUNTS(33, + "shareaccounts"), RECURRING_DEPOSIT_ACCOUNTS( + 34, + "recurringdeposits"), RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS( + 35, + "recurringdepositstransactions"), CLIENT( + 36, "client"); private final Integer value; private final String code; @@ -115,4 +96,4 @@ public enum GlobalEntityType { return name().toString(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/ImportData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/ImportData.java index 635a6a94a..83499308a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/ImportData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/ImportData.java @@ -43,27 +43,20 @@ public class ImportData { @SuppressWarnings("unused") private Integer failureCount; - public static ImportData instance(final Long importId, final Long documentId, - final LocalDate importTime, final LocalDate endTime, - final Boolean completed, final String name, - final Long createdBy, final Integer totalRecords, final Integer successCount, - final Integer failureCount) { - return new ImportData(importId, documentId, importTime, endTime, - completed, name, createdBy, totalRecords, successCount, + public static ImportData instance(final Long importId, final Long documentId, final LocalDate importTime, final LocalDate endTime, + final Boolean completed, final String name, final Long createdBy, final Integer totalRecords, final Integer successCount, + final Integer failureCount) { + return new ImportData(importId, documentId, importTime, endTime, completed, name, createdBy, totalRecords, successCount, failureCount); } - public static ImportData instance(final Long importId){ - return new ImportData(importId,null,null, - null,null,null,null,null, - null,null); + public static ImportData instance(final Long importId) { + return new ImportData(importId, null, null, null, null, null, null, null, null, null); } - private ImportData(final Long importId, final Long documentId, - final LocalDate importTime, final LocalDate endTime, - final Boolean completed, final String name, - final Long createdBy, final Integer totalRecords, final Integer successCount, - final Integer failureCount) { + private ImportData(final Long importId, final Long documentId, final LocalDate importTime, final LocalDate endTime, + final Boolean completed, final String name, final Long createdBy, final Integer totalRecords, final Integer successCount, + final Integer failureCount) { this.importId = importId; this.documentId = documentId; this.name = name; @@ -76,5 +69,4 @@ public class ImportData { this.failureCount = failureCount; } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/ImportFormatType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/ImportFormatType.java index 29bbe61a9..93e83609b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/ImportFormatType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/data/ImportFormatType.java @@ -22,15 +22,13 @@ import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRu public enum ImportFormatType { - XLSX ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), - XLS ("application/vnd.ms-excel"), - ODS ("application/vnd.oasis.opendocument.spreadsheet"); - + XLSX("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), XLS("application/vnd.ms-excel"), ODS( + "application/vnd.oasis.opendocument.spreadsheet"); private final String format; private ImportFormatType(String format) { - this.format= format; + this.format = format; } public String getFormat() { @@ -38,12 +36,9 @@ public enum ImportFormatType { } public static ImportFormatType of(String name) { - for(ImportFormatType type : ImportFormatType.values()) { - if(type.name().equalsIgnoreCase(name)) { - return type; - } + for (ImportFormatType type : ImportFormatType.values()) { + if (type.name().equalsIgnoreCase(name)) { return type; } } - throw new GeneralPlatformDomainRuleException("error.msg.invalid.file.extension", - "Uploaded file extension is not recognized."); + throw new GeneralPlatformDomainRuleException("error.msg.invalid.file.extension", "Uploaded file extension is not recognized."); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/domain/ImportDocument.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/domain/ImportDocument.java index a8d8a7eb8..ad006d873 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/domain/ImportDocument.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/domain/ImportDocument.java @@ -34,7 +34,7 @@ import org.joda.time.LocalDateTime; @Entity @Table(name = "m_import_document") -public class ImportDocument extends AbstractPersistableCustom{ +public class ImportDocument extends AbstractPersistableCustom { @OneToOne @JoinColumn(name = "document_id") @@ -71,21 +71,20 @@ public class ImportDocument extends AbstractPersistableCustom{ } - public static ImportDocument instance(final Document document, final LocalDateTime importTime, - final Integer entity_type, final AppUser createdBy, final Integer totalRecords) { + public static ImportDocument instance(final Document document, final LocalDateTime importTime, final Integer entity_type, + final AppUser createdBy, final Integer totalRecords) { final Boolean completed = Boolean.FALSE; final Integer successCount = 0; final Integer failureCount = 0; final LocalDateTime endTime = LocalDateTime.now(); - return new ImportDocument(document, importTime, endTime, completed, entity_type, - createdBy, totalRecords, successCount, failureCount); + return new ImportDocument(document, importTime, endTime, completed, entity_type, createdBy, totalRecords, successCount, + failureCount); } - private ImportDocument(final Document document, final LocalDateTime importTime, - final LocalDateTime endTime, Boolean completed, final Integer entity_type, - final AppUser createdBy, final Integer totalRecords, final Integer successCount, + private ImportDocument(final Document document, final LocalDateTime importTime, final LocalDateTime endTime, Boolean completed, + final Integer entity_type, final AppUser createdBy, final Integer totalRecords, final Integer successCount, final Integer failureCount) { this.document = document; this.importTime = importTime.toDate(); @@ -99,8 +98,7 @@ public class ImportDocument extends AbstractPersistableCustom{ } - public void update(final LocalDateTime endTime, final Integer successCount, - final Integer errorCount) { + public void update(final LocalDateTime endTime, final Integer successCount, final Integer errorCount) { this.endTime = endTime.toDate(); this.completed = Boolean.TRUE; this.successCount = successCount; @@ -115,7 +113,4 @@ public class ImportDocument extends AbstractPersistableCustom{ return this.entity_type; } - - - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/domain/ImportDocumentRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/domain/ImportDocumentRepository.java index 18e0d3d73..55a770a75 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/domain/ImportDocumentRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/domain/ImportDocumentRepository.java @@ -21,7 +21,6 @@ package org.apache.fineract.infrastructure.bulkimport.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface ImportDocumentRepository - extends JpaRepository, JpaSpecificationExecutor { +public interface ImportDocumentRepository extends JpaRepository, JpaSpecificationExecutor { // no added behaviour } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/exceptions/ImportTypeNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/exceptions/ImportTypeNotFoundException.java index 2754c2ac7..5144b8d68 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/exceptions/ImportTypeNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/exceptions/ImportTypeNotFoundException.java @@ -26,4 +26,4 @@ public class ImportTypeNotFoundException extends AbstractPlatformResourceNotFoun super("error.msg.entity.type.invalid", "Entity type " + entityType + " does not exist", entityType); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/ImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/ImportHandler.java index e185d3888..6aacc5b70 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/ImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/ImportHandler.java @@ -22,6 +22,6 @@ import org.apache.fineract.infrastructure.bulkimport.data.Count; import org.apache.poi.ss.usermodel.Workbook; public interface ImportHandler { + public Count process(Workbook workbook, String locale, String dateFormat); } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/ImportHandlerUtils.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/ImportHandlerUtils.java index fba1eb360..bf1d7a730 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/ImportHandlerUtils.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/ImportHandlerUtils.java @@ -47,7 +47,7 @@ public class ImportHandlerUtils { Integer noOfEntries = 0; // getLastRowNum and getPhysicalNumberOfRows showing false values // sometimes - while (sheet.getRow(noOfEntries+1) !=null && sheet.getRow(noOfEntries+1).getCell(primaryColumn) != null) { + while (sheet.getRow(noOfEntries + 1) != null && sheet.getRow(noOfEntries + 1).getCell(primaryColumn) != null) { noOfEntries++; } @@ -55,85 +55,77 @@ public class ImportHandlerUtils { } public static boolean isNotImported(Row row, int statusColumn) { - if (readAsString(statusColumn,row)!=null) { + if (readAsString(statusColumn, row) != null) { return !readAsString(statusColumn, row).equals(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); - }else { + } else { return true; } } public static Long readAsLong(int colIndex, Row row) { Cell c = row.getCell(colIndex); - if (c == null || c.getCellType() == CellType.BLANK) { - return null; - } + if (c == null || c.getCellType() == CellType.BLANK) { return null; } FormulaEvaluator eval = row.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - if(c.getCellType() == CellType.FORMULA) { - if(eval!=null) { + if (c.getCellType() == CellType.FORMULA) { + if (eval != null) { CellValue val = null; try { val = eval.evaluate(c); } catch (NullPointerException npe) { return null; } - return ((Double)val.getNumberValue()).longValue(); + return ((Double) val.getNumberValue()).longValue(); } - } - else if (c.getCellType()==CellType.NUMERIC){ + } else if (c.getCellType() == CellType.NUMERIC) { return ((Double) c.getNumericCellValue()).longValue(); - } - else { + } else { return Long.parseLong(row.getCell(colIndex).getStringCellValue()); } return null; } - public static String readAsString(int colIndex, Row row) { Cell c = row.getCell(colIndex); - if (c == null || c.getCellType() == CellType.BLANK) { - return null; - } + if (c == null || c.getCellType() == CellType.BLANK) { return null; } FormulaEvaluator eval = row.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - if(c.getCellType() == CellType.FORMULA) { - if (eval!=null) { + if (c.getCellType() == CellType.FORMULA) { + if (eval != null) { CellValue val = null; try { val = eval.evaluate(c); - } catch(NullPointerException npe) { + } catch (NullPointerException npe) { return null; } String res = trimEmptyDecimalPortion(val.getStringValue()); - if (res!=null) { + if (res != null) { if (!res.equals("")) { return res.trim(); } else { return null; } - }else { + } else { return null; } - }else { + } else { return null; } - }else if(c.getCellType()==CellType.STRING) { + } else if (c.getCellType() == CellType.STRING) { String res = trimEmptyDecimalPortion(c.getStringCellValue().trim()); return res.trim(); - }else if(c.getCellType()==CellType.NUMERIC) { + } else if (c.getCellType() == CellType.NUMERIC) { return ((Double) row.getCell(colIndex).getNumericCellValue()).intValue() + ""; - }else if (c.getCellType()==CellType.BOOLEAN){ - return c.getBooleanCellValue()+""; - }else { + } else if (c.getCellType() == CellType.BOOLEAN) { + return c.getBooleanCellValue() + ""; + } else { return null; } } - public static String trimEmptyDecimalPortion(String result) { - if(result != null && result.endsWith(".0")) { + if (result != null && result.endsWith(".0")) { return result.split("\\.")[0]; } else { return result; @@ -142,94 +134,86 @@ public class ImportHandlerUtils { public static LocalDate readAsDate(int colIndex, Row row) { Cell c = row.getCell(colIndex); - if(c == null || c.getCellType() == CellType.BLANK) { - return null; - } + if (c == null || c.getCellType() == CellType.BLANK) { return null; } - LocalDate localDate=new LocalDate(c.getDateCellValue()); + LocalDate localDate = new LocalDate(c.getDateCellValue()); return localDate; } public static Boolean readAsBoolean(int colIndex, Row row) { - Cell c = row.getCell(colIndex); - if(c == null || c.getCellType() == CellType.BLANK) { - return false; - } - FormulaEvaluator eval = row.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - if(c.getCellType() == CellType.FORMULA) { - if(eval!=null) { - CellValue val = null; - try { - val = eval.evaluate(c); - } catch (NullPointerException npe) { - return false; - } - return val.getBooleanValue(); - } - return false; - }else if(c.getCellType()==CellType.BOOLEAN) { - return c.getBooleanCellValue(); - } else { - String booleanString = row.getCell(colIndex).getStringCellValue().trim(); - if (booleanString.equalsIgnoreCase("TRUE")) { - return true; - } else { + Cell c = row.getCell(colIndex); + if (c == null || c.getCellType() == CellType.BLANK) { return false; } + FormulaEvaluator eval = row.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); + if (c.getCellType() == CellType.FORMULA) { + if (eval != null) { + CellValue val = null; + try { + val = eval.evaluate(c); + } catch (NullPointerException npe) { return false; } + return val.getBooleanValue(); + } + return false; + } else if (c.getCellType() == CellType.BOOLEAN) { + return c.getBooleanCellValue(); + } else { + String booleanString = row.getCell(colIndex).getStringCellValue().trim(); + if (booleanString.equalsIgnoreCase("TRUE")) { + return true; + } else { + return false; } } + } public static Integer readAsInt(int colIndex, Row row) { - Cell c = row.getCell(colIndex); - if (c == null || c.getCellType() == CellType.BLANK) { - return null; - } - FormulaEvaluator eval = row.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - if(c.getCellType() == CellType.FORMULA) { - if(eval!=null) { - CellValue val = null; - try { - val = eval.evaluate(c); - } catch (NullPointerException npe) { - return null; - } - return ((Double)val.getNumberValue()).intValue(); + Cell c = row.getCell(colIndex); + if (c == null || c.getCellType() == CellType.BLANK) { return null; } + FormulaEvaluator eval = row.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); + if (c.getCellType() == CellType.FORMULA) { + if (eval != null) { + CellValue val = null; + try { + val = eval.evaluate(c); + } catch (NullPointerException npe) { + return null; } - return null; - }else if (c.getCellType()==CellType.NUMERIC) { - return ((Double) c.getNumericCellValue()).intValue(); - }else { - return Integer.parseInt(row.getCell(colIndex).getStringCellValue()); + return ((Double) val.getNumberValue()).intValue(); } + return null; + } else if (c.getCellType() == CellType.NUMERIC) { + return ((Double) c.getNumericCellValue()).intValue(); + } else { + return Integer.parseInt(row.getCell(colIndex).getStringCellValue()); + } } public static Double readAsDouble(int colIndex, Row row) { Cell c = row.getCell(colIndex); - if (c == null || c.getCellType() == CellType.BLANK) { - return 0.0; - } + if (c == null || c.getCellType() == CellType.BLANK) { return 0.0; } FormulaEvaluator eval = row.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - if(c.getCellType() == CellType.FORMULA) { - if (eval!=null) { - CellValue val = null; - try { - val = eval.evaluate(c); - } catch (NullPointerException npe) { - return 0.0; - } - return val.getNumberValue(); - }else { + if (c.getCellType() == CellType.FORMULA) { + if (eval != null) { + CellValue val = null; + try { + val = eval.evaluate(c); + } catch (NullPointerException npe) { return 0.0; } - } else if (c.getCellType()==CellType.NUMERIC) { + return val.getNumberValue(); + } else { + return 0.0; + } + } else if (c.getCellType() == CellType.NUMERIC) { return row.getCell(colIndex).getNumericCellValue(); - }else { + } else { return Double.parseDouble(row.getCell(colIndex).getStringCellValue()); } } public static void writeString(int colIndex, Row row, String value) { - if(value!=null) { + if (value != null) { row.createCell(colIndex).setCellValue(value); } } @@ -237,7 +221,8 @@ public class ImportHandlerUtils { public static CellStyle getCellStyle(Workbook workbook, IndexedColors color) { CellReference cellReference = new CellReference("A1"); Sheet predefined = workbook.getSheet(color.toString()); - // if we have already defined this style, return it and don't create another one + // if we have already defined this style, return it and don't create + // another one if (predefined != null) { Row row = predefined.getRow(cellReference.getRow()); Cell cell = row.getCell(cellReference.getCol()); @@ -256,70 +241,70 @@ public class ImportHandlerUtils { return style; } - public static String getDefaultUserMessages(List ApiParameterErrorList){ - StringBuilder defaultUserMessages=new StringBuilder(); - for (ApiParameterError error:ApiParameterErrorList) { - defaultUserMessages=defaultUserMessages.append(error.getDefaultUserMessage()+'\t'); + public static String getDefaultUserMessages(List ApiParameterErrorList) { + StringBuilder defaultUserMessages = new StringBuilder(); + for (ApiParameterError error : ApiParameterErrorList) { + defaultUserMessages = defaultUserMessages.append(error.getDefaultUserMessage() + '\t'); } return defaultUserMessages.toString(); } - public static String getErrorList(List errorList){ - StringBuilder errors=new StringBuilder(); - for (String error: errorList) { - errors=errors.append(error); + + public static String getErrorList(List errorList) { + StringBuilder errors = new StringBuilder(); + for (String error : errorList) { + errors = errors.append(error); } return errors.toString(); } - public static void writeErrorMessage(Sheet sheet,Integer rowIndex,String errorMessage,int statusColumn){ + public static void writeErrorMessage(Sheet sheet, Integer rowIndex, String errorMessage, int statusColumn) { Cell statusCell = sheet.getRow(rowIndex).createCell(statusColumn); statusCell.setCellValue(errorMessage); statusCell.setCellStyle(getCellStyle(sheet.getWorkbook(), IndexedColors.RED)); } public static String getErrorMessage(RuntimeException re) { - if (re instanceof AbstractPlatformDomainRuleException){ - AbstractPlatformDomainRuleException abstractPlatformDomainRuleException= (AbstractPlatformDomainRuleException) re; + if (re instanceof AbstractPlatformDomainRuleException) { + AbstractPlatformDomainRuleException abstractPlatformDomainRuleException = (AbstractPlatformDomainRuleException) re; return abstractPlatformDomainRuleException.getDefaultUserMessage(); - }else if (re instanceof AbstractPlatformResourceNotFoundException){ - AbstractPlatformResourceNotFoundException abstractPlatformResourceNotFoundException= (AbstractPlatformResourceNotFoundException) re; - return abstractPlatformResourceNotFoundException.getDefaultUserMessage(); - }else if (re instanceof AbstractPlatformServiceUnavailableException) { + } else if (re instanceof AbstractPlatformResourceNotFoundException) { + AbstractPlatformResourceNotFoundException abstractPlatformResourceNotFoundException = (AbstractPlatformResourceNotFoundException) re; + return abstractPlatformResourceNotFoundException.getDefaultUserMessage(); + } else if (re instanceof AbstractPlatformServiceUnavailableException) { AbstractPlatformServiceUnavailableException abstractPlatformServiceUnavailableException = (AbstractPlatformServiceUnavailableException) re; return abstractPlatformServiceUnavailableException.getDefaultUserMessage(); - }else if (re instanceof PlatformDataIntegrityException){ - PlatformDataIntegrityException platformDataIntegrityException= (PlatformDataIntegrityException) re; + } else if (re instanceof PlatformDataIntegrityException) { + PlatformDataIntegrityException platformDataIntegrityException = (PlatformDataIntegrityException) re; return platformDataIntegrityException.getDefaultUserMessage(); - }else if (re instanceof PlatformApiDataValidationException){ - PlatformApiDataValidationException platformApiDataValidationException=(PlatformApiDataValidationException) re; + } else if (re instanceof PlatformApiDataValidationException) { + PlatformApiDataValidationException platformApiDataValidationException = (PlatformApiDataValidationException) re; return getDefaultUserMessages(platformApiDataValidationException.getErrors()); - }else if (re instanceof UnsupportedParameterException ){ - UnsupportedParameterException unsupportedParameterException= (UnsupportedParameterException) re; - return getErrorList(unsupportedParameterException.getUnsupportedParameters()); - }else { - if (re.getMessage()!=null) { + } else if (re instanceof UnsupportedParameterException) { + UnsupportedParameterException unsupportedParameterException = (UnsupportedParameterException) re; + return getErrorList(unsupportedParameterException.getUnsupportedParameters()); + } else { + if (re.getMessage() != null) { return re.getMessage(); - }else { + } else { return re.getClass().getCanonicalName(); } } } - public static Long getIdByName (Sheet sheet, String name) { + public static Long getIdByName(Sheet sheet, String name) { String sheetName = sheet.getSheetName(); - if(!sheetName.equals(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME)) { + if (!sheetName.equals(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME)) { for (Row row : sheet) { for (Cell cell : row) { - if(name!=null) { + if (name != null) { if (cell.getCellType() == CellType.STRING && cell.getRichStringCellValue().getString().trim().equals(name)) { - if (sheetName.equals(TemplatePopulateImportConstants.OFFICE_SHEET_NAME) || - sheetName.equals(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME) || - sheetName.equals(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME) || - sheetName.equals(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME)|| - sheetName.equals(TemplatePopulateImportConstants.ROLES_SHEET_NAME)) { + if (sheetName.equals(TemplatePopulateImportConstants.OFFICE_SHEET_NAME) + || sheetName.equals(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME) + || sheetName.equals(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME) + || sheetName.equals(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME) + || sheetName.equals(TemplatePopulateImportConstants.ROLES_SHEET_NAME)) { if (row.getCell(cell.getColumnIndex() - 1).getCellType() == CellType.NUMERIC) { - return ((Double) row.getCell(cell.getColumnIndex() - 1).getNumericCellValue()) - .longValue(); + return ((Double) row.getCell(cell.getColumnIndex() - 1).getNumericCellValue()).longValue(); } return 0L; } else if (sheetName.equals(TemplatePopulateImportConstants.CLIENT_SHEET_NAME) @@ -327,26 +312,25 @@ public class ImportHandlerUtils { || sheetName.equals(TemplatePopulateImportConstants.GROUP_SHEET_NAME) || sheetName.equals(TemplatePopulateImportConstants.STAFF_SHEET_NAME)) { if (row.getCell(cell.getColumnIndex() + 1).getCellType() == CellType.NUMERIC) { - return ((Double) row.getCell(cell.getColumnIndex() + 1).getNumericCellValue()) - .longValue(); + return ((Double) row.getCell(cell.getColumnIndex() + 1).getNumericCellValue()).longValue(); } } return 0L; } - }else { + } else { return 0L; } } } } else if (sheetName.equals(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME)) { - for(Row row : sheet) { - for(int i = 0; i < 2; i++) { + for (Row row : sheet) { + for (int i = 0; i < 2; i++) { if (name != null) { Cell cell = row.getCell(i); if (cell.getCellType() == CellType.STRING && cell.getRichStringCellValue().getString().trim().equals(name)) { return ((Double) row.getCell(cell.getColumnIndex() - 1).getNumericCellValue()).longValue(); } - }else { + } else { return 0L; } } @@ -354,18 +338,16 @@ public class ImportHandlerUtils { } return 0L; } + public static String getCodeByName(Sheet sheet, String name) { String sheetName = sheet.getSheetName(); sheetName.equals(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME); { for (Row row : sheet) { for (Cell cell : row) { - if (name!=null) { - if (cell.getCellType() == CellType.STRING - && cell.getRichStringCellValue().getString().trim() - .equals(name)) { - return row.getCell(cell.getColumnIndex() - 1) - .getStringCellValue().toString(); + if (name != null) { + if (cell.getCellType() == CellType.STRING && cell.getRichStringCellValue().getString().trim().equals(name)) { + return row.getCell(cell.getColumnIndex() - 1).getStringCellValue().toString(); } } @@ -376,7 +358,7 @@ public class ImportHandlerUtils { } public static String getFrequencyId(String frequency) { - if (frequency!=null) { + if (frequency != null) { if (frequency.equalsIgnoreCase(TemplatePopulateImportConstants.FREQUENCY_DAILY)) { frequency = "1"; } else if (frequency.equalsIgnoreCase(TemplatePopulateImportConstants.FREQUENCY_WEEKLY)) { @@ -387,13 +369,13 @@ public class ImportHandlerUtils { frequency = "4"; } return frequency; - }else { + } else { return null; } } public static String getRepeatsOnDayId(String repeatsOnDay) { - if (repeatsOnDay!=null) { + if (repeatsOnDay != null) { if (repeatsOnDay.equalsIgnoreCase(TemplatePopulateImportConstants.MONDAY)) { repeatsOnDay = "1"; } else if (repeatsOnDay.equalsIgnoreCase(TemplatePopulateImportConstants.TUESDAY)) { @@ -410,7 +392,7 @@ public class ImportHandlerUtils { repeatsOnDay = "7"; } return repeatsOnDay; - }else { + } else { return null; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/center/CenterImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/center/CenterImportHandler.java index dfbcdcb6f..477335932 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/center/CenterImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/center/CenterImportHandler.java @@ -51,30 +51,28 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; - @Service public class CenterImportHandler implements ImportHandler { private final static Logger LOG = LoggerFactory.getLogger(CenterImportHandler.class); private List centers; private List meetings; - private Liststatuses; + private List statuses; private Workbook workbook; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public CenterImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public CenterImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.centers=new ArrayList<>(); - this.meetings=new ArrayList<>(); - this.statuses=new ArrayList<>(); - this.workbook=workbook; + this.centers = new ArrayList<>(); + this.meetings = new ArrayList<>(); + this.statuses = new ArrayList<>(); + this.workbook = workbook; readExcelFile(locale, dateFormat); return importEntity(dateFormat); } @@ -83,38 +81,38 @@ public class CenterImportHandler implements ImportHandler { Sheet centersSheet = workbook.getSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME); Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(centersSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); - for (int rowIndex = 1; rowIndex <=noOfEntries; rowIndex++) { + for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row = centersSheet.getRow(rowIndex); - if(ImportHandlerUtils.isNotImported(row, CenterConstants.STATUS_COL)) { - centers.add(readCenter(row,locale,dateFormat)); - meetings.add(readMeeting(row,locale,dateFormat)); - } - } - } - - private CalendarData readMeeting(Row row,final String locale, final String dateFormat) { - LocalDate meetingStartDate = ImportHandlerUtils.readAsDate(CenterConstants.MEETING_START_DATE_COL, row); - Boolean isRepeating = ImportHandlerUtils.readAsBoolean(CenterConstants.IS_REPEATING_COL, row); - String frequency = ImportHandlerUtils.readAsString(CenterConstants.FREQUENCY_COL, row); - EnumOptionData frequencyEnum=new EnumOptionData(null,null,ImportHandlerUtils.getFrequencyId(frequency)); - Integer interval = ImportHandlerUtils.readAsInt(CenterConstants.INTERVAL_COL, row); - String repeatsOnDay = ImportHandlerUtils.readAsString(CenterConstants.REPEATS_ON_DAY_COL, row); - EnumOptionData repeatsOnDayEnum=new EnumOptionData(null,null,ImportHandlerUtils.getRepeatsOnDayId(repeatsOnDay)); - if(meetingStartDate==null) { - return null; - } else { - if(repeatsOnDay==null) { - return CalendarData.importInstanceNoRepeatsOnDay(meetingStartDate, isRepeating, frequencyEnum, interval, - row.getRowNum(), locale, dateFormat); - } else { - return CalendarData.importInstanceWithRepeatsOnDay(meetingStartDate, isRepeating, frequencyEnum, - interval, repeatsOnDayEnum, row.getRowNum(), locale, dateFormat); + row = centersSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, CenterConstants.STATUS_COL)) { + centers.add(readCenter(row, locale, dateFormat)); + meetings.add(readMeeting(row, locale, dateFormat)); } } } - private CenterData readCenter(Row row,final String locale, final String dateFormat) { + private CalendarData readMeeting(Row row, final String locale, final String dateFormat) { + LocalDate meetingStartDate = ImportHandlerUtils.readAsDate(CenterConstants.MEETING_START_DATE_COL, row); + Boolean isRepeating = ImportHandlerUtils.readAsBoolean(CenterConstants.IS_REPEATING_COL, row); + String frequency = ImportHandlerUtils.readAsString(CenterConstants.FREQUENCY_COL, row); + EnumOptionData frequencyEnum = new EnumOptionData(null, null, ImportHandlerUtils.getFrequencyId(frequency)); + Integer interval = ImportHandlerUtils.readAsInt(CenterConstants.INTERVAL_COL, row); + String repeatsOnDay = ImportHandlerUtils.readAsString(CenterConstants.REPEATS_ON_DAY_COL, row); + EnumOptionData repeatsOnDayEnum = new EnumOptionData(null, null, ImportHandlerUtils.getRepeatsOnDayId(repeatsOnDay)); + if (meetingStartDate == null) { + return null; + } else { + if (repeatsOnDay == null) { + return CalendarData.importInstanceNoRepeatsOnDay(meetingStartDate, isRepeating, frequencyEnum, interval, row.getRowNum(), + locale, dateFormat); + } else { + return CalendarData.importInstanceWithRepeatsOnDay(meetingStartDate, isRepeating, frequencyEnum, interval, repeatsOnDayEnum, + row.getRowNum(), locale, dateFormat); + } + } + } + + private CenterData readCenter(Row row, final String locale, final String dateFormat) { String status = ImportHandlerUtils.readAsString(CenterConstants.STATUS_COL, row); String officeName = ImportHandlerUtils.readAsString(CenterConstants.OFFICE_NAME_COL, row); Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName); @@ -123,40 +121,36 @@ public class CenterImportHandler implements ImportHandler { String externalId = ImportHandlerUtils.readAsString(CenterConstants.EXTERNAL_ID_COL, row); Boolean active = ImportHandlerUtils.readAsBoolean(CenterConstants.ACTIVE_COL, row); - LocalDate submittedOn=ImportHandlerUtils.readAsDate(CenterConstants.SUBMITTED_ON_DATE_COL,row); + LocalDate submittedOn = ImportHandlerUtils.readAsDate(CenterConstants.SUBMITTED_ON_DATE_COL, row); LocalDate activationDate = null; - if (active){ - activationDate=ImportHandlerUtils.readAsDate(CenterConstants.ACTIVATION_DATE_COL, row); - }else { - activationDate=submittedOn; + if (active) { + activationDate = ImportHandlerUtils.readAsDate(CenterConstants.ACTIVATION_DATE_COL, row); + } else { + activationDate = submittedOn; } String centerName = ImportHandlerUtils.readAsString(CenterConstants.CENTER_NAME_COL, row); - if(centerName==null||centerName.equals("")) { - throw new IllegalArgumentException("Name is blank"); - } + if (centerName == null || centerName.equals("")) { throw new IllegalArgumentException("Name is blank"); } List groupMembers = new ArrayList(); - for (int cellNo =CenterConstants. GROUP_NAMES_STARTING_COL; cellNo < CenterConstants.GROUP_NAMES_ENDING_COL; cellNo++) { + for (int cellNo = CenterConstants.GROUP_NAMES_STARTING_COL; cellNo < CenterConstants.GROUP_NAMES_ENDING_COL; cellNo++) { String groupName = ImportHandlerUtils.readAsString(cellNo, row); - if (groupName==null||groupName.equals("")) { + if (groupName == null || groupName.equals("")) { break; } Long groupId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME), groupName); GroupGeneralData group = new GroupGeneralData(groupId); - if (!containsGroupId(groupMembers,groupId)) { + if (!containsGroupId(groupMembers, groupId)) { groupMembers.add(group); } } statuses.add(status); - return CenterData.importInstance(centerName,groupMembers,activationDate, active,submittedOn, externalId, - officeId, staffId, row.getRowNum(),dateFormat,locale); + return CenterData.importInstance(centerName, groupMembers, activationDate, active, submittedOn, externalId, officeId, staffId, + row.getRowNum(), dateFormat, locale); } - private boolean containsGroupId(List groupMembers,Long groupId){ - for (GroupGeneralData group: groupMembers) { - if (group.getId().equals(groupId)){ - return true; - } + private boolean containsGroupId(List groupMembers, Long groupId) { + for (GroupGeneralData group : groupMembers) { + if (group.getId().equals(groupId)) { return true; } } return false; } @@ -182,8 +176,7 @@ public class CenterImportHandler implements ImportHandler { centerId = result.getGroupId().toString(); progressLevel = 1; } else { - centerId = ImportHandlerUtils - .readAsInt(CenterConstants.CENTER_ID_COL, centerSheet.getRow(centers.get(i).getRowIndex())) + centerId = ImportHandlerUtils.readAsInt(CenterConstants.CENTER_ID_COL, centerSheet.getRow(centers.get(i).getRowIndex())) .toString(); } @@ -193,18 +186,19 @@ public class CenterImportHandler implements ImportHandler { successCount++; statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Runtime Exception occured in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - writeCenterErrorMessage(centerId,errorMessage,progressLevel,statusCell,errorReportCell,row); + LOG.error("Runtime Exception occured in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + writeCenterErrorMessage(centerId, errorMessage, progressLevel, statusCell, errorReportCell, row); } } setReportHeaders(centerSheet); return Count.instance(successCount, errorCount); } - private void writeCenterErrorMessage(String centerId,String errorMessage,int progressLevel,Cell statusCell,Cell errorReportCell,Row row){ + private void writeCenterErrorMessage(String centerId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell, + Row row) { String status = ""; if (progressLevel == 0) { status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED; @@ -222,19 +216,18 @@ public class CenterImportHandler implements ImportHandler { private int getProgressLevel(String status) { - if(status==null || status.equals(TemplatePopulateImportConstants.STATUS_CREATION_FAILED)) { + if (status == null || status.equals(TemplatePopulateImportConstants.STATUS_CREATION_FAILED)) { return 0; - } else if (status.equals(TemplatePopulateImportConstants.STATUS_MEETING_FAILED)) { - return 1; - } + } else if (status.equals(TemplatePopulateImportConstants.STATUS_MEETING_FAILED)) { return 1; } return 0; } - private CommandProcessingResult importCenter(int rowIndex,String dateFormat) { + + private CommandProcessingResult importCenter(int rowIndex, String dateFormat) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); Type groupCollectionType = new TypeToken>() {}.getType(); - gsonBuilder.registerTypeAdapter(groupCollectionType,new GroupIdSerializer()); - String payload= gsonBuilder.create().toJson(centers.get(rowIndex)); + gsonBuilder.registerTypeAdapter(groupCollectionType, new GroupIdSerializer()); + String payload = gsonBuilder.create().toJson(centers.get(rowIndex)); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createCenter() // .withJson(payload) // @@ -244,30 +237,31 @@ public class CenterImportHandler implements ImportHandler { } private void setReportHeaders(Sheet sheet) { - ImportHandlerUtils.writeString(CenterConstants.STATUS_COL, sheet.getRow(0), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - ImportHandlerUtils.writeString(CenterConstants.CENTER_ID_COL, sheet.getRow(0), TemplatePopulateImportConstants.CENTERID_COL_REPORT_HEADER); - ImportHandlerUtils.writeString(CenterConstants.FAILURE_COL, sheet.getRow(0), TemplatePopulateImportConstants.FAILURE_COL_REPORT_HEADER); + ImportHandlerUtils.writeString(CenterConstants.STATUS_COL, sheet.getRow(0), + TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); + ImportHandlerUtils.writeString(CenterConstants.CENTER_ID_COL, sheet.getRow(0), + TemplatePopulateImportConstants.CENTERID_COL_REPORT_HEADER); + ImportHandlerUtils.writeString(CenterConstants.FAILURE_COL, sheet.getRow(0), + TemplatePopulateImportConstants.FAILURE_COL_REPORT_HEADER); } - private Integer importCenterMeeting(CommandProcessingResult result, int rowIndex,String dateFormat) { - CalendarData calendarData=meetings.get(rowIndex); + private Integer importCenterMeeting(CommandProcessingResult result, int rowIndex, String dateFormat) { + CalendarData calendarData = meetings.get(rowIndex); calendarData.setTitle("centers_" + result.getGroupId().toString() + "_CollectionMeeting"); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - gsonBuilder.registerTypeAdapter(EnumOptionData.class,new EnumOptionDataValueSerializer()); + gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataValueSerializer()); String payload = gsonBuilder.create().toJson(calendarData); - CommandWrapper commandWrapper=new CommandWrapper(result.getOfficeId(),result.getGroupId(),result.getClientId(), - result.getLoanId(),result.getSavingsId(),null,null,null,null, - null,payload,result.getTransactionId(),result.getProductId(),null,null, - null); + CommandWrapper commandWrapper = new CommandWrapper(result.getOfficeId(), result.getGroupId(), result.getClientId(), + result.getLoanId(), result.getSavingsId(), null, null, null, null, null, payload, result.getTransactionId(), + result.getProductId(), null, null, null); final CommandWrapper commandRequest = new CommandWrapperBuilder() // - .createCalendar(commandWrapper,TemplatePopulateImportConstants.CENTER_ENTITY_TYPE,result.getGroupId()) // + .createCalendar(commandWrapper, TemplatePopulateImportConstants.CENTER_ENTITY_TYPE, result.getGroupId()) // .withJson(payload) // .build(); // final CommandProcessingResult meetingresult = commandsSourceWritePlatformService.logCommandSource(commandRequest); return 2; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/chartofaccounts/ChartOfAccountsImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/chartofaccounts/ChartOfAccountsImportHandler.java index 6a46f6812..e3b575838 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/chartofaccounts/ChartOfAccountsImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/chartofaccounts/ChartOfAccountsImportHandler.java @@ -47,74 +47,73 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; - @Service public class ChartOfAccountsImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(ChartOfAccountsImportHandler.class); - private List glAccounts; - private Workbook workbook; + private List glAccounts; + private Workbook workbook; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public ChartOfAccountsImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public ChartOfAccountsImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.glAccounts=new ArrayList<>(); - this.workbook=workbook; + this.glAccounts = new ArrayList<>(); + this.workbook = workbook; readExcelFile(); return importEntity(); } public void readExcelFile() { - Sheet chartOfAccountsSheet=workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME); - Integer noOfEntries= ImportHandlerUtils.getNumberOfRows(chartOfAccountsSheet,TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); - for (int rowIndex=1;rowIndex<=noOfEntries;rowIndex++){ + Sheet chartOfAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME); + Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(chartOfAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); + for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row=chartOfAccountsSheet.getRow(rowIndex); - if (ImportHandlerUtils.isNotImported(row, ChartOfAcountsConstants.STATUS_COL)){ - glAccounts.add(readGlAccounts(row)); - } + row = chartOfAccountsSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, ChartOfAcountsConstants.STATUS_COL)) { + glAccounts.add(readGlAccounts(row)); + } } } private GLAccountData readGlAccounts(Row row) { - String accountType=ImportHandlerUtils.readAsString(ChartOfAcountsConstants.ACCOUNT_TYPE_COL,row); - EnumOptionData accountTypeEnum=GLAccountType.fromString(accountType); - String accountName=ImportHandlerUtils.readAsString(ChartOfAcountsConstants.ACCOUNT_NAME_COL,row); - String usage=ImportHandlerUtils.readAsString(ChartOfAcountsConstants.ACCOUNT_USAGE_COL,row); - Long usageId=null; - EnumOptionData usageEnum=null; - if (usage!=null&& usage.equals(GLAccountUsage.DETAIL.toString())){ - usageId=1L; - usageEnum=new EnumOptionData(usageId,null,null); - }else if (usage!=null&&usage.equals(GLAccountUsage.HEADER.toString())){ - usageId=2L; - usageEnum=new EnumOptionData(usageId,null,null); + String accountType = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.ACCOUNT_TYPE_COL, row); + EnumOptionData accountTypeEnum = GLAccountType.fromString(accountType); + String accountName = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.ACCOUNT_NAME_COL, row); + String usage = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.ACCOUNT_USAGE_COL, row); + Long usageId = null; + EnumOptionData usageEnum = null; + if (usage != null && usage.equals(GLAccountUsage.DETAIL.toString())) { + usageId = 1L; + usageEnum = new EnumOptionData(usageId, null, null); + } else if (usage != null && usage.equals(GLAccountUsage.HEADER.toString())) { + usageId = 2L; + usageEnum = new EnumOptionData(usageId, null, null); } - Boolean manualEntriesAllowed=ImportHandlerUtils.readAsBoolean(ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL,row); - Long parentId=null; - if (ImportHandlerUtils.readAsString(ChartOfAcountsConstants.PARENT_ID_COL,row)!=null) { - parentId = Long.parseLong(ImportHandlerUtils.readAsString(ChartOfAcountsConstants.PARENT_ID_COL,row)); + Boolean manualEntriesAllowed = ImportHandlerUtils.readAsBoolean(ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL, row); + Long parentId = null; + if (ImportHandlerUtils.readAsString(ChartOfAcountsConstants.PARENT_ID_COL, row) != null) { + parentId = Long.parseLong(ImportHandlerUtils.readAsString(ChartOfAcountsConstants.PARENT_ID_COL, row)); } - String glCode=ImportHandlerUtils.readAsString(ChartOfAcountsConstants.GL_CODE_COL,row); - Long tagId=null; - if(ImportHandlerUtils.readAsString(ChartOfAcountsConstants.TAG_ID_COL,row)!=null) { + String glCode = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.GL_CODE_COL, row); + Long tagId = null; + if (ImportHandlerUtils.readAsString(ChartOfAcountsConstants.TAG_ID_COL, row) != null) { tagId = Long.parseLong(ImportHandlerUtils.readAsString(ChartOfAcountsConstants.TAG_ID_COL, row)); } - CodeValueData tagIdCodeValueData=new CodeValueData(tagId); - String description=ImportHandlerUtils.readAsString(ChartOfAcountsConstants.DESCRIPTION_COL,row); - return GLAccountData.importInstance(accountName,parentId,glCode,manualEntriesAllowed,accountTypeEnum, - usageEnum,description,tagIdCodeValueData,row.getRowNum()); + CodeValueData tagIdCodeValueData = new CodeValueData(tagId); + String description = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.DESCRIPTION_COL, row); + return GLAccountData.importInstance(accountName, parentId, glCode, manualEntriesAllowed, accountTypeEnum, usageEnum, description, + tagIdCodeValueData, row.getRowNum()); } public Count importEntity() { - Sheet chartOfAccountsSheet=workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME); + Sheet chartOfAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer()); @@ -122,9 +121,9 @@ public class ChartOfAccountsImportHandler implements ImportHandler { int successCount = 0; int errorCount = 0; String errorMessage = ""; - for (GLAccountData glAccount: glAccounts) { + for (GLAccountData glAccount : glAccounts) { try { - String payload=gsonBuilder.create().toJson(glAccount); + String payload = gsonBuilder.create().toJson(glAccount); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createGLAccount() // .withJson(payload) // @@ -134,18 +133,19 @@ public class ChartOfAccountsImportHandler implements ImportHandler { Cell statusCell = chartOfAccountsSheet.getRow(glAccount.getRowIndex()).createCell(ChartOfAcountsConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(chartOfAccountsSheet,glAccount.getRowIndex(),errorMessage,ChartOfAcountsConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(chartOfAccountsSheet, glAccount.getRowIndex(), errorMessage, + ChartOfAcountsConstants.STATUS_COL); } } chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(ChartOfAcountsConstants.STATUS_COL, chartOfAccountsSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), + ImportHandlerUtils.writeString(ChartOfAcountsConstants.STATUS_COL, + chartOfAccountsSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COLUMN_HEADER); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/client/ClientEntityImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/client/ClientEntityImportHandler.java index 3a5665ec3..024106e57 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/client/ClientEntityImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/client/ClientEntityImportHandler.java @@ -57,74 +57,73 @@ public class ClientEntityImportHandler implements ImportHandler { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public ClientEntityImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public ClientEntityImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { this.workbook = workbook; - this.clients=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.clients = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } public void readExcelFile(final String locale, final String dateFormat) { - Sheet clientSheet=workbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME); - Integer noOfEntries= ImportHandlerUtils.getNumberOfRows(clientSheet,0); - for (int rowIndex=1;rowIndex<=noOfEntries;rowIndex++){ + Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME); + Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(clientSheet, 0); + for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row=clientSheet.getRow(rowIndex); - if (ImportHandlerUtils.isNotImported(row, ClientEntityConstants.STATUS_COL)){ - clients.add(readClient(row,locale,dateFormat)); - } + row = clientSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, ClientEntityConstants.STATUS_COL)) { + clients.add(readClient(row, locale, dateFormat)); + } } } - private ClientData readClient(Row row,final String locale, final String dateFormat) { - Long legalFormId=2L; + private ClientData readClient(Row row, final String locale, final String dateFormat) { + Long legalFormId = 2L; String name = ImportHandlerUtils.readAsString(ClientEntityConstants.NAME_COL, row); String officeName = ImportHandlerUtils.readAsString(ClientEntityConstants.OFFICE_NAME_COL, row); Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName); String staffName = ImportHandlerUtils.readAsString(ClientEntityConstants.STAFF_NAME_COL, row); Long staffId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), staffName); - LocalDate incorportionDate=ImportHandlerUtils.readAsDate(ClientEntityConstants.INCOPORATION_DATE_COL,row); - LocalDate incorporationTill=ImportHandlerUtils.readAsDate(ClientEntityConstants.INCOPORATION_VALID_TILL_COL,row); - String mobileNo=null; - if (ImportHandlerUtils.readAsLong(ClientEntityConstants.MOBILE_NO_COL, row)!=null) { + LocalDate incorportionDate = ImportHandlerUtils.readAsDate(ClientEntityConstants.INCOPORATION_DATE_COL, row); + LocalDate incorporationTill = ImportHandlerUtils.readAsDate(ClientEntityConstants.INCOPORATION_VALID_TILL_COL, row); + String mobileNo = null; + if (ImportHandlerUtils.readAsLong(ClientEntityConstants.MOBILE_NO_COL, row) != null) { mobileNo = ImportHandlerUtils.readAsLong(ClientEntityConstants.MOBILE_NO_COL, row).toString(); } - String clientType=ImportHandlerUtils.readAsString(ClientEntityConstants.CLIENT_TYPE_COL, row); + String clientType = ImportHandlerUtils.readAsString(ClientEntityConstants.CLIENT_TYPE_COL, row); Long clientTypeId = null; - if (clientType!=null) { - String[] clientTypeAr =clientType .split("-"); + if (clientType != null) { + String[] clientTypeAr = clientType.split("-"); if (clientTypeAr[1] != null) { clientTypeId = Long.parseLong(clientTypeAr[1]); } } - String clientClassification= ImportHandlerUtils.readAsString(ClientEntityConstants.CLIENT_CLASSIFICATION_COL, row); + String clientClassification = ImportHandlerUtils.readAsString(ClientEntityConstants.CLIENT_CLASSIFICATION_COL, row); Long clientClassicationId = null; - if (clientClassification!=null) { - String[] clientClassificationAr =clientClassification.split("-"); + if (clientClassification != null) { + String[] clientClassificationAr = clientClassification.split("-"); if (clientClassificationAr[1] != null) { clientClassicationId = Long.parseLong(clientClassificationAr[1]); } } - String incorporationNo=ImportHandlerUtils.readAsString(ClientEntityConstants.INCOPORATION_NUMBER_COL,row); + String incorporationNo = ImportHandlerUtils.readAsString(ClientEntityConstants.INCOPORATION_NUMBER_COL, row); - String mainBusinessLine=ImportHandlerUtils.readAsString(ClientEntityConstants.MAIN_BUSINESS_LINE,row); + String mainBusinessLine = ImportHandlerUtils.readAsString(ClientEntityConstants.MAIN_BUSINESS_LINE, row); Long mainBusinessId = null; - if (mainBusinessLine!=null) { + if (mainBusinessLine != null) { String[] mainBusinessLineAr = ImportHandlerUtils.readAsString(ClientEntityConstants.MAIN_BUSINESS_LINE, row).split("-"); if (mainBusinessLineAr[1] != null) { mainBusinessId = Long.parseLong(mainBusinessLineAr[1]); } } - String constitution= ImportHandlerUtils.readAsString(ClientEntityConstants.CONSTITUTION_COL,row); + String constitution = ImportHandlerUtils.readAsString(ClientEntityConstants.CONSTITUTION_COL, row); Long constitutionId = null; - if (constitution!=null) { + if (constitution != null) { String[] constitutionAr = constitution.split("-"); if (constitutionAr[1] != null) { constitutionId = Long.parseLong(constitutionAr[1]); @@ -132,25 +131,25 @@ public class ClientEntityImportHandler implements ImportHandler { } String remarks = ImportHandlerUtils.readAsString(ClientEntityConstants.REMARKS_COL, row); - ClientNonPersonData clientNonPersonData= ClientNonPersonData.importInstance(incorporationNo,incorporationTill,remarks, - mainBusinessId,constitutionId,locale,dateFormat); + ClientNonPersonData clientNonPersonData = ClientNonPersonData.importInstance(incorporationNo, incorporationTill, remarks, + mainBusinessId, constitutionId, locale, dateFormat); - String externalId= ImportHandlerUtils.readAsString(ClientEntityConstants.EXTERNAL_ID_COL, row); + String externalId = ImportHandlerUtils.readAsString(ClientEntityConstants.EXTERNAL_ID_COL, row); Boolean active = ImportHandlerUtils.readAsBoolean(ClientEntityConstants.ACTIVE_COL, row); - LocalDate submittedOn=ImportHandlerUtils.readAsDate(ClientEntityConstants.SUBMITTED_ON_COL,row); + LocalDate submittedOn = ImportHandlerUtils.readAsDate(ClientEntityConstants.SUBMITTED_ON_COL, row); LocalDate activationDate = ImportHandlerUtils.readAsDate(ClientEntityConstants.ACTIVATION_DATE_COL, row); - if (!active){ - activationDate=submittedOn; + if (!active) { + activationDate = submittedOn; } - AddressData addressDataObj=null; + AddressData addressDataObj = null; Collection addressList = null; - if (ImportHandlerUtils.readAsBoolean(ClientEntityConstants.ADDRESS_ENABLED,row)) { + if (ImportHandlerUtils.readAsBoolean(ClientEntityConstants.ADDRESS_ENABLED, row)) { String addressType = ImportHandlerUtils.readAsString(ClientEntityConstants.ADDRESS_TYPE_COL, row); Long addressTypeId = null; - if (addressType!=null) { + if (addressType != null) { String[] addressTypeAr = addressType.split("-"); if (addressTypeAr[1] != null) { addressTypeId = Long.parseLong(addressTypeAr[1]); @@ -165,33 +164,33 @@ public class ClientEntityImportHandler implements ImportHandler { String postalCode = ImportHandlerUtils.readAsString(ClientEntityConstants.POSTAL_CODE_COL, row); Boolean isActiveAddress = ImportHandlerUtils.readAsBoolean(ClientEntityConstants.IS_ACTIVE_ADDRESS_COL, row); - String stateProvince=ImportHandlerUtils.readAsString(ClientEntityConstants.STATE_PROVINCE_COL, row); + String stateProvince = ImportHandlerUtils.readAsString(ClientEntityConstants.STATE_PROVINCE_COL, row); Long stateProvinceId = null; - if (stateProvince!=null) { + if (stateProvince != null) { String[] stateProvinceAr = stateProvince.split("-"); if (stateProvinceAr[1] != null) { stateProvinceId = Long.parseLong(stateProvinceAr[1]); } } - String country= ImportHandlerUtils.readAsString(ClientEntityConstants.COUNTRY_COL, row); + String country = ImportHandlerUtils.readAsString(ClientEntityConstants.COUNTRY_COL, row); Long countryId = null; - if (country!=null) { + if (country != null) { String[] countryAr = country.split("-"); if (countryAr[1] != null) { countryId = Long.parseLong(countryAr[1]); } } - addressDataObj = new AddressData(addressTypeId, street, addressLine1, addressLine2, addressLine3, - city, postalCode, isActiveAddress, stateProvinceId, countryId); + addressDataObj = new AddressData(addressTypeId, street, addressLine1, addressLine2, addressLine3, city, postalCode, + isActiveAddress, stateProvinceId, countryId); addressList = new ArrayList(Arrays.asList(addressDataObj)); } - return ClientData.importClientEntityInstance(legalFormId,row.getRowNum(),name,officeId,clientTypeId,clientClassicationId, - staffId, active, activationDate, submittedOn, externalId, incorportionDate, mobileNo, - clientNonPersonData, addressList, locale, dateFormat); + return ClientData.importClientEntityInstance(legalFormId, row.getRowNum(), name, officeId, clientTypeId, clientClassicationId, + staffId, active, activationDate, submittedOn, externalId, incorportionDate, mobileNo, clientNonPersonData, addressList, + locale, dateFormat); } public Count importEntity(String dateFormat) { - Sheet clientSheet=workbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME); + Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME); int successCount = 0; int errorCount = 0; @@ -200,9 +199,9 @@ public class ClientEntityImportHandler implements ImportHandler { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - for (ClientData client: clients) { + for (ClientData client : clients) { try { - String payload=gsonBuilder.create().toJson(client); + String payload = gsonBuilder.create().toJson(client); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createClient() // .withJson(payload) // @@ -212,19 +211,18 @@ public class ClientEntityImportHandler implements ImportHandler { Cell statusCell = clientSheet.getRow(client.getRowIndex()).createCell(ClientEntityConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(clientSheet,client.getRowIndex(),errorMessage,ClientEntityConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(clientSheet, client.getRowIndex(), errorMessage, ClientEntityConstants.STATUS_COL); } } clientSheet.setColumnWidth(ClientEntityConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(ClientEntityConstants.STATUS_COL, clientSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), - TemplatePopulateImportConstants.STATUS_COLUMN_HEADER); + ImportHandlerUtils.writeString(ClientEntityConstants.STATUS_COL, + clientSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COLUMN_HEADER); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/client/ClientPersonImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/client/ClientPersonImportHandler.java index e52bd98e6..5507dad41 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/client/ClientPersonImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/client/ClientPersonImportHandler.java @@ -47,40 +47,40 @@ import org.springframework.stereotype.Service; @Service public class ClientPersonImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(ClientPersonImportHandler.class); private Workbook workbook; private List clients; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - @Autowired - public ClientPersonImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + @Autowired + public ClientPersonImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { this.workbook = workbook; - this.clients=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.clients = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } public void readExcelFile(final String locale, final String dateFormat) { - Sheet clientSheet=workbook.getSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME); - Integer noOfEntries= ImportHandlerUtils.getNumberOfRows(clientSheet,0); - for (int rowIndex=1;rowIndex<=noOfEntries;rowIndex++){ + Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME); + Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(clientSheet, 0); + for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row=clientSheet.getRow(rowIndex); - if (ImportHandlerUtils.isNotImported(row, ClientPersonConstants.STATUS_COL)){ - clients.add(readClient(row,locale,dateFormat)); - } + row = clientSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, ClientPersonConstants.STATUS_COL)) { + clients.add(readClient(row, locale, dateFormat)); + } } } - private ClientData readClient(Row row,final String locale, final String dateFormat) { - Long legalFormId=1L; + private ClientData readClient(Row row, final String locale, final String dateFormat) { + Long legalFormId = 1L; String firstName = ImportHandlerUtils.readAsString(ClientPersonConstants.FIRST_NAME_COL, row); String lastName = ImportHandlerUtils.readAsString(ClientPersonConstants.LAST_NAME_COL, row); String middleName = ImportHandlerUtils.readAsString(ClientPersonConstants.MIDDLE_NAME_COL, row); @@ -89,37 +89,37 @@ public class ClientPersonImportHandler implements ImportHandler { String staffName = ImportHandlerUtils.readAsString(ClientPersonConstants.STAFF_NAME_COL, row); Long staffId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), staffName); String externalId = ImportHandlerUtils.readAsString(ClientPersonConstants.EXTERNAL_ID_COL, row); - LocalDate submittedOn=ImportHandlerUtils.readAsDate(ClientPersonConstants.SUBMITTED_ON_COL,row); + LocalDate submittedOn = ImportHandlerUtils.readAsDate(ClientPersonConstants.SUBMITTED_ON_COL, row); LocalDate activationDate = ImportHandlerUtils.readAsDate(ClientPersonConstants.ACTIVATION_DATE_COL, row); Boolean active = ImportHandlerUtils.readAsBoolean(ClientPersonConstants.ACTIVE_COL, row); - if (!active){ - activationDate=submittedOn; + if (!active) { + activationDate = submittedOn; } - String mobileNo=null; - if (ImportHandlerUtils.readAsLong(ClientPersonConstants.MOBILE_NO_COL, row)!=null) { + String mobileNo = null; + if (ImportHandlerUtils.readAsLong(ClientPersonConstants.MOBILE_NO_COL, row) != null) { mobileNo = ImportHandlerUtils.readAsLong(ClientPersonConstants.MOBILE_NO_COL, row).toString(); } LocalDate dob = ImportHandlerUtils.readAsDate(ClientPersonConstants.DOB_COL, row); - String clientType=ImportHandlerUtils.readAsString(ClientPersonConstants.CLIENT_TYPE_COL, row); + String clientType = ImportHandlerUtils.readAsString(ClientPersonConstants.CLIENT_TYPE_COL, row); Long clientTypeId = null; - if (clientType!=null) { + if (clientType != null) { String[] clientTypeAr = clientType.split("-"); if (clientTypeAr.length > 1 && clientTypeAr[1] != null) { clientTypeId = Long.parseLong(clientTypeAr[1]); } } - String gender=ImportHandlerUtils.readAsString(ClientPersonConstants.GENDER_COL, row); + String gender = ImportHandlerUtils.readAsString(ClientPersonConstants.GENDER_COL, row); Long genderId = null; - if (gender!=null) { + if (gender != null) { String[] genderAr = gender.split("-"); if (genderAr.length > 1 && genderAr[1] != null) { genderId = Long.parseLong(genderAr[1]); } } - String clientClassification= ImportHandlerUtils.readAsString(ClientPersonConstants.CLIENT_CLASSIFICATION_COL, row); + String clientClassification = ImportHandlerUtils.readAsString(ClientPersonConstants.CLIENT_CLASSIFICATION_COL, row); Long clientClassificationId = null; - if (clientClassification!=null) { + if (clientClassification != null) { String[] clientClassificationAr = clientClassification.split("-"); if (clientClassificationAr.length > 1 && clientClassificationAr[1] != null) { clientClassificationId = Long.parseLong(clientClassificationAr[1]); @@ -127,12 +127,12 @@ public class ClientPersonImportHandler implements ImportHandler { } Boolean isStaff = ImportHandlerUtils.readAsBoolean(ClientPersonConstants.IS_STAFF_COL, row); - AddressData addressDataObj=null; + AddressData addressDataObj = null; Collection addressList = null; - if (ImportHandlerUtils.readAsBoolean(ClientPersonConstants.ADDRESS_ENABLED_COL,row)) { - String addressType=ImportHandlerUtils.readAsString(ClientPersonConstants.ADDRESS_TYPE_COL, row); + if (ImportHandlerUtils.readAsBoolean(ClientPersonConstants.ADDRESS_ENABLED_COL, row)) { + String addressType = ImportHandlerUtils.readAsString(ClientPersonConstants.ADDRESS_TYPE_COL, row); Long addressTypeId = null; - if (addressType!=null) { + if (addressType != null) { String[] addressTypeAr = addressType.split("-"); if (addressTypeAr.length > 1 && addressTypeAr[1] != null) { @@ -148,44 +148,45 @@ public class ClientPersonImportHandler implements ImportHandler { String postalCode = ImportHandlerUtils.readAsString(ClientPersonConstants.POSTAL_CODE_COL, row); Boolean isActiveAddress = ImportHandlerUtils.readAsBoolean(ClientPersonConstants.IS_ACTIVE_ADDRESS_COL, row); - String stateProvince=ImportHandlerUtils.readAsString(ClientPersonConstants.STATE_PROVINCE_COL, row); + String stateProvince = ImportHandlerUtils.readAsString(ClientPersonConstants.STATE_PROVINCE_COL, row); Long stateProvinceId = null; if (stateProvince != null) { String[] stateProvinceAr = stateProvince.split("-"); // Arkansas-AL <-- expected format of the cell - // but probably it's either an empty cell or it is missing a hyphen + // but probably it's either an empty cell or it is missing a + // hyphen if (stateProvinceAr.length > 1 && stateProvinceAr[1] != null) { stateProvinceId = Long.parseLong(stateProvinceAr[1]); } } - String country=ImportHandlerUtils.readAsString(ClientPersonConstants.COUNTRY_COL, row); - Long countryId=null; - if (country!=null) { + String country = ImportHandlerUtils.readAsString(ClientPersonConstants.COUNTRY_COL, row); + Long countryId = null; + if (country != null) { String[] countryAr = country.split("-"); if (countryAr.length > 1 && countryAr[1] != null) { countryId = Long.parseLong(countryAr[1]); } } - addressDataObj = new AddressData(addressTypeId, street, addressLine1, addressLine2, addressLine3, - city, postalCode, isActiveAddress, stateProvinceId, countryId); - addressList = new ArrayList(Arrays.asList(addressDataObj)); + addressDataObj = new AddressData(addressTypeId, street, addressLine1, addressLine2, addressLine3, city, postalCode, + isActiveAddress, stateProvinceId, countryId); + addressList = new ArrayList(Arrays.asList(addressDataObj)); } - return ClientData.importClientPersonInstance(legalFormId,row.getRowNum(),firstName,lastName,middleName,submittedOn,activationDate,active,externalId, - officeId, staffId, mobileNo, dob, clientTypeId, genderId, clientClassificationId, isStaff, - addressList, locale, dateFormat); + return ClientData.importClientPersonInstance(legalFormId, row.getRowNum(), firstName, lastName, middleName, submittedOn, + activationDate, active, externalId, officeId, staffId, mobileNo, dob, clientTypeId, genderId, clientClassificationId, + isStaff, addressList, locale, dateFormat); } public Count importEntity(String dateFormat) { - Sheet clientSheet=workbook.getSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; + Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME); + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - for (ClientData client: clients) { + for (ClientData client : clients) { try { - String payload=gsonBuilder.create().toJson(client); + String payload = gsonBuilder.create().toJson(client); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createClient() // .withJson(payload) // @@ -195,19 +196,18 @@ public class ClientPersonImportHandler implements ImportHandler { Cell statusCell = clientSheet.getRow(client.getRowIndex()).createCell(ClientPersonConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(clientSheet,client.getRowIndex(),errorMessage,ClientPersonConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(clientSheet, client.getRowIndex(), errorMessage, ClientPersonConstants.STATUS_COL); } } clientSheet.setColumnWidth(ClientPersonConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(ClientPersonConstants.STATUS_COL, clientSheet. - getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COLUMN_HEADER); + ImportHandlerUtils.writeString(ClientPersonConstants.STATUS_COL, + clientSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COLUMN_HEADER); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/fixeddeposits/FixedDepositImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/fixeddeposits/FixedDepositImportHandler.java index 96f8b123e..048357e53 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/fixeddeposits/FixedDepositImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/fixeddeposits/FixedDepositImportHandler.java @@ -52,8 +52,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; + @Service public class FixedDepositImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(FixedDepositImportHandler.class); private Workbook workbook; @@ -66,21 +68,19 @@ public class FixedDepositImportHandler implements ImportHandler { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public FixedDepositImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public FixedDepositImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } - @Override public Count process(Workbook workbook, String locale, String dateFormat) { this.workbook = workbook; - savings=new ArrayList<>(); - approvalDates=new ArrayList<>(); - activationDates=new ArrayList<>(); - closedOnDate=new ArrayList<>(); - statuses=new ArrayList<>(); - readExcelFile(locale,dateFormat); + savings = new ArrayList<>(); + approvalDates = new ArrayList<>(); + activationDates = new ArrayList<>(); + closedOnDate = new ArrayList<>(); + statuses = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } @@ -89,58 +89,59 @@ public class FixedDepositImportHandler implements ImportHandler { Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row = savingsSheet.getRow(rowIndex); - if (ImportHandlerUtils.isNotImported(row, FixedDepositConstants.STATUS_COL)) { - savings.add(readSavings(row,locale,dateFormat)); - approvalDates.add(readSavingsApproval(row,locale,dateFormat)); - activationDates.add(readSavingsActivation(row,locale,dateFormat)); - closedOnDate.add(readSavingsClosed(row,locale,dateFormat)); - } + row = savingsSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, FixedDepositConstants.STATUS_COL)) { + savings.add(readSavings(row, locale, dateFormat)); + approvalDates.add(readSavingsApproval(row, locale, dateFormat)); + activationDates.add(readSavingsActivation(row, locale, dateFormat)); + closedOnDate.add(readSavingsClosed(row, locale, dateFormat)); + } } } - private ClosingOfSavingsAccounts readSavingsClosed(Row row,String locale,String dateFormat) { + private ClosingOfSavingsAccounts readSavingsClosed(Row row, String locale, String dateFormat) { LocalDate closedOnDate = ImportHandlerUtils.readAsDate(FixedDepositConstants.CLOSED_ON_DATE, row); Long onAccountClosureId = ImportHandlerUtils.readAsLong(FixedDepositConstants.ON_ACCOUNT_CLOSURE_ID, row); Long toSavingsAccountId = ImportHandlerUtils.readAsLong(FixedDepositConstants.TO_SAVINGS_ACCOUNT_ID, row); - if (closedOnDate!=null) { - return ClosingOfSavingsAccounts.importInstance(null, closedOnDate, onAccountClosureId, toSavingsAccountId, - null, row.getRowNum(), locale, dateFormat); + if (closedOnDate != null) { + return ClosingOfSavingsAccounts.importInstance(null, closedOnDate, onAccountClosureId, toSavingsAccountId, null, + row.getRowNum(), locale, dateFormat); } else { return null; } } - private SavingsActivation readSavingsActivation(Row row,String locale,String dateFormat) { + private SavingsActivation readSavingsActivation(Row row, String locale, String dateFormat) { LocalDate activationDate = ImportHandlerUtils.readAsDate(FixedDepositConstants.ACTIVATION_DATE_COL, row); - if (activationDate!=null) { + if (activationDate != null) { return SavingsActivation.importInstance(activationDate, row.getRowNum(), locale, dateFormat); } else { return null; } } - private SavingsApproval readSavingsApproval(Row row,String locale,String dateFormat) { + private SavingsApproval readSavingsApproval(Row row, String locale, String dateFormat) { LocalDate approvalDate = ImportHandlerUtils.readAsDate(FixedDepositConstants.APPROVED_DATE_COL, row); - if (approvalDate!=null) { + if (approvalDate != null) { return SavingsApproval.importInstance(approvalDate, row.getRowNum(), locale, dateFormat); } else { return null; } } - private FixedDepositAccountData readSavings(Row row,String locale,String dateFormat) { + private FixedDepositAccountData readSavings(Row row, String locale, String dateFormat) { String productName = ImportHandlerUtils.readAsString(FixedDepositConstants.PRODUCT_COL, row); Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName); String fieldOfficerName = ImportHandlerUtils.readAsString(FixedDepositConstants.FIELD_OFFICER_NAME_COL, row); - Long fieldOfficerId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), fieldOfficerName); + Long fieldOfficerId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), + fieldOfficerName); LocalDate submittedOnDate = ImportHandlerUtils.readAsDate(FixedDepositConstants.SUBMITTED_ON_DATE_COL, row); String interestCompoundingPeriodType = ImportHandlerUtils.readAsString(FixedDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, row); Long interestCompoundingPeriodTypeId = null; - EnumOptionData interestCompoundingPeriodTypeEnum=null; - if (interestCompoundingPeriodType!=null) { + EnumOptionData interestCompoundingPeriodTypeEnum = null; + if (interestCompoundingPeriodType != null) { if (interestCompoundingPeriodType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_DAILY)) { interestCompoundingPeriodTypeId = 1L; } else if (interestCompoundingPeriodType @@ -156,57 +157,53 @@ public class FixedDepositImportHandler implements ImportHandler { .equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_ANNUALLY)) { interestCompoundingPeriodTypeId = 7L; } - interestCompoundingPeriodTypeEnum = new EnumOptionData(interestCompoundingPeriodTypeId, null, null); + interestCompoundingPeriodTypeEnum = new EnumOptionData(interestCompoundingPeriodTypeId, null, null); } String interestPostingPeriodType = ImportHandlerUtils.readAsString(FixedDepositConstants.INTEREST_POSTING_PERIOD_COL, row); Long interestPostingPeriodTypeId = null; - EnumOptionData interestPostingPeriodTypeEnum=null; - if (interestCompoundingPeriodType!=null) { + EnumOptionData interestPostingPeriodTypeEnum = null; + if (interestCompoundingPeriodType != null) { if (interestPostingPeriodType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_MONTHLY)) { interestPostingPeriodTypeId = 4L; - } else if (interestPostingPeriodType - .equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_QUARTERLY)) { + } else if (interestPostingPeriodType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_QUARTERLY)) { interestPostingPeriodTypeId = 5L; - } else if (interestPostingPeriodType - .equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_ANNUALLY)) { + } else if (interestPostingPeriodType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_ANNUALLY)) { interestPostingPeriodTypeId = 7L; - } else if (interestPostingPeriodType - .equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_BIANUALLY)) { + } else if (interestPostingPeriodType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_BIANUALLY)) { interestPostingPeriodTypeId = 6L; } - interestPostingPeriodTypeEnum = new EnumOptionData(interestPostingPeriodTypeId, null, null); + interestPostingPeriodTypeEnum = new EnumOptionData(interestPostingPeriodTypeId, null, null); } String interestCalculationType = ImportHandlerUtils.readAsString(FixedDepositConstants.INTEREST_CALCULATION_COL, row); - EnumOptionData interestCalculationTypeEnum=null; - if (interestCalculationType!=null) { + EnumOptionData interestCalculationTypeEnum = null; + if (interestCalculationType != null) { Long interestCalculationTypeId = null; if (interestCalculationType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_CAL_DAILY_BALANCE)) { interestCalculationTypeId = 1L; - } else if (interestCalculationType - .equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_CAL_AVG_BALANCE)) { + } else if (interestCalculationType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_CAL_AVG_BALANCE)) { interestCalculationTypeId = 2L; } - interestCalculationTypeEnum = new EnumOptionData(interestCalculationTypeId, null, null); + interestCalculationTypeEnum = new EnumOptionData(interestCalculationTypeId, null, null); } - String interestCalculationDaysInYearType = ImportHandlerUtils.readAsString(FixedDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row); + String interestCalculationDaysInYearType = ImportHandlerUtils + .readAsString(FixedDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row); Long interestCalculationDaysInYearTypeId = null; - EnumOptionData interestCalculationDaysInYearTypeEnum=null; - if (interestCalculationDaysInYearType!=null) { + EnumOptionData interestCalculationDaysInYearTypeEnum = null; + if (interestCalculationDaysInYearType != null) { if (interestCalculationDaysInYearType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_360)) { interestCalculationDaysInYearTypeId = 360L; - } else if (interestCalculationDaysInYearType - .equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_365)) { + } else if (interestCalculationDaysInYearType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_365)) { interestCalculationDaysInYearTypeId = 365L; } - interestCalculationDaysInYearTypeEnum = new EnumOptionData(interestCalculationDaysInYearTypeId, null, null); + interestCalculationDaysInYearTypeEnum = new EnumOptionData(interestCalculationDaysInYearTypeId, null, null); } Integer lockinPeriodFrequency = ImportHandlerUtils.readAsInt(FixedDepositConstants.LOCKIN_PERIOD_COL, row); String lockinPeriodFrequencyType = ImportHandlerUtils.readAsString(FixedDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, row); - Long lockinPeriodFrequencyTypeId =null; - EnumOptionData lockinPeriodFrequencyTypeEnum=null; - if (lockinPeriodFrequencyType!=null) { + Long lockinPeriodFrequencyTypeId = null; + EnumOptionData lockinPeriodFrequencyTypeEnum = null; + if (lockinPeriodFrequencyType != null) { if (lockinPeriodFrequencyType.equalsIgnoreCase(TemplatePopulateImportConstants.FREQUENCY_DAYS)) { lockinPeriodFrequencyTypeId = 0L; } else if (lockinPeriodFrequencyType.equalsIgnoreCase(TemplatePopulateImportConstants.FREQUENCY_WEEKS)) { @@ -216,17 +213,17 @@ public class FixedDepositImportHandler implements ImportHandler { } else if (lockinPeriodFrequencyType.equalsIgnoreCase(TemplatePopulateImportConstants.FREQUENCY_YEARS)) { lockinPeriodFrequencyTypeId = 3L; } - lockinPeriodFrequencyTypeEnum = new EnumOptionData(lockinPeriodFrequencyTypeId, null, null); + lockinPeriodFrequencyTypeEnum = new EnumOptionData(lockinPeriodFrequencyTypeId, null, null); } - BigDecimal depositAmount=null; - if (ImportHandlerUtils.readAsDouble(FixedDepositConstants.DEPOSIT_AMOUNT_COL, row)!=null) { + BigDecimal depositAmount = null; + if (ImportHandlerUtils.readAsDouble(FixedDepositConstants.DEPOSIT_AMOUNT_COL, row) != null) { depositAmount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(FixedDepositConstants.DEPOSIT_AMOUNT_COL, row)); } Integer depositPeriod = ImportHandlerUtils.readAsInt(FixedDepositConstants.DEPOSIT_PERIOD_COL, row); String depositPeriodFrequency = ImportHandlerUtils.readAsString(FixedDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, row); Long depositPeriodFrequencyId = null; - if (depositPeriodFrequency!=null) { + if (depositPeriodFrequency != null) { if (depositPeriodFrequency.equalsIgnoreCase(TemplatePopulateImportConstants.FREQUENCY_DAYS)) { depositPeriodFrequencyId = 0L; } else if (depositPeriodFrequency.equalsIgnoreCase(TemplatePopulateImportConstants.FREQUENCY_WEEKS)) { @@ -245,46 +242,43 @@ public class FixedDepositImportHandler implements ImportHandler { String charge1 = ImportHandlerUtils.readAsString(FixedDepositConstants.CHARGE_ID_1, row); String charge2 = ImportHandlerUtils.readAsString(FixedDepositConstants.CHARGE_ID_2, row); - if (charge1!=null) { - if (ImportHandlerUtils.readAsDouble(FixedDepositConstants.CHARGE_AMOUNT_1, row)!=null) { - charges.add(new SavingsAccountChargeData( - ImportHandlerUtils.readAsLong(FixedDepositConstants.CHARGE_ID_1, row), + if (charge1 != null) { + if (ImportHandlerUtils.readAsDouble(FixedDepositConstants.CHARGE_AMOUNT_1, row) != null) { + charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(FixedDepositConstants.CHARGE_ID_1, row), BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(FixedDepositConstants.CHARGE_AMOUNT_1, row)), ImportHandlerUtils.readAsDate(FixedDepositConstants.CHARGE_DUE_DATE_1, row))); } - }else { - charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(FixedDepositConstants.CHARGE_ID_1, row), - null, + } else { + charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(FixedDepositConstants.CHARGE_ID_1, row), null, ImportHandlerUtils.readAsDate(FixedDepositConstants.CHARGE_DUE_DATE_1, row))); } - if (charge2!=null) { - if (ImportHandlerUtils.readAsDouble(FixedDepositConstants.CHARGE_AMOUNT_2, row)!=null) { + if (charge2 != null) { + if (ImportHandlerUtils.readAsDouble(FixedDepositConstants.CHARGE_AMOUNT_2, row) != null) { charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(FixedDepositConstants.CHARGE_ID_2, row), BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(FixedDepositConstants.CHARGE_AMOUNT_2, row)), ImportHandlerUtils.readAsDate(FixedDepositConstants.CHARGE_DUE_DATE_2, row))); - }else { - charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(FixedDepositConstants.CHARGE_ID_2, row), - null, + } else { + charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(FixedDepositConstants.CHARGE_ID_2, row), null, ImportHandlerUtils.readAsDate(FixedDepositConstants.CHARGE_DUE_DATE_2, row))); } } String status = ImportHandlerUtils.readAsString(FixedDepositConstants.STATUS_COL, row); statuses.add(status); Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), clientName); - return FixedDepositAccountData.importInstance (clientId, productId, fieldOfficerId, submittedOnDate, + return FixedDepositAccountData.importInstance(clientId, productId, fieldOfficerId, submittedOnDate, interestCompoundingPeriodTypeEnum, interestPostingPeriodTypeEnum, interestCalculationTypeEnum, - interestCalculationDaysInYearTypeEnum, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, - depositAmount, depositPeriod, depositPeriodFrequencyId, externalId, charges,row.getRowNum(),locale,dateFormat); + interestCalculationDaysInYearTypeEnum, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, depositAmount, depositPeriod, + depositPeriodFrequencyId, externalId, charges, row.getRowNum(), locale, dateFormat); } public Count importEntity(String dateFormat) { Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; int progressLevel = 0; - Long savingsId=null; + Long savingsId = null; for (int i = 0; i < savings.size(); i++) { Row row = savingsSheet.getRow(savings.get(i).getRowIndex()); Cell statusCell = row.createCell(FixedDepositConstants.STATUS_COL); @@ -294,7 +288,7 @@ public class FixedDepositImportHandler implements ImportHandler { progressLevel = getProgressLevel(status); if (progressLevel == 0) { - CommandProcessingResult result= importSavings(i,dateFormat); + CommandProcessingResult result = importSavings(i, dateFormat); savingsId = result.getSavingsId(); progressLevel = 1; } else { @@ -317,18 +311,20 @@ public class FixedDepositImportHandler implements ImportHandler { successCount++; statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - writeFixedDepositErrorMessage(savingsId,errorMessage,progressLevel,statusCell,errorReportCell,row); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + writeFixedDepositErrorMessage(savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row); } } setReportHeaders(savingsSheet); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - private void writeFixedDepositErrorMessage(Long savingsId,String errorMessage,int progressLevel,Cell statusCell,Cell errorReportCell,Row row){ + + private void writeFixedDepositErrorMessage(Long savingsId, String errorMessage, int progressLevel, Cell statusCell, + Cell errorReportCell, Row row) { String status = ""; if (progressLevel == 0) { status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED; @@ -346,8 +342,8 @@ public class FixedDepositImportHandler implements ImportHandler { errorReportCell.setCellValue(errorMessage); } - private int importSavingsClosing(Long savingsId, int i,String dateFormat) { - if(closedOnDate.get(i)!=null) { + private int importSavingsClosing(Long savingsId, int i, String dateFormat) { + if (closedOnDate.get(i) != null) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); String payload = gsonBuilder.create().toJson(closedOnDate.get(i)); @@ -360,22 +356,22 @@ public class FixedDepositImportHandler implements ImportHandler { return 4; } - private CommandProcessingResult importSavings(int i,String dateFormat) { + private CommandProcessingResult importSavings(int i, String dateFormat) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - gsonBuilder.registerTypeAdapter(EnumOptionData.class,new EnumOptionDataIdSerializer()); - JsonObject savingsJsonob=gsonBuilder.create().toJsonTree(savings.get(i)).getAsJsonObject(); + gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer()); + JsonObject savingsJsonob = gsonBuilder.create().toJsonTree(savings.get(i)).getAsJsonObject(); savingsJsonob.remove("withdrawalFeeForTransfers"); - JsonArray chargesJsonAr=savingsJsonob.getAsJsonArray("charges"); - for (int j=0;j savingsTransactions; private String savingsAccountId = ""; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + @Autowired - public FixedDepositTransactionImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public FixedDepositTransactionImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } + @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - this.savingsTransactions=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + this.savingsTransactions = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } @@ -74,67 +76,68 @@ public class FixedDepositTransactionImportHandler implements ImportHandler { for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; row = savingsTransactionSheet.getRow(rowIndex); - if(ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) { + if (ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) { savingsTransactions.add(readSavingsTransaction(row, locale, dateFormat)); } } } - private SavingsAccountTransactionData readSavingsTransaction(Row row,String locale,String dateFormat) { - String savingsAccountIdCheck=null; - if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row)!=null) { - savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) - .toString(); + private SavingsAccountTransactionData readSavingsTransaction(Row row, String locale, String dateFormat) { + String savingsAccountIdCheck = null; + if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) != null) { + savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row).toString(); } - if(savingsAccountIdCheck!=null) { + if (savingsAccountIdCheck != null) { savingsAccountId = savingsAccountIdCheck; } String transactionType = ImportHandlerUtils.readAsString(TransactionConstants.TRANSACTION_TYPE_COL, row); - SavingsAccountTransactionEnumData savingsAccountTransactionEnumData=new SavingsAccountTransactionEnumData(null,null,transactionType); + SavingsAccountTransactionEnumData savingsAccountTransactionEnumData = new SavingsAccountTransactionEnumData(null, null, + transactionType); - BigDecimal amount=null; - if (ImportHandlerUtils.readAsDouble(TransactionConstants.AMOUNT_COL, row)!=null) { + BigDecimal amount = null; + if (ImportHandlerUtils.readAsDouble(TransactionConstants.AMOUNT_COL, row) != null) { amount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(TransactionConstants.AMOUNT_COL, row)); } LocalDate transactionDate = ImportHandlerUtils.readAsDate(TransactionConstants.TRANSACTION_DATE_COL, row); String paymentType = ImportHandlerUtils.readAsString(TransactionConstants.PAYMENT_TYPE_COL, row); - Long paymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), paymentType); + Long paymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), + paymentType); String accountNumber = ImportHandlerUtils.readAsString(TransactionConstants.ACCOUNT_NO_COL, row); String checkNumber = ImportHandlerUtils.readAsString(TransactionConstants.CHECK_NO_COL, row); String routingCode = ImportHandlerUtils.readAsString(TransactionConstants.ROUTING_CODE_COL, row); String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row); String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row); - return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, - checkNumber, routingCode, receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(),locale,dateFormat); + return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode, + receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(), locale, + dateFormat); } public Count importEntity(String dateFormat) { Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_TRANSACTION_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - gsonBuilder.registerTypeAdapter(SavingsAccountTransactionEnumData.class - ,new SavingsAccountTransactionEnumValueSerialiser()); + gsonBuilder.registerTypeAdapter(SavingsAccountTransactionEnumData.class, new SavingsAccountTransactionEnumValueSerialiser()); for (SavingsAccountTransactionData transaction : savingsTransactions) { try { - JsonObject savingsTransactionJsonob=gsonBuilder.create().toJsonTree(transaction).getAsJsonObject(); + JsonObject savingsTransactionJsonob = gsonBuilder.create().toJsonTree(transaction).getAsJsonObject(); savingsTransactionJsonob.remove("transactionType"); savingsTransactionJsonob.remove("reversed"); savingsTransactionJsonob.remove("interestedPostedAsOn"); - String payload= savingsTransactionJsonob.toString(); - CommandWrapper commandRequest=null; + String payload = savingsTransactionJsonob.toString(); + CommandWrapper commandRequest = null; if (transaction.getTransactionType().getValue().equals("Withdrawal")) { commandRequest = new CommandWrapperBuilder() // .fixedDepositAccountWithdrawal(transaction.getSavingsAccountId()) // .withJson(payload) // .build(); // - }else if (transaction.getTransactionType().getValue().equals("Deposit")){ + } else if (transaction.getTransactionType().getValue().equals("Deposit")) { commandRequest = new CommandWrapperBuilder() // .fixedDepositAccountDeposit(transaction.getSavingsAccountId()) // .withJson(payload) // @@ -145,17 +148,18 @@ public class FixedDepositTransactionImportHandler implements ImportHandler { Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(savingsTransactionSheet,transaction.getRowIndex(),errorMessage,TransactionConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(savingsTransactionSheet, transaction.getRowIndex(), errorMessage, + TransactionConstants.STATUS_COL); } } - savingsTransactionSheet.setColumnWidth(TransactionConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(TransactionConstants.STATUS_COL, savingsTransactionSheet.getRow(TransactionConstants.STATUS_COL), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - return Count.instance(successCount,errorCount); + savingsTransactionSheet.setColumnWidth(TransactionConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + ImportHandlerUtils.writeString(TransactionConstants.STATUS_COL, savingsTransactionSheet.getRow(TransactionConstants.STATUS_COL), + TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/group/GroupImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/group/GroupImportHandler.java index d054b6662..142e8c9ed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/group/GroupImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/group/GroupImportHandler.java @@ -53,27 +53,27 @@ import org.springframework.stereotype.Service; @Service public class GroupImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(GroupImportHandler.class); private List groups; private List meetings; private Workbook workbook; - private Liststatuses; + private List statuses; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public GroupImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public GroupImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - groups=new ArrayList<>(); - meetings=new ArrayList<>(); - statuses=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + groups = new ArrayList<>(); + meetings = new ArrayList<>(); + statuses = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } @@ -82,131 +82,128 @@ public class GroupImportHandler implements ImportHandler { Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(groupsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row = groupsSheet.getRow(rowIndex); - if(ImportHandlerUtils.isNotImported(row, GroupConstants.STATUS_COL)) { - groups.add(readGroup(row,locale,dateFormat)); - meetings.add(readMeeting(row,locale,dateFormat)); - } - } - } - - private CalendarData readMeeting(Row row,String locale,String dateFormat) { - LocalDate meetingStartDate = ImportHandlerUtils.readAsDate(GroupConstants.MEETING_START_DATE_COL, row); - Boolean isRepeating = ImportHandlerUtils.readAsBoolean(GroupConstants.IS_REPEATING_COL, row); - String frequency = ImportHandlerUtils.readAsString(GroupConstants.FREQUENCY_COL, row); - EnumOptionData frequencyEnum=new EnumOptionData(null,null,ImportHandlerUtils.getFrequencyId(frequency)); - Integer interval = ImportHandlerUtils.readAsInt(GroupConstants.INTERVAL_COL, row); - String repeatsOnDay = ImportHandlerUtils.readAsString(GroupConstants.REPEATS_ON_DAY_COL, row); - EnumOptionData repeatsOnDayEnum=new EnumOptionData(null,null,ImportHandlerUtils.getRepeatsOnDayId(repeatsOnDay)); - if(meetingStartDate==null) { - return null; - } else { - if(repeatsOnDay==null) { - return CalendarData.importInstanceNoRepeatsOnDay(meetingStartDate, isRepeating, frequencyEnum, interval, - row.getRowNum(), locale, dateFormat); - } else { - return CalendarData.importInstanceWithRepeatsOnDay(meetingStartDate, isRepeating, frequencyEnum, - interval, repeatsOnDayEnum, row.getRowNum(), locale, dateFormat); + row = groupsSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, GroupConstants.STATUS_COL)) { + groups.add(readGroup(row, locale, dateFormat)); + meetings.add(readMeeting(row, locale, dateFormat)); } } } - private GroupGeneralData readGroup(Row row,String locale,String dateFormat) { + + private CalendarData readMeeting(Row row, String locale, String dateFormat) { + LocalDate meetingStartDate = ImportHandlerUtils.readAsDate(GroupConstants.MEETING_START_DATE_COL, row); + Boolean isRepeating = ImportHandlerUtils.readAsBoolean(GroupConstants.IS_REPEATING_COL, row); + String frequency = ImportHandlerUtils.readAsString(GroupConstants.FREQUENCY_COL, row); + EnumOptionData frequencyEnum = new EnumOptionData(null, null, ImportHandlerUtils.getFrequencyId(frequency)); + Integer interval = ImportHandlerUtils.readAsInt(GroupConstants.INTERVAL_COL, row); + String repeatsOnDay = ImportHandlerUtils.readAsString(GroupConstants.REPEATS_ON_DAY_COL, row); + EnumOptionData repeatsOnDayEnum = new EnumOptionData(null, null, ImportHandlerUtils.getRepeatsOnDayId(repeatsOnDay)); + if (meetingStartDate == null) { + return null; + } else { + if (repeatsOnDay == null) { + return CalendarData.importInstanceNoRepeatsOnDay(meetingStartDate, isRepeating, frequencyEnum, interval, row.getRowNum(), + locale, dateFormat); + } else { + return CalendarData.importInstanceWithRepeatsOnDay(meetingStartDate, isRepeating, frequencyEnum, interval, repeatsOnDayEnum, + row.getRowNum(), locale, dateFormat); + } + } + } + + private GroupGeneralData readGroup(Row row, String locale, String dateFormat) { String status = ImportHandlerUtils.readAsString(GroupConstants.STATUS_COL, row); String officeName = ImportHandlerUtils.readAsString(GroupConstants.OFFICE_NAME_COL, row); Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName); String staffName = ImportHandlerUtils.readAsString(GroupConstants.STAFF_NAME_COL, row); Long staffId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), staffName); String centerName = ImportHandlerUtils.readAsString(GroupConstants.CENTER_NAME_COL, row); - Long centerId=null; - if(centerName!=null) { - centerId = ImportHandlerUtils - .getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME), centerName); + Long centerId = null; + if (centerName != null) { + centerId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME), centerName); } String externalId = ImportHandlerUtils.readAsString(GroupConstants.EXTERNAL_ID_COL, row); Boolean active = ImportHandlerUtils.readAsBoolean(GroupConstants.ACTIVE_COL, row); - LocalDate submittedOnDate=ImportHandlerUtils.readAsDate(GroupConstants.SUBMITTED_ON_DATE_COL,row); - LocalDate activationDate=null; - if(active) { + LocalDate submittedOnDate = ImportHandlerUtils.readAsDate(GroupConstants.SUBMITTED_ON_DATE_COL, row); + LocalDate activationDate = null; + if (active) { activationDate = ImportHandlerUtils.readAsDate(GroupConstants.ACTIVATION_DATE_COL, row); - }else { - activationDate=submittedOnDate; + } else { + activationDate = submittedOnDate; } String groupName = ImportHandlerUtils.readAsString(GroupConstants.NAME_COL, row); - if (groupName == null || groupName.equals("")) { - throw new IllegalArgumentException("Name is blank"); - } + if (groupName == null || groupName.equals("")) { throw new IllegalArgumentException("Name is blank"); } List clientMembers = new ArrayList<>(); - for (int cellNo = GroupConstants.CLIENT_NAMES_STARTING_COL; cellNo clientMembers,Long clientId){ - for (ClientData client: clientMembers) { - if (client.getId().equals(clientId)){ - return true; - } - } - return false; - } + private boolean containsClientId(List clientMembers, Long clientId) { + for (ClientData client : clientMembers) { + if (client.getId().equals(clientId)) { return true; } + } + return false; + } public Count importEntity(String dateFormat) { Sheet groupSheet = workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME); - int successCount=0; - int errorCount=0; + int successCount = 0; + int errorCount = 0; int progressLevel = 0; String groupId = ""; - String errorMessage=""; + String errorMessage = ""; for (int i = 0; i < groups.size(); i++) { Row row = groupSheet.getRow(groups.get(i).getRowIndex()); Cell errorReportCell = row.createCell(GroupConstants.FAILURE_COL); Cell statusCell = row.createCell(GroupConstants.STATUS_COL); - CommandProcessingResult result=null; + CommandProcessingResult result = null; try { String status = statuses.get(i); progressLevel = getProgressLevel(status); - if(progressLevel == 0) - { - result = importGroup(i,dateFormat); + if (progressLevel == 0) { + result = importGroup(i, dateFormat); groupId = result.getGroupId().toString(); progressLevel = 1; } else { - groupId = ImportHandlerUtils - .readAsInt(GroupConstants.GROUP_ID_COL, groupSheet.getRow(groups.get(i).getRowIndex())) + groupId = ImportHandlerUtils.readAsInt(GroupConstants.GROUP_ID_COL, groupSheet.getRow(groups.get(i).getRowIndex())) .toString(); } - if(meetings.get(i) != null && groups.get(i).getCenterId() == null) { + if (meetings.get(i) != null && groups.get(i).getCenterId() == null) { progressLevel = importGroupMeeting(result, i, dateFormat); } statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - writeGroupErrorMessage(groupId,errorMessage,progressLevel,statusCell,errorReportCell,row); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + writeGroupErrorMessage(groupId, errorMessage, progressLevel, statusCell, errorReportCell, row); } } setReportHeaders(groupSheet); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - private void writeGroupErrorMessage(String groupId,String errorMessage,int progressLevel,Cell statusCell,Cell errorReportCell,Row row){ + + private void writeGroupErrorMessage(String groupId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell, + Row row) { String status = ""; - if(progressLevel == 0) { + if (progressLevel == 0) { status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED; } else if (progressLevel == 1) { status = TemplatePopulateImportConstants.STATUS_MEETING_FAILED; @@ -214,11 +211,12 @@ public class GroupImportHandler implements ImportHandler { statusCell.setCellValue(status); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.RED)); - if(progressLevel>0) { + if (progressLevel > 0) { row.createCell(GroupConstants.GROUP_ID_COL).setCellValue(Integer.parseInt(groupId)); } errorReportCell.setCellValue(errorMessage); } + private void setReportHeaders(Sheet groupSheet) { ImportHandlerUtils.writeString(GroupConstants.STATUS_COL, groupSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); @@ -229,19 +227,18 @@ public class GroupImportHandler implements ImportHandler { } private Integer importGroupMeeting(CommandProcessingResult result, int rowIndex, String dateFormat) { - CalendarData calendarData=meetings.get(rowIndex); + CalendarData calendarData = meetings.get(rowIndex); calendarData.setTitle("group_" + result.getGroupId().toString() + "_CollectionMeeting"); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - gsonBuilder.registerTypeAdapter(EnumOptionData.class,new EnumOptionDataValueSerializer()); + gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataValueSerializer()); String payload = gsonBuilder.create().toJson(calendarData); - CommandWrapper commandWrapper=new CommandWrapper(result.getOfficeId(),result.getGroupId(), - result.getClientId(),result.getLoanId(),result.getSavingsId(),null, - null,null,null,null,payload,result.getTransactionId(), - result.getProductId(),null,null,null); + CommandWrapper commandWrapper = new CommandWrapper(result.getOfficeId(), result.getGroupId(), result.getClientId(), + result.getLoanId(), result.getSavingsId(), null, null, null, null, null, payload, result.getTransactionId(), + result.getProductId(), null, null, null); final CommandWrapper commandRequest = new CommandWrapperBuilder() // - .createCalendar(commandWrapper,TemplatePopulateImportConstants.CENTER_ENTITY_TYPE,result.getGroupId()) // + .createCalendar(commandWrapper, TemplatePopulateImportConstants.CENTER_ENTITY_TYPE, result.getGroupId()) // .withJson(payload) // .build(); // final CommandProcessingResult meetingresult = commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -252,8 +249,8 @@ public class GroupImportHandler implements ImportHandler { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); Type clientCollectionType = new TypeToken>() {}.getType(); - gsonBuilder.registerTypeAdapter(clientCollectionType,new ClientIdSerializer()); - String payload= gsonBuilder.create().toJson(groups.get(rowIndex)); + gsonBuilder.registerTypeAdapter(clientCollectionType, new ClientIdSerializer()); + String payload = gsonBuilder.create().toJson(groups.get(rowIndex)); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createGroup() // .withJson(payload) // @@ -263,13 +260,10 @@ public class GroupImportHandler implements ImportHandler { } private int getProgressLevel(String status) { - if(status==null || status.equals(TemplatePopulateImportConstants.STATUS_CREATION_FAILED)) { + if (status == null || status.equals(TemplatePopulateImportConstants.STATUS_CREATION_FAILED)) { return 0; - } else if (status.equals(TemplatePopulateImportConstants.STATUS_MEETING_FAILED)) { - return 1; - } + } else if (status.equals(TemplatePopulateImportConstants.STATUS_MEETING_FAILED)) { return 1; } return 0; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/guarantor/GuarantorImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/guarantor/GuarantorImportHandler.java index 15b300d8a..1b553048e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/guarantor/GuarantorImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/guarantor/GuarantorImportHandler.java @@ -47,24 +47,24 @@ import org.springframework.stereotype.Service; @Service public class GuarantorImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(GuarantorImportHandler.class); private Workbook workbook; private List guarantors; - private Long loanAccountId ; + private Long loanAccountId; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; -@Autowired - public GuarantorImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + @Autowired + public GuarantorImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - this.guarantors=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + this.guarantors = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } @@ -73,24 +73,24 @@ public class GuarantorImportHandler implements ImportHandler { Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(addGuarantorSheet, GuarantorConstants.LOAN_ACCOUNT_NO_COL); for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row = addGuarantorSheet.getRow(rowIndex); - if (ImportHandlerUtils.isNotImported(row, GuarantorConstants.STATUS_COL)) { - guarantors.add(readGuarantor(row, locale, dateFormat)); - } + row = addGuarantorSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, GuarantorConstants.STATUS_COL)) { + guarantors.add(readGuarantor(row, locale, dateFormat)); + } } } - private GuarantorData readGuarantor(Row row,String locale,String dateFormat) { - String loanaccountInfo=ImportHandlerUtils.readAsString(GuarantorConstants.LOAN_ACCOUNT_NO_COL, row); - if (loanaccountInfo!=null){ - String[] loanAccountAr=loanaccountInfo.split("-"); - loanAccountId=Long.parseLong(loanAccountAr[0]); + private GuarantorData readGuarantor(Row row, String locale, String dateFormat) { + String loanaccountInfo = ImportHandlerUtils.readAsString(GuarantorConstants.LOAN_ACCOUNT_NO_COL, row); + if (loanaccountInfo != null) { + String[] loanAccountAr = loanaccountInfo.split("-"); + loanAccountId = Long.parseLong(loanAccountAr[0]); } String guarantorType = ImportHandlerUtils.readAsString(GuarantorConstants.GUARANTO_TYPE_COL, row); Integer guarantorTypeId = null; - if (guarantorType!=null) { + if (guarantorType != null) { if (guarantorType.equalsIgnoreCase(TemplatePopulateImportConstants.GUARANTOR_INTERNAL)) { guarantorTypeId = 1; } else if (guarantorType.equalsIgnoreCase(TemplatePopulateImportConstants.GUARANTOR_EXTERNAL)) { @@ -99,11 +99,11 @@ public class GuarantorImportHandler implements ImportHandler { } String clientName = ImportHandlerUtils.readAsString(GuarantorConstants.ENTITY_ID_COL, row); Long entityId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), clientName); - String clientRelationshipTypeInfo=ImportHandlerUtils.readAsString(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, row); - Integer clientRelationshipTypeId=null; - if (clientRelationshipTypeInfo!=null){ - String[] clientRelationshipTypeAr=clientRelationshipTypeInfo.split("-"); - clientRelationshipTypeId=Integer.parseInt(clientRelationshipTypeAr[1]); + String clientRelationshipTypeInfo = ImportHandlerUtils.readAsString(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, row); + Integer clientRelationshipTypeId = null; + if (clientRelationshipTypeInfo != null) { + String[] clientRelationshipTypeAr = clientRelationshipTypeInfo.split("-"); + clientRelationshipTypeId = Integer.parseInt(clientRelationshipTypeAr[1]); } String firstname = ImportHandlerUtils.readAsString(GuarantorConstants.FIRST_NAME_COL, row); String lastname = ImportHandlerUtils.readAsString(GuarantorConstants.LAST_NAME_COL, row); @@ -115,20 +115,20 @@ public class GuarantorImportHandler implements ImportHandler { Integer savingsId = ImportHandlerUtils.readAsInt(GuarantorConstants.SAVINGS_ID_COL, row); BigDecimal amount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(GuarantorConstants.AMOUNT, row)); - return GuarantorData.importInstance(guarantorTypeId,clientRelationshipTypeId,entityId,firstname, - lastname,addressLine1, addressLine2,city,dob,zip,savingsId,amount, row.getRowNum(), loanAccountId,locale,dateFormat); + return GuarantorData.importInstance(guarantorTypeId, clientRelationshipTypeId, entityId, firstname, lastname, addressLine1, + addressLine2, city, dob, zip, savingsId, amount, row.getRowNum(), loanAccountId, locale, dateFormat); } public Count importEntity(String dateFormat) { Sheet addGuarantorSheet = workbook.getSheet(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; - GsonBuilder gsonBuilder=new GsonBuilder(); + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; + GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); for (GuarantorData guarantor : guarantors) { try { - JsonObject guarantorJsonob=gsonBuilder.create().toJsonTree(guarantor).getAsJsonObject(); + JsonObject guarantorJsonob = gsonBuilder.create().toJsonTree(guarantor).getAsJsonObject(); guarantorJsonob.remove("status"); String payload = guarantorJsonob.toString(); final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -140,19 +140,20 @@ public class GuarantorImportHandler implements ImportHandler { Cell statusCell = addGuarantorSheet.getRow(guarantor.getRowIndex()).createCell(GuarantorConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(addGuarantorSheet,guarantor.getRowIndex(),errorMessage,GuarantorConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(addGuarantorSheet, guarantor.getRowIndex(), errorMessage, + GuarantorConstants.STATUS_COL); } } - addGuarantorSheet.setColumnWidth(GuarantorConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(GuarantorConstants.STATUS_COL, addGuarantorSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), + addGuarantorSheet.setColumnWidth(GuarantorConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + ImportHandlerUtils.writeString(GuarantorConstants.STATUS_COL, + addGuarantorSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/ClientIdSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/ClientIdSerializer.java index 125deffc7..87125545a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/ClientIdSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/ClientIdSerializer.java @@ -31,11 +31,11 @@ public class ClientIdSerializer implements JsonSerializer @Override public JsonElement serialize(Collection src, Type typeOfSrc, JsonSerializationContext context) { - JsonArray clientIdJsonArray=new JsonArray(); - for (ClientData client:src) { - JsonElement clientIdElment=new JsonPrimitive(client.id().toString()); + JsonArray clientIdJsonArray = new JsonArray(); + for (ClientData client : src) { + JsonElement clientIdElment = new JsonPrimitive(client.id().toString()); clientIdJsonArray.add(clientIdElment); } return clientIdJsonArray; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/CodeValueDataIdSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/CodeValueDataIdSerializer.java index 6a9b78e13..97bb215ed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/CodeValueDataIdSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/CodeValueDataIdSerializer.java @@ -26,6 +26,7 @@ import java.lang.reflect.Type; import org.apache.fineract.infrastructure.codes.data.CodeValueData; public class CodeValueDataIdSerializer implements JsonSerializer { + @Override public JsonElement serialize(CodeValueData src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getId()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/CurrencyDateCodeSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/CurrencyDateCodeSerializer.java index bc137e2b0..d35cbfa94 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/CurrencyDateCodeSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/CurrencyDateCodeSerializer.java @@ -25,7 +25,8 @@ import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import org.apache.fineract.organisation.monetary.data.CurrencyData; -public class CurrencyDateCodeSerializer implements JsonSerializer{ +public class CurrencyDateCodeSerializer implements JsonSerializer { + @Override public JsonElement serialize(CurrencyData src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.code()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/DateSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/DateSerializer.java index 8297b23b1..d21642e97 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/DateSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/DateSerializer.java @@ -37,4 +37,4 @@ public class DateSerializer implements JsonSerializer { public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString(dateFormat)); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/EnumOptionDataIdSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/EnumOptionDataIdSerializer.java index 5e7533dd5..07c0ec409 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/EnumOptionDataIdSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/EnumOptionDataIdSerializer.java @@ -26,6 +26,7 @@ import java.lang.reflect.Type; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public class EnumOptionDataIdSerializer implements JsonSerializer { + @Override public JsonElement serialize(EnumOptionData src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getId()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/EnumOptionDataValueSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/EnumOptionDataValueSerializer.java index a9456e099..69b30dce7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/EnumOptionDataValueSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/EnumOptionDataValueSerializer.java @@ -26,6 +26,7 @@ import java.lang.reflect.Type; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public class EnumOptionDataValueSerializer implements JsonSerializer { + @Override public JsonElement serialize(EnumOptionData src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getValue()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/GroupIdSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/GroupIdSerializer.java index 4e3353770..9faaf4113 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/GroupIdSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/helper/GroupIdSerializer.java @@ -28,11 +28,12 @@ import java.util.Collection; import org.apache.fineract.portfolio.group.data.GroupGeneralData; public class GroupIdSerializer implements JsonSerializer> { + @Override public JsonElement serialize(Collection src, Type typeOfSrc, JsonSerializationContext context) { - JsonArray groupIdJsonArray=new JsonArray(); - for (GroupGeneralData group:src) { - JsonElement groupIdElement=new JsonPrimitive(group.getId().toString()); + JsonArray groupIdJsonArray = new JsonArray(); + for (GroupGeneralData group : src) { + JsonElement groupIdElement = new JsonPrimitive(group.getId().toString()); groupIdJsonArray.add(groupIdElement); } return groupIdJsonArray; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/journalentry/JournalEntriesImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/journalentry/JournalEntriesImportHandler.java index dd756ae0d..f4610ee12 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/journalentry/JournalEntriesImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/journalentry/JournalEntriesImportHandler.java @@ -49,6 +49,7 @@ import org.springframework.stereotype.Service; @Service public class JournalEntriesImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(JournalEntriesImportHandler.class); private Workbook workbook; private List gltransaction; @@ -60,16 +61,15 @@ public class JournalEntriesImportHandler implements ImportHandler { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public JournalEntriesImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public JournalEntriesImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - gltransaction=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + gltransaction = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } @@ -82,67 +82,61 @@ public class JournalEntriesImportHandler implements ImportHandler { Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(addJournalEntriesSheet, 4); for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row = addJournalEntriesSheet.getRow(rowIndex); + row = addJournalEntriesSheet.getRow(rowIndex); - currentTransactionId = ImportHandlerUtils.readAsString(JournalEntryConstants.TRANSACTION_ID_COL, row); + currentTransactionId = ImportHandlerUtils.readAsString(JournalEntryConstants.TRANSACTION_ID_COL, row); - if (currentTransactionId.equals(prevTransactionId)) { - if (journalEntry != null) { + if (currentTransactionId.equals(prevTransactionId)) { + if (journalEntry != null) { - String creditGLAcct = ImportHandlerUtils.readAsString( - JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, row); - Long glAccountIdCredit = ImportHandlerUtils.getIdByName( - workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME), creditGLAcct); + String creditGLAcct = ImportHandlerUtils.readAsString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, row); + Long glAccountIdCredit = ImportHandlerUtils + .getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME), creditGLAcct); - String debitGLAcct = ImportHandlerUtils.readAsString( - JournalEntryConstants. GL_ACCOUNT_ID_DEBIT_COL, row); + String debitGLAcct = ImportHandlerUtils.readAsString(JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, row); - Long glAccountIdDebit = ImportHandlerUtils.getIdByName( - workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME), debitGLAcct); + Long glAccountIdDebit = ImportHandlerUtils + .getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME), debitGLAcct); - BigDecimal creditAmt=null; - if (ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_CREDIT_COL, row)!=null) { - creditAmt = BigDecimal.valueOf( - ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_CREDIT_COL, row)); - } - BigDecimal debitAmount=null; - if (ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_DEBIT_COL, row)!=null) { - debitAmount = BigDecimal.valueOf( - ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_DEBIT_COL, row)); - } - - if (creditGLAcct!=null) { - - CreditDebit credit = new CreditDebit( - glAccountIdCredit, creditAmt); - journalEntry.addCredits(credit); - } - if (debitGLAcct!=null) { - CreditDebit debit = new CreditDebit( - glAccountIdDebit, debitAmount); - - journalEntry.addDebits(debit); - } + BigDecimal creditAmt = null; + if (ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_CREDIT_COL, row) != null) { + creditAmt = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_CREDIT_COL, row)); } - } else { - - if (journalEntry != null) { - gltransaction.add(journalEntry); - journalEntry = null; + BigDecimal debitAmount = null; + if (ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_DEBIT_COL, row) != null) { + debitAmount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_DEBIT_COL, row)); } - journalEntry = readAddJournalEntries(row,locale,dateFormat); + if (creditGLAcct != null) { + CreditDebit credit = new CreditDebit(glAccountIdCredit, creditAmt); + journalEntry.addCredits(credit); + } + if (debitGLAcct != null) { + CreditDebit debit = new CreditDebit(glAccountIdDebit, debitAmount); + + journalEntry.addDebits(debit); + } } + } else { + + if (journalEntry != null) { + gltransaction.add(journalEntry); + journalEntry = null; + } + + journalEntry = readAddJournalEntries(row, locale, dateFormat); + + } prevTransactionId = currentTransactionId; } // Adding last JE gltransaction.add(journalEntry); } - private JournalEntryData readAddJournalEntries(Row row,String locale,String dateFormat) { + private JournalEntryData readAddJournalEntries(Row row, String locale, String dateFormat) { LocalDate transactionDateCheck = ImportHandlerUtils.readAsDate(JournalEntryConstants.TRANSACION_ON_DATE_COL, row); - if (transactionDateCheck!=null) { + if (transactionDateCheck != null) { transactionDate = transactionDateCheck; } @@ -152,8 +146,8 @@ public class JournalEntriesImportHandler implements ImportHandler { Long paymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), paymentType); String currencyName = ImportHandlerUtils.readAsString(JournalEntryConstants.CURRENCY_NAME_COL, row); - String currencyCode = ImportHandlerUtils.getCodeByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), - currencyName).toString(); + String currencyCode = ImportHandlerUtils + .getCodeByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), currencyName).toString(); String glAccountNameCredit = ImportHandlerUtils.readAsString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, row); Long glAccountIdCredit = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME), glAccountNameCredit); @@ -164,73 +158,75 @@ public class JournalEntriesImportHandler implements ImportHandler { credits = new ArrayList<>(); debits = new ArrayList<>(); - // String credit = readAsString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, row); - // String debit = readAsString(JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, row); + // String credit = + // readAsString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, row); + // String debit = + // readAsString(JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, row); - if (glAccountNameCredit!=null) { - if (ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_CREDIT_COL, row) != null){ - credits.add(new CreditDebit(glAccountIdCredit, BigDecimal.valueOf(ImportHandlerUtils.readAsDouble( - JournalEntryConstants.AMOUNT_CREDIT_COL, row)))); - }else { - credits.add(new CreditDebit(glAccountIdCredit,null)); + if (glAccountNameCredit != null) { + if (ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_CREDIT_COL, row) != null) { + credits.add(new CreditDebit(glAccountIdCredit, + BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_CREDIT_COL, row)))); + } else { + credits.add(new CreditDebit(glAccountIdCredit, null)); } } - if (glAccountNameDebit!=null) { - if (ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_DEBIT_COL, row)!=null) { - debits.add(new CreditDebit(glAccountIdDebit, BigDecimal.valueOf(ImportHandlerUtils.readAsDouble( - JournalEntryConstants.AMOUNT_DEBIT_COL, row)))); - }else { + if (glAccountNameDebit != null) { + if (ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_DEBIT_COL, row) != null) { + debits.add(new CreditDebit(glAccountIdDebit, + BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(JournalEntryConstants.AMOUNT_DEBIT_COL, row)))); + } else { debits.add(new CreditDebit(glAccountIdDebit, null)); } } - String accountNo=ImportHandlerUtils.readAsString(JournalEntryConstants.ACCOUNT_NO_COL,row); - String chequeNo=ImportHandlerUtils.readAsString(JournalEntryConstants.CHECK_NO_COL,row); - String routingCode=ImportHandlerUtils.readAsString(JournalEntryConstants.ROUTING_CODE_COL,row); - String receiptNo=ImportHandlerUtils.readAsString(JournalEntryConstants.RECEIPT_NO_COL,row); - String bankNo=ImportHandlerUtils.readAsString(JournalEntryConstants.BANK_NO_COL,row); - String comments=ImportHandlerUtils.readAsString(JournalEntryConstants.COMMENTS_COL,row); + String accountNo = ImportHandlerUtils.readAsString(JournalEntryConstants.ACCOUNT_NO_COL, row); + String chequeNo = ImportHandlerUtils.readAsString(JournalEntryConstants.CHECK_NO_COL, row); + String routingCode = ImportHandlerUtils.readAsString(JournalEntryConstants.ROUTING_CODE_COL, row); + String receiptNo = ImportHandlerUtils.readAsString(JournalEntryConstants.RECEIPT_NO_COL, row); + String bankNo = ImportHandlerUtils.readAsString(JournalEntryConstants.BANK_NO_COL, row); + String comments = ImportHandlerUtils.readAsString(JournalEntryConstants.COMMENTS_COL, row); - return JournalEntryData.importInstance(officeId, transactionDate, currencyCode, - paymentTypeId, row.getRowNum(), credits, debits,accountNo,chequeNo,routingCode,receiptNo,bankNo,comments,locale,dateFormat); + return JournalEntryData.importInstance(officeId, transactionDate, currencyCode, paymentTypeId, row.getRowNum(), credits, debits, + accountNo, chequeNo, routingCode, receiptNo, bankNo, comments, locale, dateFormat); } public Count importEntity(String dateFormat) { Sheet addJournalEntriesSheet = workbook.getSheet(TemplatePopulateImportConstants.JOURNAL_ENTRY_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - gsonBuilder.registerTypeAdapter(CurrencyData.class,new CurrencyDateCodeSerializer()); + gsonBuilder.registerTypeAdapter(CurrencyData.class, new CurrencyDateCodeSerializer()); for (JournalEntryData transaction : gltransaction) { try { - String payload =gsonBuilder.create().toJson(transaction); + String payload = gsonBuilder.create().toJson(transaction); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createJournalEntry() // .withJson(payload) // .build(); // final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest); successCount++; - Cell statusCell = addJournalEntriesSheet.getRow( - transaction.getRowIndex()).createCell(JournalEntryConstants.STATUS_COL); + Cell statusCell = addJournalEntriesSheet.getRow(transaction.getRowIndex()).createCell(JournalEntryConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); - statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, - IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(addJournalEntriesSheet,transaction.getRowIndex(),errorMessage, JournalEntryConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(addJournalEntriesSheet, transaction.getRowIndex(), errorMessage, + JournalEntryConstants.STATUS_COL); } } addJournalEntriesSheet.setColumnWidth(JournalEntryConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(JournalEntryConstants.STATUS_COL, addJournalEntriesSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - return Count.instance(successCount,errorCount); + ImportHandlerUtils.writeString(JournalEntryConstants.STATUS_COL, + addJournalEntriesSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), + TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/loan/LoanImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/loan/LoanImportHandler.java index 577bc9051..f761bf351 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/loan/LoanImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/loan/LoanImportHandler.java @@ -56,6 +56,7 @@ import org.springframework.stereotype.Service; @Service public class LoanImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(LoanImportHandler.class); private Workbook workbook; private List loans; @@ -67,19 +68,19 @@ public class LoanImportHandler implements ImportHandler { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public LoanImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public LoanImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } + @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; + this.workbook = workbook; this.loans = new ArrayList<>(); this.approvalDates = new ArrayList<>(); this.loanRepayments = new ArrayList<>(); this.disbursalDates = new ArrayList<>(); - this.statuses=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.statuses = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } @@ -88,80 +89,78 @@ public class LoanImportHandler implements ImportHandler { Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(loanSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row = loanSheet.getRow(rowIndex); - if ( ImportHandlerUtils.isNotImported(row, LoanConstants.STATUS_COL)) { - loans.add(readLoan(row,locale,dateFormat)); - approvalDates.add(readLoanApproval(row,locale,dateFormat)); - disbursalDates.add(readDisbursalData(row,locale,dateFormat)); - loanRepayments.add(readLoanRepayment(row,locale,dateFormat)); - } + row = loanSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, LoanConstants.STATUS_COL)) { + loans.add(readLoan(row, locale, dateFormat)); + approvalDates.add(readLoanApproval(row, locale, dateFormat)); + disbursalDates.add(readDisbursalData(row, locale, dateFormat)); + loanRepayments.add(readLoanRepayment(row, locale, dateFormat)); + } } } - private LoanTransactionData readLoanRepayment(Row row,String locale,String dateFormat) { - BigDecimal repaymentAmount=null; - if (ImportHandlerUtils.readAsDouble(LoanConstants.TOTAL_AMOUNT_REPAID_COL, row)!=null) { - repaymentAmount = BigDecimal - .valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.TOTAL_AMOUNT_REPAID_COL, row)); + private LoanTransactionData readLoanRepayment(Row row, String locale, String dateFormat) { + BigDecimal repaymentAmount = null; + if (ImportHandlerUtils.readAsDouble(LoanConstants.TOTAL_AMOUNT_REPAID_COL, row) != null) { + repaymentAmount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.TOTAL_AMOUNT_REPAID_COL, row)); } LocalDate lastRepaymentDate = ImportHandlerUtils.readAsDate(LoanConstants.LAST_REPAYMENT_DATE_COL, row); String repaymentType = ImportHandlerUtils.readAsString(LoanConstants.REPAYMENT_TYPE_COL, row); - Long repaymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), repaymentType); - if (repaymentAmount!=null&&lastRepaymentDate!=null&&repaymentType!=null&&repaymentTypeId!=null) { - return LoanTransactionData.importInstance(repaymentAmount, lastRepaymentDate, repaymentTypeId, - row.getRowNum(), locale, dateFormat); + Long repaymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), + repaymentType); + if (repaymentAmount != null && lastRepaymentDate != null && repaymentType != null && repaymentTypeId != null) { + return LoanTransactionData.importInstance(repaymentAmount, lastRepaymentDate, repaymentTypeId, row.getRowNum(), locale, + dateFormat); } return null; } - private DisbursementData readDisbursalData(Row row,String locale,String dateFormat) { + private DisbursementData readDisbursalData(Row row, String locale, String dateFormat) { LocalDate disbursedDate = ImportHandlerUtils.readAsDate(LoanConstants.DISBURSED_DATE_COL, row); - String linkAccountId=null; - if ( ImportHandlerUtils.readAsLong(LoanConstants.LINK_ACCOUNT_ID, row)!=null) { + String linkAccountId = null; + if (ImportHandlerUtils.readAsLong(LoanConstants.LINK_ACCOUNT_ID, row) != null) { linkAccountId = ImportHandlerUtils.readAsLong(LoanConstants.LINK_ACCOUNT_ID, row).toString(); } - if (disbursedDate!=null) { - return DisbursementData.importInstance(disbursedDate,linkAccountId,row.getRowNum(),locale,dateFormat); + if (disbursedDate != null) { + return DisbursementData.importInstance(disbursedDate, linkAccountId, row.getRowNum(), locale, dateFormat); } return null; } - private LoanApprovalData readLoanApproval(Row row,String locale,String dateFormat) { + private LoanApprovalData readLoanApproval(Row row, String locale, String dateFormat) { LocalDate approvedDate = ImportHandlerUtils.readAsDate(LoanConstants.APPROVED_DATE_COL, row); - if (approvedDate!=null) { - return LoanApprovalData.importInstance(approvedDate, row.getRowNum(), locale, dateFormat); - } + if (approvedDate != null) { return LoanApprovalData.importInstance(approvedDate, row.getRowNum(), locale, dateFormat); } return null; } - private LoanAccountData readLoan(Row row,String locale,String dateFormat) { - String externalId = ImportHandlerUtils.readAsString(LoanConstants.EXTERNAL_ID_COL, row); - String status = ImportHandlerUtils.readAsString(LoanConstants.STATUS_COL, row); - String productName = ImportHandlerUtils.readAsString(LoanConstants.PRODUCT_COL, row); - Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName); - String loanOfficerName = ImportHandlerUtils.readAsString(LoanConstants.LOAN_OFFICER_NAME_COL, row); - Long loanOfficerId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), loanOfficerName); - LocalDate submittedOnDate = ImportHandlerUtils.readAsDate(LoanConstants.SUBMITTED_ON_DATE_COL, row); - String fundName = ImportHandlerUtils.readAsString(LoanConstants.FUND_NAME_COL, row); + private LoanAccountData readLoan(Row row, String locale, String dateFormat) { + String externalId = ImportHandlerUtils.readAsString(LoanConstants.EXTERNAL_ID_COL, row); + String status = ImportHandlerUtils.readAsString(LoanConstants.STATUS_COL, row); + String productName = ImportHandlerUtils.readAsString(LoanConstants.PRODUCT_COL, row); + Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName); + String loanOfficerName = ImportHandlerUtils.readAsString(LoanConstants.LOAN_OFFICER_NAME_COL, row); + Long loanOfficerId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), + loanOfficerName); + LocalDate submittedOnDate = ImportHandlerUtils.readAsDate(LoanConstants.SUBMITTED_ON_DATE_COL, row); + String fundName = ImportHandlerUtils.readAsString(LoanConstants.FUND_NAME_COL, row); Long fundId; if (fundName == null) { fundId = null; } else { - fundId = ImportHandlerUtils - .getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), fundName); + fundId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), fundName); } BigDecimal principal = null; - if ( ImportHandlerUtils.readAsDouble(LoanConstants.PRINCIPAL_COL, row) != null) { + if (ImportHandlerUtils.readAsDouble(LoanConstants.PRINCIPAL_COL, row) != null) { principal = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.PRINCIPAL_COL, row)); } - Integer numberOfRepayments = ImportHandlerUtils.readAsInt(LoanConstants.NO_OF_REPAYMENTS_COL, row); - Integer repaidEvery = ImportHandlerUtils.readAsInt(LoanConstants.REPAID_EVERY_COL, row); - String repaidEveryFrequency = ImportHandlerUtils.readAsString(LoanConstants.REPAID_EVERY_FREQUENCY_COL, row); + Integer numberOfRepayments = ImportHandlerUtils.readAsInt(LoanConstants.NO_OF_REPAYMENTS_COL, row); + Integer repaidEvery = ImportHandlerUtils.readAsInt(LoanConstants.REPAID_EVERY_COL, row); + String repaidEveryFrequency = ImportHandlerUtils.readAsString(LoanConstants.REPAID_EVERY_FREQUENCY_COL, row); String repaidEveryFrequencyId = ""; EnumOptionData repaidEveryFrequencyEnums = null; if (repaidEveryFrequency != null) { @@ -174,8 +173,8 @@ public class LoanImportHandler implements ImportHandler { } repaidEveryFrequencyEnums = new EnumOptionData(null, null, repaidEveryFrequencyId); } - Integer loanTerm = ImportHandlerUtils.readAsInt(LoanConstants.LOAN_TERM_COL, row); - String loanTermFrequency = ImportHandlerUtils.readAsString(LoanConstants.LOAN_TERM_FREQUENCY_COL, row); + Integer loanTerm = ImportHandlerUtils.readAsInt(LoanConstants.LOAN_TERM_COL, row); + String loanTermFrequency = ImportHandlerUtils.readAsString(LoanConstants.LOAN_TERM_FREQUENCY_COL, row); EnumOptionData loanTermFrequencyEnum = null; if (loanTermFrequency != null) { String loanTermFrequencyId = ""; @@ -189,11 +188,10 @@ public class LoanImportHandler implements ImportHandler { loanTermFrequencyEnum = new EnumOptionData(null, null, loanTermFrequencyId); } BigDecimal nominalInterestRate = null; - if ( ImportHandlerUtils.readAsDouble(LoanConstants.NOMINAL_INTEREST_RATE_COL, row) != null) { - nominalInterestRate = BigDecimal - .valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.NOMINAL_INTEREST_RATE_COL, row)); + if (ImportHandlerUtils.readAsDouble(LoanConstants.NOMINAL_INTEREST_RATE_COL, row) != null) { + nominalInterestRate = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.NOMINAL_INTEREST_RATE_COL, row)); } - String amortization = ImportHandlerUtils.readAsString(LoanConstants.AMORTIZATION_COL, row); + String amortization = ImportHandlerUtils.readAsString(LoanConstants.AMORTIZATION_COL, row); String amortizationId = ""; EnumOptionData amortizationEnumOption = null; if (amortization != null) { @@ -204,7 +202,7 @@ public class LoanImportHandler implements ImportHandler { } amortizationEnumOption = new EnumOptionData(null, null, amortizationId); } - String interestMethod = ImportHandlerUtils.readAsString(LoanConstants.INTEREST_METHOD_COL, row); + String interestMethod = ImportHandlerUtils.readAsString(LoanConstants.INTEREST_METHOD_COL, row); String interestMethodId = ""; EnumOptionData interestMethodEnum = null; if (interestMethod != null) { @@ -228,13 +226,12 @@ public class LoanImportHandler implements ImportHandler { } BigDecimal arrearsTolerance = null; - if ( ImportHandlerUtils.readAsDouble(LoanConstants.ARREARS_TOLERANCE_COL, row) != null) { - arrearsTolerance = BigDecimal - .valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.ARREARS_TOLERANCE_COL, row)); + if (ImportHandlerUtils.readAsDouble(LoanConstants.ARREARS_TOLERANCE_COL, row) != null) { + arrearsTolerance = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.ARREARS_TOLERANCE_COL, row)); } - String repaymentStrategy = ImportHandlerUtils.readAsString(LoanConstants.REPAYMENT_STRATEGY_COL, row); + String repaymentStrategy = ImportHandlerUtils.readAsString(LoanConstants.REPAYMENT_STRATEGY_COL, row); Long repaymentStrategyId = null; - if (repaymentStrategy!=null) { + if (repaymentStrategy != null) { if (repaymentStrategy.equalsIgnoreCase("Penalties, Fees, Interest, Principal order")) { repaymentStrategyId = 1L; } else if (repaymentStrategy.equalsIgnoreCase("HeavensFamily Unique")) { @@ -251,15 +248,15 @@ public class LoanImportHandler implements ImportHandler { repaymentStrategyId = 7L; } } - Integer graceOnPrincipalPayment = ImportHandlerUtils.readAsInt(LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL, row); - Integer graceOnInterestPayment = ImportHandlerUtils.readAsInt(LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL, row); - Integer graceOnInterestCharged = ImportHandlerUtils.readAsInt(LoanConstants.GRACE_ON_INTEREST_CHARGED_COL, row); - LocalDate interestChargedFromDate = ImportHandlerUtils.readAsDate(LoanConstants.INTEREST_CHARGED_FROM_COL, row); - LocalDate firstRepaymentOnDate = ImportHandlerUtils.readAsDate(LoanConstants.FIRST_REPAYMENT_COL, row); - String loanType=null; - EnumOptionData loanTypeEnumOption=null; - if ( ImportHandlerUtils.readAsString(LoanConstants.LOAN_TYPE_COL, row)!=null) { - loanType = ImportHandlerUtils.readAsString(LoanConstants.LOAN_TYPE_COL, row).toLowerCase(Locale.ENGLISH); + Integer graceOnPrincipalPayment = ImportHandlerUtils.readAsInt(LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL, row); + Integer graceOnInterestPayment = ImportHandlerUtils.readAsInt(LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL, row); + Integer graceOnInterestCharged = ImportHandlerUtils.readAsInt(LoanConstants.GRACE_ON_INTEREST_CHARGED_COL, row); + LocalDate interestChargedFromDate = ImportHandlerUtils.readAsDate(LoanConstants.INTEREST_CHARGED_FROM_COL, row); + LocalDate firstRepaymentOnDate = ImportHandlerUtils.readAsDate(LoanConstants.FIRST_REPAYMENT_COL, row); + String loanType = null; + EnumOptionData loanTypeEnumOption = null; + if (ImportHandlerUtils.readAsString(LoanConstants.LOAN_TYPE_COL, row) != null) { + loanType = ImportHandlerUtils.readAsString(LoanConstants.LOAN_TYPE_COL, row).toLowerCase(Locale.ENGLISH); loanTypeEnumOption = new EnumOptionData(null, null, loanType); } @@ -268,61 +265,63 @@ public class LoanImportHandler implements ImportHandler { List charges = new ArrayList<>(); - Long charge1 = ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_1, row); - Long charge2 = ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_2, row); + Long charge1 = ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_1, row); + Long charge2 = ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_2, row); - Long groupId = ImportHandlerUtils.readAsLong(LoanConstants.GROUP_ID, row); + Long groupId = ImportHandlerUtils.readAsLong(LoanConstants.GROUP_ID, row); - String linkAccountId = ImportHandlerUtils.readAsString(LoanConstants.LINK_ACCOUNT_ID, row); + String linkAccountId = ImportHandlerUtils.readAsString(LoanConstants.LINK_ACCOUNT_ID, row); - if (charge1!=null) { - if ( ImportHandlerUtils.readAsDouble(LoanConstants.CHARGE_AMOUNT_1, row)!=null) { - charges.add(new LoanChargeData( ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_1, row), + if (charge1 != null) { + if (ImportHandlerUtils.readAsDouble(LoanConstants.CHARGE_AMOUNT_1, row) != null) { + charges.add(new LoanChargeData(ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_1, row), ImportHandlerUtils.readAsDate(LoanConstants.CHARGE_DUE_DATE_1, row), - BigDecimal.valueOf( ImportHandlerUtils.readAsDouble(LoanConstants.CHARGE_AMOUNT_1, row)))); - }else { - charges.add(new LoanChargeData( ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_1, row), - ImportHandlerUtils.readAsDate(LoanConstants.CHARGE_DUE_DATE_1, row),null)); + BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.CHARGE_AMOUNT_1, row)))); + } else { + charges.add(new LoanChargeData(ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_1, row), + ImportHandlerUtils.readAsDate(LoanConstants.CHARGE_DUE_DATE_1, row), null)); } } - if (charge2!=null) { - if ( ImportHandlerUtils.readAsDouble(LoanConstants.CHARGE_AMOUNT_2, row)!=null){ - charges.add(new LoanChargeData( ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_2, row), - ImportHandlerUtils.readAsDate(LoanConstants.CHARGE_DUE_DATE_2, row), - BigDecimal.valueOf( ImportHandlerUtils.readAsDouble(LoanConstants.CHARGE_AMOUNT_2, row)))); - }else { - charges.add(new LoanChargeData( ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_2, row), + if (charge2 != null) { + if (ImportHandlerUtils.readAsDouble(LoanConstants.CHARGE_AMOUNT_2, row) != null) { + charges.add(new LoanChargeData(ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_2, row), ImportHandlerUtils.readAsDate(LoanConstants.CHARGE_DUE_DATE_2, row), - null)); + BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.CHARGE_AMOUNT_2, row)))); + } else { + charges.add(new LoanChargeData(ImportHandlerUtils.readAsLong(LoanConstants.CHARGE_ID_2, row), + ImportHandlerUtils.readAsDate(LoanConstants.CHARGE_DUE_DATE_2, row), null)); } } statuses.add(status); - if (loanType!=null) { + if (loanType != null) { if (loanType.equals("individual")) { - Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), clientOrGroupName); - return LoanAccountData.importInstanceIndividual(loanTypeEnumOption, clientId, productId, loanOfficerId, submittedOnDate, fundId, - principal, numberOfRepayments, - repaidEvery, repaidEveryFrequencyEnums, loanTerm, loanTermFrequencyEnum, nominalInterestRate, submittedOnDate, - amortizationEnumOption, interestMethodEnum, interestCalculationPeriodEnum, arrearsTolerance, repaymentStrategyId, - graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, firstRepaymentOnDate, - row.getRowNum(), externalId, null, charges, linkAccountId,locale,dateFormat); + Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), + clientOrGroupName); + return LoanAccountData.importInstanceIndividual(loanTypeEnumOption, clientId, productId, loanOfficerId, submittedOnDate, + fundId, principal, numberOfRepayments, repaidEvery, repaidEveryFrequencyEnums, loanTerm, loanTermFrequencyEnum, + nominalInterestRate, submittedOnDate, amortizationEnumOption, interestMethodEnum, interestCalculationPeriodEnum, + arrearsTolerance, repaymentStrategyId, graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, + interestChargedFromDate, firstRepaymentOnDate, row.getRowNum(), externalId, null, charges, linkAccountId, locale, + dateFormat); } else if (loanType.equals("jlg")) { - Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), clientOrGroupName); - return LoanAccountData.importInstanceIndividual(loanTypeEnumOption, clientId, productId, loanOfficerId, submittedOnDate, fundId, - principal, numberOfRepayments, - repaidEvery, repaidEveryFrequencyEnums, loanTerm, loanTermFrequencyEnum, nominalInterestRate, submittedOnDate, - amortizationEnumOption, interestMethodEnum, interestCalculationPeriodEnum, arrearsTolerance, repaymentStrategyId, - graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, firstRepaymentOnDate, - row.getRowNum(), externalId, groupId, charges, linkAccountId,locale,dateFormat); + Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), + clientOrGroupName); + return LoanAccountData.importInstanceIndividual(loanTypeEnumOption, clientId, productId, loanOfficerId, submittedOnDate, + fundId, principal, numberOfRepayments, repaidEvery, repaidEveryFrequencyEnums, loanTerm, loanTermFrequencyEnum, + nominalInterestRate, submittedOnDate, amortizationEnumOption, interestMethodEnum, interestCalculationPeriodEnum, + arrearsTolerance, repaymentStrategyId, graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, + interestChargedFromDate, firstRepaymentOnDate, row.getRowNum(), externalId, groupId, charges, linkAccountId, locale, + dateFormat); } else { - Long groupIdforGroupLoan = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME), clientOrGroupName); - return LoanAccountData.importInstanceGroup(loanTypeEnumOption, groupIdforGroupLoan, productId, loanOfficerId, submittedOnDate, fundId, - principal, numberOfRepayments, - repaidEvery, repaidEveryFrequencyEnums, loanTerm, loanTermFrequencyEnum, nominalInterestRate, - amortizationEnumOption, interestMethodEnum, interestCalculationPeriodEnum, arrearsTolerance, - repaymentStrategyId, graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, - interestChargedFromDate, firstRepaymentOnDate, row.getRowNum(), externalId, linkAccountId,locale,dateFormat); + Long groupIdforGroupLoan = ImportHandlerUtils + .getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME), clientOrGroupName); + return LoanAccountData.importInstanceGroup(loanTypeEnumOption, groupIdforGroupLoan, productId, loanOfficerId, + submittedOnDate, fundId, principal, numberOfRepayments, repaidEvery, repaidEveryFrequencyEnums, loanTerm, + loanTermFrequencyEnum, nominalInterestRate, amortizationEnumOption, interestMethodEnum, + interestCalculationPeriodEnum, arrearsTolerance, repaymentStrategyId, graceOnPrincipalPayment, + graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, firstRepaymentOnDate, row.getRowNum(), + externalId, linkAccountId, locale, dateFormat); } } @@ -331,35 +330,34 @@ public class LoanImportHandler implements ImportHandler { public Count importEntity(String dateFormat) { Sheet loanSheet = workbook.getSheet(TemplatePopulateImportConstants.LOANS_SHEET_NAME); - int successCount=0; - int errorCount=0; + int successCount = 0; + int errorCount = 0; int progressLevel = 0; String loanId; - String errorMessage=""; + String errorMessage = ""; for (int i = 0; i < loans.size(); i++) { Row row = loanSheet.getRow(loans.get(i).getRowIndex()); Cell errorReportCell = row.createCell(LoanConstants.FAILURE_REPORT_COL); Cell statusCell = row.createCell(LoanConstants.STATUS_COL); - CommandProcessingResult result=null; - loanId=""; + CommandProcessingResult result = null; + loanId = ""; try { String status = statuses.get(i); progressLevel = getProgressLevel(status); - if (progressLevel == 0&& loans.get(i)!=null) { - result = importLoan(i,dateFormat); + if (progressLevel == 0 && loans.get(i) != null) { + result = importLoan(i, dateFormat); loanId = result.getLoanId().toString(); progressLevel = 1; } else { - loanId = ImportHandlerUtils.readAsString(LoanConstants.LOAN_ID_COL, - loanSheet.getRow(loans.get(i).getRowIndex())); + loanId = ImportHandlerUtils.readAsString(LoanConstants.LOAN_ID_COL, loanSheet.getRow(loans.get(i).getRowIndex())); } - if (progressLevel <= 1 && approvalDates.get(i)!=null) { + if (progressLevel <= 1 && approvalDates.get(i) != null) { progressLevel = importLoanApproval(result, i, dateFormat); } - if (progressLevel <= 2 && disbursalDates.get(i)!=null) { + if (progressLevel <= 2 && disbursalDates.get(i) != null) { progressLevel = importDisbursalData(result, i, dateFormat); } @@ -370,19 +368,20 @@ public class LoanImportHandler implements ImportHandler { successCount++; statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - writeLoanErrorMessage(loanId,errorMessage,progressLevel,statusCell,errorReportCell,row); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + writeLoanErrorMessage(loanId, errorMessage, progressLevel, statusCell, errorReportCell, row); } } setReportHeaders(loanSheet); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - private void writeLoanErrorMessage(String loanId,String errorMessage,int progressLevel,Cell statusCell,Cell errorReportCell,Row row){ + private void writeLoanErrorMessage(String loanId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell, + Row row) { String status = ""; if (progressLevel == 0) { status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED; @@ -401,6 +400,7 @@ public class LoanImportHandler implements ImportHandler { } errorReportCell.setCellValue(errorMessage); } + private void setReportHeaders(Sheet sheet) { sheet.setColumnWidth(LoanConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); Row rowHeader = sheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); @@ -409,12 +409,12 @@ public class LoanImportHandler implements ImportHandler { ImportHandlerUtils.writeString(LoanConstants.FAILURE_REPORT_COL, rowHeader, "Report"); } - private Integer importLoanRepayment(CommandProcessingResult result, int rowIndex,String dateFormat) { + private Integer importLoanRepayment(CommandProcessingResult result, int rowIndex, String dateFormat) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - JsonObject loanRepaymentJsonob=gsonBuilder.create().toJsonTree(loanRepayments.get(rowIndex)).getAsJsonObject(); + JsonObject loanRepaymentJsonob = gsonBuilder.create().toJsonTree(loanRepayments.get(rowIndex)).getAsJsonObject(); loanRepaymentJsonob.remove("manuallyReversed"); - String payload=loanRepaymentJsonob.toString(); + String payload = loanRepaymentJsonob.toString(); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .loanRepaymentTransaction(result.getLoanId()) // .withJson(payload) // @@ -432,7 +432,7 @@ public class LoanImportHandler implements ImportHandler { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); if (linkAccountId != null && !"".equals(linkAccountId)) { - String payload =gsonBuilder.create().toJson(disbusalData); + String payload = gsonBuilder.create().toJson(disbusalData); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .disburseLoanToSavingsApplication(result.getLoanId()) // .withJson(payload) // @@ -451,7 +451,7 @@ public class LoanImportHandler implements ImportHandler { return 3; } - private Integer importLoanApproval(CommandProcessingResult result, int rowIndex,String dateFormat) { + private Integer importLoanApproval(CommandProcessingResult result, int rowIndex, String dateFormat) { if (approvalDates.get(rowIndex) != null) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); @@ -466,17 +466,17 @@ public class LoanImportHandler implements ImportHandler { return 2; } - private CommandProcessingResult importLoan(int rowIndex,String dateFormat) { + private CommandProcessingResult importLoan(int rowIndex, String dateFormat) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - gsonBuilder.registerTypeAdapter(EnumOptionData.class,new EnumOptionDataValueSerializer()); - JsonObject loanJsonOb = gsonBuilder.create().toJsonTree(loans.get(rowIndex)).getAsJsonObject(); + gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataValueSerializer()); + JsonObject loanJsonOb = gsonBuilder.create().toJsonTree(loans.get(rowIndex)).getAsJsonObject(); loanJsonOb.remove("isLoanProductLinkedToFloatingRate"); loanJsonOb.remove("isInterestRecalculationEnabled"); loanJsonOb.remove("isFloatingInterestRate"); loanJsonOb.remove("isRatesEnabled"); - JsonArray chargesJsonAr=loanJsonOb.getAsJsonArray("charges"); - if (chargesJsonAr!=null) { + JsonArray chargesJsonAr = loanJsonOb.getAsJsonArray("charges"); + if (chargesJsonAr != null) { for (int i = 0; i < chargesJsonAr.size(); i++) { JsonElement chargesJsonElement = chargesJsonAr.get(i); JsonObject chargeJsonOb = chargesJsonElement.getAsJsonObject(); @@ -487,7 +487,7 @@ public class LoanImportHandler implements ImportHandler { } } loanJsonOb.remove("isTopup"); - String payload=loanJsonOb.toString(); + String payload = loanJsonOb.toString(); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createLoanApplication() // .withJson(payload) // @@ -497,17 +497,14 @@ public class LoanImportHandler implements ImportHandler { } private int getProgressLevel(String status) { - if (status==null || status.equals(TemplatePopulateImportConstants.STATUS_CREATION_FAILED)) { + if (status == null || status.equals(TemplatePopulateImportConstants.STATUS_CREATION_FAILED)) { return 0; } else if (status.equals(TemplatePopulateImportConstants.STATUS_APPROVAL_FAILED)) { return 1; } else if (status.equals(TemplatePopulateImportConstants.STATUS_DISBURSAL_FAILED)) { return 2; - } else if (status.equals(TemplatePopulateImportConstants.STATUS_DISBURSAL_REPAYMENT_FAILED)) { - return 3; - } + } else if (status.equals(TemplatePopulateImportConstants.STATUS_DISBURSAL_REPAYMENT_FAILED)) { return 3; } return 0; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/loanrepayment/LoanRepaymentImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/loanrepayment/LoanRepaymentImportHandler.java index e21d3b6b1..715a25a1d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/loanrepayment/LoanRepaymentImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/loanrepayment/LoanRepaymentImportHandler.java @@ -47,76 +47,79 @@ import org.springframework.stereotype.Service; @Service public class LoanRepaymentImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(LoanRepaymentImportHandler.class); - private Workbook workbook; - private List loanRepayments; + private Workbook workbook; + private List loanRepayments; private Long loanAccountId; private final LoanReadPlatformService loanReadPlatformService; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + @Autowired - public LoanRepaymentImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService, final LoanReadPlatformService loanReadPlatformService) { + public LoanRepaymentImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final LoanReadPlatformService loanReadPlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; this.loanReadPlatformService = loanReadPlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - this.loanRepayments=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + this.loanRepayments = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } + public void readExcelFile(String locale, String dateFormat) { Sheet loanRepaymentSheet = workbook.getSheet(TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME); Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(loanRepaymentSheet, LoanRepaymentConstants.AMOUNT_COL); for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row = loanRepaymentSheet.getRow(rowIndex); - if(ImportHandlerUtils.isNotImported(row, LoanRepaymentConstants.STATUS_COL)) { - loanRepayments.add(readLoanRepayment(row, locale, dateFormat)); - } + row = loanRepaymentSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, LoanRepaymentConstants.STATUS_COL)) { + loanRepayments.add(readLoanRepayment(row, locale, dateFormat)); + } } } - private LoanTransactionData readLoanRepayment(Row row,String locale, String dateFormat) { - String loanaccountInfo=ImportHandlerUtils.readAsString(LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, row); - if (loanaccountInfo!=null){ - String[] loanAccountAr=loanaccountInfo.split("-"); + private LoanTransactionData readLoanRepayment(Row row, String locale, String dateFormat) { + String loanaccountInfo = ImportHandlerUtils.readAsString(LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, row); + if (loanaccountInfo != null) { + String[] loanAccountAr = loanaccountInfo.split("-"); loanAccountId = this.loanReadPlatformService.retrieveLoanIdByAccountNumber(loanAccountAr[0]); } - BigDecimal repaymentAmount=null; - if (ImportHandlerUtils.readAsDouble(LoanRepaymentConstants.AMOUNT_COL, row)!=null) { - repaymentAmount = BigDecimal - .valueOf(ImportHandlerUtils.readAsDouble(LoanRepaymentConstants.AMOUNT_COL, row)); + BigDecimal repaymentAmount = null; + if (ImportHandlerUtils.readAsDouble(LoanRepaymentConstants.AMOUNT_COL, row) != null) { + repaymentAmount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanRepaymentConstants.AMOUNT_COL, row)); } LocalDate repaymentDate = ImportHandlerUtils.readAsDate(LoanRepaymentConstants.REPAID_ON_DATE_COL, row); String repaymentType = ImportHandlerUtils.readAsString(LoanRepaymentConstants.REPAYMENT_TYPE_COL, row); - Long repaymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), repaymentType); + Long repaymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), + repaymentType); String accountNumber = ImportHandlerUtils.readAsString(LoanRepaymentConstants.ACCOUNT_NO_COL, row); Integer checkNumber = ImportHandlerUtils.readAsInt(LoanRepaymentConstants.CHECK_NO_COL, row); Integer routingCode = ImportHandlerUtils.readAsInt(LoanRepaymentConstants.ROUTING_CODE_COL, row); Integer receiptNumber = ImportHandlerUtils.readAsInt(LoanRepaymentConstants.RECEIPT_NO_COL, row); Integer bankNumber = ImportHandlerUtils.readAsInt(LoanRepaymentConstants.BANK_NO_COL, row); - return LoanTransactionData.importInstance(repaymentAmount, repaymentDate, repaymentTypeId, accountNumber, - checkNumber, routingCode, receiptNumber, bankNumber, loanAccountId, "", row.getRowNum(),locale,dateFormat); + return LoanTransactionData.importInstance(repaymentAmount, repaymentDate, repaymentTypeId, accountNumber, checkNumber, routingCode, + receiptNumber, bankNumber, loanAccountId, "", row.getRowNum(), locale, dateFormat); } public Count importEntity(String dateFormat) { Sheet loanRepaymentSheet = workbook.getSheet(TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); for (LoanTransactionData loanRepayment : loanRepayments) { try { - JsonObject loanRepaymentJsonob=gsonBuilder.create().toJsonTree(loanRepayment).getAsJsonObject(); + JsonObject loanRepaymentJsonob = gsonBuilder.create().toJsonTree(loanRepayment).getAsJsonObject(); loanRepaymentJsonob.remove("manuallyReversed"); - String payload=loanRepaymentJsonob.toString(); + String payload = loanRepaymentJsonob.toString(); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .loanRepaymentTransaction(loanRepayment.getAccountId()) // .withJson(payload) // @@ -126,11 +129,12 @@ public class LoanRepaymentImportHandler implements ImportHandler { Cell statusCell = loanRepaymentSheet.getRow(loanRepayment.getRowIndex()).createCell(LoanRepaymentConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(loanRepaymentSheet,loanRepayment.getRowIndex(),errorMessage,LoanRepaymentConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(loanRepaymentSheet, loanRepayment.getRowIndex(), errorMessage, + LoanRepaymentConstants.STATUS_COL); } } @@ -138,8 +142,7 @@ public class LoanRepaymentImportHandler implements ImportHandler { ImportHandlerUtils.writeString(LoanRepaymentConstants.STATUS_COL, loanRepaymentSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/office/OfficeImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/office/OfficeImportHandler.java index 055e316b1..04663e6f0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/office/OfficeImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/office/OfficeImportHandler.java @@ -43,48 +43,45 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; - @Service public class OfficeImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(OfficeImportHandler.class); private List offices; private Workbook workbook; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public OfficeImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public OfficeImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(final Workbook workbook, final String locale, final String dateFormat) { - this.offices=new ArrayList<>(); - this.workbook=workbook; + this.offices = new ArrayList<>(); + this.workbook = workbook; readExcelFile(locale, dateFormat); - return importEntity (dateFormat); + return importEntity(dateFormat); } - - public void readExcelFile(final String locale, final String dateFormat) { - Sheet officeSheet=workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); - Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(officeSheet,0); - for (int rowIndex=1;rowIndex<=noOfEntries;rowIndex++) { + Sheet officeSheet = workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); + Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(officeSheet, 0); + for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row=officeSheet.getRow(rowIndex); - if (ImportHandlerUtils.isNotImported(row, OfficeConstants.STATUS_COL)){ + row = officeSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, OfficeConstants.STATUS_COL)) { offices.add(readOffice(row, locale, dateFormat)); } } } private OfficeData readOffice(Row row, final String locale, final String dateFormat) { - String officeName = ImportHandlerUtils.readAsString(OfficeConstants.OFFICE_NAME_COL,row); - Long parentId= ImportHandlerUtils.readAsLong(OfficeConstants.PARENT_OFFICE_ID_COL,row); - LocalDate openedDate= ImportHandlerUtils.readAsDate(OfficeConstants.OPENED_ON_COL,row); - String externalId= ImportHandlerUtils.readAsString(OfficeConstants.EXTERNAL_ID_COL,row); - OfficeData office = OfficeData.importInstance(officeName,parentId,openedDate,externalId); + String officeName = ImportHandlerUtils.readAsString(OfficeConstants.OFFICE_NAME_COL, row); + Long parentId = ImportHandlerUtils.readAsLong(OfficeConstants.PARENT_OFFICE_ID_COL, row); + LocalDate openedDate = ImportHandlerUtils.readAsDate(OfficeConstants.OPENED_ON_COL, row); + String externalId = ImportHandlerUtils.readAsString(OfficeConstants.EXTERNAL_ID_COL, row); + OfficeData office = OfficeData.importInstance(officeName, parentId, openedDate, externalId); office.setImportFields(row.getRowNum(), locale, dateFormat); return office; } @@ -96,8 +93,8 @@ public class OfficeImportHandler implements ImportHandler { int successCount = 0; int errorCount = 0; - String errorMessage=""; - for (OfficeData office: offices) { + String errorMessage = ""; + for (OfficeData office : offices) { try { String payload = gsonBuilder.create().toJson(office); final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -105,19 +102,20 @@ public class OfficeImportHandler implements ImportHandler { .withJson(payload) // .build(); // final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest); - successCount ++; + successCount++; Cell statusCell = officeSheet.getRow(office.getRowIndex()).createCell(OfficeConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(officeSheet,office.getRowIndex(),errorMessage,OfficeConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(officeSheet, office.getRowIndex(), errorMessage, OfficeConstants.STATUS_COL); } } officeSheet.setColumnWidth(OfficeConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(OfficeConstants.STATUS_COL, officeSheet.getRow(0), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); + ImportHandlerUtils.writeString(OfficeConstants.STATUS_COL, officeSheet.getRow(0), + TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); return Count.instance(successCount, errorCount); } @@ -125,5 +123,3 @@ public class OfficeImportHandler implements ImportHandler { return offices; } } - - diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/recurringdeposit/RecurringDepositImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/recurringdeposit/RecurringDepositImportHandler.java index 73acf8309..459843744 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/recurringdeposit/RecurringDepositImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/recurringdeposit/RecurringDepositImportHandler.java @@ -63,19 +63,19 @@ public class RecurringDepositImportHandler implements ImportHandler { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public RecurringDepositImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public RecurringDepositImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } + @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - savings=new ArrayList<>(); - approvalDates=new ArrayList<>(); - activationDates=new ArrayList<>(); - statuses=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + savings = new ArrayList<>(); + approvalDates = new ArrayList<>(); + activationDates = new ArrayList<>(); + statuses = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } @@ -84,45 +84,47 @@ public class RecurringDepositImportHandler implements ImportHandler { Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.ROWHEADER_INDEX); for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row = savingsSheet.getRow(rowIndex); - if (ImportHandlerUtils.isNotImported(row, RecurringDepositConstants.STATUS_COL)) { - savings.add(readSavings(row,locale,dateFormat)); - approvalDates.add(readSavingsApproval(row,locale,dateFormat)); - activationDates.add(readSavingsActivation(row,locale,dateFormat)); - } + row = savingsSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, RecurringDepositConstants.STATUS_COL)) { + savings.add(readSavings(row, locale, dateFormat)); + approvalDates.add(readSavingsApproval(row, locale, dateFormat)); + activationDates.add(readSavingsActivation(row, locale, dateFormat)); + } } } - private SavingsActivation readSavingsActivation(Row row,String locale, String dateFormat) { + private SavingsActivation readSavingsActivation(Row row, String locale, String dateFormat) { LocalDate activationDate = ImportHandlerUtils.readAsDate(RecurringDepositConstants.ACTIVATION_DATE_COL, row); - if (activationDate!=null) { + if (activationDate != null) { return SavingsActivation.importInstance(activationDate, row.getRowNum(), locale, dateFormat); } else { return null; } } - private SavingsApproval readSavingsApproval(Row row,String locale, String dateFormat) { + private SavingsApproval readSavingsApproval(Row row, String locale, String dateFormat) { LocalDate approvalDate = ImportHandlerUtils.readAsDate(RecurringDepositConstants.APPROVED_DATE_COL, row); - if (approvalDate!=null) { + if (approvalDate != null) { return SavingsApproval.importInstance(approvalDate, row.getRowNum(), locale, dateFormat); } else { return null; } } - private RecurringDepositAccountData readSavings(Row row,String locale, String dateFormat) { + private RecurringDepositAccountData readSavings(Row row, String locale, String dateFormat) { String productName = ImportHandlerUtils.readAsString(RecurringDepositConstants.PRODUCT_COL, row); Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName); String fieldOfficerName = ImportHandlerUtils.readAsString(RecurringDepositConstants.FIELD_OFFICER_NAME_COL, row); - Long fieldOfficerId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), fieldOfficerName); + Long fieldOfficerId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), + fieldOfficerName); LocalDate submittedOnDate = ImportHandlerUtils.readAsDate(RecurringDepositConstants.SUBMITTED_ON_DATE_COL, row); - String interestCompoundingPeriodType = ImportHandlerUtils.readAsString(RecurringDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, row); + String interestCompoundingPeriodType = ImportHandlerUtils.readAsString(RecurringDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, + row); Long interestCompoundingPeriodTypeId = null; - EnumOptionData interestCompoundingPeriodTypeEnum=null; - if (interestCompoundingPeriodType!=null) { + EnumOptionData interestCompoundingPeriodTypeEnum = null; + if (interestCompoundingPeriodType != null) { if (interestCompoundingPeriodType.equalsIgnoreCase("Daily")) { interestCompoundingPeriodTypeId = 1L; } else if (interestCompoundingPeriodType.equalsIgnoreCase("Monthly")) { @@ -138,8 +140,8 @@ public class RecurringDepositImportHandler implements ImportHandler { } String interestPostingPeriodType = ImportHandlerUtils.readAsString(RecurringDepositConstants.INTEREST_POSTING_PERIOD_COL, row); Long interestPostingPeriodTypeId = null; - EnumOptionData interestPostingPeriodTypeEnum=null; - if (interestPostingPeriodType!=null) { + EnumOptionData interestPostingPeriodTypeEnum = null; + if (interestPostingPeriodType != null) { if (interestPostingPeriodType.equalsIgnoreCase("Monthly")) { interestPostingPeriodTypeId = 4L; } else if (interestPostingPeriodType.equalsIgnoreCase("Quarterly")) { @@ -149,36 +151,37 @@ public class RecurringDepositImportHandler implements ImportHandler { } else if (interestPostingPeriodType.equalsIgnoreCase("BiAnnual")) { interestPostingPeriodTypeId = 6L; } - interestPostingPeriodTypeEnum = new EnumOptionData(interestPostingPeriodTypeId, null, null); + interestPostingPeriodTypeEnum = new EnumOptionData(interestPostingPeriodTypeId, null, null); } String interestCalculationType = ImportHandlerUtils.readAsString(RecurringDepositConstants.INTEREST_CALCULATION_COL, row); Long interestCalculationTypeId = null; - EnumOptionData interestCalculationTypeEnum=null; - if (interestCalculationType!=null) { + EnumOptionData interestCalculationTypeEnum = null; + if (interestCalculationType != null) { if (interestCalculationType.equalsIgnoreCase("Daily Balance")) { interestCalculationTypeId = 1L; } else if (interestCalculationType.equalsIgnoreCase("Average Daily Balance")) { interestCalculationTypeId = 2L; } - interestCalculationTypeEnum = new EnumOptionData(interestCalculationTypeId, null, null); + interestCalculationTypeEnum = new EnumOptionData(interestCalculationTypeId, null, null); } - String interestCalculationDaysInYearType = ImportHandlerUtils.readAsString(RecurringDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row); - EnumOptionData interestCalculationDaysInYearTypeEnum=null; + String interestCalculationDaysInYearType = ImportHandlerUtils + .readAsString(RecurringDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row); + EnumOptionData interestCalculationDaysInYearTypeEnum = null; Long interestCalculationDaysInYearTypeId = null; - if (interestCalculationDaysInYearType!=null) { + if (interestCalculationDaysInYearType != null) { if (interestCalculationDaysInYearType.equalsIgnoreCase("360 Days")) { interestCalculationDaysInYearTypeId = 360L; } else if (interestCalculationDaysInYearType.equalsIgnoreCase("365 Days")) { interestCalculationDaysInYearTypeId = 365L; } - interestCalculationDaysInYearTypeEnum = new EnumOptionData(interestCalculationDaysInYearTypeId, null, null); + interestCalculationDaysInYearTypeEnum = new EnumOptionData(interestCalculationDaysInYearTypeId, null, null); } Integer lockinPeriodFrequency = ImportHandlerUtils.readAsInt(RecurringDepositConstants.LOCKIN_PERIOD_COL, row); String lockinPeriodFrequencyType = ImportHandlerUtils.readAsString(RecurringDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, row); Long lockinPeriodFrequencyTypeId = null; - EnumOptionData lockinPeriodFrequencyTypeEnum=null; - if (lockinPeriodFrequencyType!=null) { + EnumOptionData lockinPeriodFrequencyTypeEnum = null; + if (lockinPeriodFrequencyType != null) { if (lockinPeriodFrequencyType.equalsIgnoreCase("Days")) { lockinPeriodFrequencyTypeId = 0L; } else if (lockinPeriodFrequencyType.equalsIgnoreCase("Weeks")) { @@ -188,17 +191,17 @@ public class RecurringDepositImportHandler implements ImportHandler { } else if (lockinPeriodFrequencyType.equalsIgnoreCase("Years")) { lockinPeriodFrequencyTypeId = 3L; } - lockinPeriodFrequencyTypeEnum = new EnumOptionData(lockinPeriodFrequencyTypeId, null, null); + lockinPeriodFrequencyTypeEnum = new EnumOptionData(lockinPeriodFrequencyTypeId, null, null); } - BigDecimal depositAmount=null; - if (ImportHandlerUtils.readAsDouble(RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL, row)!=null) { - depositAmount = BigDecimal.valueOf( - ImportHandlerUtils.readAsDouble(RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL, row)); + BigDecimal depositAmount = null; + if (ImportHandlerUtils.readAsDouble(RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL, row) != null) { + depositAmount = BigDecimal + .valueOf(ImportHandlerUtils.readAsDouble(RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL, row)); } Integer depositPeriod = ImportHandlerUtils.readAsInt(RecurringDepositConstants.DEPOSIT_PERIOD_COL, row); String depositPeriodFrequency = ImportHandlerUtils.readAsString(RecurringDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, row); Long depositPeriodFrequencyId = null; - if (depositPeriodFrequency!=null) { + if (depositPeriodFrequency != null) { if (depositPeriodFrequency.equalsIgnoreCase("Days")) { depositPeriodFrequencyId = 0L; } else if (depositPeriodFrequency.equalsIgnoreCase("Weeks")) { @@ -212,8 +215,8 @@ public class RecurringDepositImportHandler implements ImportHandler { Integer recurringFrequency = ImportHandlerUtils.readAsInt(RecurringDepositConstants.DEPOSIT_FREQUENCY_COL, row); String recurringFrequencyType = ImportHandlerUtils.readAsString(RecurringDepositConstants.DEPOSIT_FREQUENCY_TYPE_COL, row); Long recurringFrequencyTypeId = null; - EnumOptionData recurringFrequencyTypeEnum=null; - if (recurringFrequencyType!=null) { + EnumOptionData recurringFrequencyTypeEnum = null; + if (recurringFrequencyType != null) { if (recurringFrequencyType.equalsIgnoreCase("Days")) { recurringFrequencyTypeId = 0L; } else if (recurringFrequencyType.equalsIgnoreCase("Weeks")) { @@ -223,7 +226,7 @@ public class RecurringDepositImportHandler implements ImportHandler { } else if (recurringFrequencyType.equalsIgnoreCase("Years")) { recurringFrequencyTypeId = 3L; } - recurringFrequencyTypeEnum = new EnumOptionData(recurringFrequencyTypeId, null, null); + recurringFrequencyTypeEnum = new EnumOptionData(recurringFrequencyTypeId, null, null); } LocalDate depositStartDate = ImportHandlerUtils.readAsDate(RecurringDepositConstants.DEPOSIT_START_DATE_COL, row); Boolean allowWithdrawal = ImportHandlerUtils.readAsBoolean(RecurringDepositConstants.ALLOW_WITHDRAWAL_COL, row); @@ -237,26 +240,24 @@ public class RecurringDepositImportHandler implements ImportHandler { String charge1 = ImportHandlerUtils.readAsString(RecurringDepositConstants.CHARGE_ID_1, row); String charge2 = ImportHandlerUtils.readAsString(RecurringDepositConstants.CHARGE_ID_2, row); - if (charge1!=null) { - if (ImportHandlerUtils.readAsDouble(RecurringDepositConstants.CHARGE_AMOUNT_1, row)!=null) { + if (charge1 != null) { + if (ImportHandlerUtils.readAsDouble(RecurringDepositConstants.CHARGE_AMOUNT_1, row) != null) { charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(RecurringDepositConstants.CHARGE_ID_1, row), BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(RecurringDepositConstants.CHARGE_AMOUNT_1, row)), ImportHandlerUtils.readAsDate(RecurringDepositConstants.CHARGE_DUE_DATE_1, row))); - }else { - charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(RecurringDepositConstants.CHARGE_ID_1, row), - null, + } else { + charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(RecurringDepositConstants.CHARGE_ID_1, row), null, ImportHandlerUtils.readAsDate(RecurringDepositConstants.CHARGE_DUE_DATE_1, row))); } } - if (charge2!=null) { - if (ImportHandlerUtils.readAsDouble(RecurringDepositConstants.CHARGE_AMOUNT_2, row)!=null) { + if (charge2 != null) { + if (ImportHandlerUtils.readAsDouble(RecurringDepositConstants.CHARGE_AMOUNT_2, row) != null) { charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(RecurringDepositConstants.CHARGE_ID_2, row), BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(RecurringDepositConstants.CHARGE_AMOUNT_2, row)), ImportHandlerUtils.readAsDate(RecurringDepositConstants.CHARGE_DUE_DATE_2, row))); - }else { - charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(RecurringDepositConstants.CHARGE_ID_2, row), - null, + } else { + charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(RecurringDepositConstants.CHARGE_ID_2, row), null, ImportHandlerUtils.readAsDate(RecurringDepositConstants.CHARGE_DUE_DATE_2, row))); } } @@ -264,20 +265,19 @@ public class RecurringDepositImportHandler implements ImportHandler { statuses.add(status); Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), clientName); return RecurringDepositAccountData.importInstance(clientId, productId, fieldOfficerId, submittedOnDate, - interestCompoundingPeriodTypeEnum,interestPostingPeriodTypeEnum,interestCalculationTypeEnum, - interestCalculationDaysInYearTypeEnum, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, - depositAmount, depositPeriod, depositPeriodFrequencyId, depositStartDate, - recurringFrequency, recurringFrequencyTypeEnum, inheritCalendar, isMandatoryDeposit, - allowWithdrawal, adjustAdvancePayments, externalId,charges, row.getRowNum(),locale,dateFormat); + interestCompoundingPeriodTypeEnum, interestPostingPeriodTypeEnum, interestCalculationTypeEnum, + interestCalculationDaysInYearTypeEnum, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, depositAmount, depositPeriod, + depositPeriodFrequencyId, depositStartDate, recurringFrequency, recurringFrequencyTypeEnum, inheritCalendar, + isMandatoryDeposit, allowWithdrawal, adjustAdvancePayments, externalId, charges, row.getRowNum(), locale, dateFormat); } public Count importEntity(String dateFormat) { Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.RECURRING_DEPOSIT_SHEET_NAME); - int successCount=0; - int errorCount=0; + int successCount = 0; + int errorCount = 0; int progressLevel = 0; - Long savingsId=null; - String errorMessage=""; + Long savingsId = null; + String errorMessage = ""; for (int i = 0; i < savings.size(); i++) { Row row = savingsSheet.getRow(savings.get(i).getRowIndex()); Cell statusCell = row.createCell(RecurringDepositConstants.STATUS_COL); @@ -287,7 +287,7 @@ public class RecurringDepositImportHandler implements ImportHandler { progressLevel = getProgressLevel(status); if (progressLevel == 0) { - CommandProcessingResult result= importSavings(i,dateFormat); + CommandProcessingResult result = importSavings(i, dateFormat); savingsId = result.getSavingsId(); progressLevel = 1; } else { @@ -305,18 +305,19 @@ public class RecurringDepositImportHandler implements ImportHandler { successCount++; statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - writeRecurringDepositErrorMessage(savingsId,errorMessage,progressLevel,statusCell,errorReportCell,row); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + writeRecurringDepositErrorMessage(savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row); } } setReportHeaders(savingsSheet); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - private void writeRecurringDepositErrorMessage(Long savingsId,String errorMessage,int progressLevel,Cell statusCell,Cell errorReportCell,Row row){ + private void writeRecurringDepositErrorMessage(Long savingsId, String errorMessage, int progressLevel, Cell statusCell, + Cell errorReportCell, Row row) { String status = ""; if (progressLevel == 0) { status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED; @@ -343,8 +344,8 @@ public class RecurringDepositImportHandler implements ImportHandler { ImportHandlerUtils.writeString(RecurringDepositConstants.FAILURE_REPORT_COL, rowHeader, "Report"); } - private int importSavingsActivation(Long savingsId, int i,String dateFormat) { - if(activationDates.get(i)!=null) { + private int importSavingsActivation(Long savingsId, int i, String dateFormat) { + if (activationDates.get(i) != null) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); String payload = gsonBuilder.create().toJson(activationDates.get(i)); @@ -358,7 +359,7 @@ public class RecurringDepositImportHandler implements ImportHandler { } private int importSavingsApproval(Long savingsId, int i, String dateFormat) { - if(approvalDates.get(i)!=null) { + if (approvalDates.get(i) != null) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); String payload = gsonBuilder.create().toJson(approvalDates.get(i)); @@ -374,10 +375,10 @@ public class RecurringDepositImportHandler implements ImportHandler { private CommandProcessingResult importSavings(int i, String dateFormat) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - gsonBuilder.registerTypeAdapter(EnumOptionData.class,new EnumOptionDataIdSerializer()); - JsonObject savingsJsonob=gsonBuilder.create().toJsonTree(savings.get(i)).getAsJsonObject(); + gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer()); + JsonObject savingsJsonob = gsonBuilder.create().toJsonTree(savings.get(i)).getAsJsonObject(); savingsJsonob.remove("withdrawalFeeForTransfers"); - String payload=savingsJsonob.toString(); + String payload = savingsJsonob.toString(); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createRecurringDepositAccount() // .withJson(payload) // @@ -387,15 +388,12 @@ public class RecurringDepositImportHandler implements ImportHandler { } private int getProgressLevel(String status) { - if (status==null || status.equals(TemplatePopulateImportConstants.STATUS_CREATION_FAILED)) { + if (status == null || status.equals(TemplatePopulateImportConstants.STATUS_CREATION_FAILED)) { return 0; } else if (status.equals(TemplatePopulateImportConstants.STATUS_APPROVAL_FAILED)) { return 1; - } else if (status.equals(TemplatePopulateImportConstants.STATUS_ACTIVATION_FAILED)) { - return 2; - } + } else if (status.equals(TemplatePopulateImportConstants.STATUS_ACTIVATION_FAILED)) { return 2; } return 0; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/recurringdeposit/RecurringDepositTransactionImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/recurringdeposit/RecurringDepositTransactionImportHandler.java index d7b8938ca..7ec9ad8b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/recurringdeposit/RecurringDepositTransactionImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/recurringdeposit/RecurringDepositTransactionImportHandler.java @@ -57,17 +57,17 @@ public class RecurringDepositTransactionImportHandler implements ImportHandler { private String savingsAccountId = ""; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + @Autowired - public RecurringDepositTransactionImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public RecurringDepositTransactionImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - this.savingsTransactions=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + this.savingsTransactions = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } @@ -76,68 +76,69 @@ public class RecurringDepositTransactionImportHandler implements ImportHandler { Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsTransactionSheet, TransactionConstants.AMOUNT_COL); for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row = savingsTransactionSheet.getRow(rowIndex); - if(ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) { - savingsTransactions.add(readSavingsTransaction(row, locale, dateFormat)); - } + row = savingsTransactionSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) { + savingsTransactions.add(readSavingsTransaction(row, locale, dateFormat)); + } } } - private SavingsAccountTransactionData readSavingsTransaction(Row row,String locale, String dateFormat) { - String savingsAccountIdCheck=null; - if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row)!=null) { - savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) - .toString(); + private SavingsAccountTransactionData readSavingsTransaction(Row row, String locale, String dateFormat) { + String savingsAccountIdCheck = null; + if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) != null) { + savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row).toString(); } - if(savingsAccountIdCheck!=null) { + if (savingsAccountIdCheck != null) { savingsAccountId = savingsAccountIdCheck; } String transactionType = ImportHandlerUtils.readAsString(TransactionConstants.TRANSACTION_TYPE_COL, row); - SavingsAccountTransactionEnumData savingsAccountTransactionEnumData=new SavingsAccountTransactionEnumData(null,null,transactionType); + SavingsAccountTransactionEnumData savingsAccountTransactionEnumData = new SavingsAccountTransactionEnumData(null, null, + transactionType); - BigDecimal amount=null; - if (ImportHandlerUtils.readAsDouble(TransactionConstants.AMOUNT_COL, row)!=null) { + BigDecimal amount = null; + if (ImportHandlerUtils.readAsDouble(TransactionConstants.AMOUNT_COL, row) != null) { amount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(TransactionConstants.AMOUNT_COL, row)); } LocalDate transactionDate = ImportHandlerUtils.readAsDate(TransactionConstants.TRANSACTION_DATE_COL, row); String paymentType = ImportHandlerUtils.readAsString(TransactionConstants.PAYMENT_TYPE_COL, row); - Long paymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), paymentType); + Long paymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), + paymentType); String accountNumber = ImportHandlerUtils.readAsString(TransactionConstants.ACCOUNT_NO_COL, row); String checkNumber = ImportHandlerUtils.readAsString(TransactionConstants.CHECK_NO_COL, row); String routingCode = ImportHandlerUtils.readAsString(TransactionConstants.ROUTING_CODE_COL, row); String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row); String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row); - return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, - checkNumber, routingCode, receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(),locale,dateFormat); + return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode, + receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(), locale, + dateFormat); } public Count importEntity(String dateFormat) { Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - gsonBuilder.registerTypeAdapter(SavingsAccountTransactionEnumData.class - ,new SavingsAccountTransactionEnumValueSerialiser()); + gsonBuilder.registerTypeAdapter(SavingsAccountTransactionEnumData.class, new SavingsAccountTransactionEnumValueSerialiser()); for (SavingsAccountTransactionData transaction : savingsTransactions) { try { - JsonObject savingsTransactionJsonob=gsonBuilder.create().toJsonTree(transaction).getAsJsonObject(); + JsonObject savingsTransactionJsonob = gsonBuilder.create().toJsonTree(transaction).getAsJsonObject(); savingsTransactionJsonob.remove("transactionType"); savingsTransactionJsonob.remove("reversed"); savingsTransactionJsonob.remove("interestedPostedAsOn"); - String payload= savingsTransactionJsonob.toString(); - CommandWrapper commandRequest=null; + String payload = savingsTransactionJsonob.toString(); + CommandWrapper commandRequest = null; if (transaction.getTransactionType().getValue().equals("Withdrawal")) { commandRequest = new CommandWrapperBuilder() // .recurringAccountWithdrawal(transaction.getSavingsAccountId()) // .withJson(payload) // .build(); // - }else if (transaction.getTransactionType().getValue().equals("Deposit")){ + } else if (transaction.getTransactionType().getValue().equals("Deposit")) { commandRequest = new CommandWrapperBuilder() // .recurringAccountDeposit(transaction.getSavingsAccountId()) // .withJson(payload) // @@ -150,20 +151,22 @@ public class RecurringDepositTransactionImportHandler implements ImportHandler { statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); } catch (AbstractPlatformDomainRuleException e) { errorCount++; - LOG.error("Problem occurred in importEntity function",e); + LOG.error("Problem occurred in importEntity function", e); errorMessage = e.getDefaultUserMessage(); - ImportHandlerUtils.writeErrorMessage(savingsTransactionSheet,transaction.getRowIndex(),errorMessage,TransactionConstants.STATUS_COL); - }catch (RuntimeException ex){ + ImportHandlerUtils.writeErrorMessage(savingsTransactionSheet, transaction.getRowIndex(), errorMessage, + TransactionConstants.STATUS_COL); + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(savingsTransactionSheet,transaction.getRowIndex(),errorMessage,TransactionConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(savingsTransactionSheet, transaction.getRowIndex(), errorMessage, + TransactionConstants.STATUS_COL); } } savingsTransactionSheet.setColumnWidth(TransactionConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(TransactionConstants.STATUS_COL, savingsTransactionSheet.getRow(TransactionConstants.STATUS_COL), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - return Count.instance(successCount,errorCount); + ImportHandlerUtils.writeString(TransactionConstants.STATUS_COL, savingsTransactionSheet.getRow(TransactionConstants.STATUS_COL), + TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/savings/SavingsImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/savings/SavingsImportHandler.java index 13564ce49..ccd9ea6ed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/savings/SavingsImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/savings/SavingsImportHandler.java @@ -51,7 +51,6 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; - @Service public class SavingsImportHandler implements ImportHandler { @@ -60,73 +59,75 @@ public class SavingsImportHandler implements ImportHandler { private List savings; private List approvalDates; private List activationDates; - private Liststatuses; + private List statuses; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public SavingsImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public SavingsImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - this.savings=new ArrayList<>(); - this.approvalDates=new ArrayList<>(); - this.activationDates=new ArrayList<>(); - this.statuses=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + this.savings = new ArrayList<>(); + this.approvalDates = new ArrayList<>(); + this.activationDates = new ArrayList<>(); + this.statuses = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } + public void readExcelFile(String locale, String dateFormat) { Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME); Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row = savingsSheet.getRow(rowIndex); - if (ImportHandlerUtils.isNotImported(row, SavingsConstants.STATUS_COL)) { - savings.add(readSavings(row,locale,dateFormat)); - approvalDates.add(readSavingsApproval(row,locale,dateFormat)); - activationDates.add(readSavingsActivation(row,locale,dateFormat)); - } + row = savingsSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, SavingsConstants.STATUS_COL)) { + savings.add(readSavings(row, locale, dateFormat)); + approvalDates.add(readSavingsApproval(row, locale, dateFormat)); + activationDates.add(readSavingsActivation(row, locale, dateFormat)); + } } } - private SavingsActivation readSavingsActivation(Row row,String locale, String dateFormat) { - LocalDate activationDate = ImportHandlerUtils.readAsDate( SavingsConstants.ACTIVATION_DATE_COL, row); - if (activationDate!=null) { + private SavingsActivation readSavingsActivation(Row row, String locale, String dateFormat) { + LocalDate activationDate = ImportHandlerUtils.readAsDate(SavingsConstants.ACTIVATION_DATE_COL, row); + if (activationDate != null) { return SavingsActivation.importInstance(activationDate, row.getRowNum(), locale, dateFormat); } else { return null; } } - private SavingsApproval readSavingsApproval(Row row,String locale, String dateFormat) { - LocalDate approvalDate = ImportHandlerUtils.readAsDate( SavingsConstants.APPROVED_DATE_COL, row); - if (approvalDate!=null) { + private SavingsApproval readSavingsApproval(Row row, String locale, String dateFormat) { + LocalDate approvalDate = ImportHandlerUtils.readAsDate(SavingsConstants.APPROVED_DATE_COL, row); + if (approvalDate != null) { return SavingsApproval.importInstance(approvalDate, row.getRowNum(), locale, dateFormat); } else { return null; } } - private SavingsAccountData readSavings(Row row,String locale, String dateFormat) { - String productName = ImportHandlerUtils.readAsString( SavingsConstants.PRODUCT_COL, row); + private SavingsAccountData readSavings(Row row, String locale, String dateFormat) { + String productName = ImportHandlerUtils.readAsString(SavingsConstants.PRODUCT_COL, row); Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName); String fieldOfficerName = ImportHandlerUtils.readAsString(SavingsConstants.FIELD_OFFICER_NAME_COL, row); - Long fieldOfficerId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), fieldOfficerName); + Long fieldOfficerId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), + fieldOfficerName); LocalDate submittedOnDate = ImportHandlerUtils.readAsDate(SavingsConstants.SUBMITTED_ON_DATE_COL, row); - BigDecimal nominalAnnualInterestRate=null; - if (ImportHandlerUtils.readAsDouble(SavingsConstants.NOMINAL_ANNUAL_INTEREST_RATE_COL, row)!=null) { - nominalAnnualInterestRate = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(SavingsConstants.NOMINAL_ANNUAL_INTEREST_RATE_COL, row)); + BigDecimal nominalAnnualInterestRate = null; + if (ImportHandlerUtils.readAsDouble(SavingsConstants.NOMINAL_ANNUAL_INTEREST_RATE_COL, row) != null) { + nominalAnnualInterestRate = BigDecimal + .valueOf(ImportHandlerUtils.readAsDouble(SavingsConstants.NOMINAL_ANNUAL_INTEREST_RATE_COL, row)); } String interestCompoundingPeriodType = ImportHandlerUtils.readAsString(SavingsConstants.INTEREST_COMPOUNDING_PERIOD_COL, row); Long interestCompoundingPeriodTypeId = null; - EnumOptionData interestCompoundingPeriodTypeEnum=null; - if (interestCompoundingPeriodType!=null) { + EnumOptionData interestCompoundingPeriodTypeEnum = null; + if (interestCompoundingPeriodType != null) { if (interestCompoundingPeriodType.equalsIgnoreCase("Daily")) { interestCompoundingPeriodTypeId = 1L; } else if (interestCompoundingPeriodType.equalsIgnoreCase("Monthly")) { @@ -138,12 +139,12 @@ public class SavingsImportHandler implements ImportHandler { } else if (interestCompoundingPeriodType.equalsIgnoreCase("Annually")) { interestCompoundingPeriodTypeId = 7L; } - interestCompoundingPeriodTypeEnum = new EnumOptionData(interestCompoundingPeriodTypeId, null, null); + interestCompoundingPeriodTypeEnum = new EnumOptionData(interestCompoundingPeriodTypeId, null, null); } String interestPostingPeriodType = ImportHandlerUtils.readAsString(SavingsConstants.INTEREST_POSTING_PERIOD_COL, row); Long interestPostingPeriodTypeId = null; - EnumOptionData interestPostingPeriodTypeEnum=null; - if (interestPostingPeriodType!=null) { + EnumOptionData interestPostingPeriodTypeEnum = null; + if (interestPostingPeriodType != null) { if (interestPostingPeriodType.equalsIgnoreCase("Monthly")) { interestPostingPeriodTypeId = 4L; } else if (interestPostingPeriodType.equalsIgnoreCase("Quarterly")) { @@ -157,8 +158,8 @@ public class SavingsImportHandler implements ImportHandler { } String interestCalculationType = ImportHandlerUtils.readAsString(SavingsConstants.INTEREST_CALCULATION_COL, row); Long interestCalculationTypeId = null; - EnumOptionData interestCalculationTypeEnum=null; - if (interestCalculationType!=null) { + EnumOptionData interestCalculationTypeEnum = null; + if (interestCalculationType != null) { if (interestCalculationType.equalsIgnoreCase("Daily Balance")) { interestCalculationTypeId = 1L; } else if (interestCalculationType.equalsIgnoreCase("Average Daily Balance")) { @@ -166,10 +167,11 @@ public class SavingsImportHandler implements ImportHandler { } interestCalculationTypeEnum = new EnumOptionData(interestCalculationTypeId, null, null); } - String interestCalculationDaysInYearType = ImportHandlerUtils.readAsString(SavingsConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row); - EnumOptionData interestCalculationDaysInYearTypeEnum=null; + String interestCalculationDaysInYearType = ImportHandlerUtils.readAsString(SavingsConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, + row); + EnumOptionData interestCalculationDaysInYearTypeEnum = null; Long interestCalculationDaysInYearTypeId = null; - if (interestCalculationDaysInYearType!=null) { + if (interestCalculationDaysInYearType != null) { if (interestCalculationDaysInYearType.equalsIgnoreCase("360 Days")) { interestCalculationDaysInYearTypeId = 360L; } else if (interestCalculationDaysInYearType.equalsIgnoreCase("365 Days")) { @@ -177,15 +179,15 @@ public class SavingsImportHandler implements ImportHandler { } interestCalculationDaysInYearTypeEnum = new EnumOptionData(interestCalculationDaysInYearTypeId, null, null); } - BigDecimal minRequiredOpeningBalance=null; - if (ImportHandlerUtils.readAsDouble(SavingsConstants.MIN_OPENING_BALANCE_COL, row)!=null) { - minRequiredOpeningBalance = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(SavingsConstants.MIN_OPENING_BALANCE_COL, row)); + BigDecimal minRequiredOpeningBalance = null; + if (ImportHandlerUtils.readAsDouble(SavingsConstants.MIN_OPENING_BALANCE_COL, row) != null) { + minRequiredOpeningBalance = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(SavingsConstants.MIN_OPENING_BALANCE_COL, row)); } Integer lockinPeriodFrequency = ImportHandlerUtils.readAsInt(SavingsConstants.LOCKIN_PERIOD_COL, row); String lockinPeriodFrequencyType = ImportHandlerUtils.readAsString(SavingsConstants.LOCKIN_PERIOD_FREQUENCY_COL, row); Long lockinPeriodFrequencyTypeId = null; - EnumOptionData lockinPeriodFrequencyTypeEnum=null; - if (lockinPeriodFrequencyType!=null) { + EnumOptionData lockinPeriodFrequencyTypeEnum = null; + if (lockinPeriodFrequencyType != null) { if (lockinPeriodFrequencyType.equalsIgnoreCase("Days")) { lockinPeriodFrequencyTypeId = 0L; } else if (lockinPeriodFrequencyType.equalsIgnoreCase("Weeks")) { @@ -199,10 +201,9 @@ public class SavingsImportHandler implements ImportHandler { } Boolean applyWithdrawalFeeForTransfers = ImportHandlerUtils.readAsBoolean(SavingsConstants.APPLY_WITHDRAWAL_FEE_FOR_TRANSFERS, row); - String savingsType=null; - if (ImportHandlerUtils.readAsString(SavingsConstants.SAVINGS_TYPE_COL, row)!=null) { - savingsType = ImportHandlerUtils.readAsString(SavingsConstants.SAVINGS_TYPE_COL, row) - .toLowerCase(Locale.ENGLISH); + String savingsType = null; + if (ImportHandlerUtils.readAsString(SavingsConstants.SAVINGS_TYPE_COL, row) != null) { + savingsType = ImportHandlerUtils.readAsString(SavingsConstants.SAVINGS_TYPE_COL, row).toLowerCase(Locale.ENGLISH); } String clientOrGroupName = ImportHandlerUtils.readAsString(SavingsConstants.CLIENT_NAME_COL, row); @@ -210,64 +211,65 @@ public class SavingsImportHandler implements ImportHandler { String externalId = ImportHandlerUtils.readAsString(SavingsConstants.EXTERNAL_ID_COL, row); List charges = new ArrayList<>(); - Boolean allowOverdraft = ImportHandlerUtils.readAsBoolean(SavingsConstants.ALLOW_OVER_DRAFT_COL, row); BigDecimal overdraftLimit = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(SavingsConstants.OVER_DRAFT_LIMIT_COL, row)); String charge1 = ImportHandlerUtils.readAsString(SavingsConstants.CHARGE_ID_1, row); String charge2 = ImportHandlerUtils.readAsString(SavingsConstants.CHARGE_ID_2, row); - if (charge1!=null) { - if (ImportHandlerUtils.readAsDouble(SavingsConstants.CHARGE_AMOUNT_1, row)!=null) { + if (charge1 != null) { + if (ImportHandlerUtils.readAsDouble(SavingsConstants.CHARGE_AMOUNT_1, row) != null) { charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(SavingsConstants.CHARGE_ID_1, row), BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(SavingsConstants.CHARGE_AMOUNT_1, row)), ImportHandlerUtils.readAsDate(SavingsConstants.CHARGE_DUE_DATE_1, row))); - }else { - charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(SavingsConstants.CHARGE_ID_1, row), - null, + } else { + charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(SavingsConstants.CHARGE_ID_1, row), null, ImportHandlerUtils.readAsDate(SavingsConstants.CHARGE_DUE_DATE_1, row))); } } - if (charge2!=null) { - if (ImportHandlerUtils.readAsDouble(SavingsConstants.CHARGE_AMOUNT_2, row)!=null) { + if (charge2 != null) { + if (ImportHandlerUtils.readAsDouble(SavingsConstants.CHARGE_AMOUNT_2, row) != null) { charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(SavingsConstants.CHARGE_ID_2, row), BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(SavingsConstants.CHARGE_AMOUNT_2, row)), ImportHandlerUtils.readAsDate(SavingsConstants.CHARGE_DUE_DATE_2, row))); - }else { - charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(SavingsConstants.CHARGE_ID_2, row), - null, + } else { + charges.add(new SavingsAccountChargeData(ImportHandlerUtils.readAsLong(SavingsConstants.CHARGE_ID_2, row), null, ImportHandlerUtils.readAsDate(SavingsConstants.CHARGE_DUE_DATE_2, row))); } } String status = ImportHandlerUtils.readAsString(SavingsConstants.STATUS_COL, row); statuses.add(status); - if (savingsType!=null) { + if (savingsType != null) { if (savingsType.equals("individual")) { - Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), clientOrGroupName); - return SavingsAccountData.importInstanceIndividual(clientId, productId, fieldOfficerId, submittedOnDate, nominalAnnualInterestRate, - interestCompoundingPeriodTypeEnum, interestPostingPeriodTypeEnum, interestCalculationTypeEnum, - interestCalculationDaysInYearTypeEnum, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, - applyWithdrawalFeeForTransfers, row.getRowNum(), externalId, charges, allowOverdraft, overdraftLimit,locale,dateFormat); + Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), + clientOrGroupName); + return SavingsAccountData.importInstanceIndividual(clientId, productId, fieldOfficerId, submittedOnDate, + nominalAnnualInterestRate, interestCompoundingPeriodTypeEnum, interestPostingPeriodTypeEnum, + interestCalculationTypeEnum, interestCalculationDaysInYearTypeEnum, minRequiredOpeningBalance, + lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, applyWithdrawalFeeForTransfers, row.getRowNum(), externalId, + charges, allowOverdraft, overdraftLimit, locale, dateFormat); } - Long groupId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME), clientOrGroupName); - return SavingsAccountData.importInstanceGroup(groupId, productId, fieldOfficerId, submittedOnDate, nominalAnnualInterestRate, + Long groupId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME), + clientOrGroupName); + return SavingsAccountData.importInstanceGroup(groupId, productId, fieldOfficerId, submittedOnDate, nominalAnnualInterestRate, interestCompoundingPeriodTypeEnum, interestPostingPeriodTypeEnum, interestCalculationTypeEnum, interestCalculationDaysInYearTypeEnum, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, - applyWithdrawalFeeForTransfers, row.getRowNum(), externalId, charges, allowOverdraft, overdraftLimit,locale,dateFormat); - }else { - return null; + applyWithdrawalFeeForTransfers, row.getRowNum(), externalId, charges, allowOverdraft, overdraftLimit, locale, + dateFormat); + } else { + return null; } } public Count importEntity(String dateFormat) { Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME); - int successCount=0; - int errorCount=0; + int successCount = 0; + int errorCount = 0; int progressLevel = 0; - String errorMessage=""; - Long savingsId=null; + String errorMessage = ""; + Long savingsId = null; for (int i = 0; i < savings.size(); i++) { Row row = savingsSheet.getRow(savings.get(i).getRowIndex()); Cell statusCell = row.createCell(SavingsConstants.STATUS_COL); @@ -277,7 +279,7 @@ public class SavingsImportHandler implements ImportHandler { progressLevel = getProgressLevel(status); if (progressLevel == 0) { - CommandProcessingResult result = importSavings(i,dateFormat); + CommandProcessingResult result = importSavings(i, dateFormat); savingsId = result.getSavingsId(); progressLevel = 1; } else { @@ -295,18 +297,19 @@ public class SavingsImportHandler implements ImportHandler { successCount++; statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - writeSavingsErrorMessage(savingsId,errorMessage,progressLevel,statusCell,errorReportCell,row); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + writeSavingsErrorMessage(savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row); } } setReportHeaders(savingsSheet); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - private void writeSavingsErrorMessage(Long savingsId,String errorMessage,int progressLevel,Cell statusCell,Cell errorReportCell,Row row){ + private void writeSavingsErrorMessage(Long savingsId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell, + Row row) { String status = ""; if (progressLevel == 0) { @@ -325,16 +328,19 @@ public class SavingsImportHandler implements ImportHandler { errorReportCell.setCellValue(errorMessage); } + private void setReportHeaders(Sheet savingsSheet) { savingsSheet.setColumnWidth(SavingsConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); Row rowHeader = savingsSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); ImportHandlerUtils.writeString(SavingsConstants.STATUS_COL, rowHeader, TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - ImportHandlerUtils.writeString(SavingsConstants.SAVINGS_ID_COL, rowHeader, TemplatePopulateImportConstants.SAVINGS_ID_COL_REPORT_HEADER); - ImportHandlerUtils.writeString(SavingsConstants.FAILURE_REPORT_COL, rowHeader, TemplatePopulateImportConstants.FAILURE_COL_REPORT_HEADER); + ImportHandlerUtils.writeString(SavingsConstants.SAVINGS_ID_COL, rowHeader, + TemplatePopulateImportConstants.SAVINGS_ID_COL_REPORT_HEADER); + ImportHandlerUtils.writeString(SavingsConstants.FAILURE_REPORT_COL, rowHeader, + TemplatePopulateImportConstants.FAILURE_COL_REPORT_HEADER); } private int importSavingsActivation(Long savingsId, int i, String dateFormat) { - if(activationDates.get(i)!=null) { + if (activationDates.get(i) != null) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); String payload = gsonBuilder.create().toJson(activationDates.get(i)); @@ -347,9 +353,8 @@ public class SavingsImportHandler implements ImportHandler { return 3; } - private int importSavingsApproval(Long savingsId, int i, - String dateFormat) { - if(approvalDates.get(i)!=null) { + private int importSavingsApproval(Long savingsId, int i, String dateFormat) { + if (approvalDates.get(i) != null) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); String payload = gsonBuilder.create().toJson(approvalDates.get(i)); @@ -357,18 +362,18 @@ public class SavingsImportHandler implements ImportHandler { .approveSavingsAccountApplication(savingsId)// .withJson(payload) // .build(); // - final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest); + final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest); } return 2; } - private CommandProcessingResult importSavings(int i,String dateFormat) { + private CommandProcessingResult importSavings(int i, String dateFormat) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - gsonBuilder.registerTypeAdapter(EnumOptionData.class,new EnumOptionDataIdSerializer()); - JsonObject savingsJsonob=gsonBuilder.create().toJsonTree(savings.get(i)).getAsJsonObject(); + gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer()); + JsonObject savingsJsonob = gsonBuilder.create().toJsonTree(savings.get(i)).getAsJsonObject(); savingsJsonob.remove("isDormancyTrackingActive"); - String payload= savingsJsonob.toString(); + String payload = savingsJsonob.toString(); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createSavingsAccount() // .withJson(payload) // @@ -378,15 +383,12 @@ public class SavingsImportHandler implements ImportHandler { } private int getProgressLevel(String status) { - if (status==null || status.equals(TemplatePopulateImportConstants.STATUS_CREATION_FAILED)) { + if (status == null || status.equals(TemplatePopulateImportConstants.STATUS_CREATION_FAILED)) { return 0; } else if (status.equals(TemplatePopulateImportConstants.STATUS_APPROVAL_FAILED)) { return 1; - } else if (status.equals(TemplatePopulateImportConstants.STATUS_ACTIVATION_FAILED)) { - return 2; - } + } else if (status.equals(TemplatePopulateImportConstants.STATUS_ACTIVATION_FAILED)) { return 2; } return 0; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/savings/SavingsTransactionImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/savings/SavingsTransactionImportHandler.java index 628d8f8a0..71f6604ef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/savings/SavingsTransactionImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/savings/SavingsTransactionImportHandler.java @@ -49,6 +49,7 @@ import org.springframework.stereotype.Service; @Service public class SavingsTransactionImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(SavingsTransactionImportHandler.class); private Workbook workbook; private List savingsTransactions; @@ -57,16 +58,15 @@ public class SavingsTransactionImportHandler implements ImportHandler { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public SavingsTransactionImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + public SavingsTransactionImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - this.savingsTransactions=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + this.savingsTransactions = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } @@ -76,67 +76,68 @@ public class SavingsTransactionImportHandler implements ImportHandler { for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; row = savingsTransactionSheet.getRow(rowIndex); - if(ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) { + if (ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) { savingsTransactions.add(readSavingsTransaction(row, locale, dateFormat)); } } } - private SavingsAccountTransactionData readSavingsTransaction(Row row,String locale, String dateFormat) { - String savingsAccountIdCheck=null; - if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row)!=null) { - savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) - .toString(); + private SavingsAccountTransactionData readSavingsTransaction(Row row, String locale, String dateFormat) { + String savingsAccountIdCheck = null; + if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) != null) { + savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row).toString(); } - if(savingsAccountIdCheck!=null) { + if (savingsAccountIdCheck != null) { savingsAccountId = savingsAccountIdCheck; } String transactionType = ImportHandlerUtils.readAsString(TransactionConstants.TRANSACTION_TYPE_COL, row); - SavingsAccountTransactionEnumData savingsAccountTransactionEnumData=new SavingsAccountTransactionEnumData(null,null,transactionType); + SavingsAccountTransactionEnumData savingsAccountTransactionEnumData = new SavingsAccountTransactionEnumData(null, null, + transactionType); - BigDecimal amount=null; - if (ImportHandlerUtils.readAsDouble(TransactionConstants.AMOUNT_COL, row)!=null) { + BigDecimal amount = null; + if (ImportHandlerUtils.readAsDouble(TransactionConstants.AMOUNT_COL, row) != null) { amount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(TransactionConstants.AMOUNT_COL, row)); } LocalDate transactionDate = ImportHandlerUtils.readAsDate(TransactionConstants.TRANSACTION_DATE_COL, row); String paymentType = ImportHandlerUtils.readAsString(TransactionConstants.PAYMENT_TYPE_COL, row); - Long paymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), paymentType); + Long paymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), + paymentType); String accountNumber = ImportHandlerUtils.readAsString(TransactionConstants.ACCOUNT_NO_COL, row); String checkNumber = ImportHandlerUtils.readAsString(TransactionConstants.CHECK_NO_COL, row); String routingCode = ImportHandlerUtils.readAsString(TransactionConstants.ROUTING_CODE_COL, row); String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row); String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row); - return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, - checkNumber, routingCode, receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(),locale,dateFormat); + return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode, + receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(), locale, + dateFormat); } public Count importEntity(String dateFormat) { Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - gsonBuilder.registerTypeAdapter(SavingsAccountTransactionEnumData.class - ,new SavingsAccountTransactionEnumValueSerialiser()); + gsonBuilder.registerTypeAdapter(SavingsAccountTransactionEnumData.class, new SavingsAccountTransactionEnumValueSerialiser()); for (SavingsAccountTransactionData transaction : savingsTransactions) { try { - JsonObject savingsTransactionJsonob=gsonBuilder.create().toJsonTree(transaction).getAsJsonObject(); + JsonObject savingsTransactionJsonob = gsonBuilder.create().toJsonTree(transaction).getAsJsonObject(); savingsTransactionJsonob.remove("transactionType"); savingsTransactionJsonob.remove("reversed"); savingsTransactionJsonob.remove("interestedPostedAsOn"); - String payload= savingsTransactionJsonob.toString(); - CommandWrapper commandRequest=null; + String payload = savingsTransactionJsonob.toString(); + CommandWrapper commandRequest = null; if (transaction.getTransactionType().getValue().equals("Withdrawal")) { commandRequest = new CommandWrapperBuilder() // .savingsAccountWithdrawal(transaction.getSavingsAccountId()) // .withJson(payload) // .build(); // - }else if (transaction.getTransactionType().getValue().equals("Deposit")){ + } else if (transaction.getTransactionType().getValue().equals("Deposit")) { commandRequest = new CommandWrapperBuilder() // .savingsAccountDeposit(transaction.getSavingsAccountId()) // .withJson(payload) // @@ -147,17 +148,18 @@ public class SavingsTransactionImportHandler implements ImportHandler { Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(savingsTransactionSheet,transaction.getRowIndex(),errorMessage,TransactionConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(savingsTransactionSheet, transaction.getRowIndex(), errorMessage, + TransactionConstants.STATUS_COL); } } savingsTransactionSheet.setColumnWidth(TransactionConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(TransactionConstants.STATUS_COL, savingsTransactionSheet.getRow(TransactionConstants.STATUS_COL), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - return Count.instance(successCount,errorCount); + ImportHandlerUtils.writeString(TransactionConstants.STATUS_COL, savingsTransactionSheet.getRow(TransactionConstants.STATUS_COL), + TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/sharedaccount/SharedAccountImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/sharedaccount/SharedAccountImportHandler.java index 37b83ceea..77a0df75f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/sharedaccount/SharedAccountImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/sharedaccount/SharedAccountImportHandler.java @@ -51,58 +51,60 @@ public class SharedAccountImportHandler implements ImportHandler { private final static Logger LOG = LoggerFactory.getLogger(SharedAccountImportHandler.class); private Workbook workbook; private List shareAccountDataList; - private Liststatuses; + private List statuses; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public SharedAccountImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public SharedAccountImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } + @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - this.shareAccountDataList=new ArrayList<>(); - statuses=new ArrayList(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + this.shareAccountDataList = new ArrayList<>(); + statuses = new ArrayList(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } + public void readExcelFile(String locale, String dateFormat) { - Sheet sharedAccountsSheet=workbook.getSheet(TemplatePopulateImportConstants.SHARED_ACCOUNTS_SHEET_NAME); - Integer noOfEntries= ImportHandlerUtils.getNumberOfRows(sharedAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); - for (int rowIndex=1;rowIndex<=noOfEntries;rowIndex++){ + Sheet sharedAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.SHARED_ACCOUNTS_SHEET_NAME); + Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(sharedAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); + for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row=sharedAccountsSheet.getRow(rowIndex); - if (ImportHandlerUtils.isNotImported(row, SharedAccountsConstants.STATUS_COL)){ - shareAccountDataList.add(readSharedAccount(row,locale,dateFormat)); - } + row = sharedAccountsSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, SharedAccountsConstants.STATUS_COL)) { + shareAccountDataList.add(readSharedAccount(row, locale, dateFormat)); + } } } - private ShareAccountData readSharedAccount(Row row,String locale, String dateFormat) { + private ShareAccountData readSharedAccount(Row row, String locale, String dateFormat) { String clientName = ImportHandlerUtils.readAsString(SharedAccountsConstants.CLIENT_NAME_COL, row); Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), clientName); String productName = ImportHandlerUtils.readAsString(SharedAccountsConstants.PRODUCT_COL, row); - Long productId=ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME),productName); + Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME), + productName); - LocalDate submittedOnDate=ImportHandlerUtils.readAsDate(SharedAccountsConstants.SUBMITTED_ON_COL,row); + LocalDate submittedOnDate = ImportHandlerUtils.readAsDate(SharedAccountsConstants.SUBMITTED_ON_COL, row); String externalId = ImportHandlerUtils.readAsString(SharedAccountsConstants.EXTERNAL_ID_COL, row); - Integer totNoOfShares=ImportHandlerUtils.readAsInt(SharedAccountsConstants.TOTAL_NO_SHARES_COL,row); + Integer totNoOfShares = ImportHandlerUtils.readAsInt(SharedAccountsConstants.TOTAL_NO_SHARES_COL, row); - Long defaultSavingsAccountId=ImportHandlerUtils.readAsLong(SharedAccountsConstants.DEFAULT_SAVINGS_AC_COL,row); + Long defaultSavingsAccountId = ImportHandlerUtils.readAsLong(SharedAccountsConstants.DEFAULT_SAVINGS_AC_COL, row); - Integer minimumActivePeriodDays=ImportHandlerUtils.readAsInt(SharedAccountsConstants.MINIMUM_ACTIVE_PERIOD_IN_DAYS_COL,row); - Integer minimumActivePeriodFrequencyType=0; + Integer minimumActivePeriodDays = ImportHandlerUtils.readAsInt(SharedAccountsConstants.MINIMUM_ACTIVE_PERIOD_IN_DAYS_COL, row); + Integer minimumActivePeriodFrequencyType = 0; - Integer lockInPeriod=ImportHandlerUtils.readAsInt(SharedAccountsConstants.LOCK_IN_PERIOD_COL,row); + Integer lockInPeriod = ImportHandlerUtils.readAsInt(SharedAccountsConstants.LOCK_IN_PERIOD_COL, row); - Integer lockPeriodFrequencyType=null; + Integer lockPeriodFrequencyType = null; - if (ImportHandlerUtils.readAsString(SharedAccountsConstants.LOCK_IN_PERIOD_FREQUENCY_TYPE,row)!=null) { + if (ImportHandlerUtils.readAsString(SharedAccountsConstants.LOCK_IN_PERIOD_FREQUENCY_TYPE, row) != null) { if (ImportHandlerUtils.readAsString(SharedAccountsConstants.LOCK_IN_PERIOD_FREQUENCY_TYPE, row) .equals(TemplatePopulateImportConstants.FREQUENCY_DAYS)) { lockPeriodFrequencyType = 0; @@ -117,66 +119,68 @@ public class SharedAccountImportHandler implements ImportHandler { lockPeriodFrequencyType = 3; } } - LocalDate applicationDate=ImportHandlerUtils.readAsDate(SharedAccountsConstants.APPLICATION_DATE_COL,row); - Boolean allowDividendCalc=ImportHandlerUtils.readAsBoolean(SharedAccountsConstants.ALLOW_DIVIDEND_CALCULATION_FOR_INACTIVE_CLIENTS_COL,row); + LocalDate applicationDate = ImportHandlerUtils.readAsDate(SharedAccountsConstants.APPLICATION_DATE_COL, row); + Boolean allowDividendCalc = ImportHandlerUtils + .readAsBoolean(SharedAccountsConstants.ALLOW_DIVIDEND_CALCULATION_FOR_INACTIVE_CLIENTS_COL, row); - List charges=new ArrayList<>(); - for (int cellNo=SharedAccountsConstants.CHARGES_NAME_1_COL;cellNo charges = new ArrayList<>(); + for (int cellNo = SharedAccountsConstants.CHARGES_NAME_1_COL; cellNo < SharedAccountsConstants.CHARGES_NAME_3_COL; cellNo += 2) { + String chargeName = ImportHandlerUtils.readAsString(cellNo, row); + if (chargeName == null || chargeName.equals("0")) { break; } - Long chargeId=ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME),chargeName); + Long chargeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME), + chargeName); - BigDecimal amount=null; - if(ImportHandlerUtils.readAsDouble(cellNo+1,row)!=null) { + BigDecimal amount = null; + if (ImportHandlerUtils.readAsDouble(cellNo + 1, row) != null) { amount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(cellNo + 1, row)); } - ShareAccountChargeData shareAccountChargeData=new ShareAccountChargeData(chargeId,amount); + ShareAccountChargeData shareAccountChargeData = new ShareAccountChargeData(chargeId, amount); charges.add(shareAccountChargeData); } - String status=ImportHandlerUtils.readAsString(SharedAccountsConstants.STATUS_COL,row); + String status = ImportHandlerUtils.readAsString(SharedAccountsConstants.STATUS_COL, row); statuses.add(status); - return ShareAccountData.importInstance(clientId,productId,totNoOfShares,externalId,submittedOnDate,minimumActivePeriodDays, - minimumActivePeriodFrequencyType,lockInPeriod,lockPeriodFrequencyType,applicationDate,allowDividendCalc,charges, - defaultSavingsAccountId,row.getRowNum(),locale,dateFormat); + return ShareAccountData.importInstance(clientId, productId, totNoOfShares, externalId, submittedOnDate, minimumActivePeriodDays, + minimumActivePeriodFrequencyType, lockInPeriod, lockPeriodFrequencyType, applicationDate, allowDividendCalc, charges, + defaultSavingsAccountId, row.getRowNum(), locale, dateFormat); } public Count importEntity(String dateFormat) { - Sheet sharedAccountsSheet=workbook.getSheet(TemplatePopulateImportConstants.SHARED_ACCOUNTS_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; + Sheet sharedAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.SHARED_ACCOUNTS_SHEET_NAME); + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - for (ShareAccountData shareAccountData: shareAccountDataList) { + for (ShareAccountData shareAccountData : shareAccountDataList) { try { - String payload=gsonBuilder.create().toJson(shareAccountData); + String payload = gsonBuilder.create().toJson(shareAccountData); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createAccount("share")// .withJson(payload) // .build(); // final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest); successCount++; - Cell statusCell = sharedAccountsSheet.getRow(shareAccountData.getRowIndex()) - .createCell(SharedAccountsConstants.STATUS_COL); + Cell statusCell = sharedAccountsSheet.getRow(shareAccountData.getRowIndex()).createCell(SharedAccountsConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(sharedAccountsSheet,shareAccountData.getRowIndex(),errorMessage,SharedAccountsConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(sharedAccountsSheet, shareAccountData.getRowIndex(), errorMessage, + SharedAccountsConstants.STATUS_COL); } } sharedAccountsSheet.setColumnWidth(SharedAccountsConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(SharedAccountsConstants.STATUS_COL, sharedAccountsSheet.getRow(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT), + ImportHandlerUtils.writeString(SharedAccountsConstants.STATUS_COL, + sharedAccountsSheet.getRow(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/staff/StaffImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/staff/StaffImportHandler.java index 7bdf02fc1..51694c9e0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/staff/StaffImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/staff/StaffImportHandler.java @@ -45,6 +45,7 @@ import org.springframework.stereotype.Service; @Service public class StaffImportHandler implements ImportHandler { + private final static Logger LOG = LoggerFactory.getLogger(StaffImportHandler.class); private List staffList; private Workbook workbook; @@ -52,59 +53,59 @@ public class StaffImportHandler implements ImportHandler { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public StaffImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public StaffImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - this.staffList=new ArrayList<>(); - readExcelFile(locale,dateFormat); + this.workbook = workbook; + this.staffList = new ArrayList<>(); + readExcelFile(locale, dateFormat); return importEntity(dateFormat); } + public void readExcelFile(String locale, String dateFormat) { - Sheet staffSheet=workbook.getSheet(TemplatePopulateImportConstants.EMPLOYEE_SHEET_NAME); - Integer noOfEntries= ImportHandlerUtils.getNumberOfRows(staffSheet,TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); - for (int rowIndex=1;rowIndex<=noOfEntries;rowIndex++){ + Sheet staffSheet = workbook.getSheet(TemplatePopulateImportConstants.EMPLOYEE_SHEET_NAME); + Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(staffSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX); + for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; - row=staffSheet.getRow(rowIndex); - if ( ImportHandlerUtils.isNotImported(row, StaffConstants.STATUS_COL)){ - staffList.add(readStaff(row,locale,dateFormat)); - } + row = staffSheet.getRow(rowIndex); + if (ImportHandlerUtils.isNotImported(row, StaffConstants.STATUS_COL)) { + staffList.add(readStaff(row, locale, dateFormat)); + } } } - private StaffData readStaff(Row row,String locale, String dateFormat) { - String officeName = ImportHandlerUtils.readAsString( StaffConstants.OFFICE_NAME_COL, row); + private StaffData readStaff(Row row, String locale, String dateFormat) { + String officeName = ImportHandlerUtils.readAsString(StaffConstants.OFFICE_NAME_COL, row); Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName); String firstName = ImportHandlerUtils.readAsString(StaffConstants.FIRST_NAME_COL, row); String lastName = ImportHandlerUtils.readAsString(StaffConstants.LAST_NAME_COL, row); - Boolean isLoanOfficer=ImportHandlerUtils.readAsBoolean(StaffConstants.IS_LOAN_OFFICER,row); - String mobileNo=null; - if (ImportHandlerUtils.readAsLong(StaffConstants.MOBILE_NO_COL,row)!=null) { + Boolean isLoanOfficer = ImportHandlerUtils.readAsBoolean(StaffConstants.IS_LOAN_OFFICER, row); + String mobileNo = null; + if (ImportHandlerUtils.readAsLong(StaffConstants.MOBILE_NO_COL, row) != null) { mobileNo = ImportHandlerUtils.readAsLong(StaffConstants.MOBILE_NO_COL, row).toString(); } - LocalDate joinedOnDate=ImportHandlerUtils.readAsDate(StaffConstants.JOINED_ON_COL,row); - String externalId=ImportHandlerUtils.readAsString(StaffConstants.EXTERNAL_ID_COL,row); - Boolean isActive=ImportHandlerUtils.readAsBoolean(StaffConstants.IS_ACTIVE_COL,row); + LocalDate joinedOnDate = ImportHandlerUtils.readAsDate(StaffConstants.JOINED_ON_COL, row); + String externalId = ImportHandlerUtils.readAsString(StaffConstants.EXTERNAL_ID_COL, row); + Boolean isActive = ImportHandlerUtils.readAsBoolean(StaffConstants.IS_ACTIVE_COL, row); - return StaffData.importInstance(externalId,firstName,lastName,mobileNo,officeId,isLoanOfficer,isActive, - joinedOnDate,row.getRowNum(),locale,dateFormat); + return StaffData.importInstance(externalId, firstName, lastName, mobileNo, officeId, isLoanOfficer, isActive, joinedOnDate, + row.getRowNum(), locale, dateFormat); } public Count importEntity(String dateFormat) { - Sheet staffSheet=workbook.getSheet(TemplatePopulateImportConstants.EMPLOYEE_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; + Sheet staffSheet = workbook.getSheet(TemplatePopulateImportConstants.EMPLOYEE_SHEET_NAME); + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat)); - for (StaffData staff: staffList) { + for (StaffData staff : staffList) { try { - String payload=gsonBuilder.create().toJson(staff); + String payload = gsonBuilder.create().toJson(staff); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createStaff()// .withJson(payload) // @@ -114,17 +115,17 @@ public class StaffImportHandler implements ImportHandler { Cell statusCell = staffSheet.getRow(staff.getRowIndex()).createCell(StaffConstants.STATUS_COL); statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(staffSheet,staff.getRowIndex(),errorMessage,StaffConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(staffSheet, staff.getRowIndex(), errorMessage, StaffConstants.STATUS_COL); } } staffSheet.setColumnWidth(StaffConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - ImportHandlerUtils.writeString(StaffConstants.STATUS_COL, staffSheet.getRow(0), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - return Count.instance(successCount,errorCount); + ImportHandlerUtils.writeString(StaffConstants.STATUS_COL, staffSheet.getRow(0), + TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/users/UserImportHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/users/UserImportHandler.java index 577a40b2e..77b29014e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/users/UserImportHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/importhandler/users/UserImportHandler.java @@ -43,7 +43,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class UserImportHandler implements ImportHandler{ +public class UserImportHandler implements ImportHandler { private final static Logger LOG = LoggerFactory.getLogger(UserImportHandler.class); private Workbook workbook; @@ -53,16 +53,15 @@ public class UserImportHandler implements ImportHandler{ private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public UserImportHandler(final PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService) { + public UserImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @Override public Count process(Workbook workbook, String locale, String dateFormat) { - this.workbook=workbook; - users=new ArrayList<>(); - statuses=new ArrayList<>(); + this.workbook = workbook; + users = new ArrayList<>(); + statuses = new ArrayList<>(); readExcelFile(); return importEntity(dateFormat); } @@ -73,7 +72,7 @@ public class UserImportHandler implements ImportHandler{ for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) { Row row; row = usersSheet.getRow(rowIndex); - if(ImportHandlerUtils.isNotImported(row, UserConstants.STATUS_COL)) { + if (ImportHandlerUtils.isNotImported(row, UserConstants.STATUS_COL)) { users.add(readUsers(row)); } } @@ -84,41 +83,41 @@ public class UserImportHandler implements ImportHandler{ Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName); String staffName = ImportHandlerUtils.readAsString(UserConstants.STAFF_NAME_COL, row); Long staffId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME), staffName); - String userName=ImportHandlerUtils.readAsString(UserConstants.USER_NAME_COL,row); - String firstName=ImportHandlerUtils.readAsString(UserConstants.FIRST_NAME_COL,row); - String lastName=ImportHandlerUtils.readAsString(UserConstants.LAST_NAME_COL,row); - String email=ImportHandlerUtils.readAsString(UserConstants.EMAIL_COL,row); - Boolean autoGenPw=ImportHandlerUtils.readAsBoolean(UserConstants.AUTO_GEN_PW_COL,row); - Boolean overridepw=ImportHandlerUtils.readAsBoolean(UserConstants.OVERRIDE_PW_EXPIRY_POLICY_COL,row); - String status=ImportHandlerUtils.readAsString(UserConstants.STATUS_COL,row); + String userName = ImportHandlerUtils.readAsString(UserConstants.USER_NAME_COL, row); + String firstName = ImportHandlerUtils.readAsString(UserConstants.FIRST_NAME_COL, row); + String lastName = ImportHandlerUtils.readAsString(UserConstants.LAST_NAME_COL, row); + String email = ImportHandlerUtils.readAsString(UserConstants.EMAIL_COL, row); + Boolean autoGenPw = ImportHandlerUtils.readAsBoolean(UserConstants.AUTO_GEN_PW_COL, row); + Boolean overridepw = ImportHandlerUtils.readAsBoolean(UserConstants.OVERRIDE_PW_EXPIRY_POLICY_COL, row); + String status = ImportHandlerUtils.readAsString(UserConstants.STATUS_COL, row); statuses.add(status); - List rolesIds=new ArrayList<>(); - for (int cellNo=UserConstants.ROLE_NAME_START_COL;cellNo rolesIds = new ArrayList<>(); + for (int cellNo = UserConstants.ROLE_NAME_START_COL; cellNo < UserConstants.ROLE_NAME_END_COL; cellNo++) { + String roleName = ImportHandlerUtils.readAsString(cellNo, row); + if (roleName == null) { break; } - Long roleId=ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.ROLES_SHEET_NAME),roleName); + Long roleId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.ROLES_SHEET_NAME), roleName); if (!rolesIds.contains(roleId)) { rolesIds.add(roleId); } } - return AppUserData.importInstance(officeId,staffId,userName,firstName,lastName,email, - autoGenPw,overridepw,rolesIds,row.getRowNum()); + return AppUserData.importInstance(officeId, staffId, userName, firstName, lastName, email, autoGenPw, overridepw, rolesIds, + row.getRowNum()); } public Count importEntity(String dateFormat) { - Sheet userSheet=workbook.getSheet(TemplatePopulateImportConstants.USER_SHEET_NAME); - int successCount=0; - int errorCount=0; - String errorMessage=""; - GsonBuilder gsonBuilder=new GsonBuilder(); - for (AppUserData user:users){ + Sheet userSheet = workbook.getSheet(TemplatePopulateImportConstants.USER_SHEET_NAME); + int successCount = 0; + int errorCount = 0; + String errorMessage = ""; + GsonBuilder gsonBuilder = new GsonBuilder(); + for (AppUserData user : users) { try { - JsonObject userJsonob=gsonBuilder.create().toJsonTree(user).getAsJsonObject(); - String payload=userJsonob.toString(); + JsonObject userJsonob = gsonBuilder.create().toJsonTree(user).getAsJsonObject(); + String payload = userJsonob.toString(); final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createUser() // .withJson(payload) // @@ -129,18 +128,17 @@ public class UserImportHandler implements ImportHandler{ statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED); statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN)); - }catch (RuntimeException ex){ + } catch (RuntimeException ex) { errorCount++; - LOG.error("Problem occurred in importEntity function",ex); - errorMessage=ImportHandlerUtils.getErrorMessage(ex); - ImportHandlerUtils.writeErrorMessage(userSheet,user.getRowIndex(),errorMessage,UserConstants.STATUS_COL); + LOG.error("Problem occurred in importEntity function", ex); + errorMessage = ImportHandlerUtils.getErrorMessage(ex); + ImportHandlerUtils.writeErrorMessage(userSheet, user.getRowIndex(), errorMessage, UserConstants.STATUS_COL); } } userSheet.setColumnWidth(UserConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); ImportHandlerUtils.writeString(UserConstants.STATUS_COL, userSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER); - return Count.instance(successCount,errorCount); + return Count.instance(successCount, errorCount); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/AbstractWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/AbstractWorkbookPopulator.java index 0df95f102..73bab46dc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/AbstractWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/AbstractWorkbookPopulator.java @@ -36,112 +36,113 @@ import org.slf4j.LoggerFactory; public abstract class AbstractWorkbookPopulator implements WorkbookPopulator { - private final static Logger LOG = LoggerFactory.getLogger(AbstractWorkbookPopulator.class); - protected void writeInt(int colIndex, Row row, int value) { - row.createCell(colIndex).setCellValue(value); - } + private final static Logger LOG = LoggerFactory.getLogger(AbstractWorkbookPopulator.class); - protected void writeLong(int colIndex, Row row, long value) { - row.createCell(colIndex).setCellValue(value); - } - - protected void writeString(int colIndex, Row row, String value) { - row.createCell(colIndex).setCellValue(value); - } - - protected void writeBoolean(int colIndex,Row row,Boolean value){ - row.createCell(colIndex).setCellValue(value); - } - protected void writeDouble(int colIndex, Row row, double value) { - row.createCell(colIndex).setCellValue(value); - } - - protected void writeFormula(int colIndex, Row row, String formula) { - row.createCell(colIndex).setCellFormula(formula); - } - - protected void writeDate(int colIndex, Row row, String value, CellStyle dateCellStyle,String dateFormat) { - try { - SimpleDateFormat formatinDB=null; - if (value.matches("\\d{4}-\\d{1,2}-\\d{1,2}")){ - formatinDB=new SimpleDateFormat("yyyy-mm-dd"); - }else if (value.matches("\\d{1,2}/\\d{1,2}/\\d{4}")){ - formatinDB=new SimpleDateFormat("dd/mm/yyyy"); - }else if(value.matches("\\d{1,2} \\w{3,12} \\d{4}")){ - formatinDB=new SimpleDateFormat("dd MMMM yyyy"); - } - Date date1=formatinDB.parse(value); - SimpleDateFormat expectedFormat=new SimpleDateFormat(dateFormat); - Date date2=expectedFormat.parse(expectedFormat.format(date1)); - Calendar cal = Calendar.getInstance(); - cal.setTime(date2); - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - Date dateWithoutTime = cal.getTime(); - row.createCell(colIndex).setCellValue(dateWithoutTime); - row.getCell(colIndex).setCellStyle(dateCellStyle); - } catch (ParseException pe) { - throw new IllegalArgumentException("ParseException"); + protected void writeInt(int colIndex, Row row, int value) { + row.createCell(colIndex).setCellValue(value); } - } - protected void writeBigDecimal(int colIndex, Row row, BigDecimal value) { + protected void writeLong(int colIndex, Row row, long value) { + row.createCell(colIndex).setCellValue(value); + } + + protected void writeString(int colIndex, Row row, String value) { + row.createCell(colIndex).setCellValue(value); + } + + protected void writeBoolean(int colIndex, Row row, Boolean value) { + row.createCell(colIndex).setCellValue(value); + } + + protected void writeDouble(int colIndex, Row row, double value) { + row.createCell(colIndex).setCellValue(value); + } + + protected void writeFormula(int colIndex, Row row, String formula) { + row.createCell(colIndex).setCellFormula(formula); + } + + protected void writeDate(int colIndex, Row row, String value, CellStyle dateCellStyle, String dateFormat) { + try { + SimpleDateFormat formatinDB = null; + if (value.matches("\\d{4}-\\d{1,2}-\\d{1,2}")) { + formatinDB = new SimpleDateFormat("yyyy-mm-dd"); + } else if (value.matches("\\d{1,2}/\\d{1,2}/\\d{4}")) { + formatinDB = new SimpleDateFormat("dd/mm/yyyy"); + } else if (value.matches("\\d{1,2} \\w{3,12} \\d{4}")) { + formatinDB = new SimpleDateFormat("dd MMMM yyyy"); + } + Date date1 = formatinDB.parse(value); + SimpleDateFormat expectedFormat = new SimpleDateFormat(dateFormat); + Date date2 = expectedFormat.parse(expectedFormat.format(date1)); + Calendar cal = Calendar.getInstance(); + cal.setTime(date2); + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + Date dateWithoutTime = cal.getTime(); + row.createCell(colIndex).setCellValue(dateWithoutTime); + row.getCell(colIndex).setCellStyle(dateCellStyle); + } catch (ParseException pe) { + throw new IllegalArgumentException("ParseException"); + } + } + + protected void writeBigDecimal(int colIndex, Row row, BigDecimal value) { row.createCell(colIndex).setCellValue(((value != null) ? value.doubleValue() : 0)); } - protected void setOfficeDateLookupTable(Sheet sheet, List offices, int officeNameCol, - int activationDateCol,String dateFormat) { - if(offices!=null){ - Workbook workbook = sheet.getWorkbook(); - CellStyle dateCellStyle = workbook.createCellStyle(); - short df = workbook.createDataFormat().getFormat(dateFormat); - dateCellStyle.setDataFormat(df); - int rowIndex = 0; - for (OfficeData office : offices) { - Row row = sheet.createRow(++rowIndex); - writeString(officeNameCol, row, office.name().trim().replaceAll("[ )(]", "_")); - writeDate(activationDateCol, row, - "" + office.getOpeningDate().getDayOfMonth() + "/" - + office.getOpeningDate().getMonthOfYear() + "/" + office.getOpeningDate().getYear(), - dateCellStyle,dateFormat); - - } - } - } - - protected void setClientAndGroupDateLookupTable(Sheet sheet, List clients, - List groups, int nameCol, int activationDateCol,boolean containsClientExtId, - String dateFormat) { + protected void setOfficeDateLookupTable(Sheet sheet, List offices, int officeNameCol, int activationDateCol, + String dateFormat) { + if (offices != null) { Workbook workbook = sheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); dateCellStyle.setDataFormat(df); int rowIndex = 0; - SimpleDateFormat outputFormat = new SimpleDateFormat(dateFormat); - SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date date = null; - try { - if (clients != null){ - for (ClientData client : clients) { - Row row = sheet.getRow(++rowIndex); - if (row == null) { - row = sheet.createRow(rowIndex); - } - writeString(nameCol, row, client.displayName().replaceAll("[ )(] ", "_") + "(" + client.id() + ")"); + for (OfficeData office : offices) { + Row row = sheet.createRow(++rowIndex); + writeString(officeNameCol, row, office.name().trim().replaceAll("[ )(]", "_")); + writeDate( + activationDateCol, row, "" + office.getOpeningDate().getDayOfMonth() + "/" + + office.getOpeningDate().getMonthOfYear() + "/" + office.getOpeningDate().getYear(), + dateCellStyle, dateFormat); - if (client.getActivationDate() != null) { - date = inputFormat.parse(client.getActivationDate().toString()); - writeDate(activationDateCol, row, outputFormat.format(date), dateCellStyle,dateFormat); - } - if (containsClientExtId){ - if (client.getExternalId()!=null){ - writeString(nameCol+1,row,client.getExternalId()); - } - } + } + } + } + protected void setClientAndGroupDateLookupTable(Sheet sheet, List clients, List groups, int nameCol, + int activationDateCol, boolean containsClientExtId, String dateFormat) { + Workbook workbook = sheet.getWorkbook(); + CellStyle dateCellStyle = workbook.createCellStyle(); + short df = workbook.createDataFormat().getFormat(dateFormat); + dateCellStyle.setDataFormat(df); + int rowIndex = 0; + SimpleDateFormat outputFormat = new SimpleDateFormat(dateFormat); + SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd"); + Date date = null; + try { + if (clients != null) { + for (ClientData client : clients) { + Row row = sheet.getRow(++rowIndex); + if (row == null) { + row = sheet.createRow(rowIndex); } + writeString(nameCol, row, client.displayName().replaceAll("[ )(] ", "_") + "(" + client.id() + ")"); + + if (client.getActivationDate() != null) { + date = inputFormat.parse(client.getActivationDate().toString()); + writeDate(activationDateCol, row, outputFormat.format(date), dateCellStyle, dateFormat); + } + if (containsClientExtId) { + if (client.getExternalId() != null) { + writeString(nameCol + 1, row, client.getExternalId()); + } + } + + } } if (groups != null) { for (GroupGeneralData group : groups) { @@ -158,9 +159,9 @@ public abstract class AbstractWorkbookPopulator implements WorkbookPopulator { } } - } catch (ParseException e) { - LOG.error("Problem occurred in setClientAndGroupDateLookupTable function",e); - } + } catch (ParseException e) { + LOG.error("Problem occurred in setClientAndGroupDateLookupTable function", e); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/CenterSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/CenterSheetPopulator.java index 6c57c09aa..3d6ba4ffb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/CenterSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/CenterSheetPopulator.java @@ -30,6 +30,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class CenterSheetPopulator extends AbstractWorkbookPopulator { + private List allCenters; private List offices; @@ -47,7 +48,7 @@ public class CenterSheetPopulator extends AbstractWorkbookPopulator { } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet centerSheet = workbook.createSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME); setLayout(centerSheet); setOfficeToCentersMap(); @@ -74,19 +75,19 @@ public class CenterSheetPopulator extends AbstractWorkbookPopulator { writeString(OFFICE_NAME_COL, row, office.name()); ArrayList centersList = new ArrayList(); - if (officeToCenters.containsKey(office.name().trim().replaceAll("[ )(]", "_"))){ + if (officeToCenters.containsKey(office.name().trim().replaceAll("[ )(]", "_"))) { centersList = officeToCenters.get(office.name().trim().replaceAll("[ )(]", "_")); - if (!centersList.isEmpty()) { - for (String centerName : centersList) { - writeString(CENTER_NAME_COL, row, centerName); - writeLong(CENTER_ID_COL, row, centerNameToCenterId.get(centerName)); - row = centerSheet.createRow(++rowIndex); + if (!centersList.isEmpty()) { + for (String centerName : centersList) { + writeString(CENTER_NAME_COL, row, centerName); + writeLong(CENTER_ID_COL, row, centerNameToCenterId.get(centerName)); + row = centerSheet.createRow(++rowIndex); + } + officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex }); + } else { + officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex + 1 }); } - officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex }); - } else { - officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex + 1 }); } - } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/ClientSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/ClientSheetPopulator.java index 7b5c0ab34..2397b9576 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/ClientSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/ClientSheetPopulator.java @@ -30,6 +30,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class ClientSheetPopulator extends AbstractWorkbookPopulator { + private List allClients; private List officesDataList; @@ -48,7 +49,7 @@ public class ClientSheetPopulator extends AbstractWorkbookPopulator { } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet clientSheet = workbook.createSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME); setLayout(clientSheet); setOfficeToClientsMap(); @@ -61,8 +62,7 @@ public class ClientSheetPopulator extends AbstractWorkbookPopulator { private void setClientNameToClientIdMap() { clientNameToClientId = new HashMap<>(); for (ClientData clientData : allClients) { - clientNameToClientId.put(clientData.displayName().trim() + "(" + clientData.id() + ")", - clientData.id()); + clientNameToClientId.put(clientData.displayName().trim() + "(" + clientData.id() + ")", clientData.id()); } } @@ -86,10 +86,10 @@ public class ClientSheetPopulator extends AbstractWorkbookPopulator { } } - private void setClientNameToSavingsAccountsIdsMap(){ - clientNameToSavingsAccountIds=new HashMap<>(); - for (ClientData client: allClients) { - clientNameToSavingsAccountIds.put(client.displayName().trim() + "(" + client.id() + ")",client.getSavingsAccountId()); + private void setClientNameToSavingsAccountsIdsMap() { + clientNameToSavingsAccountIds = new HashMap<>(); + for (ClientData client : allClients) { + clientNameToSavingsAccountIds.put(client.displayName().trim() + "(" + client.id() + ")", client.getSavingsAccountId()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/ExtrasSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/ExtrasSheetPopulator.java index b54066e23..9a3ed0e95 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/ExtrasSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/ExtrasSheetPopulator.java @@ -40,16 +40,14 @@ public class ExtrasSheetPopulator extends AbstractWorkbookPopulator { private static final int CURRENCY_CODE_COL = 4; private static final int CURRENCY_NAME_COL = 5; - - public ExtrasSheetPopulator(List funds, List paymentTypes, - List currencies) { + public ExtrasSheetPopulator(List funds, List paymentTypes, List currencies) { this.funds = funds; this.paymentTypes = paymentTypes; this.currencies = currencies; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { int fundRowIndex = 1; Sheet extrasSheet = workbook.createSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME); setLayout(extrasSheet); @@ -101,9 +99,11 @@ public class ExtrasSheetPopulator extends AbstractWorkbookPopulator { writeString(CURRENCY_NAME_COL, rowHeader, "Currency Type "); writeString(CURRENCY_CODE_COL, rowHeader, "Currency Code "); } + public Integer getFundsSize() { return funds.size(); } + public Integer getPaymentTypesSize() { return paymentTypes.size(); } @@ -112,6 +112,4 @@ public class ExtrasSheetPopulator extends AbstractWorkbookPopulator { return currencies.size(); } - - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/FixedDepositProductSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/FixedDepositProductSheetPopulator.java index d3f2f979d..dd0c6eee9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/FixedDepositProductSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/FixedDepositProductSheetPopulator.java @@ -28,6 +28,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class FixedDepositProductSheetPopulator extends AbstractWorkbookPopulator { + List products; private static final int ID_COL = 0; @@ -55,72 +56,70 @@ public class FixedDepositProductSheetPopulator extends AbstractWorkbookPopulator private static final int IN_MULTIPLES_OF_DEPOSIT_TERM_TYPE_COL = 22; public FixedDepositProductSheetPopulator(List fixedDepositProducts) { - this.products =fixedDepositProducts; + this.products = fixedDepositProducts; } @Override - public void populate(Workbook workbook,String dateFormat) { - int rowIndex = 1; - Sheet productSheet = workbook.createSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); - setLayout(productSheet); - CellStyle dateCellStyle = workbook.createCellStyle(); - short df = workbook.createDataFormat().getFormat(dateFormat); - dateCellStyle.setDataFormat(df); - for(FixedDepositProductData product : products) { - Row row = productSheet.createRow(rowIndex++); - writeLong(ID_COL, row, product.getId()); - writeString(NAME_COL, row, product.getName().trim().replaceAll("[ )(]", "_")); - writeString(SHORT_NAME_COL, row, product.getShortName().trim().replaceAll("[ )(]", "_")); - writeBigDecimal(NOMINAL_ANNUAL_INTEREST_RATE_COL, row, product.getNominalAnnualInterestRate()); - writeString(INTEREST_COMPOUNDING_PERIOD_COL, row, product.getInterestCompoundingPeriodType().getValue()); - writeString(INTEREST_POSTING_PERIOD_COL, row, product.getInterestPostingPeriodType().getValue()); - writeString(INTEREST_CALCULATION_COL, row, product.getInterestCalculationType().getValue()); - writeString(INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, product.getInterestCalculationDaysInYearType().getValue()); + public void populate(Workbook workbook, String dateFormat) { + int rowIndex = 1; + Sheet productSheet = workbook.createSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); + setLayout(productSheet); + CellStyle dateCellStyle = workbook.createCellStyle(); + short df = workbook.createDataFormat().getFormat(dateFormat); + dateCellStyle.setDataFormat(df); + for (FixedDepositProductData product : products) { + Row row = productSheet.createRow(rowIndex++); + writeLong(ID_COL, row, product.getId()); + writeString(NAME_COL, row, product.getName().trim().replaceAll("[ )(]", "_")); + writeString(SHORT_NAME_COL, row, product.getShortName().trim().replaceAll("[ )(]", "_")); + writeBigDecimal(NOMINAL_ANNUAL_INTEREST_RATE_COL, row, product.getNominalAnnualInterestRate()); + writeString(INTEREST_COMPOUNDING_PERIOD_COL, row, product.getInterestCompoundingPeriodType().getValue()); + writeString(INTEREST_POSTING_PERIOD_COL, row, product.getInterestPostingPeriodType().getValue()); + writeString(INTEREST_CALCULATION_COL, row, product.getInterestCalculationType().getValue()); + writeString(INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, product.getInterestCalculationDaysInYearType().getValue()); - writeBoolean(PRECLOSURE_PENAL_APPLICABLE_COL, row, product.isPreClosurePenalApplicable()); - writeInt(MIN_DEPOSIT_TERM_COL, row, product.getMinDepositTerm()); - writeString(MIN_DEPOSIT_TERM_TYPE_COL, row, product.getMinDepositTermType().getValue()); + writeBoolean(PRECLOSURE_PENAL_APPLICABLE_COL, row, product.isPreClosurePenalApplicable()); + writeInt(MIN_DEPOSIT_TERM_COL, row, product.getMinDepositTerm()); + writeString(MIN_DEPOSIT_TERM_TYPE_COL, row, product.getMinDepositTermType().getValue()); - if(product.getMinDepositAmount() != null) { - writeBigDecimal(MIN_DEPOSIT_COL, row, product.getMinDepositAmount()); - } - if(product.getMaxDepositAmount() != null) { - writeBigDecimal(MAX_DEPOSIT_COL, row, product.getMaxDepositAmount()); - } - if(product.getDepositAmount() != null) { - writeBigDecimal(DEPOSIT_COL, row, product.getDepositAmount()); - } - if(product.getMaxDepositTerm() != null) { - writeInt(MAX_DEPOSIT_TERM_COL, row, product.getMaxDepositTerm()); - } - if(product.getInMultiplesOfDepositTerm() != null) { - writeInt(IN_MULTIPLES_OF_DEPOSIT_TERM_COL, row, product.getInMultiplesOfDepositTerm()); - } - if(product.getPreClosurePenalInterest() != null) { - writeBigDecimal(PRECLOSURE_PENAL_INTEREST_COL, row, product.getPreClosurePenalInterest()); - } - if(product.getMaxDepositTermType() != null) { - writeString(MAX_DEPOSIT_TERM_TYPE_COL, row, product.getMaxDepositTermType().getValue()); - } - if(product.getPreClosurePenalInterestOnType() != null) { - writeString(PRECLOSURE_INTEREST_TYPE_COL, row, - product.getPreClosurePenalInterestOnType().getValue()); - } - if(product.getInMultiplesOfDepositTermType() != null) { - writeString(IN_MULTIPLES_OF_DEPOSIT_TERM_TYPE_COL, row, - product.getInMultiplesOfDepositTermType().getValue()); - } - - if(product.getLockinPeriodFrequency() != null) { - writeInt(LOCKIN_PERIOD_COL, row, product.getLockinPeriodFrequency()); - } - if(product.getLockinPeriodFrequencyType() != null) { - writeString(LOCKIN_PERIOD_FREQUENCY_COL, row, product.getLockinPeriodFrequencyType().getValue()); - } - CurrencyData currency = product.getCurrency(); - writeString(CURRENCY_COL, row, currency.code()); + if (product.getMinDepositAmount() != null) { + writeBigDecimal(MIN_DEPOSIT_COL, row, product.getMinDepositAmount()); } - productSheet.protectSheet(""); + if (product.getMaxDepositAmount() != null) { + writeBigDecimal(MAX_DEPOSIT_COL, row, product.getMaxDepositAmount()); + } + if (product.getDepositAmount() != null) { + writeBigDecimal(DEPOSIT_COL, row, product.getDepositAmount()); + } + if (product.getMaxDepositTerm() != null) { + writeInt(MAX_DEPOSIT_TERM_COL, row, product.getMaxDepositTerm()); + } + if (product.getInMultiplesOfDepositTerm() != null) { + writeInt(IN_MULTIPLES_OF_DEPOSIT_TERM_COL, row, product.getInMultiplesOfDepositTerm()); + } + if (product.getPreClosurePenalInterest() != null) { + writeBigDecimal(PRECLOSURE_PENAL_INTEREST_COL, row, product.getPreClosurePenalInterest()); + } + if (product.getMaxDepositTermType() != null) { + writeString(MAX_DEPOSIT_TERM_TYPE_COL, row, product.getMaxDepositTermType().getValue()); + } + if (product.getPreClosurePenalInterestOnType() != null) { + writeString(PRECLOSURE_INTEREST_TYPE_COL, row, product.getPreClosurePenalInterestOnType().getValue()); + } + if (product.getInMultiplesOfDepositTermType() != null) { + writeString(IN_MULTIPLES_OF_DEPOSIT_TERM_TYPE_COL, row, product.getInMultiplesOfDepositTermType().getValue()); + } + + if (product.getLockinPeriodFrequency() != null) { + writeInt(LOCKIN_PERIOD_COL, row, product.getLockinPeriodFrequency()); + } + if (product.getLockinPeriodFrequencyType() != null) { + writeString(LOCKIN_PERIOD_FREQUENCY_COL, row, product.getLockinPeriodFrequencyType().getValue()); + } + CurrencyData currency = product.getCurrency(); + writeString(CURRENCY_COL, row, currency.code()); + } + productSheet.protectSheet(""); } private void setLayout(Sheet worksheet) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/GlAccountSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/GlAccountSheetPopulator.java index dc59e84a3..decb499c8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/GlAccountSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/GlAccountSheetPopulator.java @@ -26,6 +26,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class GlAccountSheetPopulator extends AbstractWorkbookPopulator { + private List allGlAccounts; private static final int ID_COL = 0; @@ -36,7 +37,7 @@ public class GlAccountSheetPopulator extends AbstractWorkbookPopulator { } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { int rowIndex = 1; Sheet glAccountSheet = workbook.createSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME); setLayout(glAccountSheet); @@ -67,4 +68,4 @@ public class GlAccountSheetPopulator extends AbstractWorkbookPopulator { return allGlAccounts.size(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/GroupSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/GroupSheetPopulator.java index 1d530aafd..d8f903a55 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/GroupSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/GroupSheetPopulator.java @@ -29,14 +29,14 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; - public class GroupSheetPopulator extends AbstractWorkbookPopulator { + private List groups; private List offices; private Map> officeToGroups; private Map officeNameToBeginEndIndexesOfGroups; - private Map groupNameToGroupId; + private Map groupNameToGroupId; private static final int OFFICE_NAME_COL = 0; private static final int GROUP_NAME_COL = 1; @@ -48,7 +48,7 @@ public class GroupSheetPopulator extends AbstractWorkbookPopulator { } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet groupSheet = workbook.createSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME); setLayout(groupSheet); setGroupNameToGroupIdMap(); @@ -74,7 +74,8 @@ public class GroupSheetPopulator extends AbstractWorkbookPopulator { add(group.getOfficeName().trim().replaceAll("[ )(]", "_"), group.getName().trim()); } } - //Guava Multi-map can reduce this. + + // Guava Multi-map can reduce this. private void add(String key, String value) { ArrayList values = officeToGroups.get(key); if (values == null) { @@ -83,45 +84,49 @@ public class GroupSheetPopulator extends AbstractWorkbookPopulator { values.add(value); officeToGroups.put(key, values); } + private void populateGroupsByOfficeName(Sheet groupSheet) { int rowIndex = 1; int officeIndex = 0; int startIndex = 1; officeNameToBeginEndIndexesOfGroups = new HashMap<>(); Row row = groupSheet.createRow(rowIndex); - for(OfficeData office : offices) { - startIndex = rowIndex+1; - writeString(OFFICE_NAME_COL, row, office.name()); - ArrayList groupsList = new ArrayList<>(); + for (OfficeData office : offices) { + startIndex = rowIndex + 1; + writeString(OFFICE_NAME_COL, row, office.name()); + ArrayList groupsList = new ArrayList<>(); - if(officeToGroups.containsKey(office.name().trim().replaceAll("[ )(]", "_"))) { - groupsList = officeToGroups.get(office.name().trim().replaceAll("[ )(]", "_")); - } + if (officeToGroups.containsKey(office.name().trim().replaceAll("[ )(]", "_"))) { + groupsList = officeToGroups.get(office.name().trim().replaceAll("[ )(]", "_")); + } - if(!groupsList.isEmpty()) { - for(String groupName : groupsList) { + if (!groupsList.isEmpty()) { + for (String groupName : groupsList) { writeString(GROUP_NAME_COL, row, groupName); writeLong(GROUP_ID_COL, row, groupNameToGroupId.get(groupName)); row = groupSheet.createRow(++rowIndex); } - officeNameToBeginEndIndexesOfGroups.put(officeIndex++, new Integer[]{startIndex, rowIndex}); - } - else { - officeNameToBeginEndIndexesOfGroups.put(officeIndex++, new Integer[]{startIndex, rowIndex+1}); - } + officeNameToBeginEndIndexesOfGroups.put(officeIndex++, new Integer[] { startIndex, rowIndex }); + } else { + officeNameToBeginEndIndexesOfGroups.put(officeIndex++, new Integer[] { startIndex, rowIndex + 1 }); + } } } + public List getGroups() { return groups; } + public Integer getGroupsSize() { return groups.size(); } + public Map getOfficeNameToBeginEndIndexesOfGroups() { return officeNameToBeginEndIndexesOfGroups; } - private void setGroupNameToGroupIdMap(){ - groupNameToGroupId=new HashMap(); + + private void setGroupNameToGroupIdMap() { + groupNameToGroupId = new HashMap(); for (GroupGeneralData group : groups) { groupNameToGroupId.put(group.getName().trim(), group.getId()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/LoanProductSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/LoanProductSheetPopulator.java index 6b4807240..894fe4ab2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/LoanProductSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/LoanProductSheetPopulator.java @@ -26,7 +26,6 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; - public class LoanProductSheetPopulator extends AbstractWorkbookPopulator { private List products; @@ -57,14 +56,12 @@ public class LoanProductSheetPopulator extends AbstractWorkbookPopulator { private static final int START_DATE_COL = 23; private static final int CLOSE_DATE_COL = 24; - - public LoanProductSheetPopulator(List products) { this.products = products; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { int rowIndex = 1; Sheet productSheet = workbook.createSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); setLayout(productSheet); @@ -116,8 +113,7 @@ public class LoanProductSheetPopulator extends AbstractWorkbookPopulator { writeString(INTEREST_RATE_FREQUENCY_COL, row, product.getInterestRateFrequencyType().getValue()); writeString(AMORTIZATION_TYPE_COL, row, product.getAmortizationType().getValue()); writeString(INTEREST_TYPE_COL, row, product.getInterestType().getValue()); - writeString(INTEREST_CALCULATION_PERIOD_TYPE_COL, row, - product.getInterestCalculationPeriodType().getValue()); + writeString(INTEREST_CALCULATION_PERIOD_TYPE_COL, row, product.getInterestCalculationPeriodType().getValue()); if (product.getInArrearsTolerance() != null) { writeBigDecimal(IN_ARREARS_TOLERANCE_COL, row, product.getInArrearsTolerance()); } @@ -168,8 +164,8 @@ public class LoanProductSheetPopulator extends AbstractWorkbookPopulator { worksheet.setColumnWidth(IN_ARREARS_TOLERANCE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(GRACE_ON_PRINCIPAL_PAYMENT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GRACE_ON_INTEREST_PAYMENT_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(GRACE_ON_INTEREST_CHARGED_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(GRACE_ON_INTEREST_PAYMENT_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(GRACE_ON_INTEREST_CHARGED_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(START_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(CLOSE_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); @@ -201,10 +197,12 @@ public class LoanProductSheetPopulator extends AbstractWorkbookPopulator { writeString(START_DATE_COL, rowHeader, "Start Date"); writeString(CLOSE_DATE_COL, rowHeader, "End Date"); } - public List getProducts(){ + + public List getProducts() { return products; } + public Integer getProductsSize() { return products.size(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/OfficeSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/OfficeSheetPopulator.java index a4bd3fa17..fac149b20 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/OfficeSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/OfficeSheetPopulator.java @@ -28,54 +28,53 @@ import org.apache.poi.ss.usermodel.Workbook; public class OfficeSheetPopulator extends AbstractWorkbookPopulator { - private List offices; + private List offices; - private static final int ID_COL = 0; - private static final int OFFICE_NAME_COL = 1; + private static final int ID_COL = 0; + private static final int OFFICE_NAME_COL = 1; - public OfficeSheetPopulator(final List offices) { - this.offices = offices; - } - - - @Override - public void populate(final Workbook workbook,String dateFormat) { - int rowIndex = 1; - Sheet officeSheet = workbook.createSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); - setLayout(officeSheet); - - populateOffices(officeSheet, rowIndex); - officeSheet.protectSheet(""); - } - - private void populateOffices(Sheet officeSheet, int rowIndex) { - for (OfficeData office : offices) { - Row row = officeSheet.createRow(rowIndex); - writeLong(ID_COL, row, office.getId()); - writeString(OFFICE_NAME_COL, row, office.name().trim().replaceAll("[ )(]", "_")); - rowIndex++; + public OfficeSheetPopulator(final List offices) { + this.offices = offices; } - } - private void setLayout(Sheet worksheet) { - worksheet.setColumnWidth(ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - writeString(ID_COL, rowHeader, "ID"); - writeString(OFFICE_NAME_COL, rowHeader, "Name"); - } + @Override + public void populate(final Workbook workbook, String dateFormat) { + int rowIndex = 1; + Sheet officeSheet = workbook.createSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); + setLayout(officeSheet); - public List getOffices() { - return offices; - } + populateOffices(officeSheet, rowIndex); + officeSheet.protectSheet(""); + } - public List getOfficeNames() { - List officeNames=new ArrayList<>(); - for (OfficeData office : offices) { - officeNames.add(office.name()); + private void populateOffices(Sheet officeSheet, int rowIndex) { + for (OfficeData office : offices) { + Row row = officeSheet.createRow(rowIndex); + writeLong(ID_COL, row, office.getId()); + writeString(OFFICE_NAME_COL, row, office.name().trim().replaceAll("[ )(]", "_")); + rowIndex++; } - return officeNames; - } + } -} \ No newline at end of file + private void setLayout(Sheet worksheet) { + worksheet.setColumnWidth(ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + writeString(ID_COL, rowHeader, "ID"); + writeString(OFFICE_NAME_COL, rowHeader, "Name"); + } + + public List getOffices() { + return offices; + } + + public List getOfficeNames() { + List officeNames = new ArrayList<>(); + for (OfficeData office : offices) { + officeNames.add(office.name()); + } + return officeNames; + } + +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/PersonnelSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/PersonnelSheetPopulator.java index 0a975e455..8b0c48d60 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/PersonnelSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/PersonnelSheetPopulator.java @@ -33,102 +33,101 @@ import org.apache.poi.ss.usermodel.Workbook; public class PersonnelSheetPopulator extends AbstractWorkbookPopulator { - private List personnel; - private List offices; + private List personnel; + private List offices; - // Maintaining the one to many relationship - private Map> officeToPersonnel; - - /* - * Guava Multimap would make this more readable. The value Integer[] contains the beginIndex and - * endIndex for the staff list of each office. Required for applying names in excel. - */ - private Map officeNameToBeginEndIndexesOfStaff; - - private static final int OFFICE_NAME_COL = 0; - private static final int STAFF_NAME_COL = 1; - private static final int STAFF_ID_COL = 2; - - public PersonnelSheetPopulator(List personnel, List offices) { - this.personnel = personnel; - this.offices = offices; - } - - - @Override - public void populate(Workbook workbook,String dateFormat) { - Sheet staffSheet = workbook.createSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME); - setLayout(staffSheet); + // Maintaining the one to many relationship + private Map> officeToPersonnel; /* - * This piece of code could have been avoided by making multiple trips to the database for the - * staff of each office but this is more performance efficient + * Guava Multimap would make this more readable. The value Integer[] + * contains the beginIndex and endIndex for the staff list of each office. + * Required for applying names in excel. */ - setOfficeToPersonnelMap(); + private Map officeNameToBeginEndIndexesOfStaff; - populateStaffByOfficeName(staffSheet); - staffSheet.protectSheet(""); - } + private static final int OFFICE_NAME_COL = 0; + private static final int STAFF_NAME_COL = 1; + private static final int STAFF_ID_COL = 2; + public PersonnelSheetPopulator(List personnel, List offices) { + this.personnel = personnel; + this.offices = offices; + } - private void populateStaffByOfficeName(Sheet staffSheet) { - int rowIndex = 1; - int startIndex = 1; - int officeIndex = 0; - officeNameToBeginEndIndexesOfStaff = new HashMap<>(); - Row row = staffSheet.createRow(rowIndex); - for (OfficeData office : offices) { - startIndex = rowIndex + 1; - writeString(OFFICE_NAME_COL, row, office.name().trim().replaceAll("[ )(]", "_")); + @Override + public void populate(Workbook workbook, String dateFormat) { + Sheet staffSheet = workbook.createSheet(TemplatePopulateImportConstants.STAFF_SHEET_NAME); + setLayout(staffSheet); - List staffList = - officeToPersonnel.get(office.name().trim().replaceAll("[ )(]", "_")); + /* + * This piece of code could have been avoided by making multiple trips + * to the database for the staff of each office but this is more + * performance efficient + */ + setOfficeToPersonnelMap(); - if (staffList!=null){ - if (!staffList.isEmpty()) { - for (StaffData staff : staffList) { - writeString(STAFF_NAME_COL, row, staff.getDisplayName()); - writeLong(STAFF_ID_COL, row, staff.getId()); - row = staffSheet.createRow(++rowIndex); + populateStaffByOfficeName(staffSheet); + staffSheet.protectSheet(""); + } + + private void populateStaffByOfficeName(Sheet staffSheet) { + int rowIndex = 1; + int startIndex = 1; + int officeIndex = 0; + officeNameToBeginEndIndexesOfStaff = new HashMap<>(); + Row row = staffSheet.createRow(rowIndex); + for (OfficeData office : offices) { + startIndex = rowIndex + 1; + writeString(OFFICE_NAME_COL, row, office.name().trim().replaceAll("[ )(]", "_")); + + List staffList = officeToPersonnel.get(office.name().trim().replaceAll("[ )(]", "_")); + + if (staffList != null) { + if (!staffList.isEmpty()) { + for (StaffData staff : staffList) { + writeString(STAFF_NAME_COL, row, staff.getDisplayName()); + writeLong(STAFF_ID_COL, row, staff.getId()); + row = staffSheet.createRow(++rowIndex); + } + officeNameToBeginEndIndexesOfStaff.put(officeIndex++, new Integer[] { startIndex, rowIndex }); + } + } else { + officeIndex++; + } } - officeNameToBeginEndIndexesOfStaff.put(officeIndex++, new Integer[]{startIndex, rowIndex}); - } - } else { - officeIndex++; } - } - } - private void setOfficeToPersonnelMap() { - officeToPersonnel = new HashMap<>(); - for (StaffData person : personnel) { - add(person.getOfficeName().trim().replaceAll("[ )(]", "_"), person); + private void setOfficeToPersonnelMap() { + officeToPersonnel = new HashMap<>(); + for (StaffData person : personnel) { + add(person.getOfficeName().trim().replaceAll("[ )(]", "_"), person); + } } - } - // Guava Multi-map can reduce this. - private void add(String key, StaffData value) { - List values = officeToPersonnel.get(key); - if (values == null) { - values = new ArrayList<>(); + // Guava Multi-map can reduce this. + private void add(String key, StaffData value) { + List values = officeToPersonnel.get(key); + if (values == null) { + values = new ArrayList<>(); + } + values.add(value); + officeToPersonnel.put(key, values); } - values.add(value); - officeToPersonnel.put(key, values); - } - private void setLayout(Sheet worksheet) { - for (Integer i = 0; i < 3; i++) { - worksheet.setColumnWidth(i, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + private void setLayout(Sheet worksheet) { + for (Integer i = 0; i < 3; i++) { + worksheet.setColumnWidth(i, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + } + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + writeString(OFFICE_NAME_COL, rowHeader, "Office Name"); + writeString(STAFF_NAME_COL, rowHeader, "Staff List"); + writeString(STAFF_ID_COL, rowHeader, "Staff ID"); } - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - writeString(OFFICE_NAME_COL, rowHeader, "Office Name"); - writeString(STAFF_NAME_COL, rowHeader, "Staff List"); - writeString(STAFF_ID_COL, rowHeader, "Staff ID"); - } - public Map getOfficeNameToBeginEndIndexesOfStaff() { - return officeNameToBeginEndIndexesOfStaff; - } + public Map getOfficeNameToBeginEndIndexesOfStaff() { + return officeNameToBeginEndIndexesOfStaff; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/RecurringDepositProductSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/RecurringDepositProductSheetPopulator.java index d1b391dee..a1431229b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/RecurringDepositProductSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/RecurringDepositProductSheetPopulator.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.infrastructure.bulkimport.populator; - import java.util.List; import org.apache.fineract.infrastructure.bulkimport.constants.TemplatePopulateImportConstants; import org.apache.fineract.organisation.monetary.data.CurrencyData; @@ -60,78 +59,75 @@ public class RecurringDepositProductSheetPopulator extends AbstractWorkbookPopul private static final int ADJUST_ADVANCE_COL = 25; public RecurringDepositProductSheetPopulator(List recurringDepositProducts) { - this.products=recurringDepositProducts; + this.products = recurringDepositProducts; } @Override - public void populate(Workbook workbook,String dateFormat) { - int rowIndex = 1; - Sheet productSheet = workbook.createSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); - setLayout(productSheet); - CellStyle dateCellStyle = workbook.createCellStyle(); - short df = workbook.createDataFormat().getFormat(dateFormat); - dateCellStyle.setDataFormat(df); - for(RecurringDepositProductData product : products) { - Row row = productSheet.createRow(rowIndex++); - writeLong(ID_COL, row, product.getId()); - writeString(NAME_COL, row, product.getName().trim().replaceAll("[ )(]", "_")); - writeString(SHORT_NAME_COL, row, product.getShortName().trim().replaceAll("[ )(]", "_")); - writeBigDecimal(NOMINAL_ANNUAL_INTEREST_RATE_COL, row, product.getNominalAnnualInterestRate()); - writeString(INTEREST_COMPOUNDING_PERIOD_COL, row, product.getInterestCompoundingPeriodType().getValue()); - writeString(INTEREST_POSTING_PERIOD_COL, row, product.getInterestPostingPeriodType().getValue()); - writeString(INTEREST_CALCULATION_COL, row, product.getInterestCalculationType().getValue()); - writeString(INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, product.getInterestCalculationDaysInYearType().getValue()); - writeBoolean(PRECLOSURE_PENAL_APPLICABLE_COL, row, product.isPreClosurePenalApplicable()); - writeString(MIN_DEPOSIT_TERM_TYPE_COL, row, product.getMinDepositTermType().getValue()); + public void populate(Workbook workbook, String dateFormat) { + int rowIndex = 1; + Sheet productSheet = workbook.createSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); + setLayout(productSheet); + CellStyle dateCellStyle = workbook.createCellStyle(); + short df = workbook.createDataFormat().getFormat(dateFormat); + dateCellStyle.setDataFormat(df); + for (RecurringDepositProductData product : products) { + Row row = productSheet.createRow(rowIndex++); + writeLong(ID_COL, row, product.getId()); + writeString(NAME_COL, row, product.getName().trim().replaceAll("[ )(]", "_")); + writeString(SHORT_NAME_COL, row, product.getShortName().trim().replaceAll("[ )(]", "_")); + writeBigDecimal(NOMINAL_ANNUAL_INTEREST_RATE_COL, row, product.getNominalAnnualInterestRate()); + writeString(INTEREST_COMPOUNDING_PERIOD_COL, row, product.getInterestCompoundingPeriodType().getValue()); + writeString(INTEREST_POSTING_PERIOD_COL, row, product.getInterestPostingPeriodType().getValue()); + writeString(INTEREST_CALCULATION_COL, row, product.getInterestCalculationType().getValue()); + writeString(INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, product.getInterestCalculationDaysInYearType().getValue()); + writeBoolean(PRECLOSURE_PENAL_APPLICABLE_COL, row, product.isPreClosurePenalApplicable()); + writeString(MIN_DEPOSIT_TERM_TYPE_COL, row, product.getMinDepositTermType().getValue()); - if(product.getMinDepositAmount() != null) { - writeBigDecimal(MIN_DEPOSIT_COL, row, product.getMinDepositAmount()); - } - if(product.getMaxDepositAmount() != null) { - writeBigDecimal(MAX_DEPOSIT_COL, row, product.getMaxDepositAmount()); - } - if(product.getDepositAmount() != null) { - writeBigDecimal(DEPOSIT_COL, row, product.getDepositAmount()); - } - if(product.getMaxDepositTerm() != null) { - writeInt(MAX_DEPOSIT_TERM_COL, row, product.getMaxDepositTerm()); - } - - if(product.getMinDepositTerm() != null) { - writeInt(MIN_DEPOSIT_TERM_COL, row, product.getMinDepositTerm()); - } - - - if(product.getInMultiplesOfDepositTerm() != null) { - writeInt(IN_MULTIPLES_OF_DEPOSIT_TERM_COL, row, product.getInMultiplesOfDepositTerm()); - } - if(product.getPreClosurePenalInterest() != null) { - writeBigDecimal(PRECLOSURE_PENAL_INTEREST_COL, row, product.getPreClosurePenalInterest()); - } - if(product.getMaxDepositTermType() != null) { - writeString(MAX_DEPOSIT_TERM_TYPE_COL, row, product.getMaxDepositTermType().getValue()); - } - if(product.getPreClosurePenalInterestOnType() != null) { - writeString(PRECLOSURE_INTEREST_TYPE_COL, row, - product.getPreClosurePenalInterestOnType().getValue()); - } - if(product.getInMultiplesOfDepositTermType() != null) { - writeString(IN_MULTIPLES_OF_DEPOSIT_TERM_TYPE_COL, row, - product.getInMultiplesOfDepositTermType().getValue()); - } - writeBoolean(ALLOW_WITHDRAWAL_COL, row, product.isAllowWithdrawal()); - writeBoolean(ADJUST_ADVANCE_COL, row, product.isAdjustAdvanceTowardsFuturePayments()); - writeBoolean(IS_MANDATORY_DEPOSIT_COL, row, product.isMandatoryDeposit()); - if(product.getLockinPeriodFrequency() != null) { - writeInt(LOCKIN_PERIOD_COL, row, product.getLockinPeriodFrequency()); - } - if(product.getLockinPeriodFrequencyType() != null) { - writeString(LOCKIN_PERIOD_FREQUENCY_COL, row, product.getLockinPeriodFrequencyType().getValue()); - } - CurrencyData currency = product.getCurrency(); - writeString(CURRENCY_COL, row, currency.code()); + if (product.getMinDepositAmount() != null) { + writeBigDecimal(MIN_DEPOSIT_COL, row, product.getMinDepositAmount()); } - productSheet.protectSheet(""); + if (product.getMaxDepositAmount() != null) { + writeBigDecimal(MAX_DEPOSIT_COL, row, product.getMaxDepositAmount()); + } + if (product.getDepositAmount() != null) { + writeBigDecimal(DEPOSIT_COL, row, product.getDepositAmount()); + } + if (product.getMaxDepositTerm() != null) { + writeInt(MAX_DEPOSIT_TERM_COL, row, product.getMaxDepositTerm()); + } + + if (product.getMinDepositTerm() != null) { + writeInt(MIN_DEPOSIT_TERM_COL, row, product.getMinDepositTerm()); + } + + if (product.getInMultiplesOfDepositTerm() != null) { + writeInt(IN_MULTIPLES_OF_DEPOSIT_TERM_COL, row, product.getInMultiplesOfDepositTerm()); + } + if (product.getPreClosurePenalInterest() != null) { + writeBigDecimal(PRECLOSURE_PENAL_INTEREST_COL, row, product.getPreClosurePenalInterest()); + } + if (product.getMaxDepositTermType() != null) { + writeString(MAX_DEPOSIT_TERM_TYPE_COL, row, product.getMaxDepositTermType().getValue()); + } + if (product.getPreClosurePenalInterestOnType() != null) { + writeString(PRECLOSURE_INTEREST_TYPE_COL, row, product.getPreClosurePenalInterestOnType().getValue()); + } + if (product.getInMultiplesOfDepositTermType() != null) { + writeString(IN_MULTIPLES_OF_DEPOSIT_TERM_TYPE_COL, row, product.getInMultiplesOfDepositTermType().getValue()); + } + writeBoolean(ALLOW_WITHDRAWAL_COL, row, product.isAllowWithdrawal()); + writeBoolean(ADJUST_ADVANCE_COL, row, product.isAdjustAdvanceTowardsFuturePayments()); + writeBoolean(IS_MANDATORY_DEPOSIT_COL, row, product.isMandatoryDeposit()); + if (product.getLockinPeriodFrequency() != null) { + writeInt(LOCKIN_PERIOD_COL, row, product.getLockinPeriodFrequency()); + } + if (product.getLockinPeriodFrequencyType() != null) { + writeString(LOCKIN_PERIOD_FREQUENCY_COL, row, product.getLockinPeriodFrequencyType().getValue()); + } + CurrencyData currency = product.getCurrency(); + writeString(CURRENCY_COL, row, currency.code()); + } + productSheet.protectSheet(""); } private void setLayout(Sheet worksheet) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/RoleSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/RoleSheetPopulator.java index 29c05b9bf..112c222dc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/RoleSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/RoleSheetPopulator.java @@ -26,17 +26,18 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class RoleSheetPopulator extends AbstractWorkbookPopulator { - private ListrolesList; - private static final int ID_COL=0; - private static final int ROLE_NAME=1; + private List rolesList; + + private static final int ID_COL = 0; + private static final int ROLE_NAME = 1; public RoleSheetPopulator(List roles) { - this.rolesList=roles; + this.rolesList = roles; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { int rowIndex = 1; Sheet rolesSheet = workbook.createSheet(TemplatePopulateImportConstants.ROLES_SHEET_NAME); setLayout(rolesSheet); @@ -62,5 +63,4 @@ public class RoleSheetPopulator extends AbstractWorkbookPopulator { writeString(ROLE_NAME, rowHeader, "Role Name"); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SavingsAccountSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SavingsAccountSheetPopulator.java index 3bd28778e..e86eaa401 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SavingsAccountSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SavingsAccountSheetPopulator.java @@ -29,54 +29,52 @@ import org.apache.poi.ss.usermodel.Workbook; public class SavingsAccountSheetPopulator extends AbstractWorkbookPopulator { - private List savingsAccountDataList; - private Map> clientToSavingsMap; - - private static final int SAVINGS_ACCOUNT_ID_COL=0; - private static final int SAVING_ACCOUNT_NO=1; - private static final int CURRENCY_COL=2; - private static final int CLIENT_NAME=3; + private List savingsAccountDataList; + private Map> clientToSavingsMap; + private static final int SAVINGS_ACCOUNT_ID_COL = 0; + private static final int SAVING_ACCOUNT_NO = 1; + private static final int CURRENCY_COL = 2; + private static final int CLIENT_NAME = 3; public SavingsAccountSheetPopulator(List savingsAccountDataList) { - this.savingsAccountDataList=savingsAccountDataList; + this.savingsAccountDataList = savingsAccountDataList; } @Override - public void populate(Workbook workbook,String dateFormat) { - Sheet savingsSheet=workbook.createSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME); + public void populate(Workbook workbook, String dateFormat) { + Sheet savingsSheet = workbook.createSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME); setLayout(savingsSheet); populateSavingsSheet(savingsSheet); savingsSheet.protectSheet(""); } private void populateSavingsSheet(Sheet savingsSheet) { - int rowIndex=1; - for (SavingsAccountData savings: savingsAccountDataList) { - Row row=savingsSheet.createRow(rowIndex++); - writeLong(SAVINGS_ACCOUNT_ID_COL,row,savings.id()); - writeString(SAVING_ACCOUNT_NO,row,savings.getAccountNo()); - writeString(CURRENCY_COL,row,savings.currency().code()); - writeString(CLIENT_NAME,row,savings.getClientName()); + int rowIndex = 1; + for (SavingsAccountData savings : savingsAccountDataList) { + Row row = savingsSheet.createRow(rowIndex++); + writeLong(SAVINGS_ACCOUNT_ID_COL, row, savings.id()); + writeString(SAVING_ACCOUNT_NO, row, savings.getAccountNo()); + writeString(CURRENCY_COL, row, savings.currency().code()); + writeString(CLIENT_NAME, row, savings.getClientName()); } } - private void setLayout(Sheet savingsSheet) { Row rowHeader = savingsSheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - savingsSheet.setColumnWidth(SAVINGS_ACCOUNT_ID_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - writeString(SAVINGS_ACCOUNT_ID_COL,rowHeader,"Savings Account Id"); + savingsSheet.setColumnWidth(SAVINGS_ACCOUNT_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + writeString(SAVINGS_ACCOUNT_ID_COL, rowHeader, "Savings Account Id"); - savingsSheet.setColumnWidth(SAVING_ACCOUNT_NO,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - writeString(SAVING_ACCOUNT_NO,rowHeader,"Savings Account No"); + savingsSheet.setColumnWidth(SAVING_ACCOUNT_NO, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + writeString(SAVING_ACCOUNT_NO, rowHeader, "Savings Account No"); - savingsSheet.setColumnWidth(CURRENCY_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(CURRENCY_COL,rowHeader,"Currency Code"); + savingsSheet.setColumnWidth(CURRENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(CURRENCY_COL, rowHeader, "Currency Code"); - savingsSheet.setColumnWidth(CLIENT_NAME,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(CLIENT_NAME,rowHeader,"Client Name"); + savingsSheet.setColumnWidth(CLIENT_NAME, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(CLIENT_NAME, rowHeader, "Client Name"); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SavingsProductSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SavingsProductSheetPopulator.java index 83e395776..1dedb9cf8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SavingsProductSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SavingsProductSheetPopulator.java @@ -28,6 +28,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class SavingsProductSheetPopulator extends AbstractWorkbookPopulator { + private List savingsProducts; private static final int ID_COL = 0; @@ -48,18 +49,18 @@ public class SavingsProductSheetPopulator extends AbstractWorkbookPopulator { private static final int OVERDRAFT_LIMIT_COL = 15; public SavingsProductSheetPopulator(List savingsProducts) { - this.savingsProducts=savingsProducts; + this.savingsProducts = savingsProducts; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { int rowIndex = 1; Sheet productSheet = workbook.createSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME); setLayout(productSheet); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); dateCellStyle.setDataFormat(df); - for(SavingsProductData product : savingsProducts) { + for (SavingsProductData product : savingsProducts) { Row row = productSheet.createRow(rowIndex++); writeLong(ID_COL, row, product.getId()); writeString(NAME_COL, row, product.getName().trim().replaceAll("[ )(]", "_")); @@ -68,24 +69,24 @@ public class SavingsProductSheetPopulator extends AbstractWorkbookPopulator { writeString(INTEREST_POSTING_PERIOD_COL, row, product.getInterestPostingPeriodType().getValue()); writeString(INTEREST_CALCULATION_COL, row, product.getInterestCalculationType().getValue()); writeString(INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, product.getInterestCalculationDaysInYearType().getValue()); - if(product.getMinRequiredOpeningBalance() != null) { + if (product.getMinRequiredOpeningBalance() != null) { writeBigDecimal(MIN_OPENING_BALANCE_COL, row, product.getMinRequiredOpeningBalance()); } - if(product.getLockinPeriodFrequency() != null) { + if (product.getLockinPeriodFrequency() != null) { writeInt(LOCKIN_PERIOD_COL, row, product.getLockinPeriodFrequency()); } - if(product.getLockinPeriodFrequencyType() != null) { + if (product.getLockinPeriodFrequencyType() != null) { writeString(LOCKIN_PERIOD_FREQUENCY_COL, row, product.getLockinPeriodFrequencyType().getValue()); } CurrencyData currency = product.getCurrency(); writeString(CURRENCY_COL, row, currency.code()); writeInt(DECIMAL_PLACES_COL, row, currency.decimalPlaces()); - if(currency.currencyInMultiplesOf() != null) { + if (currency.currencyInMultiplesOf() != null) { writeInt(IN_MULTIPLES_OF_COL, row, currency.currencyInMultiplesOf()); } writeBoolean(WITHDRAWAL_FEE_COL, row, product.isWithdrawalFeeForTransfers()); - writeBoolean(ALLOW_OVERDRAFT_COL, row,product.isAllowOverdraft()); - if(product.getOverdraftLimit() != null) { + writeBoolean(ALLOW_OVERDRAFT_COL, row, product.isAllowOverdraft()); + if (product.getOverdraftLimit() != null) { writeBigDecimal(OVERDRAFT_LIMIT_COL, row, product.getOverdraftLimit()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SharedProductsSheetPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SharedProductsSheetPopulator.java index b5bd1e4f1..166db87b0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SharedProductsSheetPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/SharedProductsSheetPopulator.java @@ -34,11 +34,12 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class SharedProductsSheetPopulator extends AbstractWorkbookPopulator { + private List sharedProductDataList; private List chargesForSharedProducts; - private MapproductToBeginEndIndexesofCharges; + private Map productToBeginEndIndexesofCharges; - private static final int PRODUCT_ID=0; + private static final int PRODUCT_ID = 0; private static final int PRODUCT_NAME_COL = 1; private static final int CURRENCY_COL = 2; private static final int DECIMAL_PLACES_COL = 3; @@ -51,17 +52,15 @@ public class SharedProductsSheetPopulator extends AbstractWorkbookPopulator { private static final int CHARGES_ID_3_COL = 11; private static final int CHARGES_NAME_3_COL = 12; - - - public SharedProductsSheetPopulator(List shareProductDataList,List chargesForShares) { - this.sharedProductDataList=shareProductDataList; - this.chargesForSharedProducts=chargesForShares; + public SharedProductsSheetPopulator(List shareProductDataList, List chargesForShares) { + this.sharedProductDataList = shareProductDataList; + this.chargesForSharedProducts = chargesForShares; } @Override - public void populate(Workbook workbook,String dateFormat) { - Sheet sharedProductsSheet=workbook.createSheet(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME); + public void populate(Workbook workbook, String dateFormat) { + Sheet sharedProductsSheet = workbook.createSheet(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME); setLayout(sharedProductsSheet); populateSheet(sharedProductsSheet); sharedProductsSheet.protectSheet(""); @@ -72,29 +71,30 @@ public class SharedProductsSheetPopulator extends AbstractWorkbookPopulator { int startIndexCharges = 1; int endIndexCharges = 0; productToBeginEndIndexesofCharges = new HashMap<>(); - for (ShareProductData productData : sharedProductDataList) { - Row row = sharedProductsSheet.createRow(++index); - writeLong(PRODUCT_ID, row, productData.getId()); - writeString(PRODUCT_NAME_COL, row, productData.getName().replaceAll("[ ]", "_")); - writeString(CURRENCY_COL, row, productData.getCurrency().getName().replaceAll("[ ]", "_")); - writeInt(DECIMAL_PLACES_COL, row, productData.getCurrency().decimalPlaces()); - writeBigDecimal(TODAYS_PRICE_COL, row, deriveMarketPrice(productData)); - writeInt(CURRENCY_IN_MULTIPLES_COL,row,productData.getCurrency().currencyInMultiplesOf()); - if (chargesForSharedProducts != null) { - int chargeRowIndex=0; - for (ChargeData chargeData:chargesForSharedProducts) { - if (chargeData.getCurrency().getName().equals(productData.getCurrency().getName())) { - writeString(CHARGES_NAME_1_COL+chargeRowIndex, row, chargeData.getName()); - writeLong(CHARGES_ID_1_COL+chargeRowIndex, row, chargeData.getId()); - chargeRowIndex+=2; - endIndexCharges++; - } + for (ShareProductData productData : sharedProductDataList) { + Row row = sharedProductsSheet.createRow(++index); + writeLong(PRODUCT_ID, row, productData.getId()); + writeString(PRODUCT_NAME_COL, row, productData.getName().replaceAll("[ ]", "_")); + writeString(CURRENCY_COL, row, productData.getCurrency().getName().replaceAll("[ ]", "_")); + writeInt(DECIMAL_PLACES_COL, row, productData.getCurrency().decimalPlaces()); + writeBigDecimal(TODAYS_PRICE_COL, row, deriveMarketPrice(productData)); + writeInt(CURRENCY_IN_MULTIPLES_COL, row, productData.getCurrency().currencyInMultiplesOf()); + if (chargesForSharedProducts != null) { + int chargeRowIndex = 0; + for (ChargeData chargeData : chargesForSharedProducts) { + if (chargeData.getCurrency().getName().equals(productData.getCurrency().getName())) { + writeString(CHARGES_NAME_1_COL + chargeRowIndex, row, chargeData.getName()); + writeLong(CHARGES_ID_1_COL + chargeRowIndex, row, chargeData.getId()); + chargeRowIndex += 2; + endIndexCharges++; } - productToBeginEndIndexesofCharges.put(productData.getId(), new Integer[]{startIndexCharges, endIndexCharges}); - startIndexCharges = endIndexCharges + 1; } + productToBeginEndIndexesofCharges.put(productData.getId(), new Integer[] { startIndexCharges, endIndexCharges }); + startIndexCharges = endIndexCharges + 1; } + } } + private BigDecimal deriveMarketPrice(final ShareProductData shareProductData) { BigDecimal marketValue = shareProductData.getUnitPrice(); Collection marketDataSet = shareProductData.getMarketPrice(); @@ -111,44 +111,44 @@ public class SharedProductsSheetPopulator extends AbstractWorkbookPopulator { } private void setLayout(Sheet workSheet) { - Row rowHeader=workSheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + Row rowHeader = workSheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - workSheet.setColumnWidth(PRODUCT_ID,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(PRODUCT_ID,rowHeader,"Product Id"); + workSheet.setColumnWidth(PRODUCT_ID, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(PRODUCT_ID, rowHeader, "Product Id"); - workSheet.setColumnWidth(PRODUCT_NAME_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - writeString(PRODUCT_NAME_COL,rowHeader,"Product Name"); + workSheet.setColumnWidth(PRODUCT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + writeString(PRODUCT_NAME_COL, rowHeader, "Product Name"); - workSheet.setColumnWidth(CURRENCY_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - writeString(CURRENCY_COL,rowHeader,"Currency"); + workSheet.setColumnWidth(CURRENCY_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + writeString(CURRENCY_COL, rowHeader, "Currency"); - workSheet.setColumnWidth(DECIMAL_PLACES_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(DECIMAL_PLACES_COL,rowHeader,"Decimal Places"); + workSheet.setColumnWidth(DECIMAL_PLACES_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(DECIMAL_PLACES_COL, rowHeader, "Decimal Places"); - workSheet.setColumnWidth(TODAYS_PRICE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(TODAYS_PRICE_COL,rowHeader,"Today's Price"); + workSheet.setColumnWidth(TODAYS_PRICE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(TODAYS_PRICE_COL, rowHeader, "Today's Price"); - workSheet.setColumnWidth(CURRENCY_IN_MULTIPLES_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(CURRENCY_IN_MULTIPLES_COL,rowHeader,"Currency in multiples of"); + workSheet.setColumnWidth(CURRENCY_IN_MULTIPLES_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(CURRENCY_IN_MULTIPLES_COL, rowHeader, "Currency in multiples of"); - workSheet.setColumnWidth(CHARGES_NAME_1_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(CHARGES_NAME_1_COL,rowHeader,"Charges Name 1"); + workSheet.setColumnWidth(CHARGES_NAME_1_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(CHARGES_NAME_1_COL, rowHeader, "Charges Name 1"); - workSheet.setColumnWidth(CHARGES_ID_1_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(CHARGES_ID_1_COL,rowHeader,"Charges Id 1"); + workSheet.setColumnWidth(CHARGES_ID_1_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(CHARGES_ID_1_COL, rowHeader, "Charges Id 1"); - workSheet.setColumnWidth(CHARGES_NAME_2_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(CHARGES_NAME_2_COL,rowHeader,"Charges Name 2"); + workSheet.setColumnWidth(CHARGES_NAME_2_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(CHARGES_NAME_2_COL, rowHeader, "Charges Name 2"); - workSheet.setColumnWidth(CHARGES_ID_2_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(CHARGES_ID_2_COL,rowHeader,"Charges Id 2"); + workSheet.setColumnWidth(CHARGES_ID_2_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(CHARGES_ID_2_COL, rowHeader, "Charges Id 2"); - workSheet.setColumnWidth(CHARGES_NAME_3_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(CHARGES_NAME_3_COL,rowHeader,"Charges Name 3"); + workSheet.setColumnWidth(CHARGES_NAME_3_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(CHARGES_NAME_3_COL, rowHeader, "Charges Name 3"); - workSheet.setColumnWidth(CHARGES_ID_3_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(CHARGES_ID_3_COL,rowHeader,"Charges Id 3"); + workSheet.setColumnWidth(CHARGES_ID_3_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(CHARGES_ID_3_COL, rowHeader, "Charges Id 3"); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/WorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/WorkbookPopulator.java index 9ff2a1c17..d67bdf2a2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/WorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/WorkbookPopulator.java @@ -22,6 +22,6 @@ import org.apache.poi.ss.usermodel.Workbook; public interface WorkbookPopulator { - void populate(Workbook workbook,String dateFormat); + void populate(Workbook workbook, String dateFormat); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/centers/CentersWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/centers/CentersWorkbookPopulator.java index 0219df075..b231a8dc3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/centers/CentersWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/centers/CentersWorkbookPopulator.java @@ -38,33 +38,30 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddressList; - public class CentersWorkbookPopulator extends AbstractWorkbookPopulator { - private OfficeSheetPopulator officeSheetPopulator; private PersonnelSheetPopulator personnelSheetPopulator; private GroupSheetPopulator groupSheetPopulator; - public CentersWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - PersonnelSheetPopulator personnelSheetPopulator,GroupSheetPopulator groupSheetPopulator) { + public CentersWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, + GroupSheetPopulator groupSheetPopulator) { this.officeSheetPopulator = officeSheetPopulator; this.personnelSheetPopulator = personnelSheetPopulator; - this.groupSheetPopulator=groupSheetPopulator; + this.groupSheetPopulator = groupSheetPopulator; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet centerSheet = workbook.createSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME); - personnelSheetPopulator.populate(workbook,dateFormat); - officeSheetPopulator.populate(workbook,dateFormat); - groupSheetPopulator.populate(workbook,dateFormat); + personnelSheetPopulator.populate(workbook, dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + groupSheetPopulator.populate(workbook, dateFormat); setLayout(centerSheet); - setLookupTable(centerSheet,dateFormat); - setRules(centerSheet,dateFormat); + setLookupTable(centerSheet, dateFormat); + setRules(centerSheet, dateFormat); } - private void setLayout(Sheet worksheet) { Row rowHeader = worksheet.createRow(0); rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); @@ -74,7 +71,7 @@ public class CentersWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.setColumnWidth(CenterConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(CenterConstants.ACTIVE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(CenterConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(CenterConstants.SUBMITTED_ON_DATE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(CenterConstants.SUBMITTED_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(CenterConstants.MEETING_START_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(CenterConstants.IS_REPEATING_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(CenterConstants.FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); @@ -83,7 +80,7 @@ public class CentersWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.setColumnWidth(CenterConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(CenterConstants.CENTER_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(CenterConstants.FAILURE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(CenterConstants.GROUP_NAMES_STARTING_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(CenterConstants.GROUP_NAMES_STARTING_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(CenterConstants.LOOKUP_OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(CenterConstants.LOOKUP_OFFICE_OPENING_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(CenterConstants.LOOKUP_REPEAT_NORMAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); @@ -96,100 +93,99 @@ public class CentersWorkbookPopulator extends AbstractWorkbookPopulator { writeString(CenterConstants.EXTERNAL_ID_COL, rowHeader, "External ID"); writeString(CenterConstants.ACTIVE_COL, rowHeader, "Active*"); writeString(CenterConstants.ACTIVATION_DATE_COL, rowHeader, "Activation Date*"); - writeString(CenterConstants.SUBMITTED_ON_DATE_COL,rowHeader,"Submitted On Date"); + writeString(CenterConstants.SUBMITTED_ON_DATE_COL, rowHeader, "Submitted On Date"); writeString(CenterConstants.MEETING_START_DATE_COL, rowHeader, "Meeting Start Date* (On or After)"); writeString(CenterConstants.IS_REPEATING_COL, rowHeader, "Repeat*"); writeString(CenterConstants.FREQUENCY_COL, rowHeader, "Frequency*"); writeString(CenterConstants.INTERVAL_COL, rowHeader, "Interval*"); writeString(CenterConstants.REPEATS_ON_DAY_COL, rowHeader, "Repeats On*"); - writeString(CenterConstants.GROUP_NAMES_STARTING_COL,rowHeader,"Group Names* (Enter in consecutive cells horizontally)"); + writeString(CenterConstants.GROUP_NAMES_STARTING_COL, rowHeader, "Group Names* (Enter in consecutive cells horizontally)"); writeString(CenterConstants.LOOKUP_OFFICE_NAME_COL, rowHeader, "Office Name"); writeString(CenterConstants.LOOKUP_OFFICE_OPENING_DATE_COL, rowHeader, "Opening Date"); writeString(CenterConstants.LOOKUP_REPEAT_NORMAL_COL, rowHeader, "Repeat Normal Range"); writeString(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, rowHeader, "Repeat Monthly Range"); writeString(CenterConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, rowHeader, "If Repeat Weekly Range"); } - private void setLookupTable(Sheet centerSheet,String dateFormat) { - setOfficeDateLookupTable(centerSheet, officeSheetPopulator.getOffices(), CenterConstants.LOOKUP_OFFICE_NAME_COL,CenterConstants.LOOKUP_OFFICE_OPENING_DATE_COL,dateFormat); + + private void setLookupTable(Sheet centerSheet, String dateFormat) { + setOfficeDateLookupTable(centerSheet, officeSheetPopulator.getOffices(), CenterConstants.LOOKUP_OFFICE_NAME_COL, + CenterConstants.LOOKUP_OFFICE_OPENING_DATE_COL, dateFormat); int rowIndex; - for(rowIndex = 1; rowIndex <= 11; rowIndex++) { + for (rowIndex = 1; rowIndex <= 11; rowIndex++) { Row row = centerSheet.getRow(rowIndex); - if(row == null) { + if (row == null) { row = centerSheet.createRow(rowIndex); } writeInt(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, row, rowIndex); } - for(rowIndex = 1; rowIndex <= 3; rowIndex++) { + for (rowIndex = 1; rowIndex <= 3; rowIndex++) { writeInt(CenterConstants.LOOKUP_REPEAT_NORMAL_COL, centerSheet.getRow(rowIndex), rowIndex); } - String[] days = new String[]{ - TemplatePopulateImportConstants.MONDAY, - TemplatePopulateImportConstants.TUESDAY, - TemplatePopulateImportConstants.WEDNESDAY, - TemplatePopulateImportConstants.THURSDAY, - TemplatePopulateImportConstants.FRIDAY, - TemplatePopulateImportConstants.SATURDAY, - TemplatePopulateImportConstants.SUNDAY}; + String[] days = new String[] { TemplatePopulateImportConstants.MONDAY, TemplatePopulateImportConstants.TUESDAY, + TemplatePopulateImportConstants.WEDNESDAY, TemplatePopulateImportConstants.THURSDAY, TemplatePopulateImportConstants.FRIDAY, + TemplatePopulateImportConstants.SATURDAY, TemplatePopulateImportConstants.SUNDAY }; - for(rowIndex = 1; rowIndex <= 7; rowIndex++) { + for (rowIndex = 1; rowIndex <= 7; rowIndex++) { writeString(CenterConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, centerSheet.getRow(rowIndex), days[rowIndex - 1]); } } - private void setRules(Sheet worksheet,String dateFormat) { - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.OFFICE_NAME_COL,CenterConstants. OFFICE_NAME_COL); - CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.STAFF_NAME_COL,CenterConstants. STAFF_NAME_COL); - CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),CenterConstants. ACTIVATION_DATE_COL,CenterConstants. ACTIVATION_DATE_COL); - CellRangeAddressList activeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.ACTIVE_COL, CenterConstants.ACTIVE_COL); - CellRangeAddressList submittedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),CenterConstants. SUBMITTED_ON_DATE_COL,CenterConstants.SUBMITTED_ON_DATE_COL); - CellRangeAddressList meetingStartDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.MEETING_START_DATE_COL,CenterConstants. MEETING_START_DATE_COL); - CellRangeAddressList isRepeatRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),CenterConstants. IS_REPEATING_COL,CenterConstants. IS_REPEATING_COL); - CellRangeAddressList repeatsRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.FREQUENCY_COL, CenterConstants.FREQUENCY_COL); - CellRangeAddressList repeatsEveryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.INTERVAL_COL,CenterConstants. INTERVAL_COL); - CellRangeAddressList repeatsOnRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.REPEATS_ON_DAY_COL,CenterConstants. REPEATS_ON_DAY_COL); + private void setRules(Sheet worksheet, String dateFormat) { + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CenterConstants.OFFICE_NAME_COL, CenterConstants.OFFICE_NAME_COL); + CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CenterConstants.STAFF_NAME_COL, CenterConstants.STAFF_NAME_COL); + CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CenterConstants.ACTIVATION_DATE_COL, CenterConstants.ACTIVATION_DATE_COL); + CellRangeAddressList activeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CenterConstants.ACTIVE_COL, CenterConstants.ACTIVE_COL); + CellRangeAddressList submittedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CenterConstants.SUBMITTED_ON_DATE_COL, CenterConstants.SUBMITTED_ON_DATE_COL); + CellRangeAddressList meetingStartDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CenterConstants.MEETING_START_DATE_COL, CenterConstants.MEETING_START_DATE_COL); + CellRangeAddressList isRepeatRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CenterConstants.IS_REPEATING_COL, CenterConstants.IS_REPEATING_COL); + CellRangeAddressList repeatsRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CenterConstants.FREQUENCY_COL, CenterConstants.FREQUENCY_COL); + CellRangeAddressList repeatsEveryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CenterConstants.INTERVAL_COL, CenterConstants.INTERVAL_COL); + CellRangeAddressList repeatsOnRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CenterConstants.REPEATS_ON_DAY_COL, CenterConstants.REPEATS_ON_DAY_COL); - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); List offices = officeSheetPopulator.getOffices(); setNames(worksheet, offices); - DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint staffNameConstraint = validationHelper. - createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$B1))"); - DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint - (DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($B1,$IR$2:$IS" + (offices.size() + 1)+",2,FALSE)", - "=TODAY()", dateFormat); - DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[]{"True", "False"}); - DataValidationConstraint submittedOnDateConstraint = - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, - "=$F1", null,dateFormat); - DataValidationConstraint meetingStartDateConstraint = - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, - "=$F1", "=TODAY()", dateFormat); - DataValidationConstraint repeatsConstraint = - validationHelper.createExplicitListConstraint(new String[]{ - TemplatePopulateImportConstants.FREQUENCY_DAILY, - TemplatePopulateImportConstants.FREQUENCY_WEEKLY, - TemplatePopulateImportConstants.FREQUENCY_MONTHLY, - TemplatePopulateImportConstants.FREQUENCY_YEARLY}); + DataValidationConstraint staffNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$B1))"); + DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint( + DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($B1,$IR$2:$IS" + (offices.size() + 1) + ",2,FALSE)", "=TODAY()", + dateFormat); + DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint submittedOnDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, "=$F1", null, dateFormat); + DataValidationConstraint meetingStartDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$F1", "=TODAY()", dateFormat); + DataValidationConstraint repeatsConstraint = validationHelper.createExplicitListConstraint( + new String[] { TemplatePopulateImportConstants.FREQUENCY_DAILY, TemplatePopulateImportConstants.FREQUENCY_WEEKLY, + TemplatePopulateImportConstants.FREQUENCY_MONTHLY, TemplatePopulateImportConstants.FREQUENCY_YEARLY }); DataValidationConstraint repeatsEveryConstraint = validationHelper.createFormulaListConstraint("INDIRECT($J1)"); DataValidationConstraint repeatsOnConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE($J1,\"_DAYS\"))"); - DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); DataValidation staffValidation = validationHelper.createValidation(staffNameConstraint, staffNameRange); DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange); DataValidation activeValidation = validationHelper.createValidation(booleanConstraint, activeRange); - DataValidation submittedOnValidation=validationHelper.createValidation(submittedOnDateConstraint,submittedDateRange); + DataValidation submittedOnValidation = validationHelper.createValidation(submittedOnDateConstraint, submittedDateRange); DataValidation meetingStartDateValidation = validationHelper.createValidation(meetingStartDateConstraint, meetingStartDateRange); DataValidation isRepeatValidation = validationHelper.createValidation(booleanConstraint, isRepeatRange); DataValidation repeatsValidation = validationHelper.createValidation(repeatsConstraint, repeatsRange); DataValidation repeatsEveryValidation = validationHelper.createValidation(repeatsEveryConstraint, repeatsEveryRange); DataValidation repeatsOnValidation = validationHelper.createValidation(repeatsOnConstraint, repeatsOnRange); - worksheet.addValidationData(activeValidation); worksheet.addValidationData(officeValidation); worksheet.addValidationData(staffValidation); @@ -206,38 +202,36 @@ public class CentersWorkbookPopulator extends AbstractWorkbookPopulator { Workbook centerWorkbook = worksheet.getWorkbook(); Name officeCenter = centerWorkbook.createName(); officeCenter.setNameName("Office"); - officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME +"!$B$2:$B$" + (offices.size() + 1)); + officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (offices.size() + 1)); - - //Repeat constraint names + // Repeat constraint names Name repeatsDaily = centerWorkbook.createName(); repeatsDaily.setNameName("Daily"); - repeatsDaily.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IT$2:$IT$4"); + repeatsDaily.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME + "!$IT$2:$IT$4"); Name repeatsWeekly = centerWorkbook.createName(); repeatsWeekly.setNameName("Weekly"); - repeatsWeekly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IT$2:$IT$4"); + repeatsWeekly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME + "!$IT$2:$IT$4"); Name repeatYearly = centerWorkbook.createName(); repeatYearly.setNameName("Yearly"); - repeatYearly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IT$2:$IT$4"); + repeatYearly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME + "!$IT$2:$IT$4"); Name repeatsMonthly = centerWorkbook.createName(); repeatsMonthly.setNameName("Monthly"); - repeatsMonthly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IU$2:$IU$12"); + repeatsMonthly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME + "!$IU$2:$IU$12"); Name repeatsOnWeekly = centerWorkbook.createName(); repeatsOnWeekly.setNameName("Weekly_Days"); - repeatsOnWeekly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IV$2:$IV$8"); + repeatsOnWeekly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME + "!$IV$2:$IV$8"); - - //Staff Names for each office - for(Integer i = 0; i < offices.size(); i++) { + // Staff Names for each office + for (Integer i = 0; i < offices.size(); i++) { Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i); Name loanOfficerName = centerWorkbook.createName(); - if(officeNameToBeginEndIndexesOfStaff != null) { + if (officeNameToBeginEndIndexesOfStaff != null) { loanOfficerName.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_")); - loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); - } + loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); + } } } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/chartofaccounts/ChartOfAccountsWorkbook.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/chartofaccounts/ChartOfAccountsWorkbook.java index 79a90fc56..7f67a9422 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/chartofaccounts/ChartOfAccountsWorkbook.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/chartofaccounts/ChartOfAccountsWorkbook.java @@ -43,20 +43,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChartOfAccountsWorkbook extends AbstractWorkbookPopulator { + private final static Logger LOG = LoggerFactory.getLogger(ChartOfAccountsWorkbook.class); private List glAccounts; - private Map> accountTypeToAccountNameAndTag; - private MapaccountTypeToBeginEndIndexesofAccountNames; + private Map> accountTypeToAccountNameAndTag; + private Map accountTypeToBeginEndIndexesofAccountNames; private List accountTypesNoDuplicatesList; - public ChartOfAccountsWorkbook(List glAccounts) { this.glAccounts = glAccounts; } @Override - public void populate(Workbook workbook,String dateFormat) { - Sheet chartOfAccountsSheet=workbook.createSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME); + public void populate(Workbook workbook, String dateFormat) { + Sheet chartOfAccountsSheet = workbook.createSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME); setLayout(chartOfAccountsSheet); setAccountTypeToAccountNameAndTag(); setLookupTable(chartOfAccountsSheet); @@ -65,62 +65,54 @@ public class ChartOfAccountsWorkbook extends AbstractWorkbookPopulator { } private void setAccountTypeToAccountNameAndTag() { - accountTypeToAccountNameAndTag=new HashMap<>(); - for (GLAccountData glAccount: glAccounts) { - addToaccountTypeToAccountNameMap(glAccount.getType().getValue(),glAccount.getName()+ - "-"+glAccount.getId()+"-"+glAccount.getTagId().getName()+"-"+glAccount.getTagId().getId()); + accountTypeToAccountNameAndTag = new HashMap<>(); + for (GLAccountData glAccount : glAccounts) { + addToaccountTypeToAccountNameMap(glAccount.getType().getValue(), glAccount.getName() + "-" + glAccount.getId() + "-" + + glAccount.getTagId().getName() + "-" + glAccount.getTagId().getId()); } } private void addToaccountTypeToAccountNameMap(String key, String value) { - List values=accountTypeToAccountNameAndTag.get(key); - if (values==null){ - values=new ArrayList(); + List values = accountTypeToAccountNameAndTag.get(key); + if (values == null) { + values = new ArrayList(); } - if (!values.contains(value)){ + if (!values.contains(value)) { values.add(value); - accountTypeToAccountNameAndTag.put(key,values); + accountTypeToAccountNameAndTag.put(key, values); } } private void setRules(Sheet chartOfAccountsSheet) { - CellRangeAddressList accountTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - ChartOfAcountsConstants. ACCOUNT_TYPE_COL,ChartOfAcountsConstants.ACCOUNT_TYPE_COL); - CellRangeAddressList accountUsageRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - ChartOfAcountsConstants.ACCOUNT_USAGE_COL,ChartOfAcountsConstants.ACCOUNT_USAGE_COL); - CellRangeAddressList manualEntriesAllowedRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL,ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL); - CellRangeAddressList parentRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - ChartOfAcountsConstants.PARENT_COL,ChartOfAcountsConstants.PARENT_COL); - CellRangeAddressList tagRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - ChartOfAcountsConstants.TAG_COL,ChartOfAcountsConstants.TAG_COL); + CellRangeAddressList accountTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ChartOfAcountsConstants.ACCOUNT_TYPE_COL, ChartOfAcountsConstants.ACCOUNT_TYPE_COL); + CellRangeAddressList accountUsageRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ChartOfAcountsConstants.ACCOUNT_USAGE_COL, ChartOfAcountsConstants.ACCOUNT_USAGE_COL); + CellRangeAddressList manualEntriesAllowedRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL, ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL); + CellRangeAddressList parentRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ChartOfAcountsConstants.PARENT_COL, ChartOfAcountsConstants.PARENT_COL); + CellRangeAddressList tagRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ChartOfAcountsConstants.TAG_COL, ChartOfAcountsConstants.TAG_COL); - DataValidationHelper validationHelper=new HSSFDataValidationHelper((HSSFSheet) chartOfAccountsSheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) chartOfAccountsSheet); setNames(chartOfAccountsSheet, accountTypesNoDuplicatesList); - DataValidationConstraint accountTypeConstraint=validationHelper. - createExplicitListConstraint(new String[]{ - GLAccountType.ASSET.toString(), - GLAccountType.LIABILITY.toString(), - GLAccountType.EQUITY.toString(), - GLAccountType.INCOME.toString(), - GLAccountType.EXPENSE.toString()}); - DataValidationConstraint accountUsageConstraint=validationHelper. - createExplicitListConstraint(new String[]{ - GLAccountUsage.DETAIL.toString(), - GLAccountUsage.HEADER.toString()}); - DataValidationConstraint booleanConstraint=validationHelper. - createExplicitListConstraint(new String[]{"True","False"}); - DataValidationConstraint parentConstraint=validationHelper. - createFormulaListConstraint("INDIRECT(CONCATENATE(\"AccountName_\",$A1))"); - DataValidationConstraint tagConstraint=validationHelper. - createFormulaListConstraint("INDIRECT(CONCATENATE(\"Tags_\",$A1))"); + DataValidationConstraint accountTypeConstraint = validationHelper + .createExplicitListConstraint(new String[] { GLAccountType.ASSET.toString(), GLAccountType.LIABILITY.toString(), + GLAccountType.EQUITY.toString(), GLAccountType.INCOME.toString(), GLAccountType.EXPENSE.toString() }); + DataValidationConstraint accountUsageConstraint = validationHelper + .createExplicitListConstraint(new String[] { GLAccountUsage.DETAIL.toString(), GLAccountUsage.HEADER.toString() }); + DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint parentConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"AccountName_\",$A1))"); + DataValidationConstraint tagConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Tags_\",$A1))"); - DataValidation accountTypeValidation=validationHelper.createValidation(accountTypeConstraint,accountTypeRange); - DataValidation accountUsageValidation=validationHelper.createValidation(accountUsageConstraint,accountUsageRange); - DataValidation manualEntriesValidation=validationHelper.createValidation(booleanConstraint,manualEntriesAllowedRange); - DataValidation parentValidation=validationHelper.createValidation(parentConstraint,parentRange); - DataValidation tagValidation=validationHelper.createValidation(tagConstraint,tagRange); + DataValidation accountTypeValidation = validationHelper.createValidation(accountTypeConstraint, accountTypeRange); + DataValidation accountUsageValidation = validationHelper.createValidation(accountUsageConstraint, accountUsageRange); + DataValidation manualEntriesValidation = validationHelper.createValidation(booleanConstraint, manualEntriesAllowedRange); + DataValidation parentValidation = validationHelper.createValidation(parentConstraint, parentRange); + DataValidation tagValidation = validationHelper.createValidation(tagConstraint, tagRange); chartOfAccountsSheet.addValidationData(accountTypeValidation); chartOfAccountsSheet.addValidationData(accountUsageValidation); @@ -129,26 +121,27 @@ public class ChartOfAccountsWorkbook extends AbstractWorkbookPopulator { chartOfAccountsSheet.addValidationData(tagValidation); } - private void setNames(Sheet chartOfAccountsSheet,List accountTypesNoDuplicatesList) { - Workbook chartOfAccountsWorkbook=chartOfAccountsSheet.getWorkbook(); - for (Integer i=0;i accountTypesNoDuplicatesList) { + Workbook chartOfAccountsWorkbook = chartOfAccountsSheet.getWorkbook(); + for (Integer i = 0; i < accountTypesNoDuplicatesList.size(); i++) { + Name tags = chartOfAccountsWorkbook.createName(); + Integer[] tagValueBeginEndIndexes = accountTypeToBeginEndIndexesofAccountNames.get(i); + if (accountTypeToBeginEndIndexesofAccountNames != null) { + tags.setNameName("Tags_" + accountTypesNoDuplicatesList.get(i)); + tags.setRefersToFormula(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME + "!$S$" + tagValueBeginEndIndexes[0] + + ":$S$" + tagValueBeginEndIndexes[1]); } - Name accountNames=chartOfAccountsWorkbook.createName(); - Integer [] accountNamesBeginEndIndexes=accountTypeToBeginEndIndexesofAccountNames.get(i); - if (accountNamesBeginEndIndexes!=null){ - accountNames.setNameName("AccountName_"+accountTypesNoDuplicatesList.get(i)); - accountNames.setRefersToFormula(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME+ - "!$Q$"+accountNamesBeginEndIndexes[0]+":$Q$"+accountNamesBeginEndIndexes[1]); + Name accountNames = chartOfAccountsWorkbook.createName(); + Integer[] accountNamesBeginEndIndexes = accountTypeToBeginEndIndexesofAccountNames.get(i); + if (accountNamesBeginEndIndexes != null) { + accountNames.setNameName("AccountName_" + accountTypesNoDuplicatesList.get(i)); + accountNames.setRefersToFormula(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME + "!$Q$" + + accountNamesBeginEndIndexes[0] + ":$Q$" + accountNamesBeginEndIndexes[1]); } } } - private void setDefaults(Sheet worksheet){ + + private void setDefaults(Sheet worksheet) { try { for (Integer rowNo = 1; rowNo < 3000; rowNo++) { Row row = worksheet.getRow(rowNo); @@ -156,20 +149,20 @@ public class ChartOfAccountsWorkbook extends AbstractWorkbookPopulator { row = worksheet.createRow(rowNo); } writeFormula(ChartOfAcountsConstants.PARENT_ID_COL, row, - "IF(ISERROR(VLOOKUP($E"+(rowNo+1)+",$Q$2:$R$"+(glAccounts.size()+1)+",2,FALSE))," + - "\"\",(VLOOKUP($E"+(rowNo+1)+",$Q$2:$R$"+(glAccounts.size()+1)+",2,FALSE)))"); - writeFormula(ChartOfAcountsConstants.TAG_ID_COL,row, - "IF(ISERROR(VLOOKUP($H"+(rowNo+1)+",$S$2:$T$"+(glAccounts.size()+1)+",2,FALSE))," + - "\"\",(VLOOKUP($H"+(rowNo+1)+",$S$2:$T$"+(glAccounts.size()+1)+",2,FALSE)))"); + "IF(ISERROR(VLOOKUP($E" + (rowNo + 1) + ",$Q$2:$R$" + (glAccounts.size() + 1) + ",2,FALSE))," + "\"\",(VLOOKUP($E" + + (rowNo + 1) + ",$Q$2:$R$" + (glAccounts.size() + 1) + ",2,FALSE)))"); + writeFormula(ChartOfAcountsConstants.TAG_ID_COL, row, + "IF(ISERROR(VLOOKUP($H" + (rowNo + 1) + ",$S$2:$T$" + (glAccounts.size() + 1) + ",2,FALSE))," + "\"\",(VLOOKUP($H" + + (rowNo + 1) + ",$S$2:$T$" + (glAccounts.size() + 1) + ",2,FALSE)))"); } } catch (Exception e) { - LOG.error("Problem occurred in setDefaults function",e); + LOG.error("Problem occurred in setDefaults function", e); } } private void setLookupTable(Sheet chartOfAccountsSheet) { - accountTypesNoDuplicatesList =new ArrayList<>(); - for (int i = 0; i (); + for (int i = 0; i < glAccounts.size(); i++) { if (!accountTypesNoDuplicatesList.contains(glAccounts.get(i).getType().getValue())) { accountTypesNoDuplicatesList.add(glAccounts.get(i).getType().getValue()); } @@ -177,71 +170,74 @@ public class ChartOfAccountsWorkbook extends AbstractWorkbookPopulator { int rowIndex = 1; int startIndex = 1; int accountTypeIndex = 0; - accountTypeToBeginEndIndexesofAccountNames= new HashMap(); - for (String accountType: accountTypesNoDuplicatesList) { - startIndex=rowIndex+1; - Row row =chartOfAccountsSheet.createRow(rowIndex); - writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_TYPE_COL,row,accountType); - List accountNamesandTags =accountTypeToAccountNameAndTag.get(accountType); - if (!accountNamesandTags.isEmpty()){ - for (String accountNameandTag:accountNamesandTags) { - if (chartOfAccountsSheet.getRow(rowIndex)!=null){ - String[] accountNameAndTagAr=accountNameandTag.split("-"); - writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_NAME_COL,row,accountNameAndTagAr[0]); - writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_ID_COL,row,accountNameAndTagAr[1]); - writeString(ChartOfAcountsConstants.LOOKUP_TAG_COL,row,accountNameAndTagAr[2]); - writeString(ChartOfAcountsConstants.LOOKUP_TAG_ID_COL,row,accountNameAndTagAr[3]); - rowIndex++; - }else{ - row =chartOfAccountsSheet.createRow(rowIndex); - String[] accountNameAndTagAr=accountNameandTag.split("-"); - writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_NAME_COL,row,accountNameAndTagAr[0]); - writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_ID_COL,row,accountNameAndTagAr[1]); - writeString(ChartOfAcountsConstants.LOOKUP_TAG_COL,row,accountNameAndTagAr[2]); - writeString(ChartOfAcountsConstants.LOOKUP_TAG_ID_COL,row,accountNameAndTagAr[3]); - rowIndex++; - } - } - accountTypeToBeginEndIndexesofAccountNames.put(accountTypeIndex++,new Integer[]{startIndex,rowIndex}); - }else { - accountTypeIndex++; - } + accountTypeToBeginEndIndexesofAccountNames = new HashMap(); + for (String accountType : accountTypesNoDuplicatesList) { + startIndex = rowIndex + 1; + Row row = chartOfAccountsSheet.createRow(rowIndex); + writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_TYPE_COL, row, accountType); + List accountNamesandTags = accountTypeToAccountNameAndTag.get(accountType); + if (!accountNamesandTags.isEmpty()) { + for (String accountNameandTag : accountNamesandTags) { + if (chartOfAccountsSheet.getRow(rowIndex) != null) { + String[] accountNameAndTagAr = accountNameandTag.split("-"); + writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_NAME_COL, row, accountNameAndTagAr[0]); + writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_ID_COL, row, accountNameAndTagAr[1]); + writeString(ChartOfAcountsConstants.LOOKUP_TAG_COL, row, accountNameAndTagAr[2]); + writeString(ChartOfAcountsConstants.LOOKUP_TAG_ID_COL, row, accountNameAndTagAr[3]); + rowIndex++; + } else { + row = chartOfAccountsSheet.createRow(rowIndex); + String[] accountNameAndTagAr = accountNameandTag.split("-"); + writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_NAME_COL, row, accountNameAndTagAr[0]); + writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_ID_COL, row, accountNameAndTagAr[1]); + writeString(ChartOfAcountsConstants.LOOKUP_TAG_COL, row, accountNameAndTagAr[2]); + writeString(ChartOfAcountsConstants.LOOKUP_TAG_ID_COL, row, accountNameAndTagAr[3]); + rowIndex++; + } + } + accountTypeToBeginEndIndexesofAccountNames.put(accountTypeIndex++, new Integer[] { startIndex, rowIndex }); + } else { + accountTypeIndex++; + } } } private void setLayout(Sheet chartOfAccountsSheet) { - Row rowHeader=chartOfAccountsSheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.ACCOUNT_TYPE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.ACCOUNT_NAME_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.ACCOUNT_USAGE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.PARENT_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.PARENT_ID_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.GL_CODE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.TAG_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.TAG_ID_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.DESCRIPTION_COL,TemplatePopulateImportConstants.EXTRALARGE_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.LOOKUP_ACCOUNT_TYPE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.LOOKUP_ACCOUNT_NAME_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.LOOKUP_ACCOUNT_ID_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.LOOKUP_TAG_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.LOOKUP_TAG_ID_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); + Row rowHeader = chartOfAccountsSheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.ACCOUNT_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.ACCOUNT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.ACCOUNT_USAGE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL, + TemplatePopulateImportConstants.SMALL_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.PARENT_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.PARENT_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.GL_CODE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.TAG_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.TAG_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.DESCRIPTION_COL, TemplatePopulateImportConstants.EXTRALARGE_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.LOOKUP_ACCOUNT_TYPE_COL, + TemplatePopulateImportConstants.SMALL_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.LOOKUP_ACCOUNT_NAME_COL, + TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.LOOKUP_ACCOUNT_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.LOOKUP_TAG_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.LOOKUP_TAG_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(ChartOfAcountsConstants.ACCOUNT_TYPE_COL,rowHeader,"Account Type*"); - writeString(ChartOfAcountsConstants.GL_CODE_COL,rowHeader,"GL Code *"); - writeString(ChartOfAcountsConstants.ACCOUNT_USAGE_COL,rowHeader,"Account Usage *"); - writeString(ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL,rowHeader,"Manual entries allowed *"); - writeString(ChartOfAcountsConstants.PARENT_COL,rowHeader,"Parent"); - writeString(ChartOfAcountsConstants.PARENT_ID_COL,rowHeader,"Parent Id"); - writeString(ChartOfAcountsConstants.ACCOUNT_NAME_COL,rowHeader,"Account Name"); - writeString(ChartOfAcountsConstants.TAG_COL,rowHeader,"Tag *"); - writeString(ChartOfAcountsConstants.TAG_ID_COL,rowHeader,"Tag Id"); - writeString(ChartOfAcountsConstants.DESCRIPTION_COL,rowHeader,"Description *"); - writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_TYPE_COL,rowHeader,"Lookup Account type"); - writeString(ChartOfAcountsConstants.LOOKUP_TAG_COL,rowHeader,"Lookup Tag"); - writeString(ChartOfAcountsConstants.LOOKUP_TAG_ID_COL,rowHeader,"Lookup Tag Id"); - writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_NAME_COL,rowHeader,"Lookup Account name *"); - writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_ID_COL,rowHeader,"Lookup Account Id"); + writeString(ChartOfAcountsConstants.ACCOUNT_TYPE_COL, rowHeader, "Account Type*"); + writeString(ChartOfAcountsConstants.GL_CODE_COL, rowHeader, "GL Code *"); + writeString(ChartOfAcountsConstants.ACCOUNT_USAGE_COL, rowHeader, "Account Usage *"); + writeString(ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL, rowHeader, "Manual entries allowed *"); + writeString(ChartOfAcountsConstants.PARENT_COL, rowHeader, "Parent"); + writeString(ChartOfAcountsConstants.PARENT_ID_COL, rowHeader, "Parent Id"); + writeString(ChartOfAcountsConstants.ACCOUNT_NAME_COL, rowHeader, "Account Name"); + writeString(ChartOfAcountsConstants.TAG_COL, rowHeader, "Tag *"); + writeString(ChartOfAcountsConstants.TAG_ID_COL, rowHeader, "Tag Id"); + writeString(ChartOfAcountsConstants.DESCRIPTION_COL, rowHeader, "Description *"); + writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_TYPE_COL, rowHeader, "Lookup Account type"); + writeString(ChartOfAcountsConstants.LOOKUP_TAG_COL, rowHeader, "Lookup Tag"); + writeString(ChartOfAcountsConstants.LOOKUP_TAG_ID_COL, rowHeader, "Lookup Tag Id"); + writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_NAME_COL, rowHeader, "Lookup Account name *"); + writeString(ChartOfAcountsConstants.LOOKUP_ACCOUNT_ID_COL, rowHeader, "Lookup Account Id"); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/client/ClientEntityWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/client/ClientEntityWorkbookPopulator.java index d00e9de7f..23a137dec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/client/ClientEntityWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/client/ClientEntityWorkbookPopulator.java @@ -50,98 +50,93 @@ public class ClientEntityWorkbookPopulator extends AbstractWorkbookPopulator { private List countryCodeValues; private List mainBusinesslineCodeValues; - - public ClientEntityWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - PersonnelSheetPopulator personnelSheetPopulator,ListclientTypeCodeValues, - ListconstitutionCodeValues,ListmainBusinessline , - ListclientClassification,ListaddressTypesCodeValues, - ListstateProvinceCodeValues,ListcountryCodeValues ) { + public ClientEntityWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, + List clientTypeCodeValues, List constitutionCodeValues, List mainBusinessline, + List clientClassification, List addressTypesCodeValues, + List stateProvinceCodeValues, List countryCodeValues) { this.officeSheetPopulator = officeSheetPopulator; this.personnelSheetPopulator = personnelSheetPopulator; - this.clientTypeCodeValues=clientTypeCodeValues; - this.constitutionCodeValues=constitutionCodeValues; - this.clientClassificationCodeValues=clientClassification; - this.addressTypesCodeValues=addressTypesCodeValues; - this.stateProvinceCodeValues=stateProvinceCodeValues; - this.countryCodeValues=countryCodeValues; - this.mainBusinesslineCodeValues=mainBusinessline; + this.clientTypeCodeValues = clientTypeCodeValues; + this.constitutionCodeValues = constitutionCodeValues; + this.clientClassificationCodeValues = clientClassification; + this.addressTypesCodeValues = addressTypesCodeValues; + this.stateProvinceCodeValues = stateProvinceCodeValues; + this.countryCodeValues = countryCodeValues; + this.mainBusinesslineCodeValues = mainBusinessline; } - @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet clientSheet = workbook.createSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME); - personnelSheetPopulator.populate(workbook,dateFormat); - officeSheetPopulator.populate(workbook,dateFormat); + personnelSheetPopulator.populate(workbook, dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); setLayout(clientSheet); - setOfficeDateLookupTable(clientSheet, officeSheetPopulator.getOffices(), - ClientEntityConstants.RELATIONAL_OFFICE_NAME_COL, ClientEntityConstants.RELATIONAL_OFFICE_OPENING_DATE_COL,dateFormat); + setOfficeDateLookupTable(clientSheet, officeSheetPopulator.getOffices(), ClientEntityConstants.RELATIONAL_OFFICE_NAME_COL, + ClientEntityConstants.RELATIONAL_OFFICE_OPENING_DATE_COL, dateFormat); setClientDataLookupTable(clientSheet); - setRules(clientSheet,dateFormat); + setRules(clientSheet, dateFormat); } private void setClientDataLookupTable(Sheet clientSheet) { - int rowIndex=0; - for (CodeValueData clientTypeCodeValue:clientTypeCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); + int rowIndex = 0; + for (CodeValueData clientTypeCodeValue : clientTypeCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); } - writeString(ClientEntityConstants.LOOKUP_CLIENT_TYPES,row,clientTypeCodeValue.getName()+"-"+clientTypeCodeValue.getId()); + writeString(ClientEntityConstants.LOOKUP_CLIENT_TYPES, row, clientTypeCodeValue.getName() + "-" + clientTypeCodeValue.getId()); } - rowIndex=0; - for (CodeValueData clientClassificationCodeValue:clientClassificationCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); + rowIndex = 0; + for (CodeValueData clientClassificationCodeValue : clientClassificationCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); } - writeString(ClientEntityConstants.LOOKUP_CLIENT_CLASSIFICATION,row, - clientClassificationCodeValue.getName()+"-"+clientClassificationCodeValue.getId()); + writeString(ClientEntityConstants.LOOKUP_CLIENT_CLASSIFICATION, row, + clientClassificationCodeValue.getName() + "-" + clientClassificationCodeValue.getId()); } - rowIndex=0; - for (CodeValueData constitutionCodeValue:constitutionCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); + rowIndex = 0; + for (CodeValueData constitutionCodeValue : constitutionCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); } - writeString(ClientEntityConstants.LOOKUP_CONSTITUTION_COL,row, - constitutionCodeValue.getName()+"-"+constitutionCodeValue.getId()); + writeString(ClientEntityConstants.LOOKUP_CONSTITUTION_COL, row, + constitutionCodeValue.getName() + "-" + constitutionCodeValue.getId()); } - rowIndex=0; - for (CodeValueData mainBusinessCodeValue:mainBusinesslineCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); + rowIndex = 0; + for (CodeValueData mainBusinessCodeValue : mainBusinesslineCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); } - writeString(ClientEntityConstants.LOOKUP_MAIN_BUSINESS_LINE,row, - mainBusinessCodeValue.getName()+"-"+mainBusinessCodeValue.getId()); + writeString(ClientEntityConstants.LOOKUP_MAIN_BUSINESS_LINE, row, + mainBusinessCodeValue.getName() + "-" + mainBusinessCodeValue.getId()); } - rowIndex=0; - for (CodeValueData addressTypeCodeValue:addressTypesCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); + rowIndex = 0; + for (CodeValueData addressTypeCodeValue : addressTypesCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); } - writeString(ClientEntityConstants.LOOKUP_ADDRESS_TYPE,row, - addressTypeCodeValue.getName()+"-"+addressTypeCodeValue.getId()); + writeString(ClientEntityConstants.LOOKUP_ADDRESS_TYPE, row, + addressTypeCodeValue.getName() + "-" + addressTypeCodeValue.getId()); } - rowIndex=0; - for (CodeValueData stateCodeValue:stateProvinceCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); + rowIndex = 0; + for (CodeValueData stateCodeValue : stateProvinceCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); } - writeString(ClientEntityConstants.LOOKUP_STATE_PROVINCE,row, - stateCodeValue.getName()+"-"+stateCodeValue.getId()); + writeString(ClientEntityConstants.LOOKUP_STATE_PROVINCE, row, stateCodeValue.getName() + "-" + stateCodeValue.getId()); } - rowIndex=0; - for (CodeValueData countryCodeValue: countryCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); + rowIndex = 0; + for (CodeValueData countryCodeValue : countryCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); } - writeString(ClientEntityConstants.LOOKUP_COUNTRY,row, - countryCodeValue.getName()+"-"+countryCodeValue.getId()); + writeString(ClientEntityConstants.LOOKUP_COUNTRY, row, countryCodeValue.getName() + "-" + countryCodeValue.getId()); } } @@ -154,19 +149,19 @@ public class ClientEntityWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.setColumnWidth(ClientEntityConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.INCOPORATION_DATE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.INCOPORATION_VALID_TILL_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.INCOPORATION_VALID_TILL_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.MOBILE_NO_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.CLIENT_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.CLIENT_CLASSIFICATION_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.CLIENT_CLASSIFICATION_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.INCOPORATION_NUMBER_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.MAIN_BUSINESS_LINE,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.CONSTITUTION_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.REMARKS_COL,TemplatePopulateImportConstants.LARGE_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.MAIN_BUSINESS_LINE, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.CONSTITUTION_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.REMARKS_COL, TemplatePopulateImportConstants.LARGE_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.SUBMITTED_ON_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.SUBMITTED_ON_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.ACTIVE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.ADDRESS_ENABLED,TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.ADDRESS_ENABLED, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.ADDRESS_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.STREET_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.ADDRESS_LINE_1_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); @@ -177,34 +172,34 @@ public class ClientEntityWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.setColumnWidth(ClientEntityConstants.COUNTRY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.POSTAL_CODE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.IS_ACTIVE_ADDRESS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.WARNING_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.WARNING_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.RELATIONAL_OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(ClientEntityConstants.RELATIONAL_OFFICE_OPENING_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_CONSTITUTION_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_CLIENT_TYPES,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_CLIENT_CLASSIFICATION,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_ADDRESS_TYPE,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_STATE_PROVINCE,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_COUNTRY,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_MAIN_BUSINESS_LINE,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - writeString(ClientEntityConstants.NAME_COL,rowHeader,"Name"); + worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_CONSTITUTION_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_CLIENT_TYPES, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_CLIENT_CLASSIFICATION, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_ADDRESS_TYPE, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_STATE_PROVINCE, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_COUNTRY, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientEntityConstants.LOOKUP_MAIN_BUSINESS_LINE, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + writeString(ClientEntityConstants.NAME_COL, rowHeader, "Name"); writeString(ClientEntityConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); writeString(ClientEntityConstants.STAFF_NAME_COL, rowHeader, "Staff Name"); - writeString(ClientEntityConstants.INCOPORATION_DATE_COL,rowHeader,"Incorporation Date"); - writeString(ClientEntityConstants.INCOPORATION_VALID_TILL_COL,rowHeader,"Incorporation Validity Till Date"); + writeString(ClientEntityConstants.INCOPORATION_DATE_COL, rowHeader, "Incorporation Date"); + writeString(ClientEntityConstants.INCOPORATION_VALID_TILL_COL, rowHeader, "Incorporation Validity Till Date"); writeString(ClientEntityConstants.MOBILE_NO_COL, rowHeader, "Mobile number"); writeString(ClientEntityConstants.CLIENT_TYPE_COL, rowHeader, "Client Type "); writeString(ClientEntityConstants.CLIENT_CLASSIFICATION_COL, rowHeader, "Client Classification "); - writeString(ClientEntityConstants.INCOPORATION_NUMBER_COL,rowHeader,"Incorporation Number"); - writeString(ClientEntityConstants.MAIN_BUSINESS_LINE,rowHeader,"Main Business Line"); - writeString(ClientEntityConstants.CONSTITUTION_COL,rowHeader,"Constitution"); - writeString(ClientEntityConstants.REMARKS_COL,rowHeader,"Remarks"); + writeString(ClientEntityConstants.INCOPORATION_NUMBER_COL, rowHeader, "Incorporation Number"); + writeString(ClientEntityConstants.MAIN_BUSINESS_LINE, rowHeader, "Main Business Line"); + writeString(ClientEntityConstants.CONSTITUTION_COL, rowHeader, "Constitution"); + writeString(ClientEntityConstants.REMARKS_COL, rowHeader, "Remarks"); writeString(ClientEntityConstants.EXTERNAL_ID_COL, rowHeader, "External ID "); - writeString(ClientEntityConstants.SUBMITTED_ON_COL,rowHeader,"Submitted On Date"); + writeString(ClientEntityConstants.SUBMITTED_ON_COL, rowHeader, "Submitted On Date"); writeString(ClientEntityConstants.ACTIVE_COL, rowHeader, "Active*"); writeString(ClientEntityConstants.ACTIVATION_DATE_COL, rowHeader, "Activation Date "); - writeString(ClientEntityConstants.ADDRESS_ENABLED,rowHeader,"Address Enabled "); + writeString(ClientEntityConstants.ADDRESS_ENABLED, rowHeader, "Address Enabled "); writeString(ClientEntityConstants.ADDRESS_TYPE_COL, rowHeader, "Address Type "); writeString(ClientEntityConstants.STREET_COL, rowHeader, "Street "); writeString(ClientEntityConstants.ADDRESS_LINE_1_COL, rowHeader, "Address Line 1"); @@ -225,122 +220,90 @@ public class ClientEntityWorkbookPopulator extends AbstractWorkbookPopulator { writeString(ClientEntityConstants.LOOKUP_ADDRESS_TYPE, rowHeader, "Lookup AddressType "); writeString(ClientEntityConstants.LOOKUP_STATE_PROVINCE, rowHeader, "Lookup State/Province "); writeString(ClientEntityConstants.LOOKUP_COUNTRY, rowHeader, "Lookup Country "); - writeString(ClientEntityConstants.LOOKUP_MAIN_BUSINESS_LINE,rowHeader,"Lookup Business Line"); - + writeString(ClientEntityConstants.LOOKUP_MAIN_BUSINESS_LINE, rowHeader, "Lookup Business Line"); } - private void setRules(Sheet worksheet,String dateFormat) { - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientEntityConstants.OFFICE_NAME_COL, - ClientEntityConstants.OFFICE_NAME_COL); - CellRangeAddressList staffNameRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientEntityConstants.STAFF_NAME_COL, ClientEntityConstants.STAFF_NAME_COL); - CellRangeAddressList submittedOnDateRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientEntityConstants.SUBMITTED_ON_COL,ClientEntityConstants. SUBMITTED_ON_COL); - CellRangeAddressList dateRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientEntityConstants. ACTIVATION_DATE_COL,ClientEntityConstants. ACTIVATION_DATE_COL); - CellRangeAddressList activeRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientEntityConstants. ACTIVE_COL,ClientEntityConstants. ACTIVE_COL); - CellRangeAddressList clientTypeRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientEntityConstants. CLIENT_TYPE_COL,ClientEntityConstants. CLIENT_TYPE_COL); - CellRangeAddressList constitutionRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientEntityConstants.CONSTITUTION_COL,ClientEntityConstants. CONSTITUTION_COL); - CellRangeAddressList mainBusinessLineRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientEntityConstants. MAIN_BUSINESS_LINE,ClientEntityConstants. MAIN_BUSINESS_LINE); - CellRangeAddressList clientClassificationRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientEntityConstants.CLIENT_CLASSIFICATION_COL, - ClientEntityConstants.CLIENT_CLASSIFICATION_COL); - CellRangeAddressList enabledAddressRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientEntityConstants.ADDRESS_ENABLED, ClientEntityConstants.ADDRESS_ENABLED); - CellRangeAddressList addressTypeRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientEntityConstants.ADDRESS_TYPE_COL,ClientEntityConstants. ADDRESS_TYPE_COL); - CellRangeAddressList stateProvinceRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientEntityConstants.STATE_PROVINCE_COL,ClientEntityConstants. STATE_PROVINCE_COL); - CellRangeAddressList countryRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientEntityConstants. COUNTRY_COL,ClientEntityConstants. COUNTRY_COL); - CellRangeAddressList activeAddressRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientEntityConstants. IS_ACTIVE_ADDRESS_COL,ClientEntityConstants. IS_ACTIVE_ADDRESS_COL); - CellRangeAddressList incorporateDateRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientEntityConstants.INCOPORATION_DATE_COL,ClientEntityConstants.INCOPORATION_DATE_COL); - CellRangeAddressList incorporateDateTillRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientEntityConstants.INCOPORATION_VALID_TILL_COL, - ClientEntityConstants.INCOPORATION_VALID_TILL_COL); - + private void setRules(Sheet worksheet, String dateFormat) { + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.OFFICE_NAME_COL, ClientEntityConstants.OFFICE_NAME_COL); + CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.STAFF_NAME_COL, ClientEntityConstants.STAFF_NAME_COL); + CellRangeAddressList submittedOnDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.SUBMITTED_ON_COL, ClientEntityConstants.SUBMITTED_ON_COL); + CellRangeAddressList dateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.ACTIVATION_DATE_COL, ClientEntityConstants.ACTIVATION_DATE_COL); + CellRangeAddressList activeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.ACTIVE_COL, ClientEntityConstants.ACTIVE_COL); + CellRangeAddressList clientTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.CLIENT_TYPE_COL, ClientEntityConstants.CLIENT_TYPE_COL); + CellRangeAddressList constitutionRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.CONSTITUTION_COL, ClientEntityConstants.CONSTITUTION_COL); + CellRangeAddressList mainBusinessLineRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.MAIN_BUSINESS_LINE, ClientEntityConstants.MAIN_BUSINESS_LINE); + CellRangeAddressList clientClassificationRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.CLIENT_CLASSIFICATION_COL, ClientEntityConstants.CLIENT_CLASSIFICATION_COL); + CellRangeAddressList enabledAddressRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.ADDRESS_ENABLED, ClientEntityConstants.ADDRESS_ENABLED); + CellRangeAddressList addressTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.ADDRESS_TYPE_COL, ClientEntityConstants.ADDRESS_TYPE_COL); + CellRangeAddressList stateProvinceRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.STATE_PROVINCE_COL, ClientEntityConstants.STATE_PROVINCE_COL); + CellRangeAddressList countryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.COUNTRY_COL, ClientEntityConstants.COUNTRY_COL); + CellRangeAddressList activeAddressRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.IS_ACTIVE_ADDRESS_COL, ClientEntityConstants.IS_ACTIVE_ADDRESS_COL); + CellRangeAddressList incorporateDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.INCOPORATION_DATE_COL, ClientEntityConstants.INCOPORATION_DATE_COL); + CellRangeAddressList incorporateDateTillRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientEntityConstants.INCOPORATION_VALID_TILL_COL, ClientEntityConstants.INCOPORATION_VALID_TILL_COL); DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); List offices = officeSheetPopulator.getOffices(); setNames(worksheet, offices); - DataValidationConstraint officeNameConstraint = - validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint staffNameConstraint = - validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$B1))"); - DataValidationConstraint submittedOnDateConstraint = - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, - "=$O1" ,null, dateFormat); - DataValidationConstraint activationDateConstraint = - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, - "=VLOOKUP($B1,$AJ$2:$AK" + (offices.size() + 1) + ",2,FALSE)", "=TODAY()", dateFormat); - DataValidationConstraint activeConstraint = - validationHelper.createExplicitListConstraint(new String[] {"True", "False"}); - DataValidationConstraint clientTypesConstraint = - validationHelper.createFormulaListConstraint("ClientTypes"); - DataValidationConstraint constitutionConstraint = - validationHelper.createFormulaListConstraint("Constitution"); - DataValidationConstraint mainBusinessLineConstraint = - validationHelper.createFormulaListConstraint("MainBusinessLine"); - DataValidationConstraint clientClassificationConstraint = - validationHelper.createFormulaListConstraint("ClientClassification"); - DataValidationConstraint enabledAddressConstraint = - validationHelper.createExplicitListConstraint(new String[] {"True", "False"}); - DataValidationConstraint addressTypeConstraint = - validationHelper.createFormulaListConstraint("AddressType"); - DataValidationConstraint stateProvinceConstraint = - validationHelper.createFormulaListConstraint("StateProvince"); - DataValidationConstraint countryConstraint = - validationHelper.createFormulaListConstraint("Country"); - DataValidationConstraint activeAddressConstraint = - validationHelper.createExplicitListConstraint(new String[] {"True", "False"}); - DataValidationConstraint incorpDateConstraint= - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, - "=TODAY()",null,dateFormat); - DataValidationConstraint incorpDateTillConstraint= - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, - "=TODAY()",null,dateFormat); + DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); + DataValidationConstraint staffNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$B1))"); + DataValidationConstraint submittedOnDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, "=$O1", null, dateFormat); + DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint( + DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($B1,$AJ$2:$AK" + (offices.size() + 1) + ",2,FALSE)", "=TODAY()", + dateFormat); + DataValidationConstraint activeConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint clientTypesConstraint = validationHelper.createFormulaListConstraint("ClientTypes"); + DataValidationConstraint constitutionConstraint = validationHelper.createFormulaListConstraint("Constitution"); + DataValidationConstraint mainBusinessLineConstraint = validationHelper.createFormulaListConstraint("MainBusinessLine"); + DataValidationConstraint clientClassificationConstraint = validationHelper.createFormulaListConstraint("ClientClassification"); + DataValidationConstraint enabledAddressConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint addressTypeConstraint = validationHelper.createFormulaListConstraint("AddressType"); + DataValidationConstraint stateProvinceConstraint = validationHelper.createFormulaListConstraint("StateProvince"); + DataValidationConstraint countryConstraint = validationHelper.createFormulaListConstraint("Country"); + DataValidationConstraint activeAddressConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint incorpDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, "=TODAY()", null, dateFormat); + DataValidationConstraint incorpDateTillConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "=TODAY()", null, dateFormat); - - DataValidation officeValidation = - validationHelper.createValidation(officeNameConstraint, officeNameRange); - DataValidation staffValidation = - validationHelper.createValidation(staffNameConstraint, staffNameRange); - DataValidation submittedOnDateValidation = - validationHelper.createValidation(submittedOnDateConstraint, submittedOnDateRange); - DataValidation activationDateValidation = - validationHelper.createValidation(activationDateConstraint, dateRange); - DataValidation activeValidation = - validationHelper.createValidation(activeConstraint, activeRange); - DataValidation clientTypeValidation = - validationHelper.createValidation(clientTypesConstraint, clientTypeRange); - DataValidation constitutionValidation = - validationHelper.createValidation(constitutionConstraint,constitutionRange); - DataValidation mainBusinessLineValidation = - validationHelper.createValidation(mainBusinessLineConstraint,mainBusinessLineRange); - DataValidation clientClassificationValidation = - validationHelper.createValidation(clientClassificationConstraint, clientClassificationRange); - DataValidation enabledAddressValidation= - validationHelper.createValidation(enabledAddressConstraint,enabledAddressRange); - DataValidation addressTypeValidation = - validationHelper.createValidation(addressTypeConstraint, addressTypeRange); - DataValidation stateProvinceValidation = - validationHelper.createValidation(stateProvinceConstraint, stateProvinceRange); - DataValidation countryValidation = - validationHelper.createValidation(countryConstraint, countryRange); - DataValidation activeAddressValidation = - validationHelper.createValidation(activeAddressConstraint,activeAddressRange); - DataValidation incorporateDateValidation=validationHelper.createValidation(incorpDateConstraint,incorporateDateRange); - DataValidation incorporateDateTillValidation=validationHelper.createValidation(incorpDateTillConstraint,incorporateDateTillRange); + DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); + DataValidation staffValidation = validationHelper.createValidation(staffNameConstraint, staffNameRange); + DataValidation submittedOnDateValidation = validationHelper.createValidation(submittedOnDateConstraint, submittedOnDateRange); + DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, dateRange); + DataValidation activeValidation = validationHelper.createValidation(activeConstraint, activeRange); + DataValidation clientTypeValidation = validationHelper.createValidation(clientTypesConstraint, clientTypeRange); + DataValidation constitutionValidation = validationHelper.createValidation(constitutionConstraint, constitutionRange); + DataValidation mainBusinessLineValidation = validationHelper.createValidation(mainBusinessLineConstraint, mainBusinessLineRange); + DataValidation clientClassificationValidation = validationHelper.createValidation(clientClassificationConstraint, + clientClassificationRange); + DataValidation enabledAddressValidation = validationHelper.createValidation(enabledAddressConstraint, enabledAddressRange); + DataValidation addressTypeValidation = validationHelper.createValidation(addressTypeConstraint, addressTypeRange); + DataValidation stateProvinceValidation = validationHelper.createValidation(stateProvinceConstraint, stateProvinceRange); + DataValidation countryValidation = validationHelper.createValidation(countryConstraint, countryRange); + DataValidation activeAddressValidation = validationHelper.createValidation(activeAddressConstraint, activeAddressRange); + DataValidation incorporateDateValidation = validationHelper.createValidation(incorpDateConstraint, incorporateDateRange); + DataValidation incorporateDateTillValidation = validationHelper.createValidation(incorpDateTillConstraint, + incorporateDateTillRange); worksheet.addValidationData(activeValidation); worksheet.addValidationData(officeValidation); @@ -364,52 +327,50 @@ public class ClientEntityWorkbookPopulator extends AbstractWorkbookPopulator { Workbook clientWorkbook = worksheet.getWorkbook(); Name officeGroup = clientWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (offices.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (offices.size() + 1)); Name clientTypeGroup = clientWorkbook.createName(); clientTypeGroup.setNameName("ClientTypes"); - clientTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME+"!$AN$2:$AN$" + - (clientTypeCodeValues.size() + 1)); + clientTypeGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME + "!$AN$2:$AN$" + (clientTypeCodeValues.size() + 1)); Name constitutionGroup = clientWorkbook.createName(); constitutionGroup.setNameName("Constitution"); - constitutionGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME+"!$AL$2:$AL$" + - (constitutionCodeValues.size() + 1)); + constitutionGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME + "!$AL$2:$AL$" + (constitutionCodeValues.size() + 1)); Name mainBusinessLineGroup = clientWorkbook.createName(); mainBusinessLineGroup.setNameName("MainBusinessLine"); - mainBusinessLineGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME+"!$AR$2:$AR$" + - (mainBusinesslineCodeValues.size() + 1)); + mainBusinessLineGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME + "!$AR$2:$AR$" + (mainBusinesslineCodeValues.size() + 1)); Name clientClassficationGroup = clientWorkbook.createName(); clientClassficationGroup.setNameName("ClientClassification"); - clientClassficationGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME+"!$AM$2:$AM$" + - (clientClassificationCodeValues.size() + 1)); + clientClassficationGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME + "!$AM$2:$AM$" + (clientClassificationCodeValues.size() + 1)); Name addressTypeGroup = clientWorkbook.createName(); addressTypeGroup.setNameName("AddressType"); - addressTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME+ - "!$AO$2:$AO$" + (addressTypesCodeValues.size() + 1)); + addressTypeGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME + "!$AO$2:$AO$" + (addressTypesCodeValues.size() + 1)); Name stateProvinceGroup = clientWorkbook.createName(); stateProvinceGroup.setNameName("StateProvince"); - stateProvinceGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME+ - "!$AP$2:$AP$" + (stateProvinceCodeValues.size() + 1)); + stateProvinceGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME + "!$AP$2:$AP$" + (stateProvinceCodeValues.size() + 1)); Name countryGroup = clientWorkbook.createName(); countryGroup.setNameName("Country"); - countryGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME+"!$AQ$2:$AQ$" + - (countryCodeValues.size() + 1)); + countryGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME + "!$AQ$2:$AQ$" + (countryCodeValues.size() + 1)); for (Integer i = 0; i < offices.size(); i++) { - Integer[] officeNameToBeginEndIndexesOfStaff = - personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i); + Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i); if (officeNameToBeginEndIndexesOfStaff != null) { Name name = clientWorkbook.createName(); name.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_")); - name.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+"!$B$" + - officeNameToBeginEndIndexesOfStaff[0] + ":$B$" - + officeNameToBeginEndIndexesOfStaff[1]); + name.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME + "!$B$" + officeNameToBeginEndIndexesOfStaff[0] + + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/client/ClientPersonWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/client/ClientPersonWorkbookPopulator.java index 37f1fde1f..e8c697813 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/client/ClientPersonWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/client/ClientPersonWorkbookPopulator.java @@ -40,342 +40,311 @@ import org.apache.poi.ss.util.CellRangeAddressList; public class ClientPersonWorkbookPopulator extends AbstractWorkbookPopulator { - private OfficeSheetPopulator officeSheetPopulator; - private PersonnelSheetPopulator personnelSheetPopulator; - private ListclientTypeCodeValues; - private ListgenderCodeValues; - private ListclientClassificationCodeValues; - private ListaddressTypesCodeValues; - private ListstateProvinceCodeValues; - private ListcountryCodeValues; + private OfficeSheetPopulator officeSheetPopulator; + private PersonnelSheetPopulator personnelSheetPopulator; + private List clientTypeCodeValues; + private List genderCodeValues; + private List clientClassificationCodeValues; + private List addressTypesCodeValues; + private List stateProvinceCodeValues; + private List countryCodeValues; - - public ClientPersonWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - PersonnelSheetPopulator personnelSheetPopulator,ListclientTypeCodeValues, - ListgenderCodeValues, ListclientClassification,ListaddressTypesCodeValues, - ListstateProvinceCodeValues,ListcountryCodeValues ) { - this.officeSheetPopulator = officeSheetPopulator; - this.personnelSheetPopulator = personnelSheetPopulator; - this.clientTypeCodeValues=clientTypeCodeValues; - this.genderCodeValues=genderCodeValues; - this.clientClassificationCodeValues=clientClassification; - this.addressTypesCodeValues=addressTypesCodeValues; - this.stateProvinceCodeValues=stateProvinceCodeValues; - this.countryCodeValues=countryCodeValues; - } - - - @Override - public void populate(Workbook workbook,String dateFormat) { - Sheet clientSheet = workbook.createSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME); - personnelSheetPopulator.populate(workbook,dateFormat); - officeSheetPopulator.populate(workbook,dateFormat); - setLayout(clientSheet); - setOfficeDateLookupTable(clientSheet, officeSheetPopulator.getOffices(), - ClientPersonConstants.RELATIONAL_OFFICE_NAME_COL, ClientPersonConstants.RELATIONAL_OFFICE_OPENING_DATE_COL,dateFormat); - setClientDataLookupTable(clientSheet); - setRules(clientSheet,dateFormat); - } - - private void setClientDataLookupTable(Sheet clientSheet) { - int rowIndex=0; - for (CodeValueData clientTypeCodeValue:clientTypeCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); - } - writeString(ClientPersonConstants.LOOKUP_CLIENT_TYPES_COL,row,clientTypeCodeValue.getName()+ - "-"+clientTypeCodeValue.getId()); - } - rowIndex=0; - for (CodeValueData clientClassificationCodeValue:clientClassificationCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); - } - writeString(ClientPersonConstants.LOOKUP_CLIENT_CLASSIFICATION_COL,row, - clientClassificationCodeValue.getName()+"-"+clientClassificationCodeValue.getId()); - } - rowIndex=0; - for (CodeValueData genderCodeValue:genderCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); - } - writeString(ClientPersonConstants.LOOKUP_GENDER_COL,row,genderCodeValue.getName()+"-"+genderCodeValue.getId()); - } - rowIndex=0; - for (CodeValueData addressTypeCodeValue:addressTypesCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); - } - writeString(ClientPersonConstants.LOOKUP_ADDRESS_TYPE_COL,row, - addressTypeCodeValue.getName()+"-"+addressTypeCodeValue.getId()); - } - rowIndex=0; - for (CodeValueData stateCodeValue:stateProvinceCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); - } - writeString(ClientPersonConstants.LOOKUP_STATE_PROVINCE_COL,row,stateCodeValue.getName()+"-"+stateCodeValue.getId()); - } - rowIndex=0; - for (CodeValueData countryCodeValue: countryCodeValues) { - Row row =clientSheet.getRow(++rowIndex); - if(row==null) { - row = clientSheet.createRow(rowIndex); - } - writeString(ClientPersonConstants.LOOKUP_COUNTRY_COL,row,countryCodeValue.getName()+"-"+countryCodeValue.getId()); + public ClientPersonWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, + List clientTypeCodeValues, List genderCodeValues, List clientClassification, + List addressTypesCodeValues, List stateProvinceCodeValues, + List countryCodeValues) { + this.officeSheetPopulator = officeSheetPopulator; + this.personnelSheetPopulator = personnelSheetPopulator; + this.clientTypeCodeValues = clientTypeCodeValues; + this.genderCodeValues = genderCodeValues; + this.clientClassificationCodeValues = clientClassification; + this.addressTypesCodeValues = addressTypesCodeValues; + this.stateProvinceCodeValues = stateProvinceCodeValues; + this.countryCodeValues = countryCodeValues; } - } - - private void setLayout(Sheet worksheet) { - Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); - rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); - worksheet.setColumnWidth(ClientPersonConstants.FIRST_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.LAST_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.MIDDLE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - writeString(ClientPersonConstants.FIRST_NAME_COL, rowHeader, "First Name*"); - writeString(ClientPersonConstants.LAST_NAME_COL, rowHeader, "Last Name*"); - writeString(ClientPersonConstants.MIDDLE_NAME_COL, rowHeader, "Middle Name"); - worksheet.setColumnWidth(ClientPersonConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.SUBMITTED_ON_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.ACTIVE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.MOBILE_NO_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.DOB_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.CLIENT_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.GENDER_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.CLIENT_CLASSIFICATION_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.IS_STAFF_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.ADDRESS_ENABLED_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.ADDRESS_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.STREET_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.ADDRESS_LINE_1_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.ADDRESS_LINE_2_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.ADDRESS_LINE_3_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.CITY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.STATE_PROVINCE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.COUNTRY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.POSTAL_CODE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.IS_ACTIVE_ADDRESS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.WARNING_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - - worksheet.setColumnWidth(ClientPersonConstants.RELATIONAL_OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.RELATIONAL_OFFICE_OPENING_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_GENDER_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_CLIENT_TYPES_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_CLIENT_CLASSIFICATION_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_ADDRESS_TYPE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_STATE_PROVINCE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_COUNTRY_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(ClientPersonConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); - writeString(ClientPersonConstants.STAFF_NAME_COL, rowHeader, "Staff Name"); - writeString(ClientPersonConstants.EXTERNAL_ID_COL, rowHeader, "External ID "); - writeString(ClientPersonConstants.SUBMITTED_ON_COL,rowHeader,"Submitted On Date"); - writeString(ClientPersonConstants.ACTIVATION_DATE_COL, rowHeader, "Activation date"); - writeString(ClientPersonConstants.ACTIVE_COL, rowHeader, "Active*"); - writeString(ClientPersonConstants.MOBILE_NO_COL, rowHeader, "Mobile number"); - writeString(ClientPersonConstants.DOB_COL, rowHeader, "Date of Birth "); - writeString(ClientPersonConstants.CLIENT_TYPE_COL, rowHeader, "Client Type "); - writeString(ClientPersonConstants.IS_STAFF_COL, rowHeader, "Is a staff memeber "); - writeString(ClientPersonConstants.GENDER_COL, rowHeader, "Gender "); - writeString(ClientPersonConstants.ADDRESS_ENABLED_COL,rowHeader,"Address Enabled *"); - writeString(ClientPersonConstants.CLIENT_CLASSIFICATION_COL, rowHeader, "Client Classification "); - writeString(ClientPersonConstants.ADDRESS_TYPE_COL, rowHeader, "Address Type "); - writeString(ClientPersonConstants.STREET_COL, rowHeader, "Street "); - writeString(ClientPersonConstants.ADDRESS_LINE_1_COL, rowHeader, "Address Line 1"); - writeString(ClientPersonConstants.ADDRESS_LINE_2_COL, rowHeader, "Address Line 2"); - writeString(ClientPersonConstants.ADDRESS_LINE_3_COL, rowHeader, "Address Line 3 "); - writeString(ClientPersonConstants.CITY_COL, rowHeader, "City "); - writeString(ClientPersonConstants.STATE_PROVINCE_COL, rowHeader, "State/ Province "); - writeString(ClientPersonConstants.COUNTRY_COL, rowHeader, "Country "); - writeString(ClientPersonConstants.POSTAL_CODE_COL, rowHeader, "Postal Code "); - writeString(ClientPersonConstants.IS_ACTIVE_ADDRESS_COL, rowHeader, "Is active Address ? "); - writeString(ClientPersonConstants.WARNING_COL, rowHeader, "All * marked fields are compulsory."); - - writeString(ClientPersonConstants.RELATIONAL_OFFICE_NAME_COL, rowHeader, "Lookup office Name "); - writeString(ClientPersonConstants.RELATIONAL_OFFICE_OPENING_DATE_COL, rowHeader, "Lookup Office Opened Date "); - writeString(ClientPersonConstants.LOOKUP_GENDER_COL, rowHeader, "Lookup Gender "); - writeString(ClientPersonConstants.LOOKUP_CLIENT_TYPES_COL, rowHeader, "Lookup Client Types "); - writeString(ClientPersonConstants.LOOKUP_CLIENT_CLASSIFICATION_COL, rowHeader, "Lookup Client Classification "); - writeString(ClientPersonConstants.LOOKUP_ADDRESS_TYPE_COL, rowHeader, "Lookup AddressType "); - writeString(ClientPersonConstants.LOOKUP_STATE_PROVINCE_COL, rowHeader, "Lookup State/Province "); - writeString(ClientPersonConstants.LOOKUP_COUNTRY_COL, rowHeader, "Lookup Country "); - - - } - - private void setRules(Sheet worksheet,String dateformat) { - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientPersonConstants.OFFICE_NAME_COL, ClientPersonConstants.OFFICE_NAME_COL); - CellRangeAddressList staffNameRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientPersonConstants. STAFF_NAME_COL,ClientPersonConstants. STAFF_NAME_COL); - CellRangeAddressList submittedOnDateRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientPersonConstants. SUBMITTED_ON_COL, ClientPersonConstants.SUBMITTED_ON_COL); - CellRangeAddressList activationDateRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientPersonConstants.ACTIVATION_DATE_COL, ClientPersonConstants.ACTIVATION_DATE_COL); - CellRangeAddressList activeRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientPersonConstants.ACTIVE_COL,ClientPersonConstants. ACTIVE_COL); - CellRangeAddressList clientTypeRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientPersonConstants. CLIENT_TYPE_COL,ClientPersonConstants. CLIENT_TYPE_COL); - CellRangeAddressList dobRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientPersonConstants. DOB_COL,ClientPersonConstants. DOB_COL); - CellRangeAddressList isStaffRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientPersonConstants. IS_STAFF_COL,ClientPersonConstants. IS_STAFF_COL); - CellRangeAddressList genderRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientPersonConstants.GENDER_COL,ClientPersonConstants. GENDER_COL); - CellRangeAddressList clientClassificationRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientPersonConstants.CLIENT_CLASSIFICATION_COL, ClientPersonConstants.CLIENT_CLASSIFICATION_COL); - CellRangeAddressList enabledAddressRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientPersonConstants.ADDRESS_ENABLED_COL, ClientPersonConstants.ADDRESS_ENABLED_COL); - CellRangeAddressList addressTypeRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientPersonConstants. ADDRESS_TYPE_COL, ClientPersonConstants.ADDRESS_TYPE_COL); - CellRangeAddressList stateProvinceRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientPersonConstants. STATE_PROVINCE_COL, ClientPersonConstants.STATE_PROVINCE_COL); - CellRangeAddressList countryRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), ClientPersonConstants.COUNTRY_COL, ClientPersonConstants.COUNTRY_COL); - CellRangeAddressList activeAddressRange=new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),ClientPersonConstants. IS_ACTIVE_ADDRESS_COL,ClientPersonConstants. IS_ACTIVE_ADDRESS_COL); - - - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); - - List offices = officeSheetPopulator.getOffices(); - setNames(worksheet, offices); - - DataValidationConstraint officeNameConstraint = - validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint staffNameConstraint = - validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$D1))"); - DataValidationConstraint submittedOnDateConstraint = - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, - "=$I1" ,null,dateformat); - DataValidationConstraint activationDateConstraint = - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, - "=VLOOKUP($D1,$AJ$2:$AK" + (offices.size() + 1) + ",2,FALSE)", "=TODAY()", dateformat); - DataValidationConstraint dobDateConstraint = - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, - "=TODAY()",null, dateformat); - DataValidationConstraint activeConstraint = - validationHelper.createExplicitListConstraint(new String[] {"True", "False"}); - DataValidationConstraint clientTypesConstraint = - validationHelper.createFormulaListConstraint("ClientTypes"); - DataValidationConstraint isStaffConstraint = - validationHelper.createExplicitListConstraint(new String[] {"True", "False"}); - DataValidationConstraint genderConstraint = - validationHelper.createFormulaListConstraint("Gender"); - DataValidationConstraint clientClassificationConstraint = - validationHelper.createFormulaListConstraint("ClientClassification"); - DataValidationConstraint enabledAddressConstraint = - validationHelper.createExplicitListConstraint(new String[] {"True", "False"}); - DataValidationConstraint addressTypeConstraint = - validationHelper.createFormulaListConstraint("AddressType"); - DataValidationConstraint stateProvinceConstraint = - validationHelper.createFormulaListConstraint("StateProvince"); - DataValidationConstraint countryConstraint = - validationHelper.createFormulaListConstraint("Country"); - DataValidationConstraint activeAddressConstraint = - validationHelper.createExplicitListConstraint(new String[] {"True", "False"}); - - DataValidation officeValidation = - validationHelper.createValidation(officeNameConstraint, officeNameRange); - DataValidation staffValidation = - validationHelper.createValidation(staffNameConstraint, staffNameRange); - DataValidation submittedOnDateValidation = - validationHelper.createValidation(submittedOnDateConstraint, submittedOnDateRange); - DataValidation activationDateValidation = - validationHelper.createValidation(activationDateConstraint, activationDateRange); - DataValidation dobDateValidation = - validationHelper.createValidation(dobDateConstraint, dobRange); - DataValidation activeValidation = - validationHelper.createValidation(activeConstraint, activeRange); - DataValidation clientTypeValidation = - validationHelper.createValidation(clientTypesConstraint, clientTypeRange); - DataValidation isStaffValidation = - validationHelper.createValidation(isStaffConstraint, isStaffRange); - DataValidation genderValidation = - validationHelper.createValidation(genderConstraint, genderRange); - DataValidation clientClassificationValidation = - validationHelper.createValidation(clientClassificationConstraint, clientClassificationRange); - DataValidation enabledAddressValidation= - validationHelper.createValidation(enabledAddressConstraint,enabledAddressRange); - DataValidation addressTypeValidation = - validationHelper.createValidation(addressTypeConstraint, addressTypeRange); - DataValidation stateProvinceValidation = - validationHelper.createValidation(stateProvinceConstraint, stateProvinceRange); - DataValidation countryValidation = - validationHelper.createValidation(countryConstraint, countryRange); - DataValidation activeAddressValidation = - validationHelper.createValidation(activeAddressConstraint,activeAddressRange); - - worksheet.addValidationData(activeValidation); - worksheet.addValidationData(officeValidation); - worksheet.addValidationData(staffValidation); - worksheet.addValidationData(activationDateValidation); - worksheet.addValidationData(submittedOnDateValidation); - worksheet.addValidationData(dobDateValidation); - worksheet.addValidationData(clientTypeValidation); - worksheet.addValidationData(isStaffValidation); - worksheet.addValidationData(genderValidation); - worksheet.addValidationData(clientClassificationValidation); - worksheet.addValidationData(enabledAddressValidation); - worksheet.addValidationData(addressTypeValidation); - worksheet.addValidationData(stateProvinceValidation); - worksheet.addValidationData(countryValidation); - worksheet.addValidationData(activeAddressValidation); - } - - private void setNames(Sheet worksheet, List offices) { - Workbook clientWorkbook = worksheet.getWorkbook(); - Name officeGroup = clientWorkbook.createName(); - officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (offices.size() + 1)); - - Name clientTypeGroup = clientWorkbook.createName(); - clientTypeGroup.setNameName("ClientTypes"); - clientTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME+"!$AN$2:$AN$" + - (clientTypeCodeValues.size() + 1)); - - Name genderGroup = clientWorkbook.createName(); - genderGroup.setNameName("Gender"); - genderGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME+"!$AL$2:$AL$" + (genderCodeValues.size() + 1)); - - Name clientClassficationGroup = clientWorkbook.createName(); - clientClassficationGroup.setNameName("ClientClassification"); - clientClassficationGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME+"!$AM$2:$AM$" + - (clientClassificationCodeValues.size() + 1)); - - Name addressTypeGroup = clientWorkbook.createName(); - addressTypeGroup.setNameName("AddressType"); - addressTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME+"!$AO$2:$AO$" + - (addressTypesCodeValues.size() + 1)); - - Name stateProvinceGroup = clientWorkbook.createName(); - stateProvinceGroup.setNameName("StateProvince"); - stateProvinceGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME+"!$AP$2:$AP$" + - (stateProvinceCodeValues.size() + 1)); - - Name countryGroup = clientWorkbook.createName(); - countryGroup.setNameName("Country"); - countryGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME+"!$AQ$2:$AQ$" + - (countryCodeValues.size() + 1)); - - for (Integer i = 0; i < offices.size(); i++) { - Integer[] officeNameToBeginEndIndexesOfStaff = - personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i); - if (officeNameToBeginEndIndexesOfStaff != null) { - Name name = clientWorkbook.createName(); - name.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_")); - name.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+"!$B$" + - officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); - } + @Override + public void populate(Workbook workbook, String dateFormat) { + Sheet clientSheet = workbook.createSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME); + personnelSheetPopulator.populate(workbook, dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + setLayout(clientSheet); + setOfficeDateLookupTable(clientSheet, officeSheetPopulator.getOffices(), ClientPersonConstants.RELATIONAL_OFFICE_NAME_COL, + ClientPersonConstants.RELATIONAL_OFFICE_OPENING_DATE_COL, dateFormat); + setClientDataLookupTable(clientSheet); + setRules(clientSheet, dateFormat); } - } -} \ No newline at end of file + private void setClientDataLookupTable(Sheet clientSheet) { + int rowIndex = 0; + for (CodeValueData clientTypeCodeValue : clientTypeCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); + } + writeString(ClientPersonConstants.LOOKUP_CLIENT_TYPES_COL, row, + clientTypeCodeValue.getName() + "-" + clientTypeCodeValue.getId()); + } + rowIndex = 0; + for (CodeValueData clientClassificationCodeValue : clientClassificationCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); + } + writeString(ClientPersonConstants.LOOKUP_CLIENT_CLASSIFICATION_COL, row, + clientClassificationCodeValue.getName() + "-" + clientClassificationCodeValue.getId()); + } + rowIndex = 0; + for (CodeValueData genderCodeValue : genderCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); + } + writeString(ClientPersonConstants.LOOKUP_GENDER_COL, row, genderCodeValue.getName() + "-" + genderCodeValue.getId()); + } + rowIndex = 0; + for (CodeValueData addressTypeCodeValue : addressTypesCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); + } + writeString(ClientPersonConstants.LOOKUP_ADDRESS_TYPE_COL, row, + addressTypeCodeValue.getName() + "-" + addressTypeCodeValue.getId()); + } + rowIndex = 0; + for (CodeValueData stateCodeValue : stateProvinceCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); + } + writeString(ClientPersonConstants.LOOKUP_STATE_PROVINCE_COL, row, stateCodeValue.getName() + "-" + stateCodeValue.getId()); + } + rowIndex = 0; + for (CodeValueData countryCodeValue : countryCodeValues) { + Row row = clientSheet.getRow(++rowIndex); + if (row == null) { + row = clientSheet.createRow(rowIndex); + } + writeString(ClientPersonConstants.LOOKUP_COUNTRY_COL, row, countryCodeValue.getName() + "-" + countryCodeValue.getId()); + } + + } + + private void setLayout(Sheet worksheet) { + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); + worksheet.setColumnWidth(ClientPersonConstants.FIRST_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.LAST_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.MIDDLE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + writeString(ClientPersonConstants.FIRST_NAME_COL, rowHeader, "First Name*"); + writeString(ClientPersonConstants.LAST_NAME_COL, rowHeader, "Last Name*"); + writeString(ClientPersonConstants.MIDDLE_NAME_COL, rowHeader, "Middle Name"); + worksheet.setColumnWidth(ClientPersonConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.SUBMITTED_ON_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.ACTIVE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.MOBILE_NO_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.DOB_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.CLIENT_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.GENDER_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.CLIENT_CLASSIFICATION_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.IS_STAFF_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.ADDRESS_ENABLED_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.ADDRESS_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.STREET_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.ADDRESS_LINE_1_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.ADDRESS_LINE_2_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.ADDRESS_LINE_3_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.CITY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.STATE_PROVINCE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.COUNTRY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.POSTAL_CODE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.IS_ACTIVE_ADDRESS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.WARNING_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + + worksheet.setColumnWidth(ClientPersonConstants.RELATIONAL_OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.RELATIONAL_OFFICE_OPENING_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_GENDER_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_CLIENT_TYPES_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_CLIENT_CLASSIFICATION_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_ADDRESS_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_STATE_PROVINCE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(ClientPersonConstants.LOOKUP_COUNTRY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(ClientPersonConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); + writeString(ClientPersonConstants.STAFF_NAME_COL, rowHeader, "Staff Name"); + writeString(ClientPersonConstants.EXTERNAL_ID_COL, rowHeader, "External ID "); + writeString(ClientPersonConstants.SUBMITTED_ON_COL, rowHeader, "Submitted On Date"); + writeString(ClientPersonConstants.ACTIVATION_DATE_COL, rowHeader, "Activation date"); + writeString(ClientPersonConstants.ACTIVE_COL, rowHeader, "Active*"); + writeString(ClientPersonConstants.MOBILE_NO_COL, rowHeader, "Mobile number"); + writeString(ClientPersonConstants.DOB_COL, rowHeader, "Date of Birth "); + writeString(ClientPersonConstants.CLIENT_TYPE_COL, rowHeader, "Client Type "); + writeString(ClientPersonConstants.IS_STAFF_COL, rowHeader, "Is a staff memeber "); + writeString(ClientPersonConstants.GENDER_COL, rowHeader, "Gender "); + writeString(ClientPersonConstants.ADDRESS_ENABLED_COL, rowHeader, "Address Enabled *"); + writeString(ClientPersonConstants.CLIENT_CLASSIFICATION_COL, rowHeader, "Client Classification "); + writeString(ClientPersonConstants.ADDRESS_TYPE_COL, rowHeader, "Address Type "); + writeString(ClientPersonConstants.STREET_COL, rowHeader, "Street "); + writeString(ClientPersonConstants.ADDRESS_LINE_1_COL, rowHeader, "Address Line 1"); + writeString(ClientPersonConstants.ADDRESS_LINE_2_COL, rowHeader, "Address Line 2"); + writeString(ClientPersonConstants.ADDRESS_LINE_3_COL, rowHeader, "Address Line 3 "); + writeString(ClientPersonConstants.CITY_COL, rowHeader, "City "); + writeString(ClientPersonConstants.STATE_PROVINCE_COL, rowHeader, "State/ Province "); + writeString(ClientPersonConstants.COUNTRY_COL, rowHeader, "Country "); + writeString(ClientPersonConstants.POSTAL_CODE_COL, rowHeader, "Postal Code "); + writeString(ClientPersonConstants.IS_ACTIVE_ADDRESS_COL, rowHeader, "Is active Address ? "); + writeString(ClientPersonConstants.WARNING_COL, rowHeader, "All * marked fields are compulsory."); + + writeString(ClientPersonConstants.RELATIONAL_OFFICE_NAME_COL, rowHeader, "Lookup office Name "); + writeString(ClientPersonConstants.RELATIONAL_OFFICE_OPENING_DATE_COL, rowHeader, "Lookup Office Opened Date "); + writeString(ClientPersonConstants.LOOKUP_GENDER_COL, rowHeader, "Lookup Gender "); + writeString(ClientPersonConstants.LOOKUP_CLIENT_TYPES_COL, rowHeader, "Lookup Client Types "); + writeString(ClientPersonConstants.LOOKUP_CLIENT_CLASSIFICATION_COL, rowHeader, "Lookup Client Classification "); + writeString(ClientPersonConstants.LOOKUP_ADDRESS_TYPE_COL, rowHeader, "Lookup AddressType "); + writeString(ClientPersonConstants.LOOKUP_STATE_PROVINCE_COL, rowHeader, "Lookup State/Province "); + writeString(ClientPersonConstants.LOOKUP_COUNTRY_COL, rowHeader, "Lookup Country "); + + } + + private void setRules(Sheet worksheet, String dateformat) { + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.OFFICE_NAME_COL, ClientPersonConstants.OFFICE_NAME_COL); + CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.STAFF_NAME_COL, ClientPersonConstants.STAFF_NAME_COL); + CellRangeAddressList submittedOnDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.SUBMITTED_ON_COL, ClientPersonConstants.SUBMITTED_ON_COL); + CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.ACTIVATION_DATE_COL, ClientPersonConstants.ACTIVATION_DATE_COL); + CellRangeAddressList activeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.ACTIVE_COL, ClientPersonConstants.ACTIVE_COL); + CellRangeAddressList clientTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.CLIENT_TYPE_COL, ClientPersonConstants.CLIENT_TYPE_COL); + CellRangeAddressList dobRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.DOB_COL, ClientPersonConstants.DOB_COL); + CellRangeAddressList isStaffRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.IS_STAFF_COL, ClientPersonConstants.IS_STAFF_COL); + CellRangeAddressList genderRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.GENDER_COL, ClientPersonConstants.GENDER_COL); + CellRangeAddressList clientClassificationRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.CLIENT_CLASSIFICATION_COL, ClientPersonConstants.CLIENT_CLASSIFICATION_COL); + CellRangeAddressList enabledAddressRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.ADDRESS_ENABLED_COL, ClientPersonConstants.ADDRESS_ENABLED_COL); + CellRangeAddressList addressTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.ADDRESS_TYPE_COL, ClientPersonConstants.ADDRESS_TYPE_COL); + CellRangeAddressList stateProvinceRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.STATE_PROVINCE_COL, ClientPersonConstants.STATE_PROVINCE_COL); + CellRangeAddressList countryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.COUNTRY_COL, ClientPersonConstants.COUNTRY_COL); + CellRangeAddressList activeAddressRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + ClientPersonConstants.IS_ACTIVE_ADDRESS_COL, ClientPersonConstants.IS_ACTIVE_ADDRESS_COL); + + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); + + List offices = officeSheetPopulator.getOffices(); + setNames(worksheet, offices); + + DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); + DataValidationConstraint staffNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$D1))"); + DataValidationConstraint submittedOnDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, "=$I1", null, dateformat); + DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint( + DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($D1,$AJ$2:$AK" + (offices.size() + 1) + ",2,FALSE)", "=TODAY()", + dateformat); + DataValidationConstraint dobDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, "=TODAY()", null, dateformat); + DataValidationConstraint activeConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint clientTypesConstraint = validationHelper.createFormulaListConstraint("ClientTypes"); + DataValidationConstraint isStaffConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint genderConstraint = validationHelper.createFormulaListConstraint("Gender"); + DataValidationConstraint clientClassificationConstraint = validationHelper.createFormulaListConstraint("ClientClassification"); + DataValidationConstraint enabledAddressConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint addressTypeConstraint = validationHelper.createFormulaListConstraint("AddressType"); + DataValidationConstraint stateProvinceConstraint = validationHelper.createFormulaListConstraint("StateProvince"); + DataValidationConstraint countryConstraint = validationHelper.createFormulaListConstraint("Country"); + DataValidationConstraint activeAddressConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + + DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); + DataValidation staffValidation = validationHelper.createValidation(staffNameConstraint, staffNameRange); + DataValidation submittedOnDateValidation = validationHelper.createValidation(submittedOnDateConstraint, submittedOnDateRange); + DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange); + DataValidation dobDateValidation = validationHelper.createValidation(dobDateConstraint, dobRange); + DataValidation activeValidation = validationHelper.createValidation(activeConstraint, activeRange); + DataValidation clientTypeValidation = validationHelper.createValidation(clientTypesConstraint, clientTypeRange); + DataValidation isStaffValidation = validationHelper.createValidation(isStaffConstraint, isStaffRange); + DataValidation genderValidation = validationHelper.createValidation(genderConstraint, genderRange); + DataValidation clientClassificationValidation = validationHelper.createValidation(clientClassificationConstraint, + clientClassificationRange); + DataValidation enabledAddressValidation = validationHelper.createValidation(enabledAddressConstraint, enabledAddressRange); + DataValidation addressTypeValidation = validationHelper.createValidation(addressTypeConstraint, addressTypeRange); + DataValidation stateProvinceValidation = validationHelper.createValidation(stateProvinceConstraint, stateProvinceRange); + DataValidation countryValidation = validationHelper.createValidation(countryConstraint, countryRange); + DataValidation activeAddressValidation = validationHelper.createValidation(activeAddressConstraint, activeAddressRange); + + worksheet.addValidationData(activeValidation); + worksheet.addValidationData(officeValidation); + worksheet.addValidationData(staffValidation); + worksheet.addValidationData(activationDateValidation); + worksheet.addValidationData(submittedOnDateValidation); + worksheet.addValidationData(dobDateValidation); + worksheet.addValidationData(clientTypeValidation); + worksheet.addValidationData(isStaffValidation); + worksheet.addValidationData(genderValidation); + worksheet.addValidationData(clientClassificationValidation); + worksheet.addValidationData(enabledAddressValidation); + worksheet.addValidationData(addressTypeValidation); + worksheet.addValidationData(stateProvinceValidation); + worksheet.addValidationData(countryValidation); + worksheet.addValidationData(activeAddressValidation); + } + + private void setNames(Sheet worksheet, List offices) { + Workbook clientWorkbook = worksheet.getWorkbook(); + Name officeGroup = clientWorkbook.createName(); + officeGroup.setNameName("Office"); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (offices.size() + 1)); + + Name clientTypeGroup = clientWorkbook.createName(); + clientTypeGroup.setNameName("ClientTypes"); + clientTypeGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME + "!$AN$2:$AN$" + (clientTypeCodeValues.size() + 1)); + + Name genderGroup = clientWorkbook.createName(); + genderGroup.setNameName("Gender"); + genderGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME + "!$AL$2:$AL$" + (genderCodeValues.size() + 1)); + + Name clientClassficationGroup = clientWorkbook.createName(); + clientClassficationGroup.setNameName("ClientClassification"); + clientClassficationGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME + "!$AM$2:$AM$" + (clientClassificationCodeValues.size() + 1)); + + Name addressTypeGroup = clientWorkbook.createName(); + addressTypeGroup.setNameName("AddressType"); + addressTypeGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME + "!$AO$2:$AO$" + (addressTypesCodeValues.size() + 1)); + + Name stateProvinceGroup = clientWorkbook.createName(); + stateProvinceGroup.setNameName("StateProvince"); + stateProvinceGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME + "!$AP$2:$AP$" + (stateProvinceCodeValues.size() + 1)); + + Name countryGroup = clientWorkbook.createName(); + countryGroup.setNameName("Country"); + countryGroup.setRefersToFormula( + TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME + "!$AQ$2:$AQ$" + (countryCodeValues.size() + 1)); + + for (Integer i = 0; i < offices.size(); i++) { + Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i); + if (officeNameToBeginEndIndexesOfStaff != null) { + Name name = clientWorkbook.createName(); + name.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_")); + name.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME + "!$B$" + officeNameToBeginEndIndexesOfStaff[0] + + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); + } + } + } + +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/comparator/LoanComparatorByStatusActive.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/comparator/LoanComparatorByStatusActive.java index 2d627c8e3..ce3177316 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/comparator/LoanComparatorByStatusActive.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/comparator/LoanComparatorByStatusActive.java @@ -23,29 +23,23 @@ import org.apache.fineract.portfolio.loanaccount.data.LoanAccountData; /** * Sorting the loan values based on loan status giving priority to active loans - * */ + */ public class LoanComparatorByStatusActive implements Comparator { @Override - public int compare(LoanAccountData o1, LoanAccountData o2) { + public int compare(LoanAccountData o1, LoanAccountData o2) { boolean isData1StatusActive = o1.getStatusStringValue().equals("Active"); boolean isData2StatusActive = o2.getStatusStringValue().equals("Active"); // if both status active, these have the same rank - if (isData1StatusActive && isData2StatusActive){ - return 0; - } + if (isData1StatusActive && isData2StatusActive) { return 0; } - if (isData1StatusActive){ - return -1; - } + if (isData1StatusActive) { return -1; } - if (isData2StatusActive){ - return 1; - } + if (isData2StatusActive) { return 1; } // if no status active, these have the same rank return 0; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/fixeddeposits/FixedDepositTransactionWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/fixeddeposits/FixedDepositTransactionWorkbookPopulator.java index 9aea37c14..45c547866 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/fixeddeposits/FixedDepositTransactionWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/fixeddeposits/FixedDepositTransactionWorkbookPopulator.java @@ -43,70 +43,77 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddressList; public class FixedDepositTransactionWorkbookPopulator extends AbstractWorkbookPopulator { + private OfficeSheetPopulator officeSheetPopulator; private ClientSheetPopulator clientSheetPopulator; private ExtrasSheetPopulator extrasSheetPopulator; - private ListsavingsAccounts; + private List savingsAccounts; - public FixedDepositTransactionWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - ClientSheetPopulator clientSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator, - List savingsAccounts) { + public FixedDepositTransactionWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, ClientSheetPopulator clientSheetPopulator, + ExtrasSheetPopulator extrasSheetPopulator, List savingsAccounts) { this.officeSheetPopulator = officeSheetPopulator; this.clientSheetPopulator = clientSheetPopulator; this.extrasSheetPopulator = extrasSheetPopulator; - this.savingsAccounts=savingsAccounts; + this.savingsAccounts = savingsAccounts; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet savingsTransactionSheet = workbook.createSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_TRANSACTION_SHEET_NAME); setLayout(savingsTransactionSheet); - officeSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); - extrasSheetPopulator.populate(workbook,dateFormat); - populateSavingsTable(savingsTransactionSheet,dateFormat); - setRules(savingsTransactionSheet,dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); + extrasSheetPopulator.populate(workbook, dateFormat); + populateSavingsTable(savingsTransactionSheet, dateFormat); + setRules(savingsTransactionSheet, dateFormat); setDefaults(savingsTransactionSheet); } private void setDefaults(Sheet worksheet) { - for(Integer rowNo = 1; rowNo < 3000; rowNo++) - { + for (Integer rowNo = 1; rowNo < 3000; rowNo++) { Row row = worksheet.getRow(rowNo); - if(row == null) { + if (row == null) { row = worksheet.createRow(rowNo); } - writeFormula(TransactionConstants.PRODUCT_COL, row, "IF(ISERROR(VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE)),\"\",VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE))"); - writeFormula(TransactionConstants.OPENING_BALANCE_COL, row, "IF(ISERROR(VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE)),\"\",VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE))"); + writeFormula(TransactionConstants.PRODUCT_COL, row, + "IF(ISERROR(VLOOKUP($C" + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE)),\"\",VLOOKUP($C" + + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE))"); + writeFormula(TransactionConstants.OPENING_BALANCE_COL, row, + "IF(ISERROR(VLOOKUP($C" + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE)),\"\",VLOOKUP($C" + + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE))"); } } - - private void setRules(Sheet worksheet,String dateFormat) { - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + private void setRules(Sheet worksheet, String dateFormat) { + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.OFFICE_NAME_COL, TransactionConstants.OFFICE_NAME_COL); - CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.CLIENT_NAME_COL, TransactionConstants.CLIENT_NAME_COL); - CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.SAVINGS_ACCOUNT_NO_COL, TransactionConstants.SAVINGS_ACCOUNT_NO_COL); - CellRangeAddressList transactionTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList transactionTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.TRANSACTION_TYPE_COL, TransactionConstants.TRANSACTION_TYPE_COL); CellRangeAddressList paymentTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.PAYMENT_TYPE_COL, TransactionConstants.PAYMENT_TYPE_COL); CellRangeAddressList transactionDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.TRANSACTION_DATE_COL, TransactionConstants.TRANSACTION_DATE_COL); - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); setNames(worksheet); DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint clientNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))"); - DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); - DataValidationConstraint transactionTypeConstraint = validationHelper.createExplicitListConstraint(new String[] {"Withdrawal","Deposit"}); + DataValidationConstraint clientNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))"); + DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint( + "INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); + DataValidationConstraint transactionTypeConstraint = validationHelper + .createExplicitListConstraint(new String[] { "Withdrawal", "Deposit" }); DataValidationConstraint paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentTypes"); - DataValidationConstraint transactionDateConstraint = validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($C1,$Q$2:$T$" + (savingsAccounts.size() + 1) + ",4,FALSE)", "=TODAY()", dateFormat); + DataValidationConstraint transactionDateConstraint = validationHelper.createDateConstraint( + DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($C1,$Q$2:$T$" + (savingsAccounts.size() + 1) + ",4,FALSE)", + "=TODAY()", dateFormat); DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); @@ -127,22 +134,24 @@ public class FixedDepositTransactionWorkbookPopulator extends AbstractWorkbookPo Workbook savingsTransactionWorkbook = worksheet.getWorkbook(); List officeNames = officeSheetPopulator.getOfficeNames(); - //Office Names + // Office Names Name officeGroup = savingsTransactionWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (officeNames.size() + 1)); - //Clients Named after Offices - for(Integer i = 0; i < officeNames.size(); i++) { + // Clients Named after Offices + for (Integer i = 0; i < officeNames.size(); i++) { Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator.getOfficeNameToBeginEndIndexesOfClients().get(i); Name name = savingsTransactionWorkbook.createName(); - if(officeNameToBeginEndIndexesOfClients != null) { + if (officeNameToBeginEndIndexesOfClients != null) { name.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); + name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME + "!$B$" + officeNameToBeginEndIndexesOfClients[0] + + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); } } - //Counting clients with active savings and starting and end addresses of cells for naming + // Counting clients with active savings and starting and end addresses + // of cells for naming HashMap clientNameToBeginEndIndexes = new HashMap<>(); ArrayList clientsWithActiveSavings = new ArrayList<>(); ArrayList clientIdsWithActiveSavings = new ArrayList<>(); @@ -150,36 +159,40 @@ public class FixedDepositTransactionWorkbookPopulator extends AbstractWorkbookPo int endIndex = 1; String clientName = ""; Long clientId = null; - for(int i = 0; i < savingsAccounts.size(); i++){ - if(!clientName.equals(savingsAccounts.get(i).getClientName())) { + for (int i = 0; i < savingsAccounts.size(); i++) { + if (!clientName.equals(savingsAccounts.get(i).getClientName())) { endIndex = i + 1; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); startIndex = i + 2; clientName = savingsAccounts.get(i).getClientName(); clientId = savingsAccounts.get(i).getClientId(); clientsWithActiveSavings.add(clientName); clientIdsWithActiveSavings.add(clientId); } - if(i == savingsAccounts.size()-1) { + if (i == savingsAccounts.size() - 1) { endIndex = i + 2; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); } } - //Account Number Named after Clients - for(int j = 0; j < clientsWithActiveSavings.size(); j++) { + // Account Number Named after Clients + for (int j = 0; j < clientsWithActiveSavings.size(); j++) { Name name = savingsTransactionWorkbook.createName(); - name.setNameName("Account_" + clientsWithActiveSavings.get(j).replace(" ", "_") + "_" + clientIdsWithActiveSavings.get(j) + "_"); - name.setRefersToFormula(TemplatePopulateImportConstants.FIXED_DEPOSIT_TRANSACTION_SHEET_NAME+"!$Q$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[0] + ":$Q$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[1]); + name.setNameName( + "Account_" + clientsWithActiveSavings.get(j).replace(" ", "_") + "_" + clientIdsWithActiveSavings.get(j) + "_"); + name.setRefersToFormula(TemplatePopulateImportConstants.FIXED_DEPOSIT_TRANSACTION_SHEET_NAME + "!$Q$" + + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[0] + ":$Q$" + + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[1]); } - //Payment Type Name + // Payment Type Name Name paymentTypeGroup = savingsTransactionWorkbook.createName(); paymentTypeGroup.setNameName("PaymentTypes"); - paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); + paymentTypeGroup.setRefersToFormula( + TemplatePopulateImportConstants.EXTRAS_SHEET_NAME + "!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); } - private void populateSavingsTable(Sheet savingsTransactionSheet,String dateFormat) { + private void populateSavingsTable(Sheet savingsTransactionSheet, String dateFormat) { Workbook workbook = savingsTransactionSheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); @@ -187,19 +200,20 @@ public class FixedDepositTransactionWorkbookPopulator extends AbstractWorkbookPo int rowIndex = 1; Row row; Collections.sort(savingsAccounts, SavingsAccountData.ClientNameComparator); - for(SavingsAccountData savingsAccount : savingsAccounts) { + for (SavingsAccountData savingsAccount : savingsAccounts) { row = savingsTransactionSheet.createRow(rowIndex++); - writeString(TransactionConstants.LOOKUP_CLIENT_NAME_COL, row, savingsAccount.getClientName() + "(" + savingsAccount.getClientId() + ")"); + writeString(TransactionConstants.LOOKUP_CLIENT_NAME_COL, row, + savingsAccount.getClientName() + "(" + savingsAccount.getClientId() + ")"); writeString(TransactionConstants.LOOKUP_ACCOUNT_NO_COL, row, savingsAccount.getAccountNo()); writeString(TransactionConstants.LOOKUP_PRODUCT_COL, row, savingsAccount.getSavingsProductName()); - if(savingsAccount.getMinRequiredOpeningBalance() != null) { - writeBigDecimal(TransactionConstants.LOOKUP_OPENING_BALANCE_COL, row, - savingsAccount.getMinRequiredOpeningBalance()); + if (savingsAccount.getMinRequiredOpeningBalance() != null) { + writeBigDecimal(TransactionConstants.LOOKUP_OPENING_BALANCE_COL, row, savingsAccount.getMinRequiredOpeningBalance()); } - writeDate(TransactionConstants.LOOKUP_SAVINGS_ACTIVATION_DATE_COL, row,"" + - savingsAccount.getTimeline().getActivatedOnDate().getDayOfMonth() + "/" - + savingsAccount.getTimeline().getActivatedOnDate().getMonthOfYear() + "/" - + savingsAccount.getTimeline().getActivatedOnDate().getYear() , dateCellStyle,dateFormat); + writeDate(TransactionConstants.LOOKUP_SAVINGS_ACTIVATION_DATE_COL, row, + "" + savingsAccount.getTimeline().getActivatedOnDate().getDayOfMonth() + "/" + + savingsAccount.getTimeline().getActivatedOnDate().getMonthOfYear() + "/" + + savingsAccount.getTimeline().getActivatedOnDate().getYear(), + dateCellStyle, dateFormat); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/fixeddeposits/FixedDepositWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/fixeddeposits/FixedDepositWorkbookPopulator.java index 397b5d5d7..a106cdfc9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/fixeddeposits/FixedDepositWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/fixeddeposits/FixedDepositWorkbookPopulator.java @@ -43,17 +43,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FixedDepositWorkbookPopulator extends AbstractWorkbookPopulator { + private final static Logger LOG = LoggerFactory.getLogger(FixedDepositWorkbookPopulator.class); private OfficeSheetPopulator officeSheetPopulator; private ClientSheetPopulator clientSheetPopulator; private PersonnelSheetPopulator personnelSheetPopulator; private FixedDepositProductSheetPopulator productSheetPopulator; - - - public FixedDepositWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - ClientSheetPopulator clientSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, - FixedDepositProductSheetPopulator fixedDepositProductSheetPopulator) { + public FixedDepositWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, ClientSheetPopulator clientSheetPopulator, + PersonnelSheetPopulator personnelSheetPopulator, FixedDepositProductSheetPopulator fixedDepositProductSheetPopulator) { this.officeSheetPopulator = officeSheetPopulator; this.clientSheetPopulator = clientSheetPopulator; this.personnelSheetPopulator = personnelSheetPopulator; @@ -61,129 +59,122 @@ public class FixedDepositWorkbookPopulator extends AbstractWorkbookPopulator { } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet fixedDepositSheet = workbook.createSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_SHEET_NAME); - officeSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); - personnelSheetPopulator.populate(workbook,dateFormat); - productSheetPopulator.populate(workbook,dateFormat); - setRules(fixedDepositSheet,dateFormat); - setDefaults(fixedDepositSheet,dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); + personnelSheetPopulator.populate(workbook, dateFormat); + productSheetPopulator.populate(workbook, dateFormat); + setRules(fixedDepositSheet, dateFormat); + setDefaults(fixedDepositSheet, dateFormat); setClientAndGroupDateLookupTable(fixedDepositSheet, clientSheetPopulator.getClients(), null, - FixedDepositConstants.LOOKUP_CLIENT_NAME_COL,FixedDepositConstants.LOOKUP_ACTIVATION_DATE_COL,!TemplatePopulateImportConstants.CONTAINS_CLIENT_EXTERNAL_ID,dateFormat); + FixedDepositConstants.LOOKUP_CLIENT_NAME_COL, FixedDepositConstants.LOOKUP_ACTIVATION_DATE_COL, + !TemplatePopulateImportConstants.CONTAINS_CLIENT_EXTERNAL_ID, dateFormat); setLayout(fixedDepositSheet); } - private void setRules(Sheet worksheet,String dateFormat) { - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.OFFICE_NAME_COL,FixedDepositConstants.OFFICE_NAME_COL); - CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.CLIENT_NAME_COL,FixedDepositConstants.CLIENT_NAME_COL); - CellRangeAddressList productNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.PRODUCT_COL, FixedDepositConstants.PRODUCT_COL); - CellRangeAddressList fieldOfficerRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.FIELD_OFFICER_NAME_COL, FixedDepositConstants.FIELD_OFFICER_NAME_COL); - CellRangeAddressList submittedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.SUBMITTED_ON_DATE_COL, FixedDepositConstants.SUBMITTED_ON_DATE_COL); - CellRangeAddressList approvedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.APPROVED_DATE_COL, FixedDepositConstants.APPROVED_DATE_COL); - CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.ACTIVATION_DATE_COL, FixedDepositConstants.ACTIVATION_DATE_COL); - CellRangeAddressList interestCompudingPeriodRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, FixedDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL); - CellRangeAddressList interestPostingPeriodRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.INTEREST_POSTING_PERIOD_COL, FixedDepositConstants.INTEREST_POSTING_PERIOD_COL); - CellRangeAddressList interestCalculationRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.INTEREST_CALCULATION_COL, FixedDepositConstants.INTEREST_CALCULATION_COL); - CellRangeAddressList interestCalculationDaysInYearRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), FixedDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, - FixedDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL); - CellRangeAddressList lockinPeriodFrequencyRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, FixedDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL); - CellRangeAddressList depositAmountRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.DEPOSIT_AMOUNT_COL, FixedDepositConstants.DEPOSIT_AMOUNT_COL); - CellRangeAddressList depositPeriodTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - FixedDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, FixedDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL); + private void setRules(Sheet worksheet, String dateFormat) { + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.OFFICE_NAME_COL, FixedDepositConstants.OFFICE_NAME_COL); + CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.CLIENT_NAME_COL, FixedDepositConstants.CLIENT_NAME_COL); + CellRangeAddressList productNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.PRODUCT_COL, FixedDepositConstants.PRODUCT_COL); + CellRangeAddressList fieldOfficerRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.FIELD_OFFICER_NAME_COL, FixedDepositConstants.FIELD_OFFICER_NAME_COL); + CellRangeAddressList submittedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.SUBMITTED_ON_DATE_COL, FixedDepositConstants.SUBMITTED_ON_DATE_COL); + CellRangeAddressList approvedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.APPROVED_DATE_COL, FixedDepositConstants.APPROVED_DATE_COL); + CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.ACTIVATION_DATE_COL, FixedDepositConstants.ACTIVATION_DATE_COL); + CellRangeAddressList interestCompudingPeriodRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, FixedDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL); + CellRangeAddressList interestPostingPeriodRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.INTEREST_POSTING_PERIOD_COL, FixedDepositConstants.INTEREST_POSTING_PERIOD_COL); + CellRangeAddressList interestCalculationRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.INTEREST_CALCULATION_COL, FixedDepositConstants.INTEREST_CALCULATION_COL); + CellRangeAddressList interestCalculationDaysInYearRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, FixedDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL); + CellRangeAddressList lockinPeriodFrequencyRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, FixedDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL); + CellRangeAddressList depositAmountRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.DEPOSIT_AMOUNT_COL, FixedDepositConstants.DEPOSIT_AMOUNT_COL); + CellRangeAddressList depositPeriodTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + FixedDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, FixedDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL); - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); - setNames(worksheet); + setNames(worksheet); - DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint clientNameConstraint = validationHelper - .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))"); - DataValidationConstraint productNameConstraint = validationHelper.createFormulaListConstraint("Products"); - DataValidationConstraint fieldOfficerNameConstraint = validationHelper - .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$A1))"); - DataValidationConstraint submittedDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($B1,$AF$2:$AG$" - + (clientSheetPopulator.getClientsSize() + 1) + ",2,FALSE)", "=TODAY()", - dateFormat); - DataValidationConstraint approvalDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=$E1", "=TODAY()", dateFormat); - DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=$F1", "=TODAY()", dateFormat); - DataValidationConstraint interestCompudingPeriodConstraint = validationHelper. - createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_DAILY, - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_MONTHLY, - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_QUARTERLY, - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_SEMI_ANNUALLY, - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_ANNUALLY }); - DataValidationConstraint interestPostingPeriodConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_MONTHLY, - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_QUARTERLY, - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_BIANUALLY, - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_ANNUALLY }); - DataValidationConstraint interestCalculationConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_CAL_DAILY_BALANCE, - TemplatePopulateImportConstants.INTEREST_CAL_AVG_BALANCE }); - DataValidationConstraint interestCalculationDaysInYearConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_360, - TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_365 }); - DataValidationConstraint frequency = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.FREQUENCY_DAYS, - TemplatePopulateImportConstants.FREQUENCY_WEEKS, - TemplatePopulateImportConstants.FREQUENCY_MONTHS, - TemplatePopulateImportConstants.FREQUENCY_YEARS }); - DataValidationConstraint depositConstraint = validationHelper.createDecimalConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "=INDIRECT(CONCATENATE(\"Min_Deposit_\",$C1))", null); + DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); + DataValidationConstraint clientNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))"); + DataValidationConstraint productNameConstraint = validationHelper.createFormulaListConstraint("Products"); + DataValidationConstraint fieldOfficerNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$A1))"); + DataValidationConstraint submittedDateConstraint = validationHelper.createDateConstraint( + DataValidationConstraint.OperatorType.BETWEEN, + "=VLOOKUP($B1,$AF$2:$AG$" + (clientSheetPopulator.getClientsSize() + 1) + ",2,FALSE)", "=TODAY()", dateFormat); + DataValidationConstraint approvalDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$E1", "=TODAY()", dateFormat); + DataValidationConstraint activationDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$F1", "=TODAY()", dateFormat); + DataValidationConstraint interestCompudingPeriodConstraint = validationHelper + .createExplicitListConstraint(new String[] { TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_DAILY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_MONTHLY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_QUARTERLY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_SEMI_ANNUALLY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_ANNUALLY }); + DataValidationConstraint interestPostingPeriodConstraint = validationHelper + .createExplicitListConstraint(new String[] { TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_MONTHLY, + TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_QUARTERLY, + TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_BIANUALLY, + TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_ANNUALLY }); + DataValidationConstraint interestCalculationConstraint = validationHelper.createExplicitListConstraint(new String[] { + TemplatePopulateImportConstants.INTEREST_CAL_DAILY_BALANCE, TemplatePopulateImportConstants.INTEREST_CAL_AVG_BALANCE }); + DataValidationConstraint interestCalculationDaysInYearConstraint = validationHelper + .createExplicitListConstraint(new String[] { TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_360, + TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_365 }); + DataValidationConstraint frequency = validationHelper.createExplicitListConstraint( + new String[] { TemplatePopulateImportConstants.FREQUENCY_DAYS, TemplatePopulateImportConstants.FREQUENCY_WEEKS, + TemplatePopulateImportConstants.FREQUENCY_MONTHS, TemplatePopulateImportConstants.FREQUENCY_YEARS }); + DataValidationConstraint depositConstraint = validationHelper.createDecimalConstraint( + DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "=INDIRECT(CONCATENATE(\"Min_Deposit_\",$C1))", null); - DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); - DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); - DataValidation productNameValidation = validationHelper.createValidation(productNameConstraint, productNameRange); - DataValidation fieldOfficerValidation = validationHelper.createValidation(fieldOfficerNameConstraint, fieldOfficerRange); - DataValidation interestCompudingPeriodValidation = validationHelper.createValidation(interestCompudingPeriodConstraint, - interestCompudingPeriodRange); - DataValidation interestPostingPeriodValidation = validationHelper.createValidation(interestPostingPeriodConstraint, - interestPostingPeriodRange); - DataValidation interestCalculationValidation = validationHelper.createValidation(interestCalculationConstraint, - interestCalculationRange); - DataValidation interestCalculationDaysInYearValidation = validationHelper.createValidation( - interestCalculationDaysInYearConstraint, interestCalculationDaysInYearRange); - DataValidation lockinPeriodFrequencyValidation = validationHelper.createValidation(frequency, - lockinPeriodFrequencyRange); - DataValidation depositPeriodTypeValidation = validationHelper.createValidation(frequency, - depositPeriodTypeRange); - DataValidation submittedDateValidation = validationHelper.createValidation(submittedDateConstraint, submittedDateRange); - DataValidation approvalDateValidation = validationHelper.createValidation(approvalDateConstraint, approvedDateRange); - DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange); - DataValidation depositAmountValidation = validationHelper.createValidation(depositConstraint, depositAmountRange); + DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); + DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); + DataValidation productNameValidation = validationHelper.createValidation(productNameConstraint, productNameRange); + DataValidation fieldOfficerValidation = validationHelper.createValidation(fieldOfficerNameConstraint, fieldOfficerRange); + DataValidation interestCompudingPeriodValidation = validationHelper.createValidation(interestCompudingPeriodConstraint, + interestCompudingPeriodRange); + DataValidation interestPostingPeriodValidation = validationHelper.createValidation(interestPostingPeriodConstraint, + interestPostingPeriodRange); + DataValidation interestCalculationValidation = validationHelper.createValidation(interestCalculationConstraint, + interestCalculationRange); + DataValidation interestCalculationDaysInYearValidation = validationHelper.createValidation(interestCalculationDaysInYearConstraint, + interestCalculationDaysInYearRange); + DataValidation lockinPeriodFrequencyValidation = validationHelper.createValidation(frequency, lockinPeriodFrequencyRange); + DataValidation depositPeriodTypeValidation = validationHelper.createValidation(frequency, depositPeriodTypeRange); + DataValidation submittedDateValidation = validationHelper.createValidation(submittedDateConstraint, submittedDateRange); + DataValidation approvalDateValidation = validationHelper.createValidation(approvalDateConstraint, approvedDateRange); + DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange); + DataValidation depositAmountValidation = validationHelper.createValidation(depositConstraint, depositAmountRange); - - worksheet.addValidationData(officeValidation); - worksheet.addValidationData(clientValidation); - worksheet.addValidationData(productNameValidation); - worksheet.addValidationData(fieldOfficerValidation); - worksheet.addValidationData(submittedDateValidation); - worksheet.addValidationData(approvalDateValidation); - worksheet.addValidationData(activationDateValidation); - worksheet.addValidationData(interestCompudingPeriodValidation); - worksheet.addValidationData(interestPostingPeriodValidation); - worksheet.addValidationData(interestCalculationValidation); - worksheet.addValidationData(interestCalculationDaysInYearValidation); - worksheet.addValidationData(lockinPeriodFrequencyValidation); - worksheet.addValidationData(depositPeriodTypeValidation); - worksheet.addValidationData(depositAmountValidation); + worksheet.addValidationData(officeValidation); + worksheet.addValidationData(clientValidation); + worksheet.addValidationData(productNameValidation); + worksheet.addValidationData(fieldOfficerValidation); + worksheet.addValidationData(submittedDateValidation); + worksheet.addValidationData(approvalDateValidation); + worksheet.addValidationData(activationDateValidation); + worksheet.addValidationData(interestCompudingPeriodValidation); + worksheet.addValidationData(interestPostingPeriodValidation); + worksheet.addValidationData(interestCalculationValidation); + worksheet.addValidationData(interestCalculationDaysInYearValidation); + worksheet.addValidationData(lockinPeriodFrequencyValidation); + worksheet.addValidationData(depositPeriodTypeValidation); + worksheet.addValidationData(depositAmountValidation); } @@ -195,7 +186,7 @@ public class FixedDepositWorkbookPopulator extends AbstractWorkbookPopulator { // Office Names Name officeGroup = savingsWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (officeNames.size() + 1)); // Client and Loan Officer Names for each office for (Integer i = 0; i < officeNames.size(); i++) { @@ -205,20 +196,21 @@ public class FixedDepositWorkbookPopulator extends AbstractWorkbookPopulator { Name fieldOfficerName = savingsWorkbook.createName(); if (officeNameToBeginEndIndexesOfStaff != null) { fieldOfficerName.setNameName("Staff_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - fieldOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" - + officeNameToBeginEndIndexesOfStaff[1]); + fieldOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); } if (officeNameToBeginEndIndexesOfClients != null) { clientName.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - clientName.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + ":$B$" - + officeNameToBeginEndIndexesOfClients[1]); + clientName.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfClients[0] + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); } } // Product Name Name productGroup = savingsWorkbook.createName(); productGroup.setNameName("Products"); - productGroup.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$B$2:$B$" + (productSheetPopulator.getProductsSize() + 1)); + productGroup.setRefersToFormula( + TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$B$2:$B$" + (productSheetPopulator.getProductsSize() + 1)); // Default Interest Rate, Interest Compounding Period, Interest Posting // Period, Interest Calculation, Interest Calculation Days In Year, @@ -246,30 +238,30 @@ public class FixedDepositWorkbookPopulator extends AbstractWorkbookPopulator { minDepositName.setNameName("Min_Deposit_" + productName); maxDepositName.setNameName("Max_Deposit_" + productName); depositName.setNameName("Deposit_" + productName); - interestCompoundingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$E$" + (i + 2)); - interestPostingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$F$" + (i + 2)); - interestCalculationName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$G$" + (i + 2)); - daysInYearName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$H$" + (i + 2)); - depositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$N$" + (i + 2)); - minDepositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$L$" + (i + 2)); - maxDepositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$M$" + (i + 2)); + interestCompoundingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$E$" + (i + 2)); + interestPostingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$F$" + (i + 2)); + interestCalculationName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$G$" + (i + 2)); + daysInYearName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$H$" + (i + 2)); + depositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$N$" + (i + 2)); + minDepositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$L$" + (i + 2)); + maxDepositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$M$" + (i + 2)); - if(product.getMinDepositTermType() != null) { + if (product.getMinDepositTermType() != null) { minDepositTermTypeName.setNameName("Term_Type_" + productName); - minDepositTermTypeName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$P$" + (i + 2)); + minDepositTermTypeName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$P$" + (i + 2)); } if (product.getLockinPeriodFrequency() != null) { lockinPeriodName.setNameName("Lockin_Period_" + productName); - lockinPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$I$" + (i + 2)); + lockinPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$I$" + (i + 2)); } if (product.getLockinPeriodFrequencyType() != null) { lockinPeriodFrequencyName.setNameName("Lockin_Frequency_" + productName); - lockinPeriodFrequencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$J$" + (i + 2)); + lockinPeriodFrequencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$J$" + (i + 2)); } } } - private void setDefaults(Sheet worksheet,String dateFormat) { + private void setDefaults(Sheet worksheet, String dateFormat) { Workbook workbook = worksheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); @@ -277,27 +269,33 @@ public class FixedDepositWorkbookPopulator extends AbstractWorkbookPopulator { try { for (Integer rowNo = 1; rowNo < 1000; rowNo++) { Row row = worksheet.createRow(rowNo); - writeFormula(FixedDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Compouding_\",$C" - + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Compouding_\",$C" + (rowNo + 1) + ")))"); - writeFormula(FixedDepositConstants.INTEREST_POSTING_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Posting_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Posting_\",$C" + (rowNo + 1) + ")))"); - writeFormula(FixedDepositConstants.INTEREST_CALCULATION_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Calculation_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Calculation_\",$C" + (rowNo + 1) + ")))"); - writeFormula(FixedDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Days_In_Year_\",$C" - + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Days_In_Year_\",$C" + (rowNo + 1) + ")))"); - writeFormula(FixedDepositConstants.LOCKIN_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Period_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Period_\",$C" + (rowNo + 1) + ")))"); - writeFormula(FixedDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$C" + (rowNo + 1) + ")))"); + writeFormula(FixedDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Compouding_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Compouding_\",$C" + (rowNo + 1) + ")))"); + writeFormula(FixedDepositConstants.INTEREST_POSTING_PERIOD_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Posting_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Posting_\",$C" + (rowNo + 1) + ")))"); + writeFormula(FixedDepositConstants.INTEREST_CALCULATION_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Calculation_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Calculation_\",$C" + (rowNo + 1) + ")))"); + writeFormula(FixedDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Days_In_Year_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Days_In_Year_\",$C" + (rowNo + 1) + ")))"); + writeFormula(FixedDepositConstants.LOCKIN_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Period_\",$C" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Period_\",$C" + (rowNo + 1) + ")))"); + writeFormula(FixedDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$C" + (rowNo + 1) + ")))"); writeFormula(FixedDepositConstants.DEPOSIT_AMOUNT_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Deposit_\",$C" + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Deposit_\",$C" + (rowNo + 1) + ")))"); - writeFormula(FixedDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Term_Type_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Term_Type_\",$C" + (rowNo + 1) + ")))"); + writeFormula(FixedDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Term_Type_\",$C" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Term_Type_\",$C" + (rowNo + 1) + ")))"); } } catch (RuntimeException re) { - LOG.error("Problem occurred in setDefaults function",re); + LOG.error("Problem occurred in setDefaults function", re); } } + private void setLayout(Sheet worksheet) { Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); @@ -311,7 +309,8 @@ public class FixedDepositWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.setColumnWidth(FixedDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(FixedDepositConstants.INTEREST_POSTING_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(FixedDepositConstants.INTEREST_CALCULATION_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(FixedDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(FixedDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, + TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(FixedDepositConstants.LOCKIN_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(FixedDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(FixedDepositConstants.DEPOSIT_AMOUNT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); @@ -345,15 +344,15 @@ public class FixedDepositWorkbookPopulator extends AbstractWorkbookPopulator { writeString(FixedDepositConstants.DEPOSIT_PERIOD_COL, rowHeader, "Deposit Period"); writeString(FixedDepositConstants.EXTERNAL_ID_COL, rowHeader, "External Id"); - writeString(FixedDepositConstants.CHARGE_ID_1,rowHeader,"Charge Id"); + writeString(FixedDepositConstants.CHARGE_ID_1, rowHeader, "Charge Id"); writeString(FixedDepositConstants.CHARGE_AMOUNT_1, rowHeader, "Charged Amount"); writeString(FixedDepositConstants.CHARGE_DUE_DATE_1, rowHeader, "Charged On Date"); - writeString(FixedDepositConstants.CHARGE_ID_2,rowHeader,"Charge Id"); + writeString(FixedDepositConstants.CHARGE_ID_2, rowHeader, "Charge Id"); writeString(FixedDepositConstants.CHARGE_AMOUNT_2, rowHeader, "Charged Amount"); writeString(FixedDepositConstants.CHARGE_DUE_DATE_2, rowHeader, "Charged On Date"); writeString(FixedDepositConstants.CLOSED_ON_DATE, rowHeader, "Close on Date"); - writeString(FixedDepositConstants.ON_ACCOUNT_CLOSURE_ID,rowHeader,"Action(Account Transfer(200) or cash(100) "); - writeString(FixedDepositConstants.TO_SAVINGS_ACCOUNT_ID,rowHeader, "Transfered Account No."); + writeString(FixedDepositConstants.ON_ACCOUNT_CLOSURE_ID, rowHeader, "Action(Account Transfer(200) or cash(100) "); + writeString(FixedDepositConstants.TO_SAVINGS_ACCOUNT_ID, rowHeader, "Transfered Account No."); writeString(FixedDepositConstants.LOOKUP_CLIENT_NAME_COL, rowHeader, "Client Name"); writeString(FixedDepositConstants.LOOKUP_ACTIVATION_DATE_COL, rowHeader, "Client Activation Date"); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/group/GroupsWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/group/GroupsWorkbookPopulator.java index 38f40b969..25edd9db0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/group/GroupsWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/group/GroupsWorkbookPopulator.java @@ -46,9 +46,8 @@ public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator { private CenterSheetPopulator centerSheetPopulator; private ClientSheetPopulator clientSheetPopulator; - public GroupsWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - PersonnelSheetPopulator personnelSheetPopulator, CenterSheetPopulator centerSheetPopulator, - ClientSheetPopulator clientSheetPopulator) { + public GroupsWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, + CenterSheetPopulator centerSheetPopulator, ClientSheetPopulator clientSheetPopulator) { this.officeSheetPopulator = officeSheetPopulator; this.personnelSheetPopulator = personnelSheetPopulator; this.centerSheetPopulator = centerSheetPopulator; @@ -56,15 +55,15 @@ public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator { } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet groupSheet = workbook.createSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME); - personnelSheetPopulator.populate(workbook,dateFormat); - officeSheetPopulator.populate(workbook,dateFormat); - centerSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); + personnelSheetPopulator.populate(workbook, dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + centerSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); setLayout(groupSheet); - setLookupTable(groupSheet,dateFormat); - setRules(groupSheet,dateFormat); + setLookupTable(groupSheet, dateFormat); + setRules(groupSheet, dateFormat); } @@ -73,13 +72,13 @@ public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator { rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); worksheet.setColumnWidth(GroupConstants.NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(GroupConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(GroupConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(GroupConstants.CENTER_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(GroupConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(GroupConstants.CENTER_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(GroupConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(GroupConstants.ACTIVE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(GroupConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GroupConstants.SUBMITTED_ON_DATE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GroupConstants.MEETING_START_DATE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(GroupConstants.SUBMITTED_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GroupConstants.MEETING_START_DATE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(GroupConstants.IS_REPEATING_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(GroupConstants.FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(GroupConstants.INTERVAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); @@ -88,7 +87,7 @@ public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.setColumnWidth(GroupConstants.GROUP_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(GroupConstants.FAILURE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(GroupConstants.CLIENT_NAMES_STARTING_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GroupConstants.LOOKUP_OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(GroupConstants.LOOKUP_OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(GroupConstants.LOOKUP_OFFICE_OPENING_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(GroupConstants.LOOKUP_REPEAT_MONTHLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); @@ -101,7 +100,7 @@ public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator { writeString(GroupConstants.EXTERNAL_ID_COL, rowHeader, "External ID"); writeString(GroupConstants.ACTIVE_COL, rowHeader, "Active*"); writeString(GroupConstants.ACTIVATION_DATE_COL, rowHeader, "Activation Date*"); - writeString(GroupConstants.SUBMITTED_ON_DATE_COL,rowHeader,"Submitted On Date *"); + writeString(GroupConstants.SUBMITTED_ON_DATE_COL, rowHeader, "Submitted On Date *"); writeString(GroupConstants.MEETING_START_DATE_COL, rowHeader, "Meeting Start Date* (On or After)"); writeString(GroupConstants.IS_REPEATING_COL, rowHeader, "Repeat*"); writeString(GroupConstants.FREQUENCY_COL, rowHeader, "Frequency*"); @@ -115,89 +114,82 @@ public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator { writeString(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, rowHeader, "If Repeat Weekly Range"); } - private void setLookupTable(Sheet groupSheet,String dateFormat) { - setOfficeDateLookupTable(groupSheet, officeSheetPopulator.getOffices(),GroupConstants.LOOKUP_OFFICE_NAME_COL, - GroupConstants. LOOKUP_OFFICE_OPENING_DATE_COL,dateFormat); + + private void setLookupTable(Sheet groupSheet, String dateFormat) { + setOfficeDateLookupTable(groupSheet, officeSheetPopulator.getOffices(), GroupConstants.LOOKUP_OFFICE_NAME_COL, + GroupConstants.LOOKUP_OFFICE_OPENING_DATE_COL, dateFormat); int rowIndex; - for(rowIndex = 1; rowIndex <= 11; rowIndex++) { + for (rowIndex = 1; rowIndex <= 11; rowIndex++) { Row row = groupSheet.getRow(rowIndex); - if(row == null) { - row = groupSheet.createRow(rowIndex); + if (row == null) { + row = groupSheet.createRow(rowIndex); } writeInt(GroupConstants.LOOKUP_REPEAT_MONTHLY_COL, row, rowIndex); } - for(rowIndex = 1; rowIndex <= 3; rowIndex++) { - writeInt(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, groupSheet.getRow(rowIndex), rowIndex); + for (rowIndex = 1; rowIndex <= 3; rowIndex++) { + writeInt(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, groupSheet.getRow(rowIndex), rowIndex); } - String[] days = new String[]{ - TemplatePopulateImportConstants.MONDAY, - TemplatePopulateImportConstants.TUESDAY, - TemplatePopulateImportConstants.WEDNESDAY, - TemplatePopulateImportConstants.THURSDAY, - TemplatePopulateImportConstants.FRIDAY, - TemplatePopulateImportConstants.SATURDAY, - TemplatePopulateImportConstants.SUNDAY}; - for(rowIndex = 1; rowIndex <= 7; rowIndex++) { - writeString(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, groupSheet.getRow(rowIndex), - days[rowIndex - 1]); + String[] days = new String[] { TemplatePopulateImportConstants.MONDAY, TemplatePopulateImportConstants.TUESDAY, + TemplatePopulateImportConstants.WEDNESDAY, TemplatePopulateImportConstants.THURSDAY, TemplatePopulateImportConstants.FRIDAY, + TemplatePopulateImportConstants.SATURDAY, TemplatePopulateImportConstants.SUNDAY }; + for (rowIndex = 1; rowIndex <= 7; rowIndex++) { + writeString(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, groupSheet.getRow(rowIndex), days[rowIndex - 1]); } } - private void setRules(Sheet worksheet,String dateFormat){ - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + private void setRules(Sheet worksheet, String dateFormat) { + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), GroupConstants.OFFICE_NAME_COL, GroupConstants.OFFICE_NAME_COL); - CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), GroupConstants.STAFF_NAME_COL, GroupConstants.STAFF_NAME_COL); - CellRangeAddressList centerNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList centerNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), GroupConstants.CENTER_NAME_COL, GroupConstants.CENTER_NAME_COL); - CellRangeAddressList activeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList activeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), GroupConstants.ACTIVE_COL, GroupConstants.ACTIVE_COL); - CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GroupConstants.ACTIVATION_DATE_COL,GroupConstants.ACTIVATION_DATE_COL); - CellRangeAddressList submittedOnDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GroupConstants.SUBMITTED_ON_DATE_COL,GroupConstants.SUBMITTED_ON_DATE_COL); - CellRangeAddressList meetingStartDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GroupConstants.MEETING_START_DATE_COL,GroupConstants.MEETING_START_DATE_COL); + CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GroupConstants.ACTIVATION_DATE_COL, GroupConstants.ACTIVATION_DATE_COL); + CellRangeAddressList submittedOnDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GroupConstants.SUBMITTED_ON_DATE_COL, GroupConstants.SUBMITTED_ON_DATE_COL); + CellRangeAddressList meetingStartDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GroupConstants.MEETING_START_DATE_COL, GroupConstants.MEETING_START_DATE_COL); CellRangeAddressList isRepeatRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), GroupConstants.IS_REPEATING_COL, GroupConstants.IS_REPEATING_COL); CellRangeAddressList repeatsRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GroupConstants. FREQUENCY_COL, GroupConstants.FREQUENCY_COL); + GroupConstants.FREQUENCY_COL, GroupConstants.FREQUENCY_COL); CellRangeAddressList repeatsEveryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GroupConstants.INTERVAL_COL,GroupConstants. INTERVAL_COL); + GroupConstants.INTERVAL_COL, GroupConstants.INTERVAL_COL); CellRangeAddressList repeatsOnRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), GroupConstants.REPEATS_ON_DAY_COL, GroupConstants.REPEATS_ON_DAY_COL); - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); List offices = officeSheetPopulator.getOffices(); setNames(worksheet, offices); - DataValidationConstraint centerNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Center_\",$B1))"); + DataValidationConstraint centerNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Center_\",$B1))"); DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint staffNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$B1))"); - DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[]{"True", "False"}); - DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint - (DataValidationConstraint.OperatorType.BETWEEN, - "=VLOOKUP($B1,$IR$2:$IS" + (offices.size() + 1)+",2,FALSE)", "=TODAY()", dateFormat); - DataValidationConstraint submittedOnDateConstraint = - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, - "=$G1" ,null,dateFormat); - DataValidationConstraint meetingStartDateConstraint = validationHelper. - createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, - "=$G1", "=TODAY()", dateFormat); - DataValidationConstraint repeatsConstraint = validationHelper.createExplicitListConstraint(new String[]{ - TemplatePopulateImportConstants.FREQUENCY_DAILY, - TemplatePopulateImportConstants.FREQUENCY_WEEKLY, - TemplatePopulateImportConstants.FREQUENCY_MONTHLY, - TemplatePopulateImportConstants.FREQUENCY_YEARLY}); + DataValidationConstraint staffNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$B1))"); + DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint( + DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($B1,$IR$2:$IS" + (offices.size() + 1) + ",2,FALSE)", "=TODAY()", + dateFormat); + DataValidationConstraint submittedOnDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, "=$G1", null, dateFormat); + DataValidationConstraint meetingStartDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$G1", "=TODAY()", dateFormat); + DataValidationConstraint repeatsConstraint = validationHelper.createExplicitListConstraint( + new String[] { TemplatePopulateImportConstants.FREQUENCY_DAILY, TemplatePopulateImportConstants.FREQUENCY_WEEKLY, + TemplatePopulateImportConstants.FREQUENCY_MONTHLY, TemplatePopulateImportConstants.FREQUENCY_YEARLY }); DataValidationConstraint repeatsEveryConstraint = validationHelper.createFormulaListConstraint("INDIRECT($K1)"); DataValidationConstraint repeatsOnConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE($K1,\"_DAYS\"))"); - DataValidation centerValidation=validationHelper.createValidation(centerNameConstraint, centerNameRange); + DataValidation centerValidation = validationHelper.createValidation(centerNameConstraint, centerNameRange); DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); DataValidation staffValidation = validationHelper.createValidation(staffNameConstraint, staffNameRange); DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange); DataValidation activeValidation = validationHelper.createValidation(booleanConstraint, activeRange); - DataValidation submittedOnDateValidation=validationHelper.createValidation(submittedOnDateConstraint,submittedOnDateRange); + DataValidation submittedOnDateValidation = validationHelper.createValidation(submittedOnDateConstraint, submittedOnDateRange); DataValidation meetingStartDateValidation = validationHelper.createValidation(meetingStartDateConstraint, meetingStartDateRange); DataValidation isRepeatValidation = validationHelper.createValidation(booleanConstraint, isRepeatRange); DataValidation repeatsValidation = validationHelper.createValidation(repeatsConstraint, repeatsRange); @@ -221,47 +213,45 @@ public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator { Workbook centerWorkbook = worksheet.getWorkbook(); Name officeCenter = centerWorkbook.createName(); officeCenter.setNameName("Office"); - officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (offices.size() + 1)); + officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (offices.size() + 1)); - - //Repeat constraint names + // Repeat constraint names Name repeatsDaily = centerWorkbook.createName(); repeatsDaily.setNameName("Daily"); - repeatsDaily.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IT$2:$IT$4"); + repeatsDaily.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME + "!$IT$2:$IT$4"); Name repeatsWeekly = centerWorkbook.createName(); repeatsWeekly.setNameName("Weekly"); - repeatsWeekly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IT$2:$IT$4"); + repeatsWeekly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME + "!$IT$2:$IT$4"); Name repeatYearly = centerWorkbook.createName(); repeatYearly.setNameName("Yearly"); - repeatYearly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IT$2:$IT$4"); + repeatYearly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME + "!$IT$2:$IT$4"); Name repeatsMonthly = centerWorkbook.createName(); repeatsMonthly.setNameName("Monthly"); - repeatsMonthly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IU$2:$IU$12"); + repeatsMonthly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME + "!$IU$2:$IU$12"); Name repeatsOnWeekly = centerWorkbook.createName(); repeatsOnWeekly.setNameName("Weekly_Days"); - repeatsOnWeekly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IV$2:$IV$8"); + repeatsOnWeekly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME + "!$IV$2:$IV$8"); - - //Staff Names for each office & center Names for each office - for(Integer i = 0; i < offices.size(); i++) { - Integer[] officeNameToBeginEndIndexesOfCenters =centerSheetPopulator.getOfficeNameToBeginEndIndexesOfCenters().get(i); + // Staff Names for each office & center Names for each office + for (Integer i = 0; i < offices.size(); i++) { + Integer[] officeNameToBeginEndIndexesOfCenters = centerSheetPopulator.getOfficeNameToBeginEndIndexesOfCenters().get(i); Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i); Name loanOfficerName = centerWorkbook.createName(); - Name centerName=centerWorkbook.createName(); + Name centerName = centerWorkbook.createName(); - if(officeNameToBeginEndIndexesOfStaff != null) { + if (officeNameToBeginEndIndexesOfStaff != null) { loanOfficerName.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_")); - loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+ - "!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); - } - if (officeNameToBeginEndIndexesOfCenters!=null) { - centerName.setNameName("Center_" + offices.get(i).name().trim().replaceAll("[ )(]", "_")); - centerName.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+ - "!$B$" + officeNameToBeginEndIndexesOfCenters[0] + ":$B$" + officeNameToBeginEndIndexesOfCenters[1]); + loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); + } + if (officeNameToBeginEndIndexesOfCenters != null) { + centerName.setNameName("Center_" + offices.get(i).name().trim().replaceAll("[ )(]", "_")); + centerName.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfCenters[0] + ":$B$" + officeNameToBeginEndIndexesOfCenters[1]); } } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/guarantor/GuarantorWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/guarantor/GuarantorWorkbookPopulator.java index a89d3eebd..47a4ac8d1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/guarantor/GuarantorWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/guarantor/GuarantorWorkbookPopulator.java @@ -44,84 +44,82 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddressList; public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator { + private OfficeSheetPopulator officeSheetPopulator; private ClientSheetPopulator clientSheetPopulator; private List loans; private List savings; - private ListguarantorRelationshipTypes; + private List guarantorRelationshipTypes; - public GuarantorWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - ClientSheetPopulator clientSheetPopulator, - List loans, List savings, - List guarantorRelationshipTypes) { + public GuarantorWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, ClientSheetPopulator clientSheetPopulator, + List loans, List savings, List guarantorRelationshipTypes) { this.officeSheetPopulator = officeSheetPopulator; this.clientSheetPopulator = clientSheetPopulator; this.loans = loans; this.savings = savings; - this.guarantorRelationshipTypes=guarantorRelationshipTypes; + this.guarantorRelationshipTypes = guarantorRelationshipTypes; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet addGuarantorSheet = workbook.createSheet(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME); setLayout(addGuarantorSheet); - officeSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); - populateLoansTable(addGuarantorSheet,dateFormat); - populateSavingsTable(addGuarantorSheet,dateFormat); - populateGuarantorRelationshipTypes(addGuarantorSheet,dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); + populateLoansTable(addGuarantorSheet, dateFormat); + populateSavingsTable(addGuarantorSheet, dateFormat); + populateGuarantorRelationshipTypes(addGuarantorSheet, dateFormat); setRules(addGuarantorSheet); } - - private void setLayout(Sheet worksheet) { Row rowHeader = worksheet.createRow(0); - worksheet.setColumnWidth(GuarantorConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.LOAN_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.GUARANTO_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.ENTITY_OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.ENTITY_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.FIRST_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.LAST_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.ADDRESS_LINE_1_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.ADDRESS_LINE_2_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.CITY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.DOB_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.ZIP_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.SAVINGS_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.AMOUNT, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.LOOKUP_CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.LOOKUP_SAVINGS_CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(GuarantorConstants.LOOKUP_SAVINGS_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(GuarantorConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); - writeString(GuarantorConstants.CLIENT_NAME_COL, rowHeader, "Client Name*"); - writeString(GuarantorConstants.LOAN_ACCOUNT_NO_COL, rowHeader, " Loan Account NO"); - writeString(GuarantorConstants.GUARANTO_TYPE_COL, rowHeader, "Guranter_type*"); - writeString(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, rowHeader, "Client Relationship type*"); - writeString(GuarantorConstants.ENTITY_OFFICE_NAME_COL, rowHeader, "Guranter office"); - writeString(GuarantorConstants.ENTITY_ID_COL, rowHeader, "Gurantor client id*"); - writeString(GuarantorConstants.FIRST_NAME_COL, rowHeader, "First Name*"); - writeString(GuarantorConstants.LAST_NAME_COL, rowHeader, "Last Name"); - writeString(GuarantorConstants.ADDRESS_LINE_1_COL, rowHeader, "ADDRESS LINE 1"); - writeString(GuarantorConstants.ADDRESS_LINE_2_COL, rowHeader, "ADDRESS LINE 2"); - writeString(GuarantorConstants.CITY_COL, rowHeader, "City"); - writeString(GuarantorConstants.DOB_COL, rowHeader, "Date of Birth"); - writeString(GuarantorConstants.ZIP_COL, rowHeader, "Zip*"); - writeString(GuarantorConstants.SAVINGS_ID_COL, rowHeader, "Savings Account Id"); - writeString(GuarantorConstants.AMOUNT, rowHeader, "Amount"); - writeString(GuarantorConstants.LOOKUP_CLIENT_NAME_COL, rowHeader, "Lookup Client"); - writeString(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, rowHeader, "Lookup Loan Account"); - writeString(GuarantorConstants.LOOKUP_SAVINGS_CLIENT_NAME_COL, rowHeader, "Savings Lookup Client"); - writeString(GuarantorConstants.LOOKUP_SAVINGS_ACCOUNT_NO_COL, rowHeader, "Savings Lookup Account"); + worksheet.setColumnWidth(GuarantorConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.LOAN_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.GUARANTO_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.ENTITY_OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.ENTITY_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.FIRST_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.LAST_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.ADDRESS_LINE_1_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.ADDRESS_LINE_2_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.CITY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.DOB_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.ZIP_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.SAVINGS_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.AMOUNT, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.LOOKUP_CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.LOOKUP_SAVINGS_CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(GuarantorConstants.LOOKUP_SAVINGS_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(GuarantorConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); + writeString(GuarantorConstants.CLIENT_NAME_COL, rowHeader, "Client Name*"); + writeString(GuarantorConstants.LOAN_ACCOUNT_NO_COL, rowHeader, " Loan Account NO"); + writeString(GuarantorConstants.GUARANTO_TYPE_COL, rowHeader, "Guranter_type*"); + writeString(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, rowHeader, "Client Relationship type*"); + writeString(GuarantorConstants.ENTITY_OFFICE_NAME_COL, rowHeader, "Guranter office"); + writeString(GuarantorConstants.ENTITY_ID_COL, rowHeader, "Gurantor client id*"); + writeString(GuarantorConstants.FIRST_NAME_COL, rowHeader, "First Name*"); + writeString(GuarantorConstants.LAST_NAME_COL, rowHeader, "Last Name"); + writeString(GuarantorConstants.ADDRESS_LINE_1_COL, rowHeader, "ADDRESS LINE 1"); + writeString(GuarantorConstants.ADDRESS_LINE_2_COL, rowHeader, "ADDRESS LINE 2"); + writeString(GuarantorConstants.CITY_COL, rowHeader, "City"); + writeString(GuarantorConstants.DOB_COL, rowHeader, "Date of Birth"); + writeString(GuarantorConstants.ZIP_COL, rowHeader, "Zip*"); + writeString(GuarantorConstants.SAVINGS_ID_COL, rowHeader, "Savings Account Id"); + writeString(GuarantorConstants.AMOUNT, rowHeader, "Amount"); + writeString(GuarantorConstants.LOOKUP_CLIENT_NAME_COL, rowHeader, "Lookup Client"); + writeString(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, rowHeader, "Lookup Loan Account"); + writeString(GuarantorConstants.LOOKUP_SAVINGS_CLIENT_NAME_COL, rowHeader, "Savings Lookup Client"); + writeString(GuarantorConstants.LOOKUP_SAVINGS_ACCOUNT_NO_COL, rowHeader, "Savings Lookup Account"); } - private void populateSavingsTable(Sheet addGuarantorSheet,String dateFormat) { + + private void populateSavingsTable(Sheet addGuarantorSheet, String dateFormat) { Workbook workbook = addGuarantorSheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); @@ -129,19 +127,20 @@ public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator { int rowIndex = 1; Row row; Collections.sort(savings, SavingsAccountData.ClientNameComparator); - for(SavingsAccountData savingsAccount : savings) { - if(addGuarantorSheet.getRow(rowIndex)==null) { - row = addGuarantorSheet.createRow(rowIndex++); - } - else { - row=addGuarantorSheet.getRow(rowIndex++); - } - writeString(GuarantorConstants.LOOKUP_SAVINGS_CLIENT_NAME_COL, row, savingsAccount.getClientName() + "(" + savingsAccount.getClientId() + ")"); - writeString(GuarantorConstants.LOOKUP_SAVINGS_ACCOUNT_NO_COL, row,savingsAccount.getAccountNo()); + for (SavingsAccountData savingsAccount : savings) { + if (addGuarantorSheet.getRow(rowIndex) == null) { + row = addGuarantorSheet.createRow(rowIndex++); + } else { + row = addGuarantorSheet.getRow(rowIndex++); } + writeString(GuarantorConstants.LOOKUP_SAVINGS_CLIENT_NAME_COL, row, + savingsAccount.getClientName() + "(" + savingsAccount.getClientId() + ")"); + writeString(GuarantorConstants.LOOKUP_SAVINGS_ACCOUNT_NO_COL, row, savingsAccount.getAccountNo()); + } } - private void populateLoansTable(Sheet addGuarantorSheet,String dateFormat) { + + private void populateLoansTable(Sheet addGuarantorSheet, String dateFormat) { Workbook workbook = addGuarantorSheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); @@ -149,17 +148,18 @@ public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator { int rowIndex = 1; Row row; Collections.sort(loans, LoanAccountData.ClientNameComparator); - for(LoanAccountData loan : loans) { - if(addGuarantorSheet.getRow(rowIndex)==null){ - row = addGuarantorSheet.createRow(rowIndex++); - } - else{ - row= addGuarantorSheet.getRow(rowIndex++); - } - writeString(GuarantorConstants.LOOKUP_CLIENT_NAME_COL, row, loan.getClientName() + "(" + loan.getClientId() + ")"); - writeString(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, row, Long.parseLong(loan.getAccountNo())+"-"+loan.getStatusStringValue()); + for (LoanAccountData loan : loans) { + if (addGuarantorSheet.getRow(rowIndex) == null) { + row = addGuarantorSheet.createRow(rowIndex++); + } else { + row = addGuarantorSheet.getRow(rowIndex++); } + writeString(GuarantorConstants.LOOKUP_CLIENT_NAME_COL, row, loan.getClientName() + "(" + loan.getClientId() + ")"); + writeString(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, row, + Long.parseLong(loan.getAccountNo()) + "-" + loan.getStatusStringValue()); + } } + private void populateGuarantorRelationshipTypes(Sheet addGuarantorSheet, String dateFormat) { Workbook workbook = addGuarantorSheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); @@ -167,96 +167,105 @@ public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator { dateCellStyle.setDataFormat(df); int rowIndex = 1; Row row; - for (CodeValueData relationshipType:guarantorRelationshipTypes) { - if (addGuarantorSheet.getRow(rowIndex)==null){ - row=addGuarantorSheet.createRow(rowIndex++); - }else { - row=addGuarantorSheet.getRow(rowIndex++); + for (CodeValueData relationshipType : guarantorRelationshipTypes) { + if (addGuarantorSheet.getRow(rowIndex) == null) { + row = addGuarantorSheet.createRow(rowIndex++); + } else { + row = addGuarantorSheet.getRow(rowIndex++); } - writeString(GuarantorConstants.LOOKUP_GUARANTOR_RELATIONSHIPS,row,relationshipType.getName()+"-"+relationshipType.getId()); + writeString(GuarantorConstants.LOOKUP_GUARANTOR_RELATIONSHIPS, row, + relationshipType.getName() + "-" + relationshipType.getId()); } } + private void setRules(Sheet worksheet) { - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GuarantorConstants.OFFICE_NAME_COL, GuarantorConstants.OFFICE_NAME_COL); - CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GuarantorConstants.CLIENT_NAME_COL, GuarantorConstants.CLIENT_NAME_COL); - CellRangeAddressList entityofficeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GuarantorConstants.ENTITY_OFFICE_NAME_COL, GuarantorConstants.ENTITY_OFFICE_NAME_COL); - CellRangeAddressList entityclientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GuarantorConstants.ENTITY_ID_COL, GuarantorConstants.ENTITY_ID_COL); - CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GuarantorConstants.LOAN_ACCOUNT_NO_COL, GuarantorConstants.LOAN_ACCOUNT_NO_COL); - CellRangeAddressList savingsaccountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GuarantorConstants.SAVINGS_ID_COL, GuarantorConstants.SAVINGS_ID_COL); - CellRangeAddressList guranterTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - GuarantorConstants.GUARANTO_TYPE_COL, GuarantorConstants.GUARANTO_TYPE_COL); - CellRangeAddressList guranterRelationshipTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GuarantorConstants.OFFICE_NAME_COL, GuarantorConstants.OFFICE_NAME_COL); + CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GuarantorConstants.CLIENT_NAME_COL, GuarantorConstants.CLIENT_NAME_COL); + CellRangeAddressList entityofficeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GuarantorConstants.ENTITY_OFFICE_NAME_COL, GuarantorConstants.ENTITY_OFFICE_NAME_COL); + CellRangeAddressList entityclientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GuarantorConstants.ENTITY_ID_COL, GuarantorConstants.ENTITY_ID_COL); + CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GuarantorConstants.LOAN_ACCOUNT_NO_COL, GuarantorConstants.LOAN_ACCOUNT_NO_COL); + CellRangeAddressList savingsaccountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GuarantorConstants.SAVINGS_ID_COL, GuarantorConstants.SAVINGS_ID_COL); + CellRangeAddressList guranterTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + GuarantorConstants.GUARANTO_TYPE_COL, GuarantorConstants.GUARANTO_TYPE_COL); + CellRangeAddressList guranterRelationshipTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL); - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); - setNames(worksheet); + setNames(worksheet); - DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint clientNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))"); - DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); - DataValidationConstraint savingsaccountNumberConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"SavingsAccount_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($G1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); - DataValidationConstraint guranterTypeConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.GUARANTOR_INTERNAL, - TemplatePopulateImportConstants.GUARANTOR_EXTERNAL}); - DataValidationConstraint guarantorRelationshipConstraint = validationHelper.createFormulaListConstraint("GuarantorRelationship"); - DataValidationConstraint entityofficeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint entityclientNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$F1))"); + DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); + DataValidationConstraint clientNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))"); + DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint( + "INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); + DataValidationConstraint savingsaccountNumberConstraint = validationHelper.createFormulaListConstraint( + "INDIRECT(CONCATENATE(\"SavingsAccount_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($G1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); + DataValidationConstraint guranterTypeConstraint = validationHelper.createExplicitListConstraint( + new String[] { TemplatePopulateImportConstants.GUARANTOR_INTERNAL, TemplatePopulateImportConstants.GUARANTOR_EXTERNAL }); + DataValidationConstraint guarantorRelationshipConstraint = validationHelper.createFormulaListConstraint("GuarantorRelationship"); + DataValidationConstraint entityofficeNameConstraint = validationHelper.createFormulaListConstraint("Office"); + DataValidationConstraint entityclientNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$F1))"); - DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); - DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); - DataValidation accountNumberValidation = validationHelper.createValidation(accountNumberConstraint, accountNumberRange); - DataValidation savingsaccountNumberValidation = validationHelper.createValidation(savingsaccountNumberConstraint, savingsaccountNumberRange); - DataValidation guranterTypeValidation = validationHelper.createValidation(guranterTypeConstraint, guranterTypeRange); - DataValidation guarantorRelationshipValidation=validationHelper.createValidation(guarantorRelationshipConstraint,guranterRelationshipTypeRange); - DataValidation entityofficeValidation = validationHelper.createValidation(entityofficeNameConstraint, entityofficeNameRange); - DataValidation entityclientValidation = validationHelper.createValidation(entityclientNameConstraint, entityclientNameRange); + DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); + DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); + DataValidation accountNumberValidation = validationHelper.createValidation(accountNumberConstraint, accountNumberRange); + DataValidation savingsaccountNumberValidation = validationHelper.createValidation(savingsaccountNumberConstraint, + savingsaccountNumberRange); + DataValidation guranterTypeValidation = validationHelper.createValidation(guranterTypeConstraint, guranterTypeRange); + DataValidation guarantorRelationshipValidation = validationHelper.createValidation(guarantorRelationshipConstraint, + guranterRelationshipTypeRange); + DataValidation entityofficeValidation = validationHelper.createValidation(entityofficeNameConstraint, entityofficeNameRange); + DataValidation entityclientValidation = validationHelper.createValidation(entityclientNameConstraint, entityclientNameRange); - - worksheet.addValidationData(officeValidation); - worksheet.addValidationData(clientValidation); - worksheet.addValidationData(accountNumberValidation); - worksheet.addValidationData(guranterTypeValidation); - worksheet.addValidationData(guarantorRelationshipValidation); - worksheet.addValidationData(entityofficeValidation); - worksheet.addValidationData(entityclientValidation); - worksheet.addValidationData(savingsaccountNumberValidation); + worksheet.addValidationData(officeValidation); + worksheet.addValidationData(clientValidation); + worksheet.addValidationData(accountNumberValidation); + worksheet.addValidationData(guranterTypeValidation); + worksheet.addValidationData(guarantorRelationshipValidation); + worksheet.addValidationData(entityofficeValidation); + worksheet.addValidationData(entityclientValidation); + worksheet.addValidationData(savingsaccountNumberValidation); } + private void setNames(Sheet worksheet) { Workbook addGurarantorWorkbook = worksheet.getWorkbook(); ArrayList officeNames = new ArrayList(officeSheetPopulator.getOfficeNames()); - //Office Names + // Office Names Name officeGroup = addGurarantorWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (officeNames.size() + 1)); - //GurantorRelationshipTypes Names + // GurantorRelationshipTypes Names Name guarantorRelationshipsGroup = addGurarantorWorkbook.createName(); guarantorRelationshipsGroup.setNameName("GuarantorRelationship"); - guarantorRelationshipsGroup.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CH$2:$CH$" + (guarantorRelationshipTypes.size() + 1)); + guarantorRelationshipsGroup.setRefersToFormula( + TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME + "!$CH$2:$CH$" + (guarantorRelationshipTypes.size() + 1)); - //Clients Named after Offices - for(Integer i = 0; i < officeNames.size(); i++) { + // Clients Named after Offices + for (Integer i = 0; i < officeNames.size(); i++) { Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator.getOfficeNameToBeginEndIndexesOfClients().get(i); Name name = addGurarantorWorkbook.createName(); - if(officeNameToBeginEndIndexesOfClients != null) { - name.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + - ":$B$" + officeNameToBeginEndIndexesOfClients[1]); + if (officeNameToBeginEndIndexesOfClients != null) { + name.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); + name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME + "!$B$" + officeNameToBeginEndIndexesOfClients[0] + + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); } } - //Counting clients with active loans and starting and end addresses of cells + // Counting clients with active loans and starting and end addresses of + // cells HashMap clientNameToBeginEndIndexes = new HashMap(); ArrayList clientsWithActiveLoans = new ArrayList(); ArrayList clientIdsWithActiveLoans = new ArrayList(); @@ -264,56 +273,60 @@ public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator { int endIndex = 1; String clientName = ""; String clientId = ""; - for(int i = 0; i < loans.size(); i++){ - if(!clientName.equals(loans.get(i).getClientName())) { + for (int i = 0; i < loans.size(); i++) { + if (!clientName.equals(loans.get(i).getClientName())) { endIndex = i + 1; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); startIndex = i + 2; clientName = loans.get(i).getClientName(); clientId = loans.get(i).getClientId().toString(); clientsWithActiveLoans.add(clientName); clientIdsWithActiveLoans.add(clientId); } - if(i == loans.size()-1) { + if (i == loans.size() - 1) { endIndex = i + 2; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); } } - //Account Number Named after Clients - for(int j = 0; j < clientsWithActiveLoans.size(); j++) { + // Account Number Named after Clients + for (int j = 0; j < clientsWithActiveLoans.size(); j++) { Name name = addGurarantorWorkbook.createName(); name.setNameName("Account_" + clientsWithActiveLoans.get(j).replaceAll(" ", "_") + "_" + clientIdsWithActiveLoans.get(j) + "_"); - name.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CE$" + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[0] + - ":$CE$" + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[1]); + name.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME + "!$CE$" + + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[0] + ":$CE$" + + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[1]); } - ///savings - //Counting clients with active savings and starting and end addresses of cells for naming + /// savings + // Counting clients with active savings and starting and end addresses + /// of cells for naming ArrayList clientsWithActiveSavings = new ArrayList(); ArrayList clientIdsWithActiveSavings = new ArrayList(); - clientName=""; - clientId=""; - for(int i = 0; i < savings.size(); i++){ - if(!clientName.equals(savings.get(i).getClientName())) { + clientName = ""; + clientId = ""; + for (int i = 0; i < savings.size(); i++) { + if (!clientName.equals(savings.get(i).getClientName())) { endIndex = i + 1; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); startIndex = i + 2; clientName = savings.get(i).getClientName(); clientId = savings.get(i).getClientId().toString(); clientsWithActiveSavings.add(clientName); clientIdsWithActiveSavings.add(clientId); } - if(i == savings.size()-1) { + if (i == savings.size() - 1) { endIndex = i + 2; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); } } - //Account Number Named after Clients - for(int j = 0; j < clientsWithActiveSavings.size(); j++) { + // Account Number Named after Clients + for (int j = 0; j < clientsWithActiveSavings.size(); j++) { Name name = addGurarantorWorkbook.createName(); - name.setNameName("SavingsAccount_" + clientsWithActiveSavings.get(j).replaceAll(" ", "_") + "_" + clientIdsWithActiveSavings.get(j) + "_"); - name.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CG$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[0] + - ":$CG$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[1]); + name.setNameName("SavingsAccount_" + clientsWithActiveSavings.get(j).replaceAll(" ", "_") + "_" + + clientIdsWithActiveSavings.get(j) + "_"); + name.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME + "!$CG$" + + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[0] + ":$CG$" + + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[1]); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/journalentry/JournalEntriesWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/journalentry/JournalEntriesWorkbookPopulator.java index ba9db9689..c455d6ad4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/journalentry/JournalEntriesWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/journalentry/JournalEntriesWorkbookPopulator.java @@ -37,26 +37,25 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddressList; - public class JournalEntriesWorkbookPopulator extends AbstractWorkbookPopulator { private OfficeSheetPopulator officeSheetPopulator; private GlAccountSheetPopulator glAccountSheetPopulator; private ExtrasSheetPopulator extrasSheetPopulator; - public JournalEntriesWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - GlAccountSheetPopulator glAccountSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) { + public JournalEntriesWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, GlAccountSheetPopulator glAccountSheetPopulator, + ExtrasSheetPopulator extrasSheetPopulator) { this.officeSheetPopulator = officeSheetPopulator; this.glAccountSheetPopulator = glAccountSheetPopulator; this.extrasSheetPopulator = extrasSheetPopulator; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet addJournalEntriesSheet = workbook.createSheet(TemplatePopulateImportConstants.JOURNAL_ENTRY_SHEET_NAME); - officeSheetPopulator.populate(workbook,dateFormat); - glAccountSheetPopulator.populate(workbook,dateFormat); - extrasSheetPopulator.populate(workbook,dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + glAccountSheetPopulator.populate(workbook, dateFormat); + extrasSheetPopulator.populate(workbook, dateFormat); setRules(addJournalEntriesSheet); setDefaults(addJournalEntriesSheet); setLayout(addJournalEntriesSheet); @@ -66,20 +65,20 @@ public class JournalEntriesWorkbookPopulator extends AbstractWorkbookPopulator { Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); worksheet.setColumnWidth(JournalEntryConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.TRANSACION_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.CURRENCY_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.PAYMENT_TYPE_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.TRANSACTION_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.AMOUNT_CREDIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.AMOUNT_DEBIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.ACCOUNT_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.CHECK_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.ROUTING_CODE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.RECEIPT_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.BANK_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(JournalEntryConstants.COMMENTS_COL,TemplatePopulateImportConstants.EXTRALARGE_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.TRANSACION_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.CURRENCY_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.PAYMENT_TYPE_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.TRANSACTION_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.AMOUNT_CREDIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.AMOUNT_DEBIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.CHECK_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.ROUTING_CODE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.RECEIPT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.BANK_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(JournalEntryConstants.COMMENTS_COL, TemplatePopulateImportConstants.EXTRALARGE_COL_SIZE); writeString(JournalEntryConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); writeString(JournalEntryConstants.TRANSACION_ON_DATE_COL, rowHeader, "Transaction On *"); @@ -90,12 +89,12 @@ public class JournalEntriesWorkbookPopulator extends AbstractWorkbookPopulator { writeString(JournalEntryConstants.AMOUNT_CREDIT_COL, rowHeader, "Amount*"); writeString(JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, rowHeader, "Debit Account Type*"); writeString(JournalEntryConstants.AMOUNT_DEBIT_COL, rowHeader, "Amount*"); - writeString(JournalEntryConstants.ACCOUNT_NO_COL,rowHeader,"Account#"); - writeString(JournalEntryConstants.CHECK_NO_COL,rowHeader,"Cheque#"); - writeString(JournalEntryConstants.ROUTING_CODE_COL,rowHeader,"Routing code"); - writeString(JournalEntryConstants.RECEIPT_NO_COL,rowHeader,"Receipt#"); - writeString(JournalEntryConstants.BANK_NO_COL,rowHeader,"Bank#"); - writeString(JournalEntryConstants.COMMENTS_COL,rowHeader,"Comments"); + writeString(JournalEntryConstants.ACCOUNT_NO_COL, rowHeader, "Account#"); + writeString(JournalEntryConstants.CHECK_NO_COL, rowHeader, "Cheque#"); + writeString(JournalEntryConstants.ROUTING_CODE_COL, rowHeader, "Routing code"); + writeString(JournalEntryConstants.RECEIPT_NO_COL, rowHeader, "Receipt#"); + writeString(JournalEntryConstants.BANK_NO_COL, rowHeader, "Bank#"); + writeString(JournalEntryConstants.COMMENTS_COL, rowHeader, "Comments"); // TODO Auto-generated method stub @@ -103,60 +102,45 @@ public class JournalEntriesWorkbookPopulator extends AbstractWorkbookPopulator { private void setRules(Sheet worksheet) { - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), - JournalEntryConstants.OFFICE_NAME_COL,JournalEntryConstants. OFFICE_NAME_COL); + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + JournalEntryConstants.OFFICE_NAME_COL, JournalEntryConstants.OFFICE_NAME_COL); - CellRangeAddressList currencyCodeRange = new CellRangeAddressList( - 1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - JournalEntryConstants.CURRENCY_NAME_COL, JournalEntryConstants.CURRENCY_NAME_COL); + CellRangeAddressList currencyCodeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + JournalEntryConstants.CURRENCY_NAME_COL, JournalEntryConstants.CURRENCY_NAME_COL); - CellRangeAddressList paymenttypeRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), - JournalEntryConstants.PAYMENT_TYPE_ID_COL, JournalEntryConstants.PAYMENT_TYPE_ID_COL); + CellRangeAddressList paymenttypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + JournalEntryConstants.PAYMENT_TYPE_ID_COL, JournalEntryConstants.PAYMENT_TYPE_ID_COL); - CellRangeAddressList glaccountCreditRange = new CellRangeAddressList( - 1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL); + CellRangeAddressList glaccountCreditRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL); - CellRangeAddressList glaccountDebitRange = new CellRangeAddressList( - 1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL); + CellRangeAddressList glaccountDebitRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL); - DataValidationHelper validationHelper = new HSSFDataValidationHelper( - (HSSFSheet) worksheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); - setNames(worksheet); + setNames(worksheet); - DataValidationConstraint officeNameConstraint = validationHelper - .createFormulaListConstraint("Office"); - DataValidationConstraint currencyCodeConstraint = validationHelper - .createFormulaListConstraint("Currency"); - DataValidationConstraint paymentTypeConstraint = validationHelper - .createFormulaListConstraint("PaymentType"); + DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); + DataValidationConstraint currencyCodeConstraint = validationHelper.createFormulaListConstraint("Currency"); + DataValidationConstraint paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentType"); - DataValidationConstraint glaccountConstraint = validationHelper - .createFormulaListConstraint("GlAccounts"); + DataValidationConstraint glaccountConstraint = validationHelper.createFormulaListConstraint("GlAccounts"); - DataValidation officeValidation = validationHelper - .createValidation(officeNameConstraint, officeNameRange); - DataValidation currencyCodeValidation = validationHelper - .createValidation(currencyCodeConstraint, currencyCodeRange); - DataValidation paymentTypeValidation = validationHelper - .createValidation(paymentTypeConstraint, paymenttypeRange); + DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); + DataValidation currencyCodeValidation = validationHelper.createValidation(currencyCodeConstraint, currencyCodeRange); + DataValidation paymentTypeValidation = validationHelper.createValidation(paymentTypeConstraint, paymenttypeRange); - DataValidation glaccountCreditValidation = validationHelper - .createValidation(glaccountConstraint, glaccountCreditRange); - DataValidation glaccountDebitValidation = validationHelper - .createValidation(glaccountConstraint, glaccountDebitRange); + DataValidation glaccountCreditValidation = validationHelper.createValidation(glaccountConstraint, glaccountCreditRange); + DataValidation glaccountDebitValidation = validationHelper.createValidation(glaccountConstraint, glaccountDebitRange); - worksheet.addValidationData(officeValidation); - worksheet.addValidationData(currencyCodeValidation); - worksheet.addValidationData(paymentTypeValidation); + worksheet.addValidationData(officeValidation); + worksheet.addValidationData(currencyCodeValidation); + worksheet.addValidationData(paymentTypeValidation); - worksheet.addValidationData(glaccountCreditValidation); - worksheet.addValidationData(glaccountDebitValidation); - } + worksheet.addValidationData(glaccountCreditValidation); + worksheet.addValidationData(glaccountDebitValidation); + } private void setNames(Sheet worksheet) { Workbook addJournalEntriesWorkbook = worksheet.getWorkbook(); @@ -164,23 +148,22 @@ public class JournalEntriesWorkbookPopulator extends AbstractWorkbookPopulator { // Office Names Name officeGroup = addJournalEntriesWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" - + (officeNames.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (officeNames.size() + 1)); // Payment Type Name Name paymentTypeGroup = addJournalEntriesWorkbook.createName(); paymentTypeGroup.setNameName("PaymentType"); - paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$" - + (extrasSheetPopulator.getPaymentTypesSize() + 1)); + paymentTypeGroup.setRefersToFormula( + TemplatePopulateImportConstants.EXTRAS_SHEET_NAME + "!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); // Currency Type Name Name currencyGroup = addJournalEntriesWorkbook.createName(); currencyGroup.setNameName("Currency"); - currencyGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$F$2:$F$" - + (extrasSheetPopulator.getCurrenciesSize() + 1)); + currencyGroup.setRefersToFormula( + TemplatePopulateImportConstants.EXTRAS_SHEET_NAME + "!$F$2:$F$" + (extrasSheetPopulator.getCurrenciesSize() + 1)); // Account Name Name glaccountGroup = addJournalEntriesWorkbook.createName(); glaccountGroup.setNameName("GlAccounts"); - glaccountGroup.setRefersToFormula(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME+"!$B$2:$B$" + glaccountGroup.setRefersToFormula(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME + "!$B$2:$B$" + (glAccountSheetPopulator.getGlAccountNamesSize() + 1)); } @@ -191,6 +174,4 @@ public class JournalEntriesWorkbookPopulator extends AbstractWorkbookPopulator { } - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/loan/LoanWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/loan/LoanWorkbookPopulator.java index 28cc26b39..af5c19917 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/loan/LoanWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/loan/LoanWorkbookPopulator.java @@ -53,7 +53,6 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { private LoanProductSheetPopulator productSheetPopulator; private ExtrasSheetPopulator extrasSheetPopulator; - public LoanWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, ClientSheetPopulator clientSheetPopulator, GroupSheetPopulator groupSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, LoanProductSheetPopulator productSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) { @@ -66,92 +65,84 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet loanSheet = workbook.createSheet(TemplatePopulateImportConstants.LOANS_SHEET_NAME); - officeSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); - groupSheetPopulator.populate(workbook,dateFormat); - personnelSheetPopulator.populate(workbook,dateFormat); - productSheetPopulator.populate(workbook,dateFormat); - extrasSheetPopulator.populate(workbook,dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); + groupSheetPopulator.populate(workbook, dateFormat); + personnelSheetPopulator.populate(workbook, dateFormat); + productSheetPopulator.populate(workbook, dateFormat); + extrasSheetPopulator.populate(workbook, dateFormat); setLayout(loanSheet); - setRules(loanSheet,dateFormat); + setRules(loanSheet, dateFormat); setDefaults(loanSheet); setClientAndGroupDateLookupTable(loanSheet, clientSheetPopulator.getClients(), groupSheetPopulator.getGroups(), LoanConstants.LOOKUP_CLIENT_NAME_COL, LoanConstants.LOOKUP_ACTIVATION_DATE_COL, - TemplatePopulateImportConstants.CONTAINS_CLIENT_EXTERNAL_ID,dateFormat); + TemplatePopulateImportConstants.CONTAINS_CLIENT_EXTERNAL_ID, dateFormat); } - private void setRules(Sheet worksheet,String dateFormat) { + private void setRules(Sheet worksheet, String dateFormat) { CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.OFFICE_NAME_COL, LoanConstants.OFFICE_NAME_COL); CellRangeAddressList loanTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.LOAN_TYPE_COL, LoanConstants.LOAN_TYPE_COL); CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.CLIENT_NAME_COL, LoanConstants.CLIENT_NAME_COL); - CellRangeAddressList productNameRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.PRODUCT_COL, LoanConstants.PRODUCT_COL); - CellRangeAddressList loanOfficerRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.LOAN_OFFICER_NAME_COL, LoanConstants.LOAN_OFFICER_NAME_COL); - CellRangeAddressList submittedDateRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.SUBMITTED_ON_DATE_COL,LoanConstants. SUBMITTED_ON_DATE_COL); + CellRangeAddressList productNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.PRODUCT_COL, LoanConstants.PRODUCT_COL); + CellRangeAddressList loanOfficerRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.LOAN_OFFICER_NAME_COL, LoanConstants.LOAN_OFFICER_NAME_COL); + CellRangeAddressList submittedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.SUBMITTED_ON_DATE_COL, LoanConstants.SUBMITTED_ON_DATE_COL); CellRangeAddressList fundNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.FUND_NAME_COL, LoanConstants.FUND_NAME_COL); CellRangeAddressList principalRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - LoanConstants.PRINCIPAL_COL,LoanConstants.PRINCIPAL_COL); - CellRangeAddressList noOfRepaymentsRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.NO_OF_REPAYMENTS_COL, LoanConstants.NO_OF_REPAYMENTS_COL); - CellRangeAddressList repaidFrequencyRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.REPAID_EVERY_FREQUENCY_COL, LoanConstants.REPAID_EVERY_FREQUENCY_COL); + LoanConstants.PRINCIPAL_COL, LoanConstants.PRINCIPAL_COL); + CellRangeAddressList noOfRepaymentsRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.NO_OF_REPAYMENTS_COL, LoanConstants.NO_OF_REPAYMENTS_COL); + CellRangeAddressList repaidFrequencyRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.REPAID_EVERY_FREQUENCY_COL, LoanConstants.REPAID_EVERY_FREQUENCY_COL); CellRangeAddressList loanTermRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.LOAN_TERM_COL, LoanConstants.LOAN_TERM_COL); - CellRangeAddressList loanTermFrequencyRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.LOAN_TERM_FREQUENCY_COL, LoanConstants.LOAN_TERM_FREQUENCY_COL); - CellRangeAddressList interestFrequencyRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(),LoanConstants.NOMINAL_INTEREST_RATE_FREQUENCY_COL, - LoanConstants.NOMINAL_INTEREST_RATE_FREQUENCY_COL); + CellRangeAddressList loanTermFrequencyRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.LOAN_TERM_FREQUENCY_COL, LoanConstants.LOAN_TERM_FREQUENCY_COL); + CellRangeAddressList interestFrequencyRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.NOMINAL_INTEREST_RATE_FREQUENCY_COL, LoanConstants.NOMINAL_INTEREST_RATE_FREQUENCY_COL); CellRangeAddressList interestRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.NOMINAL_INTEREST_RATE_COL, LoanConstants.NOMINAL_INTEREST_RATE_COL); - CellRangeAddressList amortizationRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.AMORTIZATION_COL, LoanConstants.AMORTIZATION_COL); - CellRangeAddressList interestMethodRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.INTEREST_METHOD_COL, LoanConstants.INTEREST_METHOD_COL); - CellRangeAddressList intrestCalculationPeriodRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.INTEREST_CALCULATION_PERIOD_COL, - LoanConstants.INTEREST_CALCULATION_PERIOD_COL); - CellRangeAddressList repaymentStrategyRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.REPAYMENT_STRATEGY_COL,LoanConstants. REPAYMENT_STRATEGY_COL); - CellRangeAddressList arrearsToleranceRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.ARREARS_TOLERANCE_COL,LoanConstants. ARREARS_TOLERANCE_COL); - CellRangeAddressList graceOnPrincipalPaymentRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL, - LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL); - CellRangeAddressList graceOnInterestPaymentRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL, - LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL); - CellRangeAddressList graceOnInterestChargedRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.GRACE_ON_INTEREST_CHARGED_COL, - LoanConstants.GRACE_ON_INTEREST_CHARGED_COL); - CellRangeAddressList approvedDateRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.APPROVED_DATE_COL, LoanConstants.APPROVED_DATE_COL); - CellRangeAddressList disbursedDateRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.DISBURSED_DATE_COL, LoanConstants.DISBURSED_DATE_COL); - CellRangeAddressList paymentTypeRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.DISBURSED_PAYMENT_TYPE_COL, LoanConstants.DISBURSED_PAYMENT_TYPE_COL); - CellRangeAddressList repaymentTypeRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.REPAYMENT_TYPE_COL,LoanConstants. REPAYMENT_TYPE_COL); - CellRangeAddressList lastrepaymentDateRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanConstants.LAST_REPAYMENT_DATE_COL, LoanConstants.LAST_REPAYMENT_DATE_COL); + CellRangeAddressList amortizationRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.AMORTIZATION_COL, LoanConstants.AMORTIZATION_COL); + CellRangeAddressList interestMethodRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.INTEREST_METHOD_COL, LoanConstants.INTEREST_METHOD_COL); + CellRangeAddressList intrestCalculationPeriodRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.INTEREST_CALCULATION_PERIOD_COL, LoanConstants.INTEREST_CALCULATION_PERIOD_COL); + CellRangeAddressList repaymentStrategyRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.REPAYMENT_STRATEGY_COL, LoanConstants.REPAYMENT_STRATEGY_COL); + CellRangeAddressList arrearsToleranceRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.ARREARS_TOLERANCE_COL, LoanConstants.ARREARS_TOLERANCE_COL); + CellRangeAddressList graceOnPrincipalPaymentRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL, LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL); + CellRangeAddressList graceOnInterestPaymentRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL, LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL); + CellRangeAddressList graceOnInterestChargedRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.GRACE_ON_INTEREST_CHARGED_COL, LoanConstants.GRACE_ON_INTEREST_CHARGED_COL); + CellRangeAddressList approvedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.APPROVED_DATE_COL, LoanConstants.APPROVED_DATE_COL); + CellRangeAddressList disbursedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.DISBURSED_DATE_COL, LoanConstants.DISBURSED_DATE_COL); + CellRangeAddressList paymentTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.DISBURSED_PAYMENT_TYPE_COL, LoanConstants.DISBURSED_PAYMENT_TYPE_COL); + CellRangeAddressList repaymentTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.REPAYMENT_TYPE_COL, LoanConstants.REPAYMENT_TYPE_COL); + CellRangeAddressList lastrepaymentDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanConstants.LAST_REPAYMENT_DATE_COL, LoanConstants.LAST_REPAYMENT_DATE_COL); DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); setNames(worksheet); DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint loanTypeConstraint = validationHelper - .createExplicitListConstraint(new String[] { - LoanConstants.LOAN_TYPE_INDIVIDUAL, - LoanConstants.LOAN_TYPE_GROUP, - LoanConstants.LOAN_TYPE_JLG}); + DataValidationConstraint loanTypeConstraint = validationHelper.createExplicitListConstraint( + new String[] { LoanConstants.LOAN_TYPE_INDIVIDUAL, LoanConstants.LOAN_TYPE_GROUP, LoanConstants.LOAN_TYPE_JLG }); DataValidationConstraint clientNameConstraint = validationHelper.createFormulaListConstraint( "IF($B1=\"Group\",INDIRECT(CONCATENATE(\"Group_\",$A1)),INDIRECT(CONCATENATE(\"Client_\",$A1)))"); DataValidationConstraint productNameConstraint = validationHelper.createFormulaListConstraint("Products"); @@ -162,8 +153,7 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { "=IF(INDIRECT(CONCATENATE(\"START_DATE_\",$E1))>VLOOKUP($C1,$AR$2:$AT$" + (clientSheetPopulator.getClientsSize() + groupSheetPopulator.getGroupsSize() + 1) + ",3,FALSE),INDIRECT(CONCATENATE(\"START_DATE_\",$E1)),VLOOKUP($C1,$AR$2:$AT$" - + (clientSheetPopulator.getClientsSize() + groupSheetPopulator.getGroupsSize() + 1) - + ",3,FALSE))", + + (clientSheetPopulator.getClientsSize() + groupSheetPopulator.getGroupsSize() + 1) + ",3,FALSE))", "=TODAY()", dateFormat); DataValidationConstraint approvalDateConstraint = validationHelper .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$G1", "=TODAY()", dateFormat); @@ -192,10 +182,9 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { .createExplicitListConstraint(new String[] { "Flat", "Declining Balance" }); DataValidationConstraint interestCalculationPeriodConstraint = validationHelper .createExplicitListConstraint(new String[] { "Daily", "Same as repayment period" }); - DataValidationConstraint repaymentStrategyConstraint = validationHelper.createExplicitListConstraint( - new String[] { "Penalties, Fees, Interest, Principal order", "HeavensFamily Unique", "Creocore Unique", - "Overdue/Due Fee/Int,Principal", "Principal, Interest, Penalties, Fees Order", - "Interest, Principal, Penalties, Fees Order", "Early Repayment Strategy" }); + DataValidationConstraint repaymentStrategyConstraint = validationHelper.createExplicitListConstraint(new String[] { + "Penalties, Fees, Interest, Principal order", "HeavensFamily Unique", "Creocore Unique", "Overdue/Due Fee/Int,Principal", + "Principal, Interest, Penalties, Fees Order", "Interest, Principal, Penalties, Fees Order", "Early Repayment Strategy" }); DataValidationConstraint arrearsToleranceConstraint = validationHelper .createIntegerConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0", null); DataValidationConstraint graceOnPrincipalPaymentConstraint = validationHelper @@ -210,50 +199,34 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); DataValidation loanTypeValidation = validationHelper.createValidation(loanTypeConstraint, loanTypeRange); DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); - DataValidation productNameValidation = validationHelper.createValidation(productNameConstraint, - productNameRange); - DataValidation loanOfficerValidation = validationHelper.createValidation(loanOfficerNameConstraint, - loanOfficerRange); + DataValidation productNameValidation = validationHelper.createValidation(productNameConstraint, productNameRange); + DataValidation loanOfficerValidation = validationHelper.createValidation(loanOfficerNameConstraint, loanOfficerRange); DataValidation fundNameValidation = validationHelper.createValidation(fundNameConstraint, fundNameRange); - DataValidation repaidFrequencyValidation = validationHelper.createValidation(frequencyConstraint, - repaidFrequencyRange); - DataValidation loanTermFrequencyValidation = validationHelper.createValidation(frequencyConstraint, - loanTermFrequencyRange); - DataValidation amortizationValidation = validationHelper.createValidation(amortizationConstraint, - amortizationRange); - DataValidation interestMethodValidation = validationHelper.createValidation(interestMethodConstraint, - interestMethodRange); - DataValidation interestCalculationPeriodValidation = validationHelper - .createValidation(interestCalculationPeriodConstraint, intrestCalculationPeriodRange); - DataValidation repaymentStrategyValidation = validationHelper.createValidation(repaymentStrategyConstraint, - repaymentStrategyRange); - DataValidation paymentTypeValidation = validationHelper.createValidation(paymentTypeConstraint, - paymentTypeRange); - DataValidation repaymentTypeValidation = validationHelper.createValidation(paymentTypeConstraint, - repaymentTypeRange); - DataValidation submittedDateValidation = validationHelper.createValidation(submittedDateConstraint, - submittedDateRange); - DataValidation approvalDateValidation = validationHelper.createValidation(approvalDateConstraint, - approvedDateRange); - DataValidation disbursedDateValidation = validationHelper.createValidation(disbursedDateConstraint, - disbursedDateRange); - DataValidation lastRepaymentDateValidation = validationHelper.createValidation(lastRepaymentDateConstraint, - lastrepaymentDateRange); + DataValidation repaidFrequencyValidation = validationHelper.createValidation(frequencyConstraint, repaidFrequencyRange); + DataValidation loanTermFrequencyValidation = validationHelper.createValidation(frequencyConstraint, loanTermFrequencyRange); + DataValidation amortizationValidation = validationHelper.createValidation(amortizationConstraint, amortizationRange); + DataValidation interestMethodValidation = validationHelper.createValidation(interestMethodConstraint, interestMethodRange); + DataValidation interestCalculationPeriodValidation = validationHelper.createValidation(interestCalculationPeriodConstraint, + intrestCalculationPeriodRange); + DataValidation repaymentStrategyValidation = validationHelper.createValidation(repaymentStrategyConstraint, repaymentStrategyRange); + DataValidation paymentTypeValidation = validationHelper.createValidation(paymentTypeConstraint, paymentTypeRange); + DataValidation repaymentTypeValidation = validationHelper.createValidation(paymentTypeConstraint, repaymentTypeRange); + DataValidation submittedDateValidation = validationHelper.createValidation(submittedDateConstraint, submittedDateRange); + DataValidation approvalDateValidation = validationHelper.createValidation(approvalDateConstraint, approvedDateRange); + DataValidation disbursedDateValidation = validationHelper.createValidation(disbursedDateConstraint, disbursedDateRange); + DataValidation lastRepaymentDateValidation = validationHelper.createValidation(lastRepaymentDateConstraint, lastrepaymentDateRange); DataValidation principalValidation = validationHelper.createValidation(principalConstraint, principalRange); DataValidation loanTermValidation = validationHelper.createValidation(loanTermConstraint, loanTermRange); - DataValidation noOfRepaymentsValidation = validationHelper.createValidation(noOfRepaymentsConstraint, - noOfRepaymentsRange); + DataValidation noOfRepaymentsValidation = validationHelper.createValidation(noOfRepaymentsConstraint, noOfRepaymentsRange); DataValidation interestValidation = validationHelper.createValidation(interestConstraint, interestRange); - DataValidation arrearsToleranceValidation = validationHelper.createValidation(arrearsToleranceConstraint, - arrearsToleranceRange); - DataValidation graceOnPrincipalPaymentValidation = validationHelper - .createValidation(graceOnPrincipalPaymentConstraint, graceOnPrincipalPaymentRange); - DataValidation graceOnInterestPaymentValidation = validationHelper - .createValidation(graceOnInterestPaymentConstraint, graceOnInterestPaymentRange); - DataValidation graceOnInterestChargedValidation = validationHelper - .createValidation(graceOnInterestChargedConstraint, graceOnInterestChargedRange); - DataValidation interestFrequencyValidation = validationHelper.createValidation(interestFrequencyConstraint, - interestFrequencyRange); + DataValidation arrearsToleranceValidation = validationHelper.createValidation(arrearsToleranceConstraint, arrearsToleranceRange); + DataValidation graceOnPrincipalPaymentValidation = validationHelper.createValidation(graceOnPrincipalPaymentConstraint, + graceOnPrincipalPaymentRange); + DataValidation graceOnInterestPaymentValidation = validationHelper.createValidation(graceOnInterestPaymentConstraint, + graceOnInterestPaymentRange); + DataValidation graceOnInterestChargedValidation = validationHelper.createValidation(graceOnInterestChargedConstraint, + graceOnInterestChargedRange); + DataValidation interestFrequencyValidation = validationHelper.createValidation(interestFrequencyConstraint, interestFrequencyRange); interestFrequencyValidation.setSuppressDropDownArrow(true); @@ -293,7 +266,7 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.setColumnWidth(LoanConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanConstants.LOAN_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanConstants.CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.CLIENT_EXTERNAL_ID,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.CLIENT_EXTERNAL_ID, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(LoanConstants.PRODUCT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanConstants.LOAN_OFFICER_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanConstants.SUBMITTED_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); @@ -322,23 +295,23 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.setColumnWidth(LoanConstants.TOTAL_AMOUNT_REPAID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanConstants.LAST_REPAYMENT_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanConstants.REPAYMENT_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.LOOKUP_CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.LOOKUP_CLIENT_EXTERNAL_ID,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.LOOKUP_ACTIVATION_DATE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.CHARGE_ID_1, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.CHARGE_AMOUNT_1, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.CHARGE_DUE_DATE_1, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.CHARGE_ID_2, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.CHARGE_AMOUNT_2, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.CHARGE_DUE_DATE_2, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.GROUP_ID, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanConstants.LINK_ACCOUNT_ID, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.LOOKUP_CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.LOOKUP_CLIENT_EXTERNAL_ID, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.LOOKUP_ACTIVATION_DATE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.CHARGE_ID_1, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.CHARGE_AMOUNT_1, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.CHARGE_DUE_DATE_1, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.CHARGE_ID_2, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.CHARGE_AMOUNT_2, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.CHARGE_DUE_DATE_2, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.GROUP_ID, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanConstants.LINK_ACCOUNT_ID, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); writeString(LoanConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); writeString(LoanConstants.LOAN_TYPE_COL, rowHeader, "Loan Type*"); writeString(LoanConstants.CLIENT_NAME_COL, rowHeader, "Client/Group Name*"); - writeString(LoanConstants.CLIENT_EXTERNAL_ID,rowHeader,"Client ExternalID"); + writeString(LoanConstants.CLIENT_EXTERNAL_ID, rowHeader, "Client ExternalID"); writeString(LoanConstants.PRODUCT_COL, rowHeader, "Product*"); writeString(LoanConstants.LOAN_OFFICER_NAME_COL, rowHeader, "Loan Officer*"); writeString(LoanConstants.SUBMITTED_ON_DATE_COL, rowHeader, "Submitted On*"); @@ -365,7 +338,7 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { writeString(LoanConstants.LAST_REPAYMENT_DATE_COL, rowHeader, "Date-Last Repayment"); writeString(LoanConstants.REPAYMENT_TYPE_COL, rowHeader, "Repayment Type"); writeString(LoanConstants.LOOKUP_CLIENT_NAME_COL, rowHeader, "Client Name"); - writeString(LoanConstants.LOOKUP_CLIENT_EXTERNAL_ID,rowHeader,"Lookup Client ExternalID"); + writeString(LoanConstants.LOOKUP_CLIENT_EXTERNAL_ID, rowHeader, "Lookup Client ExternalID"); writeString(LoanConstants.LOOKUP_ACTIVATION_DATE_COL, rowHeader, "Client Activation Date"); writeString(LoanConstants.EXTERNAL_ID_COL, rowHeader, "External Id"); writeString(LoanConstants.CHARGE_ID_1, rowHeader, "Charge Id"); @@ -385,7 +358,7 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { for (int colNo = 0; colNo < 35; colNo++) { Cell cell = rowHeader.getCell(colNo); if (cell == null) { - rowHeader.createCell(colNo); + rowHeader.createCell(colNo); } rowHeader.getCell(colNo).setCellStyle(borderStyle); } @@ -398,8 +371,9 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { for (Integer rowNo = 1; rowNo < 1000; rowNo++) { Row row = worksheet.createRow(rowNo); writeFormula(LoanConstants.CLIENT_EXTERNAL_ID, row, - "IF(ISERROR(VLOOKUP($C"+(rowNo+1)+",$AR$2:$AS$"+(clientSheetPopulator.getClients().size()+1)+",2,FALSE))," + - "\"\",(VLOOKUP($C"+(rowNo+1)+",$AR$2:$AS$"+(clientSheetPopulator.getClients().size()+1)+",2,FALSE)))"); + "IF(ISERROR(VLOOKUP($C" + (rowNo + 1) + ",$AR$2:$AS$" + (clientSheetPopulator.getClients().size() + 1) + ",2,FALSE))," + + "\"\",(VLOOKUP($C" + (rowNo + 1) + ",$AR$2:$AS$" + (clientSheetPopulator.getClients().size() + 1) + + ",2,FALSE)))"); writeFormula(LoanConstants.FUND_NAME_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"FUND_\",$E" + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"FUND_\",$E" + (rowNo + 1) + ")))"); writeFormula(LoanConstants.PRINCIPAL_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"PRINCIPAL_\",$E" + (rowNo + 1) @@ -410,33 +384,30 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"REPAYMENT_FREQUENCY_\",$E" + (rowNo + 1) + ")))"); writeFormula(LoanConstants.NO_OF_REPAYMENTS_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"NO_REPAYMENT_\",$E" + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"NO_REPAYMENT_\",$E" + (rowNo + 1) + ")))"); - writeFormula(LoanConstants.LOAN_TERM_COL, row, "IF(ISERROR($M" + (rowNo + 1) + "*$N" + (rowNo + 1) + "),\"\",$M" - + (rowNo + 1) + "*$N" + (rowNo + 1) + ")"); + writeFormula(LoanConstants.LOAN_TERM_COL, row, + "IF(ISERROR($M" + (rowNo + 1) + "*$N" + (rowNo + 1) + "),\"\",$M" + (rowNo + 1) + "*$N" + (rowNo + 1) + ")"); writeFormula(LoanConstants.LOAN_TERM_FREQUENCY_COL, row, "$O" + (rowNo + 1)); writeFormula(LoanConstants.NOMINAL_INTEREST_RATE_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"INTEREST_FREQUENCY_\",$E" + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"INTEREST_FREQUENCY_\",$E" + (rowNo + 1) + ")))"); - writeFormula(LoanConstants.NOMINAL_INTEREST_RATE_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"INTEREST_\",$E" - + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"INTEREST_\",$E" + (rowNo + 1) + ")))"); + writeFormula(LoanConstants.NOMINAL_INTEREST_RATE_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"INTEREST_\",$E" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"INTEREST_\",$E" + (rowNo + 1) + ")))"); writeFormula(LoanConstants.AMORTIZATION_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"AMORTIZATION_\",$E" + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"AMORTIZATION_\",$E" + (rowNo + 1) + ")))"); writeFormula(LoanConstants.INTEREST_METHOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"INTEREST_TYPE_\",$E" + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"INTEREST_TYPE_\",$E" + (rowNo + 1) + ")))"); - writeFormula(LoanConstants.INTEREST_CALCULATION_PERIOD_COL, row, - "IF(ISERROR(INDIRECT(CONCATENATE(\"INTEREST_CALCULATION_\",$E" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"INTEREST_CALCULATION_\",$E" + (rowNo + 1) + ")))"); - writeFormula(LoanConstants.ARREARS_TOLERANCE_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"ARREARS_TOLERANCE_\",$E" - + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"ARREARS_TOLERANCE_\",$E" + (rowNo + 1) + ")))"); + writeFormula(LoanConstants.INTEREST_CALCULATION_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"INTEREST_CALCULATION_\",$E" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"INTEREST_CALCULATION_\",$E" + (rowNo + 1) + ")))"); + writeFormula(LoanConstants.ARREARS_TOLERANCE_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"ARREARS_TOLERANCE_\",$E" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"ARREARS_TOLERANCE_\",$E" + (rowNo + 1) + ")))"); writeFormula(LoanConstants.REPAYMENT_STRATEGY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"STRATEGY_\",$E" + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"STRATEGY_\",$E" + (rowNo + 1) + ")))"); writeFormula(LoanConstants.GRACE_ON_PRINCIPAL_PAYMENT_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"GRACE_PRINCIPAL_\",$E" + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"GRACE_PRINCIPAL_\",$E" + (rowNo + 1) + ")))"); - writeFormula(LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL, row, - "IF(ISERROR(INDIRECT(CONCATENATE(\"GRACE_INTEREST_PAYMENT_\",$E" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"GRACE_INTEREST_PAYMENT_\",$E" + (rowNo + 1) + ")))"); - writeFormula(LoanConstants.GRACE_ON_INTEREST_CHARGED_COL, row, - "IF(ISERROR(INDIRECT(CONCATENATE(\"GRACE_INTEREST_CHARGED_\",$E" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"GRACE_INTEREST_CHARGED_\",$E" + (rowNo + 1) + ")))"); + writeFormula(LoanConstants.GRACE_ON_INTEREST_PAYMENT_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"GRACE_INTEREST_PAYMENT_\",$E" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"GRACE_INTEREST_PAYMENT_\",$E" + (rowNo + 1) + ")))"); + writeFormula(LoanConstants.GRACE_ON_INTEREST_CHARGED_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"GRACE_INTEREST_CHARGED_\",$E" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"GRACE_INTEREST_CHARGED_\",$E" + (rowNo + 1) + ")))"); } } @@ -449,34 +420,31 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { // Office Names Name officeGroup = loanWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (officeNames.size() + 1)); // Client and Loan Officer Names for each office for (Integer i = 0; i < officeNames.size(); i++) { - Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator - .getOfficeNameToBeginEndIndexesOfClients().get(i); - Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator - .getOfficeNameToBeginEndIndexesOfStaff().get(i); - Integer[] officeNameToBeginEndIndexesOfGroups = groupSheetPopulator.getOfficeNameToBeginEndIndexesOfGroups() - .get(i); + Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator.getOfficeNameToBeginEndIndexesOfClients().get(i); + Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i); + Integer[] officeNameToBeginEndIndexesOfGroups = groupSheetPopulator.getOfficeNameToBeginEndIndexesOfGroups().get(i); Name clientName = loanWorkbook.createName(); Name loanOfficerName = loanWorkbook.createName(); Name groupName = loanWorkbook.createName(); if (officeNameToBeginEndIndexesOfStaff != null) { loanOfficerName.setNameName("Staff_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" - + officeNameToBeginEndIndexesOfStaff[1]); + loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); } if (officeNameToBeginEndIndexesOfClients != null) { clientName.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - clientName.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + ":$B$" - + officeNameToBeginEndIndexesOfClients[1]); + clientName.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfClients[0] + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); } if (officeNameToBeginEndIndexesOfGroups != null) { groupName.setNameName("Group_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - groupName.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfGroups[0] + ":$B$" - + officeNameToBeginEndIndexesOfGroups[1]); + groupName.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfGroups[0] + ":$B$" + officeNameToBeginEndIndexesOfGroups[1]); } } @@ -484,17 +452,20 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { // Product Name Name productGroup = loanWorkbook.createName(); productGroup.setNameName("Products"); - productGroup.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$B$2:$B$" + (productSheetPopulator.getProductsSize() + 1)); + productGroup.setRefersToFormula( + TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$B$2:$B$" + (productSheetPopulator.getProductsSize() + 1)); // Fund Name Name fundGroup = loanWorkbook.createName(); fundGroup.setNameName("Funds"); - fundGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$B$2:$B$" + (extrasSheetPopulator.getFundsSize() + 1)); + fundGroup.setRefersToFormula( + TemplatePopulateImportConstants.EXTRAS_SHEET_NAME + "!$B$2:$B$" + (extrasSheetPopulator.getFundsSize() + 1)); // Payment Type Name Name paymentTypeGroup = loanWorkbook.createName(); paymentTypeGroup.setNameName("PaymentTypes"); - paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); + paymentTypeGroup.setRefersToFormula( + TemplatePopulateImportConstants.EXTRAS_SHEET_NAME + "!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); // Default Fund, Default Principal, Min Principal, Max Principal, // Default No. of Repayments, Min Repayments, Max Repayments, Repayment @@ -551,29 +522,29 @@ public class LoanWorkbookPopulator extends AbstractWorkbookPopulator { graceOnInterestChargedName.setNameName("GRACE_INTEREST_CHARGED_" + productName); startDateName.setNameName("START_DATE_" + productName); if (products.get(i).getFundName() != null) { - fundName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$C$" + (i + 2)); + fundName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$C$" + (i + 2)); } - principalName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$D$" + (i + 2)); - minPrincipalName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$E$" + (i + 2)); - maxPrincipalName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$F$" + (i + 2)); - noOfRepaymentName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$G$" + (i + 2)); - minNoOfRepayment.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$H$" + (i + 2)); - maxNoOfRepaymentName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$I$" + (i + 2)); - repaymentEveryName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$J$" + (i + 2)); - repaymentFrequencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$K$" + (i + 2)); - interestName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$L$" + (i + 2)); - minInterestName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$M$" + (i + 2)); - maxInterestName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$N$" + (i + 2)); - interestFrequencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$O$" + (i + 2)); - amortizationName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$P$" + (i + 2)); - interestTypeName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$Q$" + (i + 2)); - interestCalculationPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$R$" + (i + 2)); - transactionProcessingStrategyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$T$" + (i + 2)); - arrearsToleranceName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$S$" + (i + 2)); - graceOnPrincipalPaymentName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$U$" + (i + 2)); - graceOnInterestPaymentName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$V$" + (i + 2)); - graceOnInterestChargedName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$W$" + (i + 2)); - startDateName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$X$" + (i + 2)); + principalName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$D$" + (i + 2)); + minPrincipalName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$E$" + (i + 2)); + maxPrincipalName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$F$" + (i + 2)); + noOfRepaymentName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$G$" + (i + 2)); + minNoOfRepayment.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$H$" + (i + 2)); + maxNoOfRepaymentName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$I$" + (i + 2)); + repaymentEveryName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$J$" + (i + 2)); + repaymentFrequencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$K$" + (i + 2)); + interestName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$L$" + (i + 2)); + minInterestName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$M$" + (i + 2)); + maxInterestName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$N$" + (i + 2)); + interestFrequencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$O$" + (i + 2)); + amortizationName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$P$" + (i + 2)); + interestTypeName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$Q$" + (i + 2)); + interestCalculationPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$R$" + (i + 2)); + transactionProcessingStrategyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$T$" + (i + 2)); + arrearsToleranceName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$S$" + (i + 2)); + graceOnPrincipalPaymentName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$U$" + (i + 2)); + graceOnInterestPaymentName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$V$" + (i + 2)); + graceOnInterestChargedName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$W$" + (i + 2)); + startDateName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$X$" + (i + 2)); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/loanrepayment/LoanRepaymentWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/loanrepayment/LoanRepaymentWorkbookPopulator.java index 554f5e349..fd2aaeaba 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/loanrepayment/LoanRepaymentWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/loanrepayment/LoanRepaymentWorkbookPopulator.java @@ -51,15 +51,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { + private final static Logger LOG = LoggerFactory.getLogger(LoanRepaymentWorkbookPopulator.class); private OfficeSheetPopulator officeSheetPopulator; private ClientSheetPopulator clientSheetPopulator; private ExtrasSheetPopulator extrasSheetPopulator; private List allloans; - private Map clientIdToClientExternalId; + private Map clientIdToClientExternalId; public LoanRepaymentWorkbookPopulator(List loans, OfficeSheetPopulator officeSheetPopulator, - ClientSheetPopulator clientSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) { + ClientSheetPopulator clientSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) { this.allloans = loans; this.officeSheetPopulator = officeSheetPopulator; this.clientSheetPopulator = clientSheetPopulator; @@ -67,55 +68,51 @@ public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet loanRepaymentSheet = workbook.createSheet(TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME); setLayout(loanRepaymentSheet); - officeSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); - extrasSheetPopulator.populate(workbook,dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); + extrasSheetPopulator.populate(workbook, dateFormat); setClientIdToClientExternalId(); - populateLoansTable(loanRepaymentSheet,dateFormat); - setRules(loanRepaymentSheet,dateFormat); - setDefaults(loanRepaymentSheet,dateFormat); + populateLoansTable(loanRepaymentSheet, dateFormat); + setRules(loanRepaymentSheet, dateFormat); + setDefaults(loanRepaymentSheet, dateFormat); } private void setClientIdToClientExternalId() { - clientIdToClientExternalId =new HashMap<>(); - Listallclients=clientSheetPopulator.getClients(); - for (ClientData client: allclients) { - if (client.getExternalId()!=null) { + clientIdToClientExternalId = new HashMap<>(); + List allclients = clientSheetPopulator.getClients(); + for (ClientData client : allclients) { + if (client.getExternalId() != null) { clientIdToClientExternalId.put(client.getId(), client.getExternalId()); } } } - private void setDefaults(Sheet worksheet,String dateFormat) { + private void setDefaults(Sheet worksheet, String dateFormat) { for (Integer rowNo = 1; rowNo < 3000; rowNo++) { Row row = worksheet.getRow(rowNo); if (row == null) { row = worksheet.createRow(rowNo); } writeFormula(LoanRepaymentConstants.CLIENT_EXTERNAL_ID, row, - "IF(ISERROR(VLOOKUP($B"+(rowNo+1)+",$R$2:$S$"+(allloans.size()+1)+",2,FALSE))," + - "\"\",(VLOOKUP($B"+(rowNo+1)+",$R$2:$S$"+(allloans.size()+1)+",2,FALSE)))"); + "IF(ISERROR(VLOOKUP($B" + (rowNo + 1) + ",$R$2:$S$" + (allloans.size() + 1) + ",2,FALSE))," + "\"\",(VLOOKUP($B" + + (rowNo + 1) + ",$R$2:$S$" + (allloans.size() + 1) + ",2,FALSE)))"); writeFormula(LoanRepaymentConstants.PRODUCT_COL, row, - "IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) - + ",2,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) - + ",2,FALSE))"); + "IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) + ",2,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + + ",$T$2:$X$" + (allloans.size() + 1) + ",2,FALSE))"); writeFormula(LoanRepaymentConstants.PRINCIPAL_COL, row, - "IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) - + ",3,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) - + ",3,FALSE))"); + "IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) + ",3,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + + ",$T$2:$X$" + (allloans.size() + 1) + ",3,FALSE))"); writeFormula(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL, row, - "IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) - + ",4,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) - + ",4,FALSE))"); + "IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) + ",4,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + + ",$T$2:$X$" + (allloans.size() + 1) + ",4,FALSE))"); writeFormula(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL, row, - "IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) - + ",5,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) - + ",5,FALSE))"); - Workbook workbook=worksheet.getWorkbook(); + "IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1) + ",5,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + + ",$T$2:$X$" + (allloans.size() + 1) + ",5,FALSE))"); + Workbook workbook = worksheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); dateCellStyle.setDataFormat(df); @@ -123,17 +120,17 @@ public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { } } - private void setRules(Sheet worksheet,String dateFormat) { + private void setRules(Sheet worksheet, String dateFormat) { CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.OFFICE_NAME_COL, LoanRepaymentConstants.OFFICE_NAME_COL); CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.CLIENT_NAME_COL, LoanRepaymentConstants.CLIENT_NAME_COL); - CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL); - CellRangeAddressList repaymentTypeRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.REPAYMENT_TYPE_COL, LoanRepaymentConstants.REPAYMENT_TYPE_COL); - CellRangeAddressList repaymentDateRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.REPAID_ON_DATE_COL, LoanRepaymentConstants.REPAID_ON_DATE_COL); + CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL); + CellRangeAddressList repaymentTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanRepaymentConstants.REPAYMENT_TYPE_COL, LoanRepaymentConstants.REPAYMENT_TYPE_COL); + CellRangeAddressList repaymentDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + LoanRepaymentConstants.REPAID_ON_DATE_COL, LoanRepaymentConstants.REPAID_ON_DATE_COL); DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); @@ -146,17 +143,14 @@ public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { "INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); DataValidationConstraint paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentTypes"); DataValidationConstraint repaymentDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, - "=VLOOKUP($D1,$T$2:$X$" + (allloans.size() + 1) + ",4,FALSE)", "=TODAY()", dateFormat); + DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($D1,$T$2:$X$" + (allloans.size() + 1) + ",4,FALSE)", "=TODAY()", + dateFormat); DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); - DataValidation accountNumberValidation = validationHelper.createValidation(accountNumberConstraint, - accountNumberRange); - DataValidation repaymentTypeValidation = validationHelper.createValidation(paymentTypeConstraint, - repaymentTypeRange); - DataValidation repaymentDateValidation = validationHelper.createValidation(repaymentDateConstraint, - repaymentDateRange); + DataValidation accountNumberValidation = validationHelper.createValidation(accountNumberConstraint, accountNumberRange); + DataValidation repaymentTypeValidation = validationHelper.createValidation(paymentTypeConstraint, repaymentTypeRange); + DataValidation repaymentDateValidation = validationHelper.createValidation(repaymentDateConstraint, repaymentDateRange); worksheet.addValidationData(officeValidation); worksheet.addValidationData(clientValidation); @@ -172,17 +166,16 @@ public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { // Office Names Name officeGroup = loanRepaymentWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (officeNames.size() + 1)); // Clients Named after Offices for (Integer i = 0; i < officeNames.size(); i++) { - Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator - .getOfficeNameToBeginEndIndexesOfClients().get(i); + Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator.getOfficeNameToBeginEndIndexesOfClients().get(i); Name name = loanRepaymentWorkbook.createName(); if (officeNameToBeginEndIndexesOfClients != null) { name.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + ":$B$" - + officeNameToBeginEndIndexesOfClients[1]); + name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME + "!$B$" + officeNameToBeginEndIndexesOfClients[0] + + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); } } @@ -216,20 +209,20 @@ public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { // Account Number Named after Clients for (int j = 0; j < clientsWithActiveLoans.size(); j++) { Name name = loanRepaymentWorkbook.createName(); - name.setNameName("Account_" + clientsWithActiveLoans.get(j).replace(" ", "_") + "_" - + clientIdsWithActiveLoans.get(j) + "_"); - name.setRefersToFormula( - TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME+"!$T$" + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[0] + ":$T$" - + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[1]); + name.setNameName("Account_" + clientsWithActiveLoans.get(j).replace(" ", "_") + "_" + clientIdsWithActiveLoans.get(j) + "_"); + name.setRefersToFormula(TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME + "!$T$" + + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[0] + ":$T$" + + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[1]); } // Payment Type Name Name paymentTypeGroup = loanRepaymentWorkbook.createName(); paymentTypeGroup.setNameName("PaymentTypes"); - paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); + paymentTypeGroup.setRefersToFormula( + TemplatePopulateImportConstants.EXTRAS_SHEET_NAME + "!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); } - private void populateLoansTable(Sheet loanRepaymentSheet,String dateFormat) { + private void populateLoansTable(Sheet loanRepaymentSheet, String dateFormat) { int rowIndex = 1; Row row; Workbook workbook = loanRepaymentSheet.getWorkbook(); @@ -239,26 +232,25 @@ public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { SimpleDateFormat outputFormat = new SimpleDateFormat(dateFormat); SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; - Collections.sort(allloans,new LoanComparatorByStatusActive()); + Collections.sort(allloans, new LoanComparatorByStatusActive()); for (LoanAccountData loan : allloans) { row = loanRepaymentSheet.createRow(rowIndex++); writeString(LoanRepaymentConstants.LOOKUP_CLIENT_NAME_COL, row, loan.getClientName() + "(" + loan.getClientId() + ")"); - writeString(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID,row, clientIdToClientExternalId.get(loan.getClientId())); - writeString(LoanRepaymentConstants.LOOKUP_ACCOUNT_NO_COL, row, loan.getAccountNo()+"-"+loan.getStatusStringValue()); + writeString(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID, row, clientIdToClientExternalId.get(loan.getClientId())); + writeString(LoanRepaymentConstants.LOOKUP_ACCOUNT_NO_COL, row, loan.getAccountNo() + "-" + loan.getStatusStringValue()); writeString(LoanRepaymentConstants.LOOKUP_PRODUCT_COL, row, loan.getLoanProductName()); writeDouble(LoanRepaymentConstants.LOOKUP_PRINCIPAL_COL, row, loan.getPrincipal().doubleValue()); if (loan.getTotalOutstandingAmount() != null) { - writeBigDecimal(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL, row, - loan.getTotalOutstandingAmount()); + writeBigDecimal(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL, row, loan.getTotalOutstandingAmount()); } if (loan.getDisbursementDate() != null) { try { date = inputFormat.parse(loan.getDisbursementDate().toString()); } catch (ParseException e) { - LOG.error("Problem occurred in populateLoansTable function",e); + LOG.error("Problem occurred in populateLoansTable function", e); } - writeDate(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, row, - outputFormat.format(date), dateCellStyle,dateFormat); + writeDate(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, row, outputFormat.format(date), dateCellStyle, + dateFormat); } } } @@ -268,12 +260,12 @@ public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); worksheet.setColumnWidth(LoanRepaymentConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanRepaymentConstants.CLIENT_EXTERNAL_ID,TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanRepaymentConstants.CLIENT_EXTERNAL_ID, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.PRODUCT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + worksheet.setColumnWidth(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.AMOUNT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.REPAID_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.REPAYMENT_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); @@ -283,20 +275,21 @@ public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { worksheet.setColumnWidth(LoanRepaymentConstants.ROUTING_CODE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.BANK_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID,TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_PRODUCT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL,TemplatePopulateImportConstants.LARGE_COL_SIZE); + worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL, + TemplatePopulateImportConstants.LARGE_COL_SIZE); worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); writeString(LoanRepaymentConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); writeString(LoanRepaymentConstants.CLIENT_NAME_COL, rowHeader, "Client Name*"); - writeString(LoanRepaymentConstants.CLIENT_EXTERNAL_ID,rowHeader,"Client Ext.Id"); + writeString(LoanRepaymentConstants.CLIENT_EXTERNAL_ID, rowHeader, "Client Ext.Id"); writeString(LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, rowHeader, "Loan Account No.*"); writeString(LoanRepaymentConstants.PRODUCT_COL, rowHeader, "Product Name"); writeString(LoanRepaymentConstants.PRINCIPAL_COL, rowHeader, "Principal"); - writeString(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL,rowHeader,"Total Outstanding Amount"); - writeString(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL,rowHeader,"Loan Disbursement Date"); + writeString(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL, rowHeader, "Total Outstanding Amount"); + writeString(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL, rowHeader, "Loan Disbursement Date"); writeString(LoanRepaymentConstants.AMOUNT_COL, rowHeader, "Amount Repaid*"); writeString(LoanRepaymentConstants.REPAID_ON_DATE_COL, rowHeader, "Date*"); writeString(LoanRepaymentConstants.REPAYMENT_TYPE_COL, rowHeader, "Type*"); @@ -306,11 +299,11 @@ public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator { writeString(LoanRepaymentConstants.ROUTING_CODE_COL, rowHeader, "Routing Code"); writeString(LoanRepaymentConstants.BANK_NO_COL, rowHeader, "Bank No"); writeString(LoanRepaymentConstants.LOOKUP_CLIENT_NAME_COL, rowHeader, "Lookup Client"); - writeString(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID,rowHeader,"Lookup ClientExtId"); + writeString(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID, rowHeader, "Lookup ClientExtId"); writeString(LoanRepaymentConstants.LOOKUP_ACCOUNT_NO_COL, rowHeader, "Lookup Account"); writeString(LoanRepaymentConstants.LOOKUP_PRODUCT_COL, rowHeader, "Lookup Product"); writeString(LoanRepaymentConstants.LOOKUP_PRINCIPAL_COL, rowHeader, "Lookup Principal"); - writeString(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL,rowHeader,"Lookup Total Outstanding amount"); + writeString(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL, rowHeader, "Lookup Total Outstanding amount"); writeString(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, rowHeader, "Lookup Loan Disbursement Date"); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/office/OfficeWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/office/OfficeWorkbookPopulator.java index 360f0dace..6a468cc4f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/office/OfficeWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/office/OfficeWorkbookPopulator.java @@ -36,85 +36,88 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddressList; public class OfficeWorkbookPopulator extends AbstractWorkbookPopulator { - private List offices; + + private List offices; public OfficeWorkbookPopulator(List offices) { - this.offices=offices; + this.offices = offices; } @Override - public void populate(final Workbook workbook,final String dateFormat) { - Sheet officeSheet=workbook.createSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); + public void populate(final Workbook workbook, final String dateFormat) { + Sheet officeSheet = workbook.createSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME); setLayout(officeSheet); setLookupTable(officeSheet); - setRules(officeSheet,dateFormat); + setRules(officeSheet, dateFormat); setDefaults(officeSheet); } private void setLookupTable(final Sheet officeSheet) { - int rowIndex=1; - for (OfficeData office:offices) { - Row row=officeSheet.createRow(rowIndex); - writeString(OfficeConstants.LOOKUP_OFFICE_COL,row,office.name()); - writeLong(OfficeConstants.LOOKUP_OFFICE_ID_COL,row,office.getId()); + int rowIndex = 1; + for (OfficeData office : offices) { + Row row = officeSheet.createRow(rowIndex); + writeString(OfficeConstants.LOOKUP_OFFICE_COL, row, office.name()); + writeLong(OfficeConstants.LOOKUP_OFFICE_ID_COL, row, office.getId()); rowIndex++; } } - private void setLayout(final Sheet worksheet){ - Row rowHeader=worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); + private void setLayout(final Sheet worksheet) { + Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); worksheet.setColumnWidth(OfficeConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(OfficeConstants.PARENT_OFFICE_NAME_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(OfficeConstants.PARENT_OFFICE_ID_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(OfficeConstants.OPENED_ON_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(OfficeConstants.EXTERNAL_ID_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(OfficeConstants.LOOKUP_OFFICE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(OfficeConstants.LOOKUP_OFFICE_ID_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(OfficeConstants.PARENT_OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(OfficeConstants.PARENT_OFFICE_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(OfficeConstants.OPENED_ON_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(OfficeConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(OfficeConstants.LOOKUP_OFFICE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(OfficeConstants.LOOKUP_OFFICE_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); writeString(OfficeConstants.OFFICE_NAME_COL, rowHeader, "Office Name*"); writeString(OfficeConstants.PARENT_OFFICE_NAME_COL, rowHeader, "Parent Office*"); - writeString(OfficeConstants.PARENT_OFFICE_ID_COL,rowHeader,"Parent OfficeId*"); + writeString(OfficeConstants.PARENT_OFFICE_ID_COL, rowHeader, "Parent OfficeId*"); writeString(OfficeConstants.OPENED_ON_COL, rowHeader, "Opened On Date*"); writeString(OfficeConstants.EXTERNAL_ID_COL, rowHeader, "External Id*"); writeString(OfficeConstants.LOOKUP_OFFICE_COL, rowHeader, "Lookup Offices"); - writeString(OfficeConstants.LOOKUP_OFFICE_ID_COL,rowHeader, "Lookup OfficeId*"); + writeString(OfficeConstants.LOOKUP_OFFICE_ID_COL, rowHeader, "Lookup OfficeId*"); } - private void setRules(Sheet workSheet, final String dateFormat){ - CellRangeAddressList parentOfficeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + private void setRules(Sheet workSheet, final String dateFormat) { + CellRangeAddressList parentOfficeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), OfficeConstants.PARENT_OFFICE_NAME_COL, OfficeConstants.PARENT_OFFICE_NAME_COL); CellRangeAddressList OpenedOndateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - OfficeConstants.OPENED_ON_COL,OfficeConstants.OPENED_ON_COL); + OfficeConstants.OPENED_ON_COL, OfficeConstants.OPENED_ON_COL); - DataValidationHelper validationHelper=new HSSFDataValidationHelper((HSSFSheet) workSheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) workSheet); setNames(workSheet); - DataValidationConstraint parentOfficeNameConstraint=validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint openDateConstraint=validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL,"=TODAY()",null,dateFormat); + DataValidationConstraint parentOfficeNameConstraint = validationHelper.createFormulaListConstraint("Office"); + DataValidationConstraint openDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, "=TODAY()", null, dateFormat); - DataValidation parentOfficeValidation=validationHelper.createValidation(parentOfficeNameConstraint,parentOfficeNameRange); - DataValidation openDateValidation=validationHelper.createValidation(openDateConstraint,OpenedOndateRange); + DataValidation parentOfficeValidation = validationHelper.createValidation(parentOfficeNameConstraint, parentOfficeNameRange); + DataValidation openDateValidation = validationHelper.createValidation(openDateConstraint, OpenedOndateRange); workSheet.addValidationData(parentOfficeValidation); workSheet.addValidationData(openDateValidation); } private void setNames(final Sheet workSheet) { - Workbook officeWorkbook=workSheet.getWorkbook(); - Name parentOffice=officeWorkbook.createName(); + Workbook officeWorkbook = workSheet.getWorkbook(); + Name parentOffice = officeWorkbook.createName(); parentOffice.setNameName("Office"); - parentOffice.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$H$2:$H$"+(offices.size()+1)); + parentOffice.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$H$2:$H$" + (offices.size() + 1)); } private void setDefaults(final Sheet worksheet) { - for (Integer rowNo = 1; rowNo < 3000; rowNo++) { - Row row = worksheet.getRow(rowNo); - if (row == null) { - row = worksheet.createRow(rowNo); - } - writeFormula(OfficeConstants.PARENT_OFFICE_ID_COL, row, - "IF(ISERROR(VLOOKUP($B"+(rowNo+1)+",$H$2:$I$"+(offices.size()+1)+",2,FALSE)),\"\",(VLOOKUP($B"+(rowNo+1)+",$H$2:$I$"+(offices.size()+1)+",2,FALSE)))"); + for (Integer rowNo = 1; rowNo < 3000; rowNo++) { + Row row = worksheet.getRow(rowNo); + if (row == null) { + row = worksheet.createRow(rowNo); } + writeFormula(OfficeConstants.PARENT_OFFICE_ID_COL, row, + "IF(ISERROR(VLOOKUP($B" + (rowNo + 1) + ",$H$2:$I$" + (offices.size() + 1) + ",2,FALSE)),\"\",(VLOOKUP($B" + (rowNo + 1) + + ",$H$2:$I$" + (offices.size() + 1) + ",2,FALSE)))"); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/recurringdeposit/RecurringDepositTransactionWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/recurringdeposit/RecurringDepositTransactionWorkbookPopulator.java index 7afceb65b..ea246d2c3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/recurringdeposit/RecurringDepositTransactionWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/recurringdeposit/RecurringDepositTransactionWorkbookPopulator.java @@ -48,7 +48,7 @@ public class RecurringDepositTransactionWorkbookPopulator extends AbstractWorkbo private ClientSheetPopulator clientSheetPopulator; private ExtrasSheetPopulator extrasSheetPopulator; - private ListsavingsAccounts; + private List savingsAccounts; public RecurringDepositTransactionWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, ClientSheetPopulator clientSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator, @@ -56,60 +56,65 @@ public class RecurringDepositTransactionWorkbookPopulator extends AbstractWorkbo this.officeSheetPopulator = officeSheetPopulator; this.clientSheetPopulator = clientSheetPopulator; this.extrasSheetPopulator = extrasSheetPopulator; - this.savingsAccounts=savingsAccounts; + this.savingsAccounts = savingsAccounts; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet savingsTransactionSheet = workbook.createSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME); setLayout(savingsTransactionSheet); - officeSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); - extrasSheetPopulator.populate(workbook,dateFormat); - populateSavingsTable(savingsTransactionSheet,dateFormat); - setRules(savingsTransactionSheet,dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); + extrasSheetPopulator.populate(workbook, dateFormat); + populateSavingsTable(savingsTransactionSheet, dateFormat); + setRules(savingsTransactionSheet, dateFormat); setDefaults(savingsTransactionSheet); } private void setDefaults(Sheet worksheet) { - for(Integer rowNo = 1; rowNo < 3000; rowNo++) - { - Row row = worksheet.getRow(rowNo); - if(row == null) { - row = worksheet.createRow(rowNo); - } - writeFormula(TransactionConstants.PRODUCT_COL, row, "IF(ISERROR(VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE)),\"\",VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE))"); - writeFormula(TransactionConstants.OPENING_BALANCE_COL, row, "IF(ISERROR(VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE)),\"\",VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE))"); + for (Integer rowNo = 1; rowNo < 3000; rowNo++) { + Row row = worksheet.getRow(rowNo); + if (row == null) { + row = worksheet.createRow(rowNo); } + writeFormula(TransactionConstants.PRODUCT_COL, row, + "IF(ISERROR(VLOOKUP($C" + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE)),\"\",VLOOKUP($C" + + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE))"); + writeFormula(TransactionConstants.OPENING_BALANCE_COL, row, + "IF(ISERROR(VLOOKUP($C" + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE)),\"\",VLOOKUP($C" + + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE))"); + } } - - private void setRules(Sheet worksheet,String dateFormat) { - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + private void setRules(Sheet worksheet, String dateFormat) { + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.OFFICE_NAME_COL, TransactionConstants.OFFICE_NAME_COL); - CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.CLIENT_NAME_COL, TransactionConstants.CLIENT_NAME_COL); - CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.SAVINGS_ACCOUNT_NO_COL, TransactionConstants.SAVINGS_ACCOUNT_NO_COL); - CellRangeAddressList transactionTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList transactionTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.TRANSACTION_TYPE_COL, TransactionConstants.TRANSACTION_TYPE_COL); CellRangeAddressList paymentTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.PAYMENT_TYPE_COL, TransactionConstants.PAYMENT_TYPE_COL); CellRangeAddressList transactionDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.TRANSACTION_DATE_COL, TransactionConstants.TRANSACTION_DATE_COL); - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); setNames(worksheet); DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint clientNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))"); - DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); - DataValidationConstraint transactionTypeConstraint = validationHelper.createExplicitListConstraint(new String[] {"Withdrawal","Deposit"}); + DataValidationConstraint clientNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))"); + DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint( + "INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); + DataValidationConstraint transactionTypeConstraint = validationHelper + .createExplicitListConstraint(new String[] { "Withdrawal", "Deposit" }); DataValidationConstraint paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentTypes"); - DataValidationConstraint transactionDateConstraint = validationHelper.createDateConstraint - (DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($C1,$Q$2:$T$" + - (savingsAccounts.size() + 1) + ",4,FALSE)", "=TODAY()", dateFormat); + DataValidationConstraint transactionDateConstraint = validationHelper.createDateConstraint( + DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($C1,$Q$2:$T$" + (savingsAccounts.size() + 1) + ",4,FALSE)", + "=TODAY()", dateFormat); DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); @@ -130,22 +135,24 @@ public class RecurringDepositTransactionWorkbookPopulator extends AbstractWorkbo Workbook savingsTransactionWorkbook = worksheet.getWorkbook(); List officeNames = officeSheetPopulator.getOfficeNames(); - //Office Names + // Office Names Name officeGroup = savingsTransactionWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (officeNames.size() + 1)); - //Clients Named after Offices - for(Integer i = 0; i < officeNames.size(); i++) { + // Clients Named after Offices + for (Integer i = 0; i < officeNames.size(); i++) { Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator.getOfficeNameToBeginEndIndexesOfClients().get(i); Name name = savingsTransactionWorkbook.createName(); - if(officeNameToBeginEndIndexesOfClients != null) { + if (officeNameToBeginEndIndexesOfClients != null) { name.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); + name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME + "!$B$" + officeNameToBeginEndIndexesOfClients[0] + + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); } } - //Counting clients with active savings and starting and end addresses of cells for naming + // Counting clients with active savings and starting and end addresses + // of cells for naming HashMap clientNameToBeginEndIndexes = new HashMap<>(); ArrayList clientsWithActiveSavings = new ArrayList<>(); ArrayList clientIdsWithActiveSavings = new ArrayList<>(); @@ -153,36 +160,40 @@ public class RecurringDepositTransactionWorkbookPopulator extends AbstractWorkbo int endIndex = 1; String clientName = ""; Long clientId = null; - for(int i = 0; i < savingsAccounts.size(); i++){ - if(!clientName.equals(savingsAccounts.get(i).getClientName())) { + for (int i = 0; i < savingsAccounts.size(); i++) { + if (!clientName.equals(savingsAccounts.get(i).getClientName())) { endIndex = i + 1; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); startIndex = i + 2; clientName = savingsAccounts.get(i).getClientName(); clientId = savingsAccounts.get(i).getClientId(); clientsWithActiveSavings.add(clientName); clientIdsWithActiveSavings.add(clientId); } - if(i == savingsAccounts.size()-1) { + if (i == savingsAccounts.size() - 1) { endIndex = i + 2; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); } } - //Account Number Named after Clients - for(int j = 0; j < clientsWithActiveSavings.size(); j++) { + // Account Number Named after Clients + for (int j = 0; j < clientsWithActiveSavings.size(); j++) { Name name = savingsTransactionWorkbook.createName(); - name.setNameName("Account_" + clientsWithActiveSavings.get(j).replaceAll(" ", "_") + "_" + clientIdsWithActiveSavings.get(j) + "_"); - name.setRefersToFormula(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME+"!$Q$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[0] + ":$Q$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[1]); + name.setNameName( + "Account_" + clientsWithActiveSavings.get(j).replaceAll(" ", "_") + "_" + clientIdsWithActiveSavings.get(j) + "_"); + name.setRefersToFormula(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME + "!$Q$" + + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[0] + ":$Q$" + + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[1]); } - //Payment Type Name + // Payment Type Name Name paymentTypeGroup = savingsTransactionWorkbook.createName(); paymentTypeGroup.setNameName("PaymentTypes"); - paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); + paymentTypeGroup.setRefersToFormula( + TemplatePopulateImportConstants.EXTRAS_SHEET_NAME + "!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); } - private void populateSavingsTable(Sheet savingsTransactionSheet,String dateFormat) { + private void populateSavingsTable(Sheet savingsTransactionSheet, String dateFormat) { Workbook workbook = savingsTransactionSheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); @@ -190,20 +201,21 @@ public class RecurringDepositTransactionWorkbookPopulator extends AbstractWorkbo int rowIndex = 1; Row row; Collections.sort(savingsAccounts, SavingsAccountData.ClientNameComparator); - for(SavingsAccountData savingsAccount : savingsAccounts) { - row = savingsTransactionSheet.createRow(rowIndex++); - writeString(TransactionConstants.LOOKUP_CLIENT_NAME_COL, row, savingsAccount.getClientName() + "(" + savingsAccount.getClientId() + ")"); - writeString(TransactionConstants.LOOKUP_ACCOUNT_NO_COL, row, savingsAccount.getAccountNo()); - writeString(TransactionConstants.LOOKUP_PRODUCT_COL, row, savingsAccount.getSavingsProductName()); - if(savingsAccount.getMinRequiredOpeningBalance() != null) { - writeBigDecimal(TransactionConstants.LOOKUP_OPENING_BALANCE_COL, row, - savingsAccount.getMinRequiredOpeningBalance()); - } - writeDate(TransactionConstants.LOOKUP_SAVINGS_ACTIVATION_DATE_COL, row,"" + - savingsAccount.getTimeline().getActivatedOnDate().getDayOfMonth() + "/" - + savingsAccount.getTimeline().getActivatedOnDate().getMonthOfYear() + "/" - + savingsAccount.getTimeline().getActivatedOnDate().getYear() , dateCellStyle,dateFormat); + for (SavingsAccountData savingsAccount : savingsAccounts) { + row = savingsTransactionSheet.createRow(rowIndex++); + writeString(TransactionConstants.LOOKUP_CLIENT_NAME_COL, row, + savingsAccount.getClientName() + "(" + savingsAccount.getClientId() + ")"); + writeString(TransactionConstants.LOOKUP_ACCOUNT_NO_COL, row, savingsAccount.getAccountNo()); + writeString(TransactionConstants.LOOKUP_PRODUCT_COL, row, savingsAccount.getSavingsProductName()); + if (savingsAccount.getMinRequiredOpeningBalance() != null) { + writeBigDecimal(TransactionConstants.LOOKUP_OPENING_BALANCE_COL, row, savingsAccount.getMinRequiredOpeningBalance()); } + writeDate(TransactionConstants.LOOKUP_SAVINGS_ACTIVATION_DATE_COL, row, + "" + savingsAccount.getTimeline().getActivatedOnDate().getDayOfMonth() + "/" + + savingsAccount.getTimeline().getActivatedOnDate().getMonthOfYear() + "/" + + savingsAccount.getTimeline().getActivatedOnDate().getYear(), + dateCellStyle, dateFormat); + } } private void setLayout(Sheet worksheet) { @@ -247,6 +259,5 @@ public class RecurringDepositTransactionWorkbookPopulator extends AbstractWorkbo writeString(TransactionConstants.LOOKUP_PRODUCT_COL, rowHeader, "Lookup Product"); writeString(TransactionConstants.LOOKUP_OPENING_BALANCE_COL, rowHeader, "Lookup Opening Balance"); writeString(TransactionConstants.LOOKUP_SAVINGS_ACTIVATION_DATE_COL, rowHeader, "Lookup Savings Activation Date"); - } } - +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/recurringdeposit/RecurringDepositWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/recurringdeposit/RecurringDepositWorkbookPopulator.java index 9423bef32..5b8c72d99 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/recurringdeposit/RecurringDepositWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/recurringdeposit/RecurringDepositWorkbookPopulator.java @@ -47,10 +47,8 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator private PersonnelSheetPopulator personnelSheetPopulator; private RecurringDepositProductSheetPopulator productSheetPopulator; - - public RecurringDepositWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - ClientSheetPopulator clientSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, - RecurringDepositProductSheetPopulator recurringDepositProductSheetPopulator) { + public RecurringDepositWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, ClientSheetPopulator clientSheetPopulator, + PersonnelSheetPopulator personnelSheetPopulator, RecurringDepositProductSheetPopulator recurringDepositProductSheetPopulator) { this.officeSheetPopulator = officeSheetPopulator; this.clientSheetPopulator = clientSheetPopulator; @@ -59,16 +57,17 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet recurringDepositSheet = workbook.createSheet(TemplatePopulateImportConstants.RECURRING_DEPOSIT_SHEET_NAME); - officeSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); - personnelSheetPopulator.populate(workbook,dateFormat); - productSheetPopulator.populate(workbook,dateFormat); - setRules(recurringDepositSheet,dateFormat); - setDefaults(recurringDepositSheet,dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); + personnelSheetPopulator.populate(workbook, dateFormat); + productSheetPopulator.populate(workbook, dateFormat); + setRules(recurringDepositSheet, dateFormat); + setDefaults(recurringDepositSheet, dateFormat); setClientAndGroupDateLookupTable(recurringDepositSheet, clientSheetPopulator.getClients(), null, - RecurringDepositConstants.LOOKUP_CLIENT_NAME_COL, RecurringDepositConstants.LOOKUP_ACTIVATION_DATE_COL,!TemplatePopulateImportConstants.CONTAINS_CLIENT_EXTERNAL_ID,dateFormat); + RecurringDepositConstants.LOOKUP_CLIENT_NAME_COL, RecurringDepositConstants.LOOKUP_ACTIVATION_DATE_COL, + !TemplatePopulateImportConstants.CONTAINS_CLIENT_EXTERNAL_ID, dateFormat); setLayout(recurringDepositSheet); } @@ -77,29 +76,30 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); worksheet.setColumnWidth(RecurringDepositConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.PRODUCT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.FIELD_OFFICER_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.SUBMITTED_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.APPROVED_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.INTEREST_POSTING_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.INTEREST_CALCULATION_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.LOCKIN_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.DEPOSIT_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.DEPOSIT_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.DEPOSIT_FREQUENCY_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.DEPOSIT_START_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.IS_MANDATORY_DEPOSIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.ALLOW_WITHDRAWAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.ADJUST_ADVANCE_PAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.FREQ_SAME_AS_GROUP_CENTER_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - worksheet.setColumnWidth(RecurringDepositConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.PRODUCT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.FIELD_OFFICER_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.SUBMITTED_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.APPROVED_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.INTEREST_POSTING_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.INTEREST_CALCULATION_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, + TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.LOCKIN_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.DEPOSIT_PERIOD_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.DEPOSIT_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.DEPOSIT_FREQUENCY_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.DEPOSIT_START_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.IS_MANDATORY_DEPOSIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.ALLOW_WITHDRAWAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.ADJUST_ADVANCE_PAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.FREQ_SAME_AS_GROUP_CENTER_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + worksheet.setColumnWidth(RecurringDepositConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); worksheet.setColumnWidth(RecurringDepositConstants.CHARGE_ID_1, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); worksheet.setColumnWidth(RecurringDepositConstants.CHARGE_AMOUNT_1, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); @@ -129,14 +129,15 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator writeString(RecurringDepositConstants.DEPOSIT_START_DATE_COL, rowHeader, "Deposit Start Date"); writeString(RecurringDepositConstants.IS_MANDATORY_DEPOSIT_COL, rowHeader, "Is Mandatory Deposit?"); writeString(RecurringDepositConstants.ALLOW_WITHDRAWAL_COL, rowHeader, "Allow Withdrawal?"); - writeString(RecurringDepositConstants.ADJUST_ADVANCE_PAYMENTS_COL, rowHeader, "Adjust Advance Payments Toward Future Installments "); + writeString(RecurringDepositConstants.ADJUST_ADVANCE_PAYMENTS_COL, rowHeader, + "Adjust Advance Payments Toward Future Installments "); writeString(RecurringDepositConstants.FREQ_SAME_AS_GROUP_CENTER_COL, rowHeader, "Deposit Frequency Same as Group/Center meeting"); writeString(RecurringDepositConstants.EXTERNAL_ID_COL, rowHeader, "External Id"); - writeString(RecurringDepositConstants.CHARGE_ID_1,rowHeader,"Charge Id"); + writeString(RecurringDepositConstants.CHARGE_ID_1, rowHeader, "Charge Id"); writeString(RecurringDepositConstants.CHARGE_AMOUNT_1, rowHeader, "Charged Amount"); writeString(RecurringDepositConstants.CHARGE_DUE_DATE_1, rowHeader, "Charged On Date"); - writeString(RecurringDepositConstants.CHARGE_ID_2,rowHeader,"Charge Id"); + writeString(RecurringDepositConstants.CHARGE_ID_2, rowHeader, "Charge Id"); writeString(RecurringDepositConstants.CHARGE_AMOUNT_2, rowHeader, "Charged Amount"); writeString(RecurringDepositConstants.CHARGE_DUE_DATE_2, rowHeader, "Charged On Date"); @@ -144,39 +145,46 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator writeString(RecurringDepositConstants.LOOKUP_ACTIVATION_DATE_COL, rowHeader, "Client Activation Date"); } - private void setDefaults(Sheet worksheet,String dateFormat) { + private void setDefaults(Sheet worksheet, String dateFormat) { Workbook workbook = worksheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); dateCellStyle.setDataFormat(df); - for (Integer rowNo = 1; rowNo < 1000; rowNo++) { - Row row = worksheet.createRow(rowNo); - writeFormula(RecurringDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Compouding_\",$C" - + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Compouding_\",$C" + (rowNo + 1) + ")))"); - writeFormula(RecurringDepositConstants.INTEREST_POSTING_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Posting_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Posting_\",$C" + (rowNo + 1) + ")))"); - writeFormula(RecurringDepositConstants.INTEREST_CALCULATION_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Calculation_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Calculation_\",$C" + (rowNo + 1) + ")))"); - writeFormula(RecurringDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Days_In_Year_\",$C" - + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Days_In_Year_\",$C" + (rowNo + 1) + ")))"); - writeFormula(RecurringDepositConstants.LOCKIN_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Period_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Period_\",$C" + (rowNo + 1) + ")))"); - writeFormula(RecurringDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$C" + (rowNo + 1) + ")))"); - writeFormula(RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Deposit_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Deposit_\",$C" + (rowNo + 1) + ")))"); - writeFormula(RecurringDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Term_Type_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Term_Type_\",$C" + (rowNo + 1) + ")))"); - writeFormula(RecurringDepositConstants.IS_MANDATORY_DEPOSIT_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Mandatory_Deposit_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Mandatory_Deposit_\",$C" + (rowNo + 1) + ")))"); - writeFormula(RecurringDepositConstants.ALLOW_WITHDRAWAL_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Allow_Withdrawal_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Allow_Withdrawal_\",$C" + (rowNo + 1) + ")))"); - writeFormula(RecurringDepositConstants.ADJUST_ADVANCE_PAYMENTS_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Adjust_Advance_\",$C" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Adjust_Advance_\",$C" + (rowNo + 1) + ")))"); - } + for (Integer rowNo = 1; rowNo < 1000; rowNo++) { + Row row = worksheet.createRow(rowNo); + writeFormula(RecurringDepositConstants.INTEREST_COMPOUNDING_PERIOD_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Compouding_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Compouding_\",$C" + (rowNo + 1) + ")))"); + writeFormula(RecurringDepositConstants.INTEREST_POSTING_PERIOD_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Posting_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Posting_\",$C" + (rowNo + 1) + ")))"); + writeFormula(RecurringDepositConstants.INTEREST_CALCULATION_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Calculation_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Calculation_\",$C" + (rowNo + 1) + ")))"); + writeFormula(RecurringDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Days_In_Year_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Days_In_Year_\",$C" + (rowNo + 1) + ")))"); + writeFormula(RecurringDepositConstants.LOCKIN_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Period_\",$C" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Period_\",$C" + (rowNo + 1) + ")))"); + writeFormula(RecurringDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$C" + (rowNo + 1) + ")))"); + writeFormula(RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Deposit_\",$C" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Deposit_\",$C" + (rowNo + 1) + ")))"); + writeFormula(RecurringDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Term_Type_\",$C" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Term_Type_\",$C" + (rowNo + 1) + ")))"); + writeFormula(RecurringDepositConstants.IS_MANDATORY_DEPOSIT_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Mandatory_Deposit_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Mandatory_Deposit_\",$C" + (rowNo + 1) + ")))"); + writeFormula(RecurringDepositConstants.ALLOW_WITHDRAWAL_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Allow_Withdrawal_\",$C" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Allow_Withdrawal_\",$C" + (rowNo + 1) + ")))"); + writeFormula(RecurringDepositConstants.ADJUST_ADVANCE_PAYMENTS_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Adjust_Advance_\",$C" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Adjust_Advance_\",$C" + (rowNo + 1) + ")))"); + } } - private void setRules(Sheet worksheet,String dateFormat) { + private void setRules(Sheet worksheet, String dateFormat) { CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), RecurringDepositConstants.OFFICE_NAME_COL, RecurringDepositConstants.OFFICE_NAME_COL); CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), @@ -197,23 +205,23 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator RecurringDepositConstants.INTEREST_POSTING_PERIOD_COL, RecurringDepositConstants.INTEREST_POSTING_PERIOD_COL); CellRangeAddressList interestCalculationRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), RecurringDepositConstants.INTEREST_CALCULATION_COL, RecurringDepositConstants.INTEREST_CALCULATION_COL); - CellRangeAddressList interestCalculationDaysInYearRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), RecurringDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, + CellRangeAddressList interestCalculationDaysInYearRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + RecurringDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, RecurringDepositConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL); CellRangeAddressList lockinPeriodFrequencyRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), RecurringDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL, RecurringDepositConstants.LOCKIN_PERIOD_FREQUENCY_COL); CellRangeAddressList depositAmountRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL,RecurringDepositConstants. RECURRING_DEPOSIT_AMOUNT_COL); + RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL, RecurringDepositConstants.RECURRING_DEPOSIT_AMOUNT_COL); CellRangeAddressList depositPeriodTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), RecurringDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, RecurringDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL); CellRangeAddressList depositFrequencyTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), RecurringDepositConstants.DEPOSIT_FREQUENCY_TYPE_COL, RecurringDepositConstants.DEPOSIT_FREQUENCY_TYPE_COL); CellRangeAddressList isMandatoryDepositRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - RecurringDepositConstants. IS_MANDATORY_DEPOSIT_COL, RecurringDepositConstants.IS_MANDATORY_DEPOSIT_COL); + RecurringDepositConstants.IS_MANDATORY_DEPOSIT_COL, RecurringDepositConstants.IS_MANDATORY_DEPOSIT_COL); CellRangeAddressList allowWithdrawalRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), RecurringDepositConstants.ALLOW_WITHDRAWAL_COL, RecurringDepositConstants.ALLOW_WITHDRAWAL_COL); CellRangeAddressList adjustAdvancePaymentRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - RecurringDepositConstants. ADJUST_ADVANCE_PAYMENTS_COL, RecurringDepositConstants.ADJUST_ADVANCE_PAYMENTS_COL); + RecurringDepositConstants.ADJUST_ADVANCE_PAYMENTS_COL, RecurringDepositConstants.ADJUST_ADVANCE_PAYMENTS_COL); CellRangeAddressList sameFreqAsGroupRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), RecurringDepositConstants.FREQ_SAME_AS_GROUP_CENTER_COL, RecurringDepositConstants.FREQ_SAME_AS_GROUP_CENTER_COL); CellRangeAddressList depositStartDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), @@ -230,41 +238,37 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator DataValidationConstraint fieldOfficerNameConstraint = validationHelper .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$A1))"); DataValidationConstraint submittedDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($B1,$AF$2:$AG$" - + (clientSheetPopulator.getClientsSize() + 1) + ",2,FALSE)", "=TODAY()", - dateFormat); - DataValidationConstraint approvalDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=$E1", "=TODAY()", dateFormat); - DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=$F1", "=TODAY()", dateFormat); - DataValidationConstraint interestCompudingPeriodConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_DAILY , - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_MONTHLY, - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_QUARTERLY, - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_SEMI_ANNUALLY, - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_ANNUALLY}); - DataValidationConstraint interestPostingPeriodConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_MONTHLY , - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_QUARTERLY, - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_BIANUALLY, - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_ANNUALLY }); + DataValidationConstraint.OperatorType.BETWEEN, + "=VLOOKUP($B1,$AF$2:$AG$" + (clientSheetPopulator.getClientsSize() + 1) + ",2,FALSE)", "=TODAY()", dateFormat); + DataValidationConstraint approvalDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$E1", "=TODAY()", dateFormat); + DataValidationConstraint activationDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$F1", "=TODAY()", dateFormat); + DataValidationConstraint interestCompudingPeriodConstraint = validationHelper + .createExplicitListConstraint(new String[] { TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_DAILY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_MONTHLY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_QUARTERLY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_SEMI_ANNUALLY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_ANNUALLY }); + DataValidationConstraint interestPostingPeriodConstraint = validationHelper + .createExplicitListConstraint(new String[] { TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_MONTHLY, + TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_QUARTERLY, + TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_BIANUALLY, + TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_ANNUALLY }); DataValidationConstraint interestCalculationConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_CAL_DAILY_BALANCE, - TemplatePopulateImportConstants.INTEREST_CAL_AVG_BALANCE}); + TemplatePopulateImportConstants.INTEREST_CAL_DAILY_BALANCE, TemplatePopulateImportConstants.INTEREST_CAL_AVG_BALANCE }); - DataValidationConstraint interestCalculationDaysInYearConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_360, - TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_365}); - DataValidationConstraint frequency = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.FREQUENCY_DAYS, - TemplatePopulateImportConstants.FREQUENCY_WEEKS, - TemplatePopulateImportConstants.FREQUENCY_MONTHS, - TemplatePopulateImportConstants.FREQUENCY_YEARS}); - DataValidationConstraint depositConstraint = validationHelper.createDecimalConstraint(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "=INDIRECT(CONCATENATE(\"Min_Deposit_\",$C1))", null); - DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[] { - "True", "False" }); - DataValidationConstraint depositStartDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=$G1", "=TODAY()", "dd/mm/yy"); + DataValidationConstraint interestCalculationDaysInYearConstraint = validationHelper + .createExplicitListConstraint(new String[] { TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_360, + TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_365 }); + DataValidationConstraint frequency = validationHelper.createExplicitListConstraint( + new String[] { TemplatePopulateImportConstants.FREQUENCY_DAYS, TemplatePopulateImportConstants.FREQUENCY_WEEKS, + TemplatePopulateImportConstants.FREQUENCY_MONTHS, TemplatePopulateImportConstants.FREQUENCY_YEARS }); + DataValidationConstraint depositConstraint = validationHelper.createDecimalConstraint( + DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "=INDIRECT(CONCATENATE(\"Min_Deposit_\",$C1))", null); + DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint depositStartDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$G1", "=TODAY()", "dd/mm/yy"); DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); @@ -276,28 +280,20 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator interestPostingPeriodRange); DataValidation interestCalculationValidation = validationHelper.createValidation(interestCalculationConstraint, interestCalculationRange); - DataValidation interestCalculationDaysInYearValidation = validationHelper.createValidation( - interestCalculationDaysInYearConstraint, interestCalculationDaysInYearRange); - DataValidation lockinPeriodFrequencyValidation = validationHelper.createValidation(frequency, - lockinPeriodFrequencyRange); - DataValidation depositPeriodTypeValidation = validationHelper.createValidation(frequency, - depositPeriodTypeRange); - DataValidation depositFrequencyTypeValidation = validationHelper.createValidation(frequency, - depositFrequencyTypeRange); + DataValidation interestCalculationDaysInYearValidation = validationHelper.createValidation(interestCalculationDaysInYearConstraint, + interestCalculationDaysInYearRange); + DataValidation lockinPeriodFrequencyValidation = validationHelper.createValidation(frequency, lockinPeriodFrequencyRange); + DataValidation depositPeriodTypeValidation = validationHelper.createValidation(frequency, depositPeriodTypeRange); + DataValidation depositFrequencyTypeValidation = validationHelper.createValidation(frequency, depositFrequencyTypeRange); DataValidation submittedDateValidation = validationHelper.createValidation(submittedDateConstraint, submittedDateRange); DataValidation approvalDateValidation = validationHelper.createValidation(approvalDateConstraint, approvedDateRange); DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange); - DataValidation depositAmountValidation = validationHelper.createValidation(depositConstraint, depositAmountRange); - DataValidation isMandatoryDepositValidation = validationHelper.createValidation( - booleanConstraint, isMandatoryDepositRange); - DataValidation allowWithdrawalValidation = validationHelper.createValidation( - booleanConstraint, allowWithdrawalRange); - DataValidation adjustAdvancePaymentValidation = validationHelper.createValidation( - booleanConstraint, adjustAdvancePaymentRange); - DataValidation sameFreqAsGroupValidation = validationHelper.createValidation( - booleanConstraint, sameFreqAsGroupRange); - DataValidation depositStartDateValidation = validationHelper.createValidation( - depositStartDateConstraint, depositStartDateRange); + DataValidation depositAmountValidation = validationHelper.createValidation(depositConstraint, depositAmountRange); + DataValidation isMandatoryDepositValidation = validationHelper.createValidation(booleanConstraint, isMandatoryDepositRange); + DataValidation allowWithdrawalValidation = validationHelper.createValidation(booleanConstraint, allowWithdrawalRange); + DataValidation adjustAdvancePaymentValidation = validationHelper.createValidation(booleanConstraint, adjustAdvancePaymentRange); + DataValidation sameFreqAsGroupValidation = validationHelper.createValidation(booleanConstraint, sameFreqAsGroupRange); + DataValidation depositStartDateValidation = validationHelper.createValidation(depositStartDateConstraint, depositStartDateRange); worksheet.addValidationData(officeValidation); worksheet.addValidationData(clientValidation); @@ -329,7 +325,7 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator // Office Names Name officeGroup = savingsWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (officeNames.size() + 1)); // Client and Loan Officer Names for each office for (Integer i = 0; i < officeNames.size(); i++) { @@ -339,20 +335,21 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator Name fieldOfficerName = savingsWorkbook.createName(); if (officeNameToBeginEndIndexesOfStaff != null) { fieldOfficerName.setNameName("Staff_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - fieldOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" - + officeNameToBeginEndIndexesOfStaff[1]); + fieldOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); } if (officeNameToBeginEndIndexesOfClients != null) { clientName.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - clientName.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + ":$B$" - + officeNameToBeginEndIndexesOfClients[1]); + clientName.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfClients[0] + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); } } // Product Name Name productGroup = savingsWorkbook.createName(); productGroup.setNameName("Products"); - productGroup.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$B$2:$B$" + (productSheetPopulator.getProductsSize() + 1)); + productGroup.setRefersToFormula( + TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$B$2:$B$" + (productSheetPopulator.getProductsSize() + 1)); // Default Interest Rate, Interest Compounding Period, Interest Posting // Period, Interest Calculation, Interest Calculation Days In Year, @@ -386,28 +383,28 @@ public class RecurringDepositWorkbookPopulator extends AbstractWorkbookPopulator allowWithdrawalName.setNameName("Allow_Withdrawal_" + productName); mandatoryDepositName.setNameName("Mandatory_Deposit_" + productName); adjustAdvancePaymentsName.setNameName("Adjust_Advance_" + productName); - interestCompoundingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$E$" + (i + 2)); - interestPostingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$F$" + (i + 2)); - interestCalculationName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$G$" + (i + 2)); - daysInYearName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$H$" + (i + 2)); - depositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$N$" + (i + 2)); - minDepositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$L$" + (i + 2)); - maxDepositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$M$" + (i + 2)); - allowWithdrawalName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$Y$" + (i + 2)); - mandatoryDepositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$X$" + (i + 2)); - adjustAdvancePaymentsName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$Z$" + (i + 2)); + interestCompoundingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$E$" + (i + 2)); + interestPostingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$F$" + (i + 2)); + interestCalculationName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$G$" + (i + 2)); + daysInYearName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$H$" + (i + 2)); + depositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$N$" + (i + 2)); + minDepositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$L$" + (i + 2)); + maxDepositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$M$" + (i + 2)); + allowWithdrawalName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$Y$" + (i + 2)); + mandatoryDepositName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$X$" + (i + 2)); + adjustAdvancePaymentsName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$Z$" + (i + 2)); - if(product.getMinDepositTermType() != null) { + if (product.getMinDepositTermType() != null) { minDepositTermTypeName.setNameName("Term_Type_" + productName); - minDepositTermTypeName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$P$" + (i + 2)); + minDepositTermTypeName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$P$" + (i + 2)); } if (product.getLockinPeriodFrequency() != null) { lockinPeriodName.setNameName("Lockin_Period_" + productName); - lockinPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$I$" + (i + 2)); + lockinPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$I$" + (i + 2)); } if (product.getLockinPeriodFrequencyType() != null) { lockinPeriodFrequencyName.setNameName("Lockin_Frequency_" + productName); - lockinPeriodFrequencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$J$" + (i + 2)); + lockinPeriodFrequencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$J$" + (i + 2)); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/savings/SavingsTransactionsWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/savings/SavingsTransactionsWorkbookPopulator.java index 5ae45797c..fdf143eef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/savings/SavingsTransactionsWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/savings/SavingsTransactionsWorkbookPopulator.java @@ -43,70 +43,77 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddressList; public class SavingsTransactionsWorkbookPopulator extends AbstractWorkbookPopulator { + private OfficeSheetPopulator officeSheetPopulator; private ClientSheetPopulator clientSheetPopulator; private ExtrasSheetPopulator extrasSheetPopulator; - private ListsavingsAccounts; + private List savingsAccounts; - public SavingsTransactionsWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - ClientSheetPopulator clientSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator, - List savingsAccounts) { + public SavingsTransactionsWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, ClientSheetPopulator clientSheetPopulator, + ExtrasSheetPopulator extrasSheetPopulator, List savingsAccounts) { this.officeSheetPopulator = officeSheetPopulator; this.clientSheetPopulator = clientSheetPopulator; this.extrasSheetPopulator = extrasSheetPopulator; - this.savingsAccounts=savingsAccounts; + this.savingsAccounts = savingsAccounts; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet savingsTransactionSheet = workbook.createSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME); setLayout(savingsTransactionSheet); - officeSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); - extrasSheetPopulator.populate(workbook,dateFormat); - populateSavingsTable(savingsTransactionSheet,dateFormat); - setRules(savingsTransactionSheet,dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); + extrasSheetPopulator.populate(workbook, dateFormat); + populateSavingsTable(savingsTransactionSheet, dateFormat); + setRules(savingsTransactionSheet, dateFormat); setDefaults(savingsTransactionSheet); } private void setDefaults(Sheet worksheet) { - for(Integer rowNo = 1; rowNo < 3000; rowNo++) - { + for (Integer rowNo = 1; rowNo < 3000; rowNo++) { Row row = worksheet.getRow(rowNo); - if(row == null) { + if (row == null) { row = worksheet.createRow(rowNo); } - writeFormula(TransactionConstants.PRODUCT_COL, row, "IF(ISERROR(VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE)),\"\",VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE))"); - writeFormula(TransactionConstants.OPENING_BALANCE_COL, row, "IF(ISERROR(VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE)),\"\",VLOOKUP($C"+ (rowNo+1) +",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE))"); + writeFormula(TransactionConstants.PRODUCT_COL, row, + "IF(ISERROR(VLOOKUP($C" + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE)),\"\",VLOOKUP($C" + + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",2,FALSE))"); + writeFormula(TransactionConstants.OPENING_BALANCE_COL, row, + "IF(ISERROR(VLOOKUP($C" + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE)),\"\",VLOOKUP($C" + + (rowNo + 1) + ",$Q$2:$S$" + (savingsAccounts.size() + 1) + ",3,FALSE))"); } } - - private void setRules(Sheet worksheet,String dateFormat) { - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + private void setRules(Sheet worksheet, String dateFormat) { + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.OFFICE_NAME_COL, TransactionConstants.OFFICE_NAME_COL); - CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.CLIENT_NAME_COL, TransactionConstants.CLIENT_NAME_COL); - CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.SAVINGS_ACCOUNT_NO_COL, TransactionConstants.SAVINGS_ACCOUNT_NO_COL); - CellRangeAddressList transactionTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList transactionTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.TRANSACTION_TYPE_COL, TransactionConstants.TRANSACTION_TYPE_COL); CellRangeAddressList paymentTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.PAYMENT_TYPE_COL, TransactionConstants.PAYMENT_TYPE_COL); CellRangeAddressList transactionDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), TransactionConstants.TRANSACTION_DATE_COL, TransactionConstants.TRANSACTION_DATE_COL); - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); setNames(worksheet); DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint clientNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))"); - DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); - DataValidationConstraint transactionTypeConstraint = validationHelper.createExplicitListConstraint(new String[] {"Withdrawal","Deposit"}); + DataValidationConstraint clientNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))"); + DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint( + "INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))"); + DataValidationConstraint transactionTypeConstraint = validationHelper + .createExplicitListConstraint(new String[] { "Withdrawal", "Deposit" }); DataValidationConstraint paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentTypes"); - DataValidationConstraint transactionDateConstraint = validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($C1,$Q$2:$T$" + (savingsAccounts.size() + 1) + ",4,FALSE)", "=TODAY()",dateFormat); + DataValidationConstraint transactionDateConstraint = validationHelper.createDateConstraint( + DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($C1,$Q$2:$T$" + (savingsAccounts.size() + 1) + ",4,FALSE)", + "=TODAY()", dateFormat); DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); @@ -127,22 +134,24 @@ public class SavingsTransactionsWorkbookPopulator extends AbstractWorkbookPopula Workbook savingsTransactionWorkbook = worksheet.getWorkbook(); List officeNames = officeSheetPopulator.getOfficeNames(); - //Office Names + // Office Names Name officeGroup = savingsTransactionWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (officeNames.size() + 1)); - //Clients Named after Offices - for(Integer i = 0; i < officeNames.size(); i++) { + // Clients Named after Offices + for (Integer i = 0; i < officeNames.size(); i++) { Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator.getOfficeNameToBeginEndIndexesOfClients().get(i); Name name = savingsTransactionWorkbook.createName(); - if(officeNameToBeginEndIndexesOfClients != null) { + if (officeNameToBeginEndIndexesOfClients != null) { name.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); + name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME + "!$B$" + officeNameToBeginEndIndexesOfClients[0] + + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); } } - //Counting clients with active savings and starting and end addresses of cells for naming + // Counting clients with active savings and starting and end addresses + // of cells for naming HashMap clientNameToBeginEndIndexes = new HashMap<>(); ArrayList clientsWithActiveSavings = new ArrayList<>(); ArrayList clientIdsWithActiveSavings = new ArrayList<>(); @@ -150,36 +159,40 @@ public class SavingsTransactionsWorkbookPopulator extends AbstractWorkbookPopula int endIndex = 1; String clientName = ""; Long clientId = null; - for(int i = 0; i < savingsAccounts.size(); i++){ - if(!clientName.equals(savingsAccounts.get(i).getClientName())) { + for (int i = 0; i < savingsAccounts.size(); i++) { + if (!clientName.equals(savingsAccounts.get(i).getClientName())) { endIndex = i + 1; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); startIndex = i + 2; clientName = savingsAccounts.get(i).getClientName(); clientId = savingsAccounts.get(i).getClientId(); clientsWithActiveSavings.add(clientName); clientIdsWithActiveSavings.add(clientId); } - if(i == savingsAccounts.size()-1) { + if (i == savingsAccounts.size() - 1) { endIndex = i + 2; - clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex}); + clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex }); } } - //Account Number Named after Clients - for(int j = 0; j < clientsWithActiveSavings.size(); j++) { + // Account Number Named after Clients + for (int j = 0; j < clientsWithActiveSavings.size(); j++) { Name name = savingsTransactionWorkbook.createName(); - name.setNameName("Account_" + clientsWithActiveSavings.get(j).replace(" ", "_") + "_" + clientIdsWithActiveSavings.get(j) + "_"); - name.setRefersToFormula(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME+"!$Q$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[0] + ":$Q$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[1]); + name.setNameName( + "Account_" + clientsWithActiveSavings.get(j).replace(" ", "_") + "_" + clientIdsWithActiveSavings.get(j) + "_"); + name.setRefersToFormula(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME + "!$Q$" + + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[0] + ":$Q$" + + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[1]); } - //Payment Type Name + // Payment Type Name Name paymentTypeGroup = savingsTransactionWorkbook.createName(); paymentTypeGroup.setNameName("PaymentTypes"); - paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); + paymentTypeGroup.setRefersToFormula( + TemplatePopulateImportConstants.EXTRAS_SHEET_NAME + "!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1)); } - private void populateSavingsTable(Sheet savingsTransactionSheet,String dateFormat) { + private void populateSavingsTable(Sheet savingsTransactionSheet, String dateFormat) { Workbook workbook = savingsTransactionSheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); @@ -187,19 +200,20 @@ public class SavingsTransactionsWorkbookPopulator extends AbstractWorkbookPopula int rowIndex = 1; Row row; Collections.sort(savingsAccounts, SavingsAccountData.ClientNameComparator); - for(SavingsAccountData savingsAccount : savingsAccounts) { + for (SavingsAccountData savingsAccount : savingsAccounts) { row = savingsTransactionSheet.createRow(rowIndex++); - writeString(TransactionConstants.LOOKUP_CLIENT_NAME_COL, row, savingsAccount.getClientName() + "(" + savingsAccount.getClientId() + ")"); + writeString(TransactionConstants.LOOKUP_CLIENT_NAME_COL, row, + savingsAccount.getClientName() + "(" + savingsAccount.getClientId() + ")"); writeString(TransactionConstants.LOOKUP_ACCOUNT_NO_COL, row, savingsAccount.getAccountNo()); writeString(TransactionConstants.LOOKUP_PRODUCT_COL, row, savingsAccount.getSavingsProductName()); - if(savingsAccount.getMinRequiredOpeningBalance() != null) { - writeBigDecimal(TransactionConstants.LOOKUP_OPENING_BALANCE_COL, row, - savingsAccount.getMinRequiredOpeningBalance()); + if (savingsAccount.getMinRequiredOpeningBalance() != null) { + writeBigDecimal(TransactionConstants.LOOKUP_OPENING_BALANCE_COL, row, savingsAccount.getMinRequiredOpeningBalance()); } - writeDate(TransactionConstants.LOOKUP_SAVINGS_ACTIVATION_DATE_COL, row,"" + - savingsAccount.getTimeline().getActivatedOnDate().getDayOfMonth() + "/" - + savingsAccount.getTimeline().getActivatedOnDate().getMonthOfYear() + "/" - + savingsAccount.getTimeline().getActivatedOnDate().getYear() , dateCellStyle,dateFormat); + writeDate(TransactionConstants.LOOKUP_SAVINGS_ACTIVATION_DATE_COL, row, + "" + savingsAccount.getTimeline().getActivatedOnDate().getDayOfMonth() + "/" + + savingsAccount.getTimeline().getActivatedOnDate().getMonthOfYear() + "/" + + savingsAccount.getTimeline().getActivatedOnDate().getYear(), + dateCellStyle, dateFormat); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/savings/SavingsWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/savings/SavingsWorkbookPopulator.java index 5d9790222..b9b31a91d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/savings/SavingsWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/savings/SavingsWorkbookPopulator.java @@ -49,30 +49,29 @@ public class SavingsWorkbookPopulator extends AbstractWorkbookPopulator { private PersonnelSheetPopulator personnelSheetPopulator; private SavingsProductSheetPopulator productSheetPopulator; - - public SavingsWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, ClientSheetPopulator clientSheetPopulator, GroupSheetPopulator groupSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, SavingsProductSheetPopulator savingsProductSheetPopulator) { - this.officeSheetPopulator=officeSheetPopulator; - this.clientSheetPopulator=clientSheetPopulator; - this.groupSheetPopulator=groupSheetPopulator; - this.personnelSheetPopulator=personnelSheetPopulator; - this.productSheetPopulator=savingsProductSheetPopulator; + this.officeSheetPopulator = officeSheetPopulator; + this.clientSheetPopulator = clientSheetPopulator; + this.groupSheetPopulator = groupSheetPopulator; + this.personnelSheetPopulator = personnelSheetPopulator; + this.productSheetPopulator = savingsProductSheetPopulator; } @Override - public void populate(Workbook workbook,String dateFormat) { + public void populate(Workbook workbook, String dateFormat) { Sheet savingsSheet = workbook.createSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME); - officeSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); - groupSheetPopulator.populate(workbook,dateFormat); - personnelSheetPopulator.populate(workbook,dateFormat); - productSheetPopulator.populate(workbook,dateFormat); - setRules(savingsSheet,dateFormat); - setDefaults(savingsSheet,dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); + groupSheetPopulator.populate(workbook, dateFormat); + personnelSheetPopulator.populate(workbook, dateFormat); + productSheetPopulator.populate(workbook, dateFormat); + setRules(savingsSheet, dateFormat); + setDefaults(savingsSheet, dateFormat); setClientAndGroupDateLookupTable(savingsSheet, clientSheetPopulator.getClients(), groupSheetPopulator.getGroups(), - SavingsConstants.LOOKUP_CLIENT_NAME_COL, SavingsConstants.LOOKUP_ACTIVATION_DATE_COL,!TemplatePopulateImportConstants.CONTAINS_CLIENT_EXTERNAL_ID,dateFormat); + SavingsConstants.LOOKUP_CLIENT_NAME_COL, SavingsConstants.LOOKUP_ACTIVATION_DATE_COL, + !TemplatePopulateImportConstants.CONTAINS_CLIENT_EXTERNAL_ID, dateFormat); setLayout(savingsSheet); } @@ -140,56 +139,57 @@ public class SavingsWorkbookPopulator extends AbstractWorkbookPopulator { writeString(SavingsConstants.EXTERNAL_ID_COL, rowHeader, "External Id"); writeString(SavingsConstants.ALLOW_OVER_DRAFT_COL, rowHeader, "Is Overdraft Allowed "); - writeString(SavingsConstants.OVER_DRAFT_LIMIT_COL, rowHeader," Maximum Overdraft Amount Limit "); + writeString(SavingsConstants.OVER_DRAFT_LIMIT_COL, rowHeader, " Maximum Overdraft Amount Limit "); - writeString(SavingsConstants.CHARGE_ID_1,rowHeader,"Charge Id"); + writeString(SavingsConstants.CHARGE_ID_1, rowHeader, "Charge Id"); writeString(SavingsConstants.CHARGE_AMOUNT_1, rowHeader, "Charged Amount"); writeString(SavingsConstants.CHARGE_DUE_DATE_1, rowHeader, "Charged On Date"); - writeString(SavingsConstants.CHARGE_ID_2,rowHeader,"Charge Id"); + writeString(SavingsConstants.CHARGE_ID_2, rowHeader, "Charge Id"); writeString(SavingsConstants.CHARGE_AMOUNT_2, rowHeader, "Charged Amount"); writeString(SavingsConstants.CHARGE_DUE_DATE_2, rowHeader, "Charged On Date"); } - private void setDefaults(Sheet worksheet,String dateFormat) { + private void setDefaults(Sheet worksheet, String dateFormat) { Workbook workbook = worksheet.getWorkbook(); CellStyle dateCellStyle = workbook.createCellStyle(); short df = workbook.createDataFormat().getFormat(dateFormat); dateCellStyle.setDataFormat(df); - for (Integer rowNo = 1; rowNo < 1000; rowNo++) { - Row row = worksheet.createRow(rowNo); - writeFormula(SavingsConstants.CURRENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Currency_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Currency_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.DECIMAL_PLACES_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Decimal_Places_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Decimal_Places_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.IN_MULTIPLES_OF_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"In_Multiples_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"In_Multiples_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.NOMINAL_ANNUAL_INTEREST_RATE_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Rate_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Rate_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.INTEREST_COMPOUNDING_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Compouding_\",$D" - + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Compouding_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.INTEREST_POSTING_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Posting_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Posting_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.INTEREST_CALCULATION_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Calculation_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Calculation_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Days_In_Year_\",$D" - + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Days_In_Year_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.MIN_OPENING_BALANCE_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Min_Balance_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Min_Balance_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.LOCKIN_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Period_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Period_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.LOCKIN_PERIOD_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.APPLY_WITHDRAWAL_FEE_FOR_TRANSFERS, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Withdrawal_Fee_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Withdrawal_Fee_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.ALLOW_OVER_DRAFT_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Overdraft_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Overdraft_\",$D" + (rowNo + 1) + ")))"); - writeFormula(SavingsConstants.OVER_DRAFT_LIMIT_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Overdraft_Limit_\",$D" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"Overdraft_Limit_\",$D" + (rowNo + 1) + ")))"); - } + for (Integer rowNo = 1; rowNo < 1000; rowNo++) { + Row row = worksheet.createRow(rowNo); + writeFormula(SavingsConstants.CURRENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Currency_\",$D" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Currency_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.DECIMAL_PLACES_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Decimal_Places_\",$D" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Decimal_Places_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.IN_MULTIPLES_OF_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"In_Multiples_\",$D" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"In_Multiples_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.NOMINAL_ANNUAL_INTEREST_RATE_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Rate_\",$D" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Rate_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.INTEREST_COMPOUNDING_PERIOD_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Compouding_\",$D" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Compouding_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.INTEREST_POSTING_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Posting_\",$D" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Posting_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.INTEREST_CALCULATION_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Interest_Calculation_\",$D" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Interest_Calculation_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Days_In_Year_\",$D" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Days_In_Year_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.MIN_OPENING_BALANCE_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Min_Balance_\",$D" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Min_Balance_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.LOCKIN_PERIOD_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Period_\",$D" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Period_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.LOCKIN_PERIOD_FREQUENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$D" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Lockin_Frequency_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.APPLY_WITHDRAWAL_FEE_FOR_TRANSFERS, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Withdrawal_Fee_\",$D" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"Withdrawal_Fee_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.ALLOW_OVER_DRAFT_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Overdraft_\",$D" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Overdraft_\",$D" + (rowNo + 1) + ")))"); + writeFormula(SavingsConstants.OVER_DRAFT_LIMIT_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"Overdraft_Limit_\",$D" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"Overdraft_Limit_\",$D" + (rowNo + 1) + ")))"); } + } - private void setRules(Sheet worksheet,String dateFormat) { + private void setRules(Sheet worksheet, String dateFormat) { CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), SavingsConstants.OFFICE_NAME_COL, SavingsConstants.OFFICE_NAME_COL); CellRangeAddressList savingsTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), @@ -212,63 +212,57 @@ public class SavingsWorkbookPopulator extends AbstractWorkbookPopulator { SavingsConstants.INTEREST_POSTING_PERIOD_COL, SavingsConstants.INTEREST_POSTING_PERIOD_COL); CellRangeAddressList interestCalculationRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), SavingsConstants.INTEREST_CALCULATION_COL, SavingsConstants.INTEREST_CALCULATION_COL); - CellRangeAddressList interestCalculationDaysInYearRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), SavingsConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, - SavingsConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL); + CellRangeAddressList interestCalculationDaysInYearRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + SavingsConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL, SavingsConstants.INTEREST_CALCULATION_DAYS_IN_YEAR_COL); CellRangeAddressList lockinPeriodFrequencyRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), SavingsConstants.LOCKIN_PERIOD_FREQUENCY_COL, SavingsConstants.LOCKIN_PERIOD_FREQUENCY_COL); - CellRangeAddressList applyWithdrawalFeeForTransfersRange = new CellRangeAddressList(1, - SpreadsheetVersion.EXCEL97.getLastRowIndex(), SavingsConstants.APPLY_WITHDRAWAL_FEE_FOR_TRANSFERS, SavingsConstants.APPLY_WITHDRAWAL_FEE_FOR_TRANSFERS); - CellRangeAddressList allowOverdraftRange = new CellRangeAddressList(1,SpreadsheetVersion.EXCEL97.getLastRowIndex(),SavingsConstants.ALLOW_OVER_DRAFT_COL,SavingsConstants.ALLOW_OVER_DRAFT_COL); - - + CellRangeAddressList applyWithdrawalFeeForTransfersRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + SavingsConstants.APPLY_WITHDRAWAL_FEE_FOR_TRANSFERS, SavingsConstants.APPLY_WITHDRAWAL_FEE_FOR_TRANSFERS); + CellRangeAddressList allowOverdraftRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + SavingsConstants.ALLOW_OVER_DRAFT_COL, SavingsConstants.ALLOW_OVER_DRAFT_COL); DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet); setNames(worksheet); DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint savingsTypeConstraint = validationHelper.createExplicitListConstraint(new String[] { "Individual", - "Group" }); - DataValidationConstraint clientNameConstraint = validationHelper - .createFormulaListConstraint("IF($B1=\"Individual\",INDIRECT(CONCATENATE(\"Client_\",$A1)),INDIRECT(CONCATENATE(\"Group_\",$A1)))"); + DataValidationConstraint savingsTypeConstraint = validationHelper + .createExplicitListConstraint(new String[] { "Individual", "Group" }); + DataValidationConstraint clientNameConstraint = validationHelper.createFormulaListConstraint( + "IF($B1=\"Individual\",INDIRECT(CONCATENATE(\"Client_\",$A1)),INDIRECT(CONCATENATE(\"Group_\",$A1)))"); DataValidationConstraint productNameConstraint = validationHelper.createFormulaListConstraint("Products"); DataValidationConstraint fieldOfficerNameConstraint = validationHelper .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$A1))"); DataValidationConstraint submittedDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($C1,$AF$2:$AG$" - + (clientSheetPopulator.getClientsSize() + groupSheetPopulator.getGroupsSize() + 1) + ",2,FALSE)", "=TODAY()", - dateFormat); - DataValidationConstraint approvalDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=$F1", "=TODAY()", dateFormat); - DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint( - DataValidationConstraint.OperatorType.BETWEEN, "=$G1", "=TODAY()", dateFormat); - DataValidationConstraint interestCompudingPeriodConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_DAILY , - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_MONTHLY, - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_QUARTERLY, - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_SEMI_ANNUALLY, - TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_ANNUALLY }); - DataValidationConstraint interestPostingPeriodConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_MONTHLY , - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_QUARTERLY, - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_BIANUALLY, - TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_ANNUALLY }); + DataValidationConstraint.OperatorType.BETWEEN, + "=VLOOKUP($C1,$AF$2:$AG$" + (clientSheetPopulator.getClientsSize() + groupSheetPopulator.getGroupsSize() + 1) + ",2,FALSE)", + "=TODAY()", dateFormat); + DataValidationConstraint approvalDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$F1", "=TODAY()", dateFormat); + DataValidationConstraint activationDateConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN, "=$G1", "=TODAY()", dateFormat); + DataValidationConstraint interestCompudingPeriodConstraint = validationHelper + .createExplicitListConstraint(new String[] { TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_DAILY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_MONTHLY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_QUARTERLY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_SEMI_ANNUALLY, + TemplatePopulateImportConstants.INTEREST_COMPOUNDING_PERIOD_ANNUALLY }); + DataValidationConstraint interestPostingPeriodConstraint = validationHelper + .createExplicitListConstraint(new String[] { TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_MONTHLY, + TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_QUARTERLY, + TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_BIANUALLY, + TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_ANNUALLY }); DataValidationConstraint interestCalculationConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_CAL_DAILY_BALANCE, - TemplatePopulateImportConstants.INTEREST_CAL_AVG_BALANCE }); - DataValidationConstraint interestCalculationDaysInYearConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_360, - TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_365 }); - DataValidationConstraint lockinPeriodFrequencyConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.FREQUENCY_DAYS, - TemplatePopulateImportConstants.FREQUENCY_WEEKS, - TemplatePopulateImportConstants.FREQUENCY_MONTHS, - TemplatePopulateImportConstants.FREQUENCY_YEARS }); - DataValidationConstraint applyWithdrawalFeeForTransferConstraint = validationHelper.createExplicitListConstraint(new String[] { - "True", "False" }); - DataValidationConstraint allowOverdraftConstraint = validationHelper.createExplicitListConstraint(new String[] { - "True", "False" }); + TemplatePopulateImportConstants.INTEREST_CAL_DAILY_BALANCE, TemplatePopulateImportConstants.INTEREST_CAL_AVG_BALANCE }); + DataValidationConstraint interestCalculationDaysInYearConstraint = validationHelper + .createExplicitListConstraint(new String[] { TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_360, + TemplatePopulateImportConstants.INTEREST_CAL_DAYS_IN_YEAR_365 }); + DataValidationConstraint lockinPeriodFrequencyConstraint = validationHelper.createExplicitListConstraint( + new String[] { TemplatePopulateImportConstants.FREQUENCY_DAYS, TemplatePopulateImportConstants.FREQUENCY_WEEKS, + TemplatePopulateImportConstants.FREQUENCY_MONTHS, TemplatePopulateImportConstants.FREQUENCY_YEARS }); + DataValidationConstraint applyWithdrawalFeeForTransferConstraint = validationHelper + .createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint allowOverdraftConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); DataValidation savingsTypeValidation = validationHelper.createValidation(savingsTypeConstraint, savingsTypeRange); @@ -281,17 +275,16 @@ public class SavingsWorkbookPopulator extends AbstractWorkbookPopulator { interestPostingPeriodRange); DataValidation interestCalculationValidation = validationHelper.createValidation(interestCalculationConstraint, interestCalculationRange); - DataValidation interestCalculationDaysInYearValidation = validationHelper.createValidation( - interestCalculationDaysInYearConstraint, interestCalculationDaysInYearRange); + DataValidation interestCalculationDaysInYearValidation = validationHelper.createValidation(interestCalculationDaysInYearConstraint, + interestCalculationDaysInYearRange); DataValidation lockinPeriodFrequencyValidation = validationHelper.createValidation(lockinPeriodFrequencyConstraint, lockinPeriodFrequencyRange); - DataValidation applyWithdrawalFeeForTransferValidation = validationHelper.createValidation( - applyWithdrawalFeeForTransferConstraint, applyWithdrawalFeeForTransfersRange); + DataValidation applyWithdrawalFeeForTransferValidation = validationHelper.createValidation(applyWithdrawalFeeForTransferConstraint, + applyWithdrawalFeeForTransfersRange); DataValidation submittedDateValidation = validationHelper.createValidation(submittedDateConstraint, submittedDateRange); DataValidation approvalDateValidation = validationHelper.createValidation(approvalDateConstraint, approvedDateRange); DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange); - DataValidation allowOverdraftValidation = validationHelper.createValidation( - allowOverdraftConstraint, allowOverdraftRange); + DataValidation allowOverdraftValidation = validationHelper.createValidation(allowOverdraftConstraint, allowOverdraftRange); worksheet.addValidationData(officeValidation); worksheet.addValidationData(savingsTypeValidation); @@ -318,7 +311,7 @@ public class SavingsWorkbookPopulator extends AbstractWorkbookPopulator { // Office Names Name officeGroup = savingsWorkbook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (officeNames.size() + 1)); // Client and Loan Officer Names for each office for (Integer i = 0; i < officeNames.size(); i++) { @@ -330,25 +323,26 @@ public class SavingsWorkbookPopulator extends AbstractWorkbookPopulator { Name groupName = savingsWorkbook.createName(); if (officeNameToBeginEndIndexesOfStaff != null) { fieldOfficerName.setNameName("Staff_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - fieldOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" - + officeNameToBeginEndIndexesOfStaff[1]); + fieldOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]); } if (officeNameToBeginEndIndexesOfClients != null) { clientName.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - clientName.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + ":$B$" - + officeNameToBeginEndIndexesOfClients[1]); + clientName.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfClients[0] + ":$B$" + officeNameToBeginEndIndexesOfClients[1]); } if (officeNameToBeginEndIndexesOfGroups != null) { groupName.setNameName("Group_" + officeNames.get(i).trim().replaceAll("[ )(]", "_")); - groupName.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfGroups[0] + ":$B$" - + officeNameToBeginEndIndexesOfGroups[1]); + groupName.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME + "!$B$" + + officeNameToBeginEndIndexesOfGroups[0] + ":$B$" + officeNameToBeginEndIndexesOfGroups[1]); } } // Product Name Name productGroup = savingsWorkbook.createName(); productGroup.setNameName("Products"); - productGroup.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$B$2:$B$" + (productSheetPopulator.getProductsSize() + 1)); + productGroup.setRefersToFormula( + TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$B$2:$B$" + (productSheetPopulator.getProductsSize() + 1)); // Default Interest Rate, Interest Compounding Period, Interest Posting // Period, Interest Calculation, Interest Calculation Days In Year, @@ -386,37 +380,35 @@ public class SavingsWorkbookPopulator extends AbstractWorkbookPopulator { withdrawalFeeName.setNameName("Withdrawal_Fee_" + productName); allowOverdraftName.setNameName("Overdraft_" + productName); - interestCompoundingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$D$" + (i + 2)); - interestPostingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$E$" + (i + 2)); - interestCalculationName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$F$" + (i + 2)); - daysInYearName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$G$" + (i + 2)); - currencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$K$" + (i + 2)); - decimalPlacesName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$L$" + (i + 2)); - withdrawalFeeName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$N$" + (i + 2)); - allowOverdraftName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$O$" + (i + 2)); + interestCompoundingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$D$" + (i + 2)); + interestPostingPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$E$" + (i + 2)); + interestCalculationName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$F$" + (i + 2)); + daysInYearName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$G$" + (i + 2)); + currencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$K$" + (i + 2)); + decimalPlacesName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$L$" + (i + 2)); + withdrawalFeeName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$N$" + (i + 2)); + allowOverdraftName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$O$" + (i + 2)); if (product.getOverdraftLimit() != null) { overdraftLimitName.setNameName("Overdraft_Limit_" + productName); - overdraftLimitName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$P$" + (i + 2)); + overdraftLimitName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$P$" + (i + 2)); } if (product.getMinRequiredOpeningBalance() != null) { minOpeningBalanceName.setNameName("Min_Balance_" + productName); - minOpeningBalanceName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$H$" + (i + 2)); + minOpeningBalanceName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$H$" + (i + 2)); } if (product.getLockinPeriodFrequency() != null) { lockinPeriodName.setNameName("Lockin_Period_" + productName); - lockinPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$I$" + (i + 2)); + lockinPeriodName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$I$" + (i + 2)); } if (product.getLockinPeriodFrequencyType() != null) { lockinPeriodFrequencyName.setNameName("Lockin_Frequency_" + productName); - lockinPeriodFrequencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$J$" + (i + 2)); + lockinPeriodFrequencyName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$J$" + (i + 2)); } if (product.getCurrency().currencyInMultiplesOf() != null) { inMultiplesOfName.setNameName("In_Multiples_" + productName); - inMultiplesOfName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME+"!$M$" + (i + 2)); + inMultiplesOfName.setRefersToFormula(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME + "!$M$" + (i + 2)); } } } } - - diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/shareaccount/SharedAccountWorkBookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/shareaccount/SharedAccountWorkBookPopulator.java index a92e3061a..3bc646ac4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/shareaccount/SharedAccountWorkBookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/shareaccount/SharedAccountWorkBookPopulator.java @@ -41,81 +41,81 @@ import org.apache.poi.ss.util.CellRangeAddressList; public class SharedAccountWorkBookPopulator extends AbstractWorkbookPopulator { - private SharedProductsSheetPopulator sharedProductsSheetPopulator; - private ClientSheetPopulator clientSheetPopulator; - private SavingsAccountSheetPopulator savingsAccountSheetPopulator; + private SharedProductsSheetPopulator sharedProductsSheetPopulator; + private ClientSheetPopulator clientSheetPopulator; + private SavingsAccountSheetPopulator savingsAccountSheetPopulator; public SharedAccountWorkBookPopulator(SharedProductsSheetPopulator sharedProductsSheetPopulator, - ClientSheetPopulator clientSheetPopulator,SavingsAccountSheetPopulator savingsAccountSheetPopulator) { - this.sharedProductsSheetPopulator=sharedProductsSheetPopulator; - this.clientSheetPopulator=clientSheetPopulator; - this.savingsAccountSheetPopulator=savingsAccountSheetPopulator; + ClientSheetPopulator clientSheetPopulator, SavingsAccountSheetPopulator savingsAccountSheetPopulator) { + this.sharedProductsSheetPopulator = sharedProductsSheetPopulator; + this.clientSheetPopulator = clientSheetPopulator; + this.savingsAccountSheetPopulator = savingsAccountSheetPopulator; } @Override - public void populate(Workbook workbook,String dateFormat) { - Sheet sharedAccountSheet= workbook.createSheet(TemplatePopulateImportConstants.SHARED_ACCOUNTS_SHEET_NAME); - sharedProductsSheetPopulator.populate(workbook,dateFormat); - clientSheetPopulator.populate(workbook,dateFormat); - savingsAccountSheetPopulator.populate(workbook,dateFormat); + public void populate(Workbook workbook, String dateFormat) { + Sheet sharedAccountSheet = workbook.createSheet(TemplatePopulateImportConstants.SHARED_ACCOUNTS_SHEET_NAME); + sharedProductsSheetPopulator.populate(workbook, dateFormat); + clientSheetPopulator.populate(workbook, dateFormat); + savingsAccountSheetPopulator.populate(workbook, dateFormat); setLayout(sharedAccountSheet); - setRules(sharedAccountSheet,dateFormat); + setRules(sharedAccountSheet, dateFormat); setDefaults(sharedAccountSheet); } private void setDefaults(Sheet sharedAccountSheet) { - for (Integer rowNo=1;rowNo<3000;rowNo++){ - Row row=sharedAccountSheet.createRow(rowNo); - writeFormula(SharedAccountsConstants.CURRENCY_COL,row,"IF(ISERROR(INDIRECT(CONCATENATE(\"CURRENCY_\",$B" + (rowNo + 1) + for (Integer rowNo = 1; rowNo < 3000; rowNo++) { + Row row = sharedAccountSheet.createRow(rowNo); + writeFormula(SharedAccountsConstants.CURRENCY_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"CURRENCY_\",$B" + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"CURRENCY_\",$B" + (rowNo + 1) + ")))"); - writeFormula(SharedAccountsConstants.DECIMAL_PLACES_COL,row,"IF(ISERROR(INDIRECT(CONCATENATE(\"DECIMAL_PLACES_\",$B" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"DECIMAL_PLACES_\",$B" + (rowNo + 1) + ")))"); - writeFormula(SharedAccountsConstants.TODAYS_PRICE_COL,row,"IF(ISERROR(INDIRECT(CONCATENATE(\"TODAYS_PRICE_\",$B" + (rowNo + 1) + writeFormula(SharedAccountsConstants.DECIMAL_PLACES_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"DECIMAL_PLACES_\",$B" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"DECIMAL_PLACES_\",$B" + (rowNo + 1) + ")))"); + writeFormula(SharedAccountsConstants.TODAYS_PRICE_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"TODAYS_PRICE_\",$B" + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"TODAYS_PRICE_\",$B" + (rowNo + 1) + ")))"); - writeFormula(SharedAccountsConstants.CURRENCY_IN_MULTIPLES_COL,row,"IF(ISERROR(INDIRECT(CONCATENATE(\"CURRENCY_IN_MULTIPLES_\",$B" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"CURRENCY_IN_MULTIPLES_\",$B" + (rowNo + 1) + ")))"); - writeFormula(SharedAccountsConstants.CHARGES_NAME_1_COL,row,"IF(ISERROR(INDIRECT(CONCATENATE(\"CHARGES_NAME_1_\",$B" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"CHARGES_NAME_1_\",$B" + (rowNo + 1) + ")))"); - writeFormula(SharedAccountsConstants.CHARGES_NAME_2_COL,row,"IF(ISERROR(INDIRECT(CONCATENATE(\"CHARGES_NAME_2_\",$B" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"CHARGES_NAME_2_\",$B" + (rowNo + 1) + ")))"); - writeFormula(SharedAccountsConstants.CHARGES_NAME_3_COL,row,"IF(ISERROR(INDIRECT(CONCATENATE(\"CHARGES_NAME_3_\",$B" + (rowNo + 1) - + "))),\"\",INDIRECT(CONCATENATE(\"CHARGES_NAME_3_\",$B" + (rowNo + 1) + ")))"); - } + writeFormula(SharedAccountsConstants.CURRENCY_IN_MULTIPLES_COL, row, + "IF(ISERROR(INDIRECT(CONCATENATE(\"CURRENCY_IN_MULTIPLES_\",$B" + (rowNo + 1) + + "))),\"\",INDIRECT(CONCATENATE(\"CURRENCY_IN_MULTIPLES_\",$B" + (rowNo + 1) + ")))"); + writeFormula(SharedAccountsConstants.CHARGES_NAME_1_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"CHARGES_NAME_1_\",$B" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"CHARGES_NAME_1_\",$B" + (rowNo + 1) + ")))"); + writeFormula(SharedAccountsConstants.CHARGES_NAME_2_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"CHARGES_NAME_2_\",$B" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"CHARGES_NAME_2_\",$B" + (rowNo + 1) + ")))"); + writeFormula(SharedAccountsConstants.CHARGES_NAME_3_COL, row, "IF(ISERROR(INDIRECT(CONCATENATE(\"CHARGES_NAME_3_\",$B" + + (rowNo + 1) + "))),\"\",INDIRECT(CONCATENATE(\"CHARGES_NAME_3_\",$B" + (rowNo + 1) + ")))"); + } } - private void setRules(Sheet sharedAccountSheet,String dateFormat) { + private void setRules(Sheet sharedAccountSheet, String dateFormat) { CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - SharedAccountsConstants.CLIENT_NAME_COL,SharedAccountsConstants.CLIENT_NAME_COL); + SharedAccountsConstants.CLIENT_NAME_COL, SharedAccountsConstants.CLIENT_NAME_COL); CellRangeAddressList productRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - SharedAccountsConstants.PRODUCT_COL,SharedAccountsConstants.PRODUCT_COL); + SharedAccountsConstants.PRODUCT_COL, SharedAccountsConstants.PRODUCT_COL); CellRangeAddressList submittedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), SharedAccountsConstants.SUBMITTED_ON_COL, SharedAccountsConstants.SUBMITTED_ON_COL); CellRangeAddressList lockingFrequencyTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - SharedAccountsConstants.LOCK_IN_PERIOD_FREQUENCY_TYPE,SharedAccountsConstants. LOCK_IN_PERIOD_FREQUENCY_TYPE); + SharedAccountsConstants.LOCK_IN_PERIOD_FREQUENCY_TYPE, SharedAccountsConstants.LOCK_IN_PERIOD_FREQUENCY_TYPE); CellRangeAddressList applicationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), SharedAccountsConstants.APPLICATION_DATE_COL, SharedAccountsConstants.APPLICATION_DATE_COL); CellRangeAddressList allowDividendCalcRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), - SharedAccountsConstants.ALLOW_DIVIDEND_CALCULATION_FOR_INACTIVE_CLIENTS_COL, SharedAccountsConstants.ALLOW_DIVIDEND_CALCULATION_FOR_INACTIVE_CLIENTS_COL); + SharedAccountsConstants.ALLOW_DIVIDEND_CALCULATION_FOR_INACTIVE_CLIENTS_COL, + SharedAccountsConstants.ALLOW_DIVIDEND_CALCULATION_FOR_INACTIVE_CLIENTS_COL); DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) sharedAccountSheet); setNames(sharedAccountSheet); DataValidationConstraint clientNameConstraint = validationHelper.createFormulaListConstraint("Clients"); DataValidationConstraint productNameConstraint = validationHelper.createFormulaListConstraint("Products"); - DataValidationConstraint dateConstraint = validationHelper.createDateConstraint - (DataValidationConstraint.OperatorType.LESS_OR_EQUAL,"=TODAY()",null, dateFormat); - DataValidationConstraint frequencyConstraint = validationHelper.createExplicitListConstraint(new String[] { - TemplatePopulateImportConstants.FREQUENCY_DAYS, - TemplatePopulateImportConstants.FREQUENCY_WEEKS, - TemplatePopulateImportConstants.FREQUENCY_MONTHS, - TemplatePopulateImportConstants.FREQUENCY_YEARS }); - DataValidationConstraint booleanConstraint=validationHelper.createExplicitListConstraint(new String[]{"True","False"}); + DataValidationConstraint dateConstraint = validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, + "=TODAY()", null, dateFormat); + DataValidationConstraint frequencyConstraint = validationHelper.createExplicitListConstraint( + new String[] { TemplatePopulateImportConstants.FREQUENCY_DAYS, TemplatePopulateImportConstants.FREQUENCY_WEEKS, + TemplatePopulateImportConstants.FREQUENCY_MONTHS, TemplatePopulateImportConstants.FREQUENCY_YEARS }); + DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange); - DataValidation productValidation=validationHelper.createValidation(productNameConstraint,productRange); - DataValidation submittedOnValidation=validationHelper.createValidation(dateConstraint,submittedDateRange); - DataValidation frequencyValidation=validationHelper.createValidation(frequencyConstraint,lockingFrequencyTypeRange); - DataValidation applicationDateValidation=validationHelper.createValidation(dateConstraint,applicationDateRange); - DataValidation allowDividendValidation=validationHelper.createValidation(booleanConstraint,allowDividendCalcRange); + DataValidation productValidation = validationHelper.createValidation(productNameConstraint, productRange); + DataValidation submittedOnValidation = validationHelper.createValidation(dateConstraint, submittedDateRange); + DataValidation frequencyValidation = validationHelper.createValidation(frequencyConstraint, lockingFrequencyTypeRange); + DataValidation applicationDateValidation = validationHelper.createValidation(dateConstraint, applicationDateRange); + DataValidation allowDividendValidation = validationHelper.createValidation(booleanConstraint, allowDividendCalcRange); sharedAccountSheet.addValidationData(clientValidation); sharedAccountSheet.addValidationData(productValidation); @@ -127,119 +127,122 @@ public class SharedAccountWorkBookPopulator extends AbstractWorkbookPopulator { } private void setNames(Sheet sharedAccountSheet) { - List clients=clientSheetPopulator.getClients(); - List products=sharedProductsSheetPopulator.getSharedProductDataList(); - Workbook sharedAccountWorkbook=sharedAccountSheet.getWorkbook(); + List clients = clientSheetPopulator.getClients(); + List products = sharedProductsSheetPopulator.getSharedProductDataList(); + Workbook sharedAccountWorkbook = sharedAccountSheet.getWorkbook(); - Name clientsGroup=sharedAccountWorkbook.createName(); + Name clientsGroup = sharedAccountWorkbook.createName(); clientsGroup.setNameName("Clients"); - clientsGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$2:$B$"+clients.size()+1); + clientsGroup.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME + "!$B$2:$B$" + clients.size() + 1); - Name productGroup=sharedAccountWorkbook.createName(); + Name productGroup = sharedAccountWorkbook.createName(); productGroup.setNameName("Products"); - productGroup.setRefersToFormula(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME+"!$B$2:$B$"+products.size()+1); + productGroup.setRefersToFormula(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME + "!$B$2:$B$" + products.size() + 1); - for (Integer i=0;i offices = officeSheetPopulator.getOffices(); setNames(staffSheet, offices); - DataValidationConstraint officeNameConstraint = - validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint isLoanOfficerConstraint = - validationHelper.createExplicitListConstraint(new String[] {"True", "False"}); - DataValidationConstraint joinedOnConstraint = - validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, - "=TODAY()",null, dateFormat); - DataValidationConstraint isActiveConstraint = - validationHelper.createExplicitListConstraint(new String[] {"True", "False"}); + DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); + DataValidationConstraint isLoanOfficerConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); + DataValidationConstraint joinedOnConstraint = validationHelper + .createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL, "=TODAY()", null, dateFormat); + DataValidationConstraint isActiveConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); - DataValidation officeValidation = - validationHelper.createValidation(officeNameConstraint, officeNameRange); - DataValidation isLoanOfficerValidation = - validationHelper.createValidation(isLoanOfficerConstraint, isLoanOfficerNameRange); - DataValidation joinedOnValidation = - validationHelper.createValidation(joinedOnConstraint, joinedOnNameRange); - DataValidation isActiveValidation = - validationHelper.createValidation(isActiveConstraint, isActiveNameRange); + DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); + DataValidation isLoanOfficerValidation = validationHelper.createValidation(isLoanOfficerConstraint, isLoanOfficerNameRange); + DataValidation joinedOnValidation = validationHelper.createValidation(joinedOnConstraint, joinedOnNameRange); + DataValidation isActiveValidation = validationHelper.createValidation(isActiveConstraint, isActiveNameRange); staffSheet.addValidationData(officeValidation); staffSheet.addValidationData(isLoanOfficerValidation); @@ -95,30 +86,30 @@ public class StaffWorkbookPopulator extends AbstractWorkbookPopulator { } private void setNames(Sheet staffSheet, List offices) { - Workbook staffWorkBook=staffSheet.getWorkbook(); - Name officeGroup=staffWorkBook.createName(); + Workbook staffWorkBook = staffSheet.getWorkbook(); + Name officeGroup = staffWorkBook.createName(); officeGroup.setNameName("Office"); - officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (offices.size() + 1)); + officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (offices.size() + 1)); } private void setLayout(Sheet staffSheet) { Row rowHeader = staffSheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX); rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT); staffSheet.setColumnWidth(StaffConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); - staffSheet.setColumnWidth(StaffConstants.FIRST_NAME_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - staffSheet.setColumnWidth(StaffConstants.LAST_NAME_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - staffSheet.setColumnWidth(StaffConstants.IS_LOAN_OFFICER,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - staffSheet.setColumnWidth(StaffConstants.MOBILE_NO_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE); - staffSheet.setColumnWidth(StaffConstants.JOINED_ON_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - staffSheet.setColumnWidth(StaffConstants.EXTERNAL_ID_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - staffSheet.setColumnWidth(StaffConstants.IS_ACTIVE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE); - writeString(StaffConstants.OFFICE_NAME_COL,rowHeader,"Office Name *"); - writeString(StaffConstants.FIRST_NAME_COL,rowHeader,"First Name *"); - writeString(StaffConstants.LAST_NAME_COL,rowHeader,"Last Name *"); - writeString(StaffConstants.IS_LOAN_OFFICER,rowHeader,"Is Loan Officer *"); - writeString(StaffConstants.MOBILE_NO_COL,rowHeader, "Mobile no"); - writeString(StaffConstants.JOINED_ON_COL,rowHeader,"Joined on *"); - writeString(StaffConstants.EXTERNAL_ID_COL,rowHeader,"External Id *"); - writeString(StaffConstants.IS_ACTIVE_COL,rowHeader,"Is Active *"); + staffSheet.setColumnWidth(StaffConstants.FIRST_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + staffSheet.setColumnWidth(StaffConstants.LAST_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + staffSheet.setColumnWidth(StaffConstants.IS_LOAN_OFFICER, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + staffSheet.setColumnWidth(StaffConstants.MOBILE_NO_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE); + staffSheet.setColumnWidth(StaffConstants.JOINED_ON_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + staffSheet.setColumnWidth(StaffConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + staffSheet.setColumnWidth(StaffConstants.IS_ACTIVE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE); + writeString(StaffConstants.OFFICE_NAME_COL, rowHeader, "Office Name *"); + writeString(StaffConstants.FIRST_NAME_COL, rowHeader, "First Name *"); + writeString(StaffConstants.LAST_NAME_COL, rowHeader, "Last Name *"); + writeString(StaffConstants.IS_LOAN_OFFICER, rowHeader, "Is Loan Officer *"); + writeString(StaffConstants.MOBILE_NO_COL, rowHeader, "Mobile no"); + writeString(StaffConstants.JOINED_ON_COL, rowHeader, "Joined on *"); + writeString(StaffConstants.EXTERNAL_ID_COL, rowHeader, "External Id *"); + writeString(StaffConstants.IS_ACTIVE_COL, rowHeader, "Is Active *"); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/users/UserWorkbookPopulator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/users/UserWorkbookPopulator.java index cf8ec9199..3c00d414c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/users/UserWorkbookPopulator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/populator/users/UserWorkbookPopulator.java @@ -44,46 +44,46 @@ public class UserWorkbookPopulator extends AbstractWorkbookPopulator { private PersonnelSheetPopulator personnelSheetPopulator; private RoleSheetPopulator roleSheetPopulator; - public UserWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, - PersonnelSheetPopulator personnelSheetPopulator, + public UserWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator, PersonnelSheetPopulator personnelSheetPopulator, RoleSheetPopulator roleSheetPopulator) { - this.officeSheetPopulator=officeSheetPopulator; - this.personnelSheetPopulator=personnelSheetPopulator; - this.roleSheetPopulator=roleSheetPopulator; + this.officeSheetPopulator = officeSheetPopulator; + this.personnelSheetPopulator = personnelSheetPopulator; + this.roleSheetPopulator = roleSheetPopulator; } @Override - public void populate(Workbook workbook,String dateFormat) { - Sheet usersheet=workbook.createSheet(TemplatePopulateImportConstants.USER_SHEET_NAME); - personnelSheetPopulator.populate(workbook,dateFormat); - officeSheetPopulator.populate(workbook,dateFormat); - roleSheetPopulator.populate(workbook,dateFormat); + public void populate(Workbook workbook, String dateFormat) { + Sheet usersheet = workbook.createSheet(TemplatePopulateImportConstants.USER_SHEET_NAME); + personnelSheetPopulator.populate(workbook, dateFormat); + officeSheetPopulator.populate(workbook, dateFormat); + roleSheetPopulator.populate(workbook, dateFormat); setLayout(usersheet); setRules(usersheet); } private void setRules(Sheet usersheet) { - CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), UserConstants.OFFICE_NAME_COL, UserConstants.OFFICE_NAME_COL); - CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), UserConstants.STAFF_NAME_COL, UserConstants.STAFF_NAME_COL); - CellRangeAddressList autoGenPwRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList autoGenPwRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), UserConstants.AUTO_GEN_PW_COL, UserConstants.AUTO_GEN_PW_COL); - CellRangeAddressList overridePwExpiryPolicyRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), + CellRangeAddressList overridePwExpiryPolicyRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), UserConstants.OVERRIDE_PW_EXPIRY_POLICY_COL, UserConstants.OVERRIDE_PW_EXPIRY_POLICY_COL); - DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)usersheet); + DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) usersheet); List offices = officeSheetPopulator.getOffices(); setNames(usersheet, offices); DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office"); - DataValidationConstraint staffNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$A1))"); - DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[]{"True", "False"}); + DataValidationConstraint staffNameConstraint = validationHelper + .createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$A1))"); + DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[] { "True", "False" }); DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange); DataValidation staffValidation = validationHelper.createValidation(staffNameConstraint, staffNameRange); - DataValidation autoGenPwValidation=validationHelper.createValidation(booleanConstraint,autoGenPwRange); - DataValidation overridePwExpiryPolicyValidation=validationHelper.createValidation(booleanConstraint,overridePwExpiryPolicyRange); + DataValidation autoGenPwValidation = validationHelper.createValidation(booleanConstraint, autoGenPwRange); + DataValidation overridePwExpiryPolicyValidation = validationHelper.createValidation(booleanConstraint, overridePwExpiryPolicyRange); usersheet.addValidationData(officeValidation); usersheet.addValidationData(staffValidation); @@ -92,22 +92,22 @@ public class UserWorkbookPopulator extends AbstractWorkbookPopulator { } private void setNames(Sheet usersheet, List offices) { - Workbook userWorkbook=usersheet.getWorkbook(); + Workbook userWorkbook = usersheet.getWorkbook(); Name officeUser = userWorkbook.createName(); officeUser.setNameName("Office"); - officeUser.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (offices.size() + 1)); + officeUser.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME + "!$B$2:$B$" + (offices.size() + 1)); - //Staff Names for each office - for (Integer i=0;i { + private final static Logger LOG = LoggerFactory.getLogger(BulkImportEventListener.class); private final TenantDetailsService tenantDetailsService; private final ApplicationContext applicationContext; @@ -55,11 +56,8 @@ public class BulkImportEventListener implements ApplicationListener offices = fetchOffices(officeId); - List staff = fetchStaff(staffId); - List clientTypeCodeValues =fetchCodeValuesByCodeName("ClientType"); - List clientClassification=fetchCodeValuesByCodeName("ClientClassification"); - List addressTypesCodeValues=fetchCodeValuesByCodeName("ADDRESS_TYPE"); - List stateProvinceCodeValues=fetchCodeValuesByCodeName("STATE"); - List countryCodeValues=fetchCodeValuesByCodeName("COUNTRY"); - if(entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_PERSON.toString())) { - List genderCodeValues = fetchCodeValuesByCodeName("Gender"); - return new ClientPersonWorkbookPopulator(new OfficeSheetPopulator(offices), - new PersonnelSheetPopulator(staff, offices), clientTypeCodeValues, genderCodeValues, clientClassification - , addressTypesCodeValues, stateProvinceCodeValues, countryCodeValues); - }else if(entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_ENTTTY.toString())){ - List constitutionCodeValues=fetchCodeValuesByCodeName("Constitution"); - List mainBusinessline=fetchCodeValuesByCodeName("Main Business Line"); - return new ClientEntityWorkbookPopulator(new OfficeSheetPopulator(offices), - new PersonnelSheetPopulator(staff, offices), clientTypeCodeValues, constitutionCodeValues,mainBusinessline, - clientClassification, addressTypesCodeValues, stateProvinceCodeValues, countryCodeValues); - } - return null; - } - - private Response buildResponse(final Workbook workbook, final String entity) { - String filename = entity + DateUtils.getLocalDateOfTenant().toString() + ".xls"; - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - workbook.write(baos); - } catch (IOException e) { - LOG.error("Problem occurred in buildResponse function",e); + private WorkbookPopulator populateClientWorkbook(final String entityType, final Long officeId, final Long staffId) { + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List staff = fetchStaff(staffId); + List clientTypeCodeValues = fetchCodeValuesByCodeName("ClientType"); + List clientClassification = fetchCodeValuesByCodeName("ClientClassification"); + List addressTypesCodeValues = fetchCodeValuesByCodeName("ADDRESS_TYPE"); + List stateProvinceCodeValues = fetchCodeValuesByCodeName("STATE"); + List countryCodeValues = fetchCodeValuesByCodeName("COUNTRY"); + if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_PERSON.toString())) { + List genderCodeValues = fetchCodeValuesByCodeName("Gender"); + return new ClientPersonWorkbookPopulator(new OfficeSheetPopulator(offices), new PersonnelSheetPopulator(staff, offices), + clientTypeCodeValues, genderCodeValues, clientClassification, addressTypesCodeValues, stateProvinceCodeValues, + countryCodeValues); + } else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_ENTTTY.toString())) { + List constitutionCodeValues = fetchCodeValuesByCodeName("Constitution"); + List mainBusinessline = fetchCodeValuesByCodeName("Main Business Line"); + return new ClientEntityWorkbookPopulator(new OfficeSheetPopulator(offices), new PersonnelSheetPopulator(staff, offices), + clientTypeCodeValues, constitutionCodeValues, mainBusinessline, clientClassification, addressTypesCodeValues, + stateProvinceCodeValues, countryCodeValues); + } + return null; } - final ResponseBuilder response = Response.ok(baos.toByteArray()); - response.header("Content-Disposition", "attachment; filename=\"" + filename + "\""); - response.header("Content-Type", "application/vnd.ms-excel"); - return response.build(); - } + private Response buildResponse(final Workbook workbook, final String entity) { + String filename = entity + DateUtils.getLocalDateOfTenant().toString() + ".xls"; + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + workbook.write(baos); + } catch (IOException e) { + LOG.error("Problem occurred in buildResponse function", e); + } - @SuppressWarnings("unchecked") - private List fetchOffices(final Long officeId) { - List offices = null; - if (officeId == null) { - Boolean includeAllOffices = Boolean.TRUE; - offices = (List) this.officeReadPlatformService.retrieveAllOffices(includeAllOffices, null); - } else { - offices = new ArrayList<>(); - offices.add(this.officeReadPlatformService.retrieveOffice(officeId)); + final ResponseBuilder response = Response.ok(baos.toByteArray()); + response.header("Content-Disposition", "attachment; filename=\"" + filename + "\""); + response.header("Content-Type", "application/vnd.ms-excel"); + return response.build(); } - return offices; - } - @SuppressWarnings("unchecked") - private List fetchStaff(final Long staffId) { - List staff = null; - if (staffId == null){ - staff = - (List) this.staffReadPlatformService.retrieveAllStaff(null, null, Boolean.FALSE, null); - }else { - staff = new ArrayList<>(); - staff.add(this.staffReadPlatformService.retrieveStaff(staffId)); + @SuppressWarnings("unchecked") + private List fetchOffices(final Long officeId) { + List offices = null; + if (officeId == null) { + Boolean includeAllOffices = Boolean.TRUE; + offices = (List) this.officeReadPlatformService.retrieveAllOffices(includeAllOffices, null); + } else { + offices = new ArrayList<>(); + offices.add(this.officeReadPlatformService.retrieveOffice(officeId)); + } + return offices; } - return staff; - } - private List fetchCodeValuesByCodeName(String codeName){ - List codeValues=null; - if (codeName!=null){ - codeValues=(List)codeValueReadPlatformService.retrieveCodeValuesByCode(codeName); - }else { - throw new NullPointerException(); - } - return codeValues; - } - private ListfetchSavingsProducts(){ - List savingsProducts=(List)savingsProductReadPlatformService.retrieveAll(); - return savingsProducts; - } -private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE); - this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GROUP_ENTITY_TYPE); - List offices = fetchOffices(officeId); - List staff = fetchStaff(staffId); - List groups = fetchGroups(officeId); - return new CentersWorkbookPopulator(new OfficeSheetPopulator(offices), - new PersonnelSheetPopulator(staff, offices),new GroupSheetPopulator(groups,offices)); -} + @SuppressWarnings("unchecked") + private List fetchStaff(final Long staffId) { + List staff = null; + if (staffId == null) { + staff = (List) this.staffReadPlatformService.retrieveAllStaff(null, null, Boolean.FALSE, null); + } else { + staff = new ArrayList<>(); + staff.add(this.staffReadPlatformService.retrieveStaff(staffId)); + } + return staff; + } + + private List fetchCodeValuesByCodeName(String codeName) { + List codeValues = null; + if (codeName != null) { + codeValues = (List) codeValueReadPlatformService.retrieveCodeValuesByCode(codeName); + } else { + throw new NullPointerException(); + } + return codeValues; + } + + private List fetchSavingsProducts() { + List savingsProducts = (List) savingsProductReadPlatformService.retrieveAll(); + return savingsProducts; + } + + private WorkbookPopulator populateCenterWorkbook(Long officeId, Long staffId) { + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE); + this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GROUP_ENTITY_TYPE); + List offices = fetchOffices(officeId); + List staff = fetchStaff(staffId); + List groups = fetchGroups(officeId); + return new CentersWorkbookPopulator(new OfficeSheetPopulator(offices), new PersonnelSheetPopulator(staff, offices), + new GroupSheetPopulator(groups, offices)); + } private WorkbookPopulator populateGroupsWorkbook(Long officeId, Long staffId) { this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); @@ -330,37 +324,38 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ List staff = fetchStaff(staffId); List centers = fetchCenters(officeId); List clients = fetchClients(officeId); - return new GroupsWorkbookPopulator(new OfficeSheetPopulator(offices), - new PersonnelSheetPopulator(staff, offices), new CenterSheetPopulator(centers, offices), - new ClientSheetPopulator(clients, offices)); + return new GroupsWorkbookPopulator(new OfficeSheetPopulator(offices), new PersonnelSheetPopulator(staff, offices), + new CenterSheetPopulator(centers, offices), new ClientSheetPopulator(clients, offices)); } + private List fetchCenters(Long officeId) { - Listcenters=null; - if (officeId==null) { - centers=(List) this.centerReadPlatformService.retrieveAll(null, null); + List centers = null; + if (officeId == null) { + centers = (List) this.centerReadPlatformService.retrieveAll(null, null); } else { SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null); - centers = (List)centerReadPlatformService.retrieveAll(searchParameters,null); + centers = (List) centerReadPlatformService.retrieveAll(searchParameters, null); } return centers; } + private List fetchClients(Long officeId) { - List clients=null; - if (officeId==null) { - Page clientDataPage =this.clientReadPlatformService.retrieveAll(null); - if (clientDataPage!=null){ - clients=new ArrayList<>(); - for (ClientData client: clientDataPage.getPageItems()) { + List clients = null; + if (officeId == null) { + Page clientDataPage = this.clientReadPlatformService.retrieveAll(null); + if (clientDataPage != null) { + clients = new ArrayList<>(); + for (ClientData client : clientDataPage.getPageItems()) { clients.add(client); } } } else { SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null); - Page clientDataPage =this.clientReadPlatformService.retrieveAll(searchParameters); - if (clientDataPage!=null){ - clients=new ArrayList<>(); - for (ClientData client: clientDataPage.getPageItems()) { + Page clientDataPage = this.clientReadPlatformService.retrieveAll(searchParameters); + if (clientDataPage != null) { + clients = new ArrayList<>(); + for (ClientData client : clientDataPage.getPageItems()) { clients.add(client); } } @@ -368,7 +363,6 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ return clients; } - private WorkbookPopulator populateLoanWorkbook(Long officeId, Long staffId) { this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE); @@ -392,25 +386,22 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ } private List fetchCurrencies() { - List currencies =(List) this.currencyReadPlatformService. - retrieveAllPlatformCurrencies(); + List currencies = (List) this.currencyReadPlatformService.retrieveAllPlatformCurrencies(); return currencies; } private List fetchPaymentTypes() { - List paymentTypeData =(List) this.paymentTypeReadPlatformService - .retrieveAllPaymentTypes(); + List paymentTypeData = (List) this.paymentTypeReadPlatformService.retrieveAllPaymentTypes(); return paymentTypeData; } private List fetchFunds() { - List funds =(List) this.fundReadPlatformService.retrieveAllFunds(); + List funds = (List) this.fundReadPlatformService.retrieveAllFunds(); return funds; } private List fetchLoanProducts() { - Listloanproducts =(List) this.loanProductReadPlatformService - .retrieveAllLoanProducts(); + List loanproducts = (List) this.loanProductReadPlatformService.retrieveAllLoanProducts(); return loanproducts; } @@ -420,7 +411,7 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ groups = (List) this.groupReadPlatformService.retrieveAll(null, null); } else { SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null); - groups = (List)groupReadPlatformService.retrieveAll(searchParameters,null); + groups = (List) groupReadPlatformService.retrieveAll(searchParameters, null); } return groups; @@ -438,15 +429,15 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ List paymentTypes = fetchPaymentTypes(); List currencies = fetchCurrencies(); List loans = fetchLoanAccounts(officeId); - return new LoanRepaymentWorkbookPopulator(loans, new OfficeSheetPopulator(offices), - new ClientSheetPopulator(clients, offices), new ExtrasSheetPopulator(funds, paymentTypes, currencies)); + return new LoanRepaymentWorkbookPopulator(loans, new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), + new ExtrasSheetPopulator(funds, paymentTypes, currencies)); } private List fetchLoanAccounts(final Long officeId) { List loanAccounts = null; - if(officeId==null){ - loanAccounts= loanReadPlatformService.retrieveAll(null).getPageItems(); - }else { + if (officeId == null) { + loanAccounts = loanReadPlatformService.retrieveAll(null).getPageItems(); + } else { SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null); loanAccounts = loanReadPlatformService.retrieveAll(searchParameters).getPageItems(); } @@ -464,14 +455,12 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ List funds = fetchFunds(); List paymentTypes = fetchPaymentTypes(); List currencies = fetchCurrencies(); - return new JournalEntriesWorkbookPopulator(new OfficeSheetPopulator(offices), - new GlAccountSheetPopulator(glAccounts), new ExtrasSheetPopulator(funds, paymentTypes, currencies)); + return new JournalEntriesWorkbookPopulator(new OfficeSheetPopulator(offices), new GlAccountSheetPopulator(glAccounts), + new ExtrasSheetPopulator(funds, paymentTypes, currencies)); } private List fetchGLAccounts() { - List glaccounts = this.glAccountReadPlatformService. - retrieveAllGLAccounts(null, null, null, - null, null, null); + List glaccounts = this.glAccountReadPlatformService.retrieveAllGLAccounts(null, null, null, null, null, null); return glaccounts; } @@ -479,72 +468,65 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE); List offices = fetchOffices(officeId); - Listclients=fetchClients(officeId); + List clients = fetchClients(officeId); List loans = fetchLoanAccounts(officeId); List savingsaccounts = fetchSavingsAccounts(officeId); - List guarantorRelationshipTypes=fetchCodeValuesByCodeName("GuarantorRelationship"); - return new GuarantorWorkbookPopulator(new OfficeSheetPopulator(offices), - new ClientSheetPopulator(clients, offices),loans,savingsaccounts,guarantorRelationshipTypes); + List guarantorRelationshipTypes = fetchCodeValuesByCodeName("GuarantorRelationship"); + return new GuarantorWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), loans, + savingsaccounts, guarantorRelationshipTypes); } private List fetchSavingsAccounts(Long officeId) { - List savingsAccounts=null; - if (officeId!=null) { - String activeAccounts="sa.status_enum = 300"; + List savingsAccounts = null; + if (officeId != null) { + String activeAccounts = "sa.status_enum = 300"; SearchParameters searchParameters = SearchParameters.from(activeAccounts, officeId, null, null, null); savingsAccounts = savingsAccountReadPlatformService.retrieveAll(searchParameters).getPageItems(); - }else { - savingsAccounts= savingsAccountReadPlatformService.retrieveAll(null).getPageItems(); + } else { + savingsAccounts = savingsAccountReadPlatformService.retrieveAll(null).getPageItems(); } return savingsAccounts; } - private WorkbookPopulator populateOfficeWorkbook() { this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); List offices = fetchOffices(null); return new OfficeWorkbookPopulator(offices); } - - - private WorkbookPopulator populateChartOfAccountsWorkbook() { this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GL_ACCOUNT_ENTITY_TYPE); List glAccounts = fetchGLAccounts(); return new ChartOfAccountsWorkbook(glAccounts); } - private WorkbookPopulator populateStaffWorkbook(Long officeId) { this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); - List offices=fetchOffices(officeId); + List offices = fetchOffices(officeId); return new StaffWorkbookPopulator(new OfficeSheetPopulator(offices)); } - - private WorkbookPopulator populateSharedAcountsWorkbook(Long officeId) { this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.SHARED_ACCOUNT_ENTITY_TYPE); - List shareProductDataList=fetchSharedProducts(); - List chargesForShares=fetchChargesForShares(); - List clientDataList=fetchClients(officeId); - ListofficeDataList=fetchOffices(officeId); + List shareProductDataList = fetchSharedProducts(); + List chargesForShares = fetchChargesForShares(); + List clientDataList = fetchClients(officeId); + List officeDataList = fetchOffices(officeId); List savingsAccounts = fetchSavingsAccounts(officeId); - return new SharedAccountWorkBookPopulator(new SharedProductsSheetPopulator(shareProductDataList,chargesForShares), - new ClientSheetPopulator(clientDataList,officeDataList),new SavingsAccountSheetPopulator(savingsAccounts)); + return new SharedAccountWorkBookPopulator(new SharedProductsSheetPopulator(shareProductDataList, chargesForShares), + new ClientSheetPopulator(clientDataList, officeDataList), new SavingsAccountSheetPopulator(savingsAccounts)); } private List fetchChargesForShares() { - ListchargesForShares=(List) chargeReadPlatformService.retrieveSharesApplicableCharges(); + List chargesForShares = (List) chargeReadPlatformService.retrieveSharesApplicableCharges(); return chargesForShares; } private List fetchSharedProducts() { - List productDataList = productReadPlatformService.retrieveAllProducts(0,50).getPageItems() ; - List sharedProductDataList=new ArrayList<>(); - if(productDataList!=null) { + List productDataList = productReadPlatformService.retrieveAllProducts(0, 50).getPageItems(); + List sharedProductDataList = new ArrayList<>(); + if (productDataList != null) { for (ProductData data : productDataList) { ShareProductData shareProduct = (ShareProductData) data; sharedProductDataList.add(shareProduct); @@ -553,7 +535,6 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ return sharedProductDataList; } - private WorkbookPopulator populateSavingsAccountWorkbook(Long officeId, Long staffId) { this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE); @@ -564,14 +545,12 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ List staff = fetchStaff(staffId); List clients = fetchClients(officeId); List groups = fetchGroups(officeId); - List savingsProducts=fetchSavingsProducts(); + List savingsProducts = fetchSavingsProducts(); return new SavingsWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), new GroupSheetPopulator(groups, offices), new PersonnelSheetPopulator(staff, offices), new SavingsProductSheetPopulator(savingsProducts)); } - - private WorkbookPopulator populateSavingsTransactionWorkbook(Long officeId) { this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); @@ -583,13 +562,12 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ List funds = fetchFunds(); List paymentTypes = fetchPaymentTypes(); List currencies = fetchCurrencies(); - List savingsAccounts=fetchSavingsAccounts(officeId); + List savingsAccounts = fetchSavingsAccounts(officeId); return new SavingsTransactionsWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), - new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts); + new ExtrasSheetPopulator(funds, paymentTypes, currencies), savingsAccounts); } - - private WorkbookPopulator populateRecurringDepositWorkbook(Long officeId,Long staffId) { + private WorkbookPopulator populateRecurringDepositWorkbook(Long officeId, Long staffId) { this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE); @@ -599,22 +577,20 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ List staff = fetchStaff(staffId); List recurringDepositProducts = fetchRecurringDepositProducts(); return new RecurringDepositWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), - new PersonnelSheetPopulator(staff,offices),new RecurringDepositProductSheetPopulator(recurringDepositProducts)); + new PersonnelSheetPopulator(staff, offices), new RecurringDepositProductSheetPopulator(recurringDepositProducts)); } private List fetchRecurringDepositProducts() { - List depositProducts=(List)depositProductReadPlatformService + List depositProducts = (List) depositProductReadPlatformService .retrieveAll(DepositAccountType.RECURRING_DEPOSIT); - List recurringDepositProducts=new ArrayList<>(); - for (DepositProductData depositproduct: depositProducts) { - RecurringDepositProductData recurringDepositProduct= (RecurringDepositProductData) depositproduct; + List recurringDepositProducts = new ArrayList<>(); + for (DepositProductData depositproduct : depositProducts) { + RecurringDepositProductData recurringDepositProduct = (RecurringDepositProductData) depositproduct; recurringDepositProducts.add(recurringDepositProduct); } return recurringDepositProducts; } - - private WorkbookPopulator populateRecurringDepositTransactionWorkbook(Long officeId) { this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE); this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE); @@ -626,9 +602,9 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ List funds = fetchFunds(); List paymentTypes = fetchPaymentTypes(); List currencies = fetchCurrencies(); - List savingsAccounts=fetchSavingsAccounts(officeId); - return new RecurringDepositTransactionWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), - new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts); + List savingsAccounts = fetchSavingsAccounts(officeId); + return new RecurringDepositTransactionWorkbookPopulator(new OfficeSheetPopulator(offices), + new ClientSheetPopulator(clients, offices), new ExtrasSheetPopulator(funds, paymentTypes, currencies), savingsAccounts); } private WorkbookPopulator populateFixedDepositWorkbook(Long officeId, Long staffId) { @@ -641,17 +617,16 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ List staff = fetchStaff(staffId); List fixedDepositProducts = fetchFixedDepositProducts(); return new FixedDepositWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), - new PersonnelSheetPopulator(staff,offices),new FixedDepositProductSheetPopulator(fixedDepositProducts)); - + new PersonnelSheetPopulator(staff, offices), new FixedDepositProductSheetPopulator(fixedDepositProducts)); } private List fetchFixedDepositProducts() { - List depositProducts=(List)depositProductReadPlatformService + List depositProducts = (List) depositProductReadPlatformService .retrieveAll(DepositAccountType.FIXED_DEPOSIT); - List fixedDepositProducts=new ArrayList<>(); - for (DepositProductData depositproduct: depositProducts) { - FixedDepositProductData fixedDepositProduct= (FixedDepositProductData) depositproduct; + List fixedDepositProducts = new ArrayList<>(); + for (DepositProductData depositproduct : depositProducts) { + FixedDepositProductData fixedDepositProduct = (FixedDepositProductData) depositproduct; fixedDepositProducts.add(fixedDepositProduct); } return fixedDepositProducts; @@ -662,13 +637,13 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.USER_ENTITY_TYPE); List offices = fetchOffices(officeId); List staff = fetchStaff(staffId); - List roles=fetchRoles(); - return new UserWorkbookPopulator(new OfficeSheetPopulator(offices), new PersonnelSheetPopulator(staff,offices), + List roles = fetchRoles(); + return new UserWorkbookPopulator(new OfficeSheetPopulator(offices), new PersonnelSheetPopulator(staff, offices), new RoleSheetPopulator(roles)); } private List fetchRoles() { - List rolesList= (List) roleReadPlatformService.retrieveAllActiveRoles(); + List rolesList = (List) roleReadPlatformService.retrieveAllActiveRoles(); return rolesList; } @@ -683,9 +658,9 @@ private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){ List funds = fetchFunds(); List paymentTypes = fetchPaymentTypes(); List currencies = fetchCurrencies(); - List savingsAccounts=fetchSavingsAccounts(officeId); + List savingsAccounts = fetchSavingsAccounts(officeId); return new FixedDepositTransactionWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices), - new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts); + new ExtrasSheetPopulator(funds, paymentTypes, currencies), savingsAccounts); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookService.java index 1ebac9627..c2f727852 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookService.java @@ -28,8 +28,9 @@ import org.apache.fineract.infrastructure.documentmanagement.data.DocumentData; public interface BulkImportWorkbookService { - public Long importWorkbook(String entityType, InputStream inputStream, FormDataContentDisposition fileDetail, - final String locale, final String dateFormat); + public Long importWorkbook(String entityType, InputStream inputStream, FormDataContentDisposition fileDetail, final String locale, + final String dateFormat); + public Collection getImports(GlobalEntityType type); public DocumentData getOutputTemplateLocation(String importDocumentId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookServiceImpl.java index 3f75f04d5..2cb9cd46f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/bulkimport/service/BulkImportWorkbookServiceImpl.java @@ -62,6 +62,7 @@ import org.springframework.stereotype.Service; @Service public class BulkImportWorkbookServiceImpl implements BulkImportWorkbookService { + private final static Logger LOG = LoggerFactory.getLogger(BulkImportWorkbookServiceImpl.class); private final ApplicationContext applicationContext; private final PlatformSecurityContext securityContext; @@ -71,10 +72,8 @@ public class BulkImportWorkbookServiceImpl implements BulkImportWorkbookService private final JdbcTemplate jdbcTemplate; @Autowired - public BulkImportWorkbookServiceImpl(final ApplicationContext applicationContext, - final PlatformSecurityContext securityContext, - final DocumentWritePlatformService documentWritePlatformService, - final DocumentRepository documentRepository, + public BulkImportWorkbookServiceImpl(final ApplicationContext applicationContext, final PlatformSecurityContext securityContext, + final DocumentWritePlatformService documentWritePlatformService, final DocumentRepository documentRepository, final ImportDocumentRepository importDocumentRepository, final RoutingDataSource dataSource) { this.applicationContext = applicationContext; this.securityContext = securityContext; @@ -85,108 +84,106 @@ public class BulkImportWorkbookServiceImpl implements BulkImportWorkbookService } @Override - public Long importWorkbook(String entity, InputStream inputStream, FormDataContentDisposition fileDetail, - final String locale, final String dateFormat) { + public Long importWorkbook(String entity, InputStream inputStream, FormDataContentDisposition fileDetail, final String locale, + final String dateFormat) { try { - if (entity !=null && inputStream!=null &&fileDetail!=null&&locale!=null&&dateFormat!=null) { + if (entity != null && inputStream != null && fileDetail != null && locale != null && dateFormat != null) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); final byte[] bytes = baos.toByteArray(); InputStream clonedInputStream = new ByteArrayInputStream(bytes); - InputStream clonedInputStreamWorkbook =new ByteArrayInputStream(bytes); + InputStream clonedInputStreamWorkbook = new ByteArrayInputStream(bytes); final Tika tika = new Tika(); final TikaInputStream tikaInputStream = TikaInputStream.get(clonedInputStream); final String fileType = tika.detect(tikaInputStream); if (!fileType.contains("msoffice") && !fileType.contains("application/vnd.ms-excel")) { - // We had a problem where we tried to upload the downloaded file from the import options, it was somehow changed the + // We had a problem where we tried to upload the downloaded + // file from the import options, it was somehow changed the // extension we use this fix. - throw new GeneralPlatformDomainRuleException("error.msg.invalid.file.extension", - "Uploaded file extension is not recognized."); + throw new GeneralPlatformDomainRuleException("error.msg.invalid.file.extension", + "Uploaded file extension is not recognized."); } Workbook workbook = new HSSFWorkbook(clonedInputStreamWorkbook); - GlobalEntityType entityType=null; - int primaryColumn=0; + GlobalEntityType entityType = null; + int primaryColumn = 0; if (entity.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_PERSON.toString())) { entityType = GlobalEntityType.CLIENTS_PERSON; primaryColumn = 0; - }else if(entity.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_ENTTTY.toString())){ + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_ENTTTY.toString())) { entityType = GlobalEntityType.CLIENTS_ENTTTY; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.CENTERS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.CENTERS.toString())) { entityType = GlobalEntityType.CENTERS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.GROUPS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.GROUPS.toString())) { entityType = GlobalEntityType.GROUPS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.LOANS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.LOANS.toString())) { entityType = GlobalEntityType.LOANS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.LOAN_TRANSACTIONS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.LOAN_TRANSACTIONS.toString())) { entityType = GlobalEntityType.LOAN_TRANSACTIONS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.GUARANTORS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.GUARANTORS.toString())) { entityType = GlobalEntityType.GUARANTORS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.OFFICES.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.OFFICES.toString())) { entityType = GlobalEntityType.OFFICES; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.CHART_OF_ACCOUNTS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.CHART_OF_ACCOUNTS.toString())) { entityType = GlobalEntityType.CHART_OF_ACCOUNTS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.GL_JOURNAL_ENTRIES.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.GL_JOURNAL_ENTRIES.toString())) { entityType = GlobalEntityType.GL_JOURNAL_ENTRIES; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.STAFF.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.STAFF.toString())) { entityType = GlobalEntityType.STAFF; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.SHARE_ACCOUNTS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.SHARE_ACCOUNTS.toString())) { entityType = GlobalEntityType.SHARE_ACCOUNTS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_ACCOUNT.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_ACCOUNT.toString())) { entityType = GlobalEntityType.SAVINGS_ACCOUNT; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_TRANSACTIONS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_TRANSACTIONS.toString())) { entityType = GlobalEntityType.SAVINGS_TRANSACTIONS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS.toString())) { entityType = GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS.toString())) { entityType = GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_ACCOUNTS.toString())) { + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_ACCOUNTS.toString())) { entityType = GlobalEntityType.FIXED_DEPOSIT_ACCOUNTS; primaryColumn = 0; - }else if (entity.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_TRANSACTIONS.toString())){ + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_TRANSACTIONS.toString())) { entityType = GlobalEntityType.FIXED_DEPOSIT_TRANSACTIONS; primaryColumn = 0; - }else if(entity.trim().equalsIgnoreCase(GlobalEntityType.USERS.toString())){ + } else if (entity.trim().equalsIgnoreCase(GlobalEntityType.USERS.toString())) { entityType = GlobalEntityType.USERS; primaryColumn = 0; - }else{ + } else { workbook.close(); - throw new GeneralPlatformDomainRuleException("error.msg.unable.to.find.resource", - "Unable to find requested resource"); + throw new GeneralPlatformDomainRuleException("error.msg.unable.to.find.resource", "Unable to find requested resource"); } - return publishEvent(primaryColumn, fileDetail, clonedInputStreamWorkbook, entityType, - workbook, locale, dateFormat); + return publishEvent(primaryColumn, fileDetail, clonedInputStreamWorkbook, entityType, workbook, locale, dateFormat); } - throw new GeneralPlatformDomainRuleException("error.msg.null","One or more of the given parameters not found"); + throw new GeneralPlatformDomainRuleException("error.msg.null", "One or more of the given parameters not found"); } catch (IOException e) { - LOG.error("Problem occurred in importWorkbook function",e); - throw new GeneralPlatformDomainRuleException("error.msg.io.exception","IO exception occured with "+fileDetail.getFileName()+" "+e.getMessage()); + LOG.error("Problem occurred in importWorkbook function", e); + throw new GeneralPlatformDomainRuleException("error.msg.io.exception", + "IO exception occured with " + fileDetail.getFileName() + " " + e.getMessage()); } } - - private Long publishEvent(final Integer primaryColumn, - final FormDataContentDisposition fileDetail, final InputStream clonedInputStreamWorkbook, - final GlobalEntityType entityType, final Workbook workbook, - final String locale, final String dateFormat) { + private Long publishEvent(final Integer primaryColumn, final FormDataContentDisposition fileDetail, + final InputStream clonedInputStreamWorkbook, final GlobalEntityType entityType, final Workbook workbook, final String locale, + final String dateFormat) { final String fileName = fileDetail.getFileName(); @@ -196,17 +193,15 @@ public class BulkImportWorkbookServiceImpl implements BulkImportWorkbookService URLConnection.guessContentTypeFromName(fileName), fileName, null, fileName); final Document document = this.documentRepository.findById(documentId).orElse(null); - final ImportDocument importDocument = ImportDocument.instance(document, - DateUtils.getLocalDateTimeOfTenant(), entityType.getValue(), - this.securityContext.authenticatedUser(), - ImportHandlerUtils.getNumberOfRows(workbook.getSheetAt(0), - primaryColumn)); + final ImportDocument importDocument = ImportDocument.instance(document, DateUtils.getLocalDateTimeOfTenant(), entityType.getValue(), + this.securityContext.authenticatedUser(), ImportHandlerUtils.getNumberOfRows(workbook.getSheetAt(0), primaryColumn)); this.importDocumentRepository.saveAndFlush(importDocument); - BulkImportEvent event = BulkImportEvent.instance(ThreadLocalContextUtil.getTenant() - .getTenantIdentifier(), workbook, importDocument.getId(), locale, dateFormat); + BulkImportEvent event = BulkImportEvent.instance(ThreadLocalContextUtil.getTenant().getTenantIdentifier(), workbook, + importDocument.getId(), locale, dateFormat); applicationContext.publishEvent(event); return importDocument.getId(); } + @Override public Collection getImports(GlobalEntityType type) { this.securityContext.authenticatedUser(); @@ -214,11 +209,9 @@ public class BulkImportWorkbookServiceImpl implements BulkImportWorkbookService final ImportMapper rm = new ImportMapper(); final String sql = "select " + rm.schema() + " order by i.id desc"; - return this.jdbcTemplate.query(sql, rm, new Object[] {type.getValue()}); + return this.jdbcTemplate.query(sql, rm, new Object[] { type.getValue() }); } - - private static final class ImportMapper implements RowMapper { public String schema() { @@ -226,8 +219,7 @@ public class BulkImportWorkbookServiceImpl implements BulkImportWorkbookService sql.append("i.id as id, i.document_id as documentId, d.name as name, i.import_time as importTime, i.end_time as endTime, ") .append("i.completed as completed, i.total_records as totalRecords, i.success_count as successCount, ") .append("i.failure_count as failureCount, i.createdby_id as createdBy ") - .append("from m_import_document i inner join m_document d on i.document_id=d.id ") - .append("where i.entity_type= ? "); + .append("from m_import_document i inner join m_document d on i.document_id=d.id ").append("where i.entity_type= ? "); return sql.toString(); } @@ -245,33 +237,33 @@ public class BulkImportWorkbookServiceImpl implements BulkImportWorkbookService final Integer failureCount = JdbcSupport.getInteger(rs, "failureCount"); final Long createdBy = rs.getLong("createdBy"); - return ImportData.instance(id, documentId, importTime, endTime, completed, - name, createdBy, totalRecords, successCount, failureCount); + return ImportData.instance(id, documentId, importTime, endTime, completed, name, createdBy, totalRecords, successCount, + failureCount); } } @Override public DocumentData getOutputTemplateLocation(String importDocumentId) { this.securityContext.authenticatedUser(); - final ImportTemplateLocationMapper importTemplateLocationMapper=new ImportTemplateLocationMapper(); + final ImportTemplateLocationMapper importTemplateLocationMapper = new ImportTemplateLocationMapper(); final String sql = "select " + importTemplateLocationMapper.schema(); - return this.jdbcTemplate.queryForObject(sql, importTemplateLocationMapper, new Object[] {importDocumentId}); + return this.jdbcTemplate.queryForObject(sql, importTemplateLocationMapper, new Object[] { importDocumentId }); } @Override public Response getOutputTemplate(String importDocumentId) { this.securityContext.authenticatedUser(); - final ImportTemplateLocationMapper importTemplateLocationMapper=new ImportTemplateLocationMapper(); + final ImportTemplateLocationMapper importTemplateLocationMapper = new ImportTemplateLocationMapper(); final String sql = "select " + importTemplateLocationMapper.schema(); - DocumentData documentData= this.jdbcTemplate.queryForObject(sql, importTemplateLocationMapper, new Object[] {importDocumentId}); + DocumentData documentData = this.jdbcTemplate.queryForObject(sql, importTemplateLocationMapper, new Object[] { importDocumentId }); return buildResponse(documentData); } private Response buildResponse(DocumentData documentData) { - String fileName="Output"+documentData.fileName(); - String fileLocation=documentData.fileLocation(); - File file=new File(fileLocation); + String fileName = "Output" + documentData.fileName(); + String fileLocation = documentData.fileLocation(); + File file = new File(fileLocation); final Response.ResponseBuilder response = Response.ok(file); response.header("Content-Disposition", "attachment; filename=\"" + fileName + "\""); response.header("Content-Type", "application/vnd.ms-excel"); @@ -279,19 +271,19 @@ public class BulkImportWorkbookServiceImpl implements BulkImportWorkbookService } private static final class ImportTemplateLocationMapper implements RowMapper { + public String schema() { final StringBuilder sql = new StringBuilder(); - sql.append("d.location,d.file_name ") - .append("from m_import_document i inner join m_document d on i.document_id=d.id ") + sql.append("d.location,d.file_name ").append("from m_import_document i inner join m_document d on i.document_id=d.id ") .append("where i.id= ? "); return sql.toString(); } - @Override - public DocumentData mapRow (ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { - final String location = rs.getString("location"); - final String fileName=rs.getString("file_name"); - return new DocumentData(null,null,null,null,fileName, - null,null,null,location,null); - } + + @Override + public DocumentData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { + final String location = rs.getString("location"); + final String fileName = rs.getString("file_name"); + return new DocumentData(null, null, null, null, fileName, null, null, null, location, null); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/PlatformCacheConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/PlatformCacheConfiguration.java index d50bd8aa3..0712cff1f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/PlatformCacheConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/PlatformCacheConfiguration.java @@ -46,7 +46,7 @@ public class PlatformCacheConfiguration implements CachingConfigurer { @Override public CacheResolver cacheResolver() { - //TODO https://issues.apache.org/jira/browse/FINERACT-705 + // TODO https://issues.apache.org/jira/browse/FINERACT-705 return null; } @@ -57,7 +57,7 @@ public class PlatformCacheConfiguration implements CachingConfigurer { @Override public CacheErrorHandler errorHandler() { - //TODO https://issues.apache.org/jira/browse/FINERACT-705 + // TODO https://issues.apache.org/jira/browse/FINERACT-705 return null; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/api/CacheApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/api/CacheApiResource.java index 9588b0dea..2d2973185 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/api/CacheApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/api/CacheApiResource.java @@ -59,10 +59,11 @@ import org.springframework.stereotype.Component; @Produces({ MediaType.APPLICATION_JSON }) @Component @Scope("singleton") -@Api(tags = {"Cache"}) -@SwaggerDefinition(tags = { - @Tag(name = "Cache", description = "The following settings are possible for cache:\n" + "\n" + "No Caching: caching turned off\n" + "Single node: caching on for single instance deployments of platorm (works for multiple tenants but only one tomcat)\n" + "By default caching is set to No Caching. Switching between caches results in the cache been clear e.g. from Single node to No cache and back again would clear down the single node cache.") -}) +@Api(tags = { "Cache" }) +@SwaggerDefinition(tags = { @Tag(name = "Cache", description = "The following settings are possible for cache:\n" + "\n" + + "No Caching: caching turned off\n" + + "Single node: caching on for single instance deployments of platorm (works for multiple tenants but only one tomcat)\n" + + "By default caching is set to No Caching. Switching between caches results in the cache been clear e.g. from Single node to No cache and back again would clear down the single node cache.") }) public class CacheApiResource { private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id")); @@ -88,7 +89,8 @@ public class CacheApiResource { @GET @ApiOperation(value = "Retrieve Cache Types", notes = "Returns the list of caches.\n" + "\n" + "Example Requests:\n" + "\n" + "caches") - @ApiResponses({@ApiResponse(code = 200, message = "", response = CacheApiResourceSwagger.GetCachesResponse.class, responseContainer = "list")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = CacheApiResourceSwagger.GetCachesResponse.class, responseContainer = "list") }) public String retrieveAll(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -101,8 +103,9 @@ public class CacheApiResource { @PUT @ApiOperation(value = "Switch Cache", notes = "Switches the cache to chosen one.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CacheApiResourceSwagger.PutCachesRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = CacheApiResourceSwagger.PutCachesResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CacheApiResourceSwagger.PutCachesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CacheApiResourceSwagger.PutCachesResponse.class) }) public String switchCache(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCache().withJson(apiRequestBodyAsJson).build(); @@ -111,4 +114,4 @@ public class CacheApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/api/CacheApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/api/CacheApiResourceSwagger.java index 6cd4b860b..7e0382229 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/api/CacheApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/api/CacheApiResourceSwagger.java @@ -26,24 +26,29 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; * Created by sanyam on 28/7/17. */ final class CacheApiResourceSwagger { + private CacheApiResourceSwagger() { } @ApiModel(value = "GetCachesResponse") public static final class GetCachesResponse { + private GetCachesResponse() { } + public EnumOptionData cacheType; public boolean enabled; } @ApiModel(value = "PutCachesRequest") public static final class PutCachesRequest { + private PutCachesRequest() { } + @ApiModelProperty(example = "2") public Long cacheType; @@ -51,17 +56,22 @@ final class CacheApiResourceSwagger { @ApiModel(value = "PutCachesResponse") public static final class PutCachesResponse { + private PutCachesResponse() { } - public static final class PutCachechangesSwagger{ + + public static final class PutCachechangesSwagger { + private PutCachechangesSwagger() { } + @ApiModelProperty(example = "2") public Long cacheType; } + public PutCachechangesSwagger cacheType; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/command/UpdateCacheCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/command/UpdateCacheCommandHandler.java index 2d6f73a4b..a2f6f06e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/command/UpdateCacheCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/command/UpdateCacheCommandHandler.java @@ -48,8 +48,7 @@ import org.springframework.transaction.annotation.Transactional; public class UpdateCacheCommandHandler implements NewCommandSourceHandler { private final CacheWritePlatformService cacheService; - private static final Set REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(CacheApiConstants - .cacheTypeParameter)); + private static final Set REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(CacheApiConstants.cacheTypeParameter)); @Autowired public UpdateCacheCommandHandler(final CacheWritePlatformService cacheService) { @@ -83,4 +82,4 @@ public class UpdateCacheCommandHandler implements NewCommandSourceHandler { return new CommandProcessingResultBuilder().withCommandId(command.commandId()).with(changes).build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/data/CacheData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/data/CacheData.java index 3162b7386..1a4d543e3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/data/CacheData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/data/CacheData.java @@ -35,4 +35,4 @@ public class CacheData { this.cacheType = cacheType; this.enabled = enabled; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/CacheType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/CacheType.java index 1af333bc3..51f2debc8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/CacheType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/CacheType.java @@ -76,4 +76,4 @@ public enum CacheType { public boolean isDistributedCache() { return MULTI_NODE.getValue().equals(this.value); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/PlatformCache.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/PlatformCache.java index abc02eeaf..c6daf687e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/PlatformCache.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/PlatformCache.java @@ -53,4 +53,4 @@ public class PlatformCache extends AbstractPersistableCustom { public void update(final CacheType cacheType) { this.cacheType = cacheType.getValue(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/PlatformCacheRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/PlatformCacheRepository.java index d4eb92a8a..9c78d7a99 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/PlatformCacheRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/domain/PlatformCacheRepository.java @@ -23,4 +23,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface PlatformCacheRepository extends JpaRepository, JpaSpecificationExecutor { // -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/CacheWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/CacheWritePlatformService.java index 8137c9ee6..b8d398e57 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/CacheWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/CacheWritePlatformService.java @@ -24,4 +24,4 @@ import org.apache.fineract.infrastructure.cache.domain.CacheType; public interface CacheWritePlatformService { Map switchToCache(CacheType cacheType); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/CacheWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/CacheWritePlatformServiceJpaRepositoryImpl.java index 230a29e5a..5afe226a3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/CacheWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/CacheWritePlatformServiceJpaRepositoryImpl.java @@ -53,4 +53,4 @@ public class CacheWritePlatformServiceJpaRepositoryImpl implements CacheWritePla return changes; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/RuntimeDelegatingCacheManager.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/RuntimeDelegatingCacheManager.java index db9309406..5fabf79b7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/RuntimeDelegatingCacheManager.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/cache/service/RuntimeDelegatingCacheManager.java @@ -122,7 +122,7 @@ public class RuntimeDelegatingCacheManager implements CacheManager { private void clearEhCache() { javax.cache.CacheManager cacheManager = this.jcacheCacheManager.getCacheManager(); Iterable cacheNames = cacheManager.getCacheNames(); - for (String cacheName: cacheNames) { + for (String cacheName : cacheNames) { cacheManager.getCache(cacheName).clear(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/constants/CampaignType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/constants/CampaignType.java index c9ee37b55..ce8ac2a20 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/constants/CampaignType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/constants/CampaignType.java @@ -21,6 +21,7 @@ package org.apache.fineract.infrastructure.campaigns.constants; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public enum CampaignType { + INVALID(0, "campaignType.invalid"), SMS(1, "campaignType.sms"), NOTIFICATION(2, "campaignType.notification"); private final Integer value; @@ -70,7 +71,8 @@ public enum CampaignType { optionData = new EnumOptionData(CampaignType.SMS.getValue().longValue(), CampaignType.SMS.getCode(), "SMS"); break; case NOTIFICATION: - optionData = new EnumOptionData(CampaignType.NOTIFICATION.getValue().longValue(), CampaignType.NOTIFICATION.getCode(), "NOTIFICATION"); + optionData = new EnumOptionData(CampaignType.NOTIFICATION.getValue().longValue(), CampaignType.NOTIFICATION.getCode(), + "NOTIFICATION"); break; } return optionData; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/EmailApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/EmailApiConstants.java index 1307467ac..bf926ab36 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/EmailApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/EmailApiConstants.java @@ -41,8 +41,8 @@ public class EmailApiConstants { // response parameters public static final String statusParamName = "status"; - public static final Set CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(localeParamName, - dateFormatParamName, groupIdParamName, clientIdParamName, staffIdParamName, messageParamName)); + public static final Set CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(localeParamName, dateFormatParamName, groupIdParamName, clientIdParamName, staffIdParamName, messageParamName)); public static final Set UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(messageParamName)); @@ -51,4 +51,4 @@ public class EmailApiConstants { public static final String SMTP_USERNAME = "SMTP_USERNAME"; public static final String SMTP_PASSWORD = "SMTP_PASSWORD"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/ScheduledEmailConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/ScheduledEmailConstants.java index 359b34011..dfb6e4f25 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/ScheduledEmailConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/ScheduledEmailConstants.java @@ -57,26 +57,24 @@ public class ScheduledEmailConstants { public static final String STRETCHY_REPORT_PARAM_NAME = "stretchyReport"; // list of permitted parameters for the create report mailing job request - public static final Set CREATE_REQUEST_PARAMETERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(LOCALE_PARAM_NAME, DATE_FORMAT_PARAM_NAME, - NAME_PARAM_NAME, DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, EMAIL_RECIPIENTS_PARAM_NAME, EMAIL_SUBJECT_PARAM_NAME, - EMAIL_MESSAGE_PARAM_NAME, EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, STRETCHY_REPORT_ID_PARAM_NAME, + public static final Set CREATE_REQUEST_PARAMETERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(LOCALE_PARAM_NAME, + DATE_FORMAT_PARAM_NAME, NAME_PARAM_NAME, DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, EMAIL_RECIPIENTS_PARAM_NAME, + EMAIL_SUBJECT_PARAM_NAME, EMAIL_MESSAGE_PARAM_NAME, EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, STRETCHY_REPORT_ID_PARAM_NAME, STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, IS_ACTIVE_PARAM_NAME, START_DATE_TIME_PARAM_NAME))); // list of permitted parameters for the update report mailing job request - public static final Set UPDATE_REQUEST_PARAMETERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(LOCALE_PARAM_NAME, DATE_FORMAT_PARAM_NAME, - NAME_PARAM_NAME, DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, EMAIL_RECIPIENTS_PARAM_NAME, EMAIL_SUBJECT_PARAM_NAME, - EMAIL_MESSAGE_PARAM_NAME, EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, STRETCHY_REPORT_ID_PARAM_NAME, + public static final Set UPDATE_REQUEST_PARAMETERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(LOCALE_PARAM_NAME, + DATE_FORMAT_PARAM_NAME, NAME_PARAM_NAME, DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, EMAIL_RECIPIENTS_PARAM_NAME, + EMAIL_SUBJECT_PARAM_NAME, EMAIL_MESSAGE_PARAM_NAME, EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, STRETCHY_REPORT_ID_PARAM_NAME, STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, IS_ACTIVE_PARAM_NAME, START_DATE_TIME_PARAM_NAME))); // list of parameters that represent the properties of a report mailing job - public static final Set REPORT_MAILING_JOB_DATA_PARAMETERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(ID_PARAM_NAME, NAME_PARAM_NAME, - DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, EMAIL_RECIPIENTS_PARAM_NAME, EMAIL_SUBJECT_PARAM_NAME, EMAIL_MESSAGE_PARAM_NAME, - EMAIL_ATTACHMENT_FILE_FORMAT_PARAM_NAME, STRETCHY_REPORT_PARAM_NAME, STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, IS_ACTIVE_PARAM_NAME, - START_DATE_TIME_PARAM_NAME, PREVIOUS_RUN_DATE_TIME_PARAM_NAME, NEXT_RUN_DATE_TIME_PARAM_NAME, PREVIOUS_RUN_STATUS, - PREVIOUS_RUN_ERROR_LOG, PREVIOUS_RUN_ERROR_MESSAGE, NUMBER_OF_RUNS))); + public static final Set REPORT_MAILING_JOB_DATA_PARAMETERS = Collections + .unmodifiableSet(new HashSet<>(Arrays.asList(ID_PARAM_NAME, NAME_PARAM_NAME, DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, + EMAIL_RECIPIENTS_PARAM_NAME, EMAIL_SUBJECT_PARAM_NAME, EMAIL_MESSAGE_PARAM_NAME, + EMAIL_ATTACHMENT_FILE_FORMAT_PARAM_NAME, STRETCHY_REPORT_PARAM_NAME, STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, + IS_ACTIVE_PARAM_NAME, START_DATE_TIME_PARAM_NAME, PREVIOUS_RUN_DATE_TIME_PARAM_NAME, NEXT_RUN_DATE_TIME_PARAM_NAME, + PREVIOUS_RUN_STATUS, PREVIOUS_RUN_ERROR_LOG, PREVIOUS_RUN_ERROR_MESSAGE, NUMBER_OF_RUNS))); // report mailing job configuration names public static final String GMAIL_SMTP_SERVER = "GMAIL_SMTP_SERVER"; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailApiResource.java index fed9411b3..5a4909604 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailApiResource.java @@ -188,4 +188,4 @@ public class EmailApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailCampaignApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailCampaignApiResource.java index b99e16623..7591b67db 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailCampaignApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailCampaignApiResource.java @@ -54,11 +54,8 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; /** - * Created with IntelliJ IDEA. - * User: andrew - * Date: 19-5-14 - * Time: 15:17 - * To change this template use File | Settings | File Templates. + * Created with IntelliJ IDEA. User: andrew Date: 19-5-14 Time: 15:17 To change + * this template use File | Settings | File Templates. */ @Path("/email/campaign") @Consumes({ MediaType.APPLICATION_JSON }) @@ -67,8 +64,7 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class EmailCampaignApiResource { - - //change name to email campaign + // change name to email campaign private final String resourceNameForPermissions = "EMAIL_CAMPAIGN"; private final PlatformSecurityContext context; @@ -80,20 +76,21 @@ public class EmailCampaignApiResource { private final EmailCampaignReadPlatformService emailCampaignReadPlatformService; private final FromJsonHelper fromJsonHelper; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final DefaultToApiJsonSerializer emailCampaignDataDefaultToApiJsonSerializer; private final EmailCampaignWritePlatformService emailCampaignWritePlatformService; private final DefaultToApiJsonSerializer previewCampaignMessageDefaultToApiJsonSerializer; - @Autowired - public EmailCampaignApiResource(final PlatformSecurityContext context,final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, - final EmailCampaignReadPlatformService emailCampaignReadPlatformService, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final DefaultToApiJsonSerializer emailCampaignDataDefaultToApiJsonSerializer, - final FromJsonHelper fromJsonHelper, final EmailCampaignWritePlatformService emailCampaignWritePlatformService, - final DefaultToApiJsonSerializer previewCampaignMessageDefaultToApiJsonSerializer) { + public EmailCampaignApiResource(final PlatformSecurityContext context, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final ApiRequestParameterHelper apiRequestParameterHelper, + final EmailCampaignReadPlatformService emailCampaignReadPlatformService, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final DefaultToApiJsonSerializer emailCampaignDataDefaultToApiJsonSerializer, + final FromJsonHelper fromJsonHelper, final EmailCampaignWritePlatformService emailCampaignWritePlatformService, + final DefaultToApiJsonSerializer previewCampaignMessageDefaultToApiJsonSerializer) { this.context = context; this.toApiJsonSerializer = toApiJsonSerializer; this.apiRequestParameterHelper = apiRequestParameterHelper; @@ -105,16 +102,15 @@ public class EmailCampaignApiResource { this.previewCampaignMessageDefaultToApiJsonSerializer = previewCampaignMessageDefaultToApiJsonSerializer; } - @GET @Path("{resourceId}") @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveOneCampaign(@PathParam("resourceId") final Long resourceId,@Context final UriInfo uriInfo){ + public String retrieveOneCampaign(@PathParam("resourceId") final Long resourceId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); EmailCampaignData emailCampaignData = this.emailCampaignReadPlatformService.retrieveOne(resourceId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.emailCampaignDataDefaultToApiJsonSerializer.serialize(settings,emailCampaignData); + return this.emailCampaignDataDefaultToApiJsonSerializer.serialize(settings, emailCampaignData); } @@ -127,13 +123,13 @@ public class EmailCampaignApiResource { final Collection emailCampaignDataCollection = this.emailCampaignReadPlatformService.retrieveAllCampaign(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.emailCampaignDataDefaultToApiJsonSerializer.serialize(settings,emailCampaignDataCollection); + return this.emailCampaignDataDefaultToApiJsonSerializer.serialize(settings, emailCampaignDataCollection); } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String createCampaign(final String apiRequestBodyAsJson,@Context final UriInfo uriInfo){ + public String createCampaign(final String apiRequestBodyAsJson, @Context final UriInfo uriInfo) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createEmailCampaign().withJson(apiRequestBodyAsJson).build(); @@ -146,9 +142,11 @@ public class EmailCampaignApiResource { @Path("{resourceId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String updateCampaign(@PathParam("resourceId") final Long campaignId,final String apiRequestBodyAsJson,@Context final UriInfo uriInfo){ + public String updateCampaign(@PathParam("resourceId") final Long campaignId, final String apiRequestBodyAsJson, + @Context final UriInfo uriInfo) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateEmailCampaign(campaignId).withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateEmailCampaign(campaignId).withJson(apiRequestBodyAsJson) + .build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -160,7 +158,7 @@ public class EmailCampaignApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String activate(@PathParam("resourceId") final Long campaignId, @QueryParam("command") final String commandParam, - final String apiRequestBodyAsJson){ + final String apiRequestBodyAsJson) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); CommandProcessingResult result = null; @@ -168,10 +166,10 @@ public class EmailCampaignApiResource { if (is(commandParam, "activate")) { commandRequest = builder.activateEmailCampaign(campaignId).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - }else if (is(commandParam, "close")){ + } else if (is(commandParam, "close")) { commandRequest = builder.closeEmailCampaign(campaignId).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - }else if (is(commandParam, "reactivate")){ + } else if (is(commandParam, "reactivate")) { commandRequest = builder.reactivateEmailCampaign(campaignId).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); } @@ -182,7 +180,7 @@ public class EmailCampaignApiResource { @Path("preview") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String preview(final String apiRequestBodyAsJson,@Context final UriInfo uriInfo){ + public String preview(final String apiRequestBodyAsJson, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); PreviewCampaignMessage campaignMessage = null; @@ -190,30 +188,29 @@ public class EmailCampaignApiResource { final JsonQuery query = JsonQuery.from(apiRequestBodyAsJson, parsedQuery, this.fromJsonHelper); campaignMessage = this.emailCampaignWritePlatformService.previewMessage(query); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.previewCampaignMessageDefaultToApiJsonSerializer.serialize(settings,campaignMessage, new HashSet()); + return this.previewCampaignMessageDefaultToApiJsonSerializer.serialize(settings, campaignMessage, new HashSet()); } - @GET() @Path("template") - public String template(@Context final UriInfo uriInfo){ + public String template(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final Collection emailBusinessRulesDataCollection = this.emailCampaignReadPlatformService.retrieveAll(); + final Collection emailBusinessRulesDataCollection = this.emailCampaignReadPlatformService.retrieveAll(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings,emailBusinessRulesDataCollection); + return this.toApiJsonSerializer.serialize(settings, emailBusinessRulesDataCollection); } @GET @Path("template/{resourceId}") - public String retrieveOneTemplate(@PathParam("resourceId") final Long resourceId,@Context final UriInfo uriInfo){ + public String retrieveOneTemplate(@PathParam("resourceId") final Long resourceId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final EmailBusinessRulesData emailBusinessRulesData = this.emailCampaignReadPlatformService.retrieveOneTemplate(resourceId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings,emailBusinessRulesData); + return this.toApiJsonSerializer.serialize(settings, emailBusinessRulesData); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailConfigurationApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailConfigurationApiResource.java index 599a84bb1..e34aa0ec4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailConfigurationApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/api/EmailConfigurationApiResource.java @@ -42,7 +42,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; - @Path("/email/configuration") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @@ -60,10 +59,10 @@ public class EmailConfigurationApiResource { @Autowired public EmailConfigurationApiResource(final PlatformSecurityContext context, final EmailReadPlatformService readPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final EmailConfigurationReadPlatformService emailConfigurationReadPlatformService) { + final DefaultToApiJsonSerializer toApiJsonSerializer, + final ApiRequestParameterHelper apiRequestParameterHelper, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final EmailConfigurationReadPlatformService emailConfigurationReadPlatformService) { this.context = context; this.readPlatformService = readPlatformService; this.toApiJsonSerializer = toApiJsonSerializer; @@ -73,7 +72,7 @@ public class EmailConfigurationApiResource { } @GET - public String retrieveAll(@Context final UriInfo uriInfo){ + public String retrieveAll(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final Collection configuration = this.emailConfigurationReadPlatformService.retrieveAll(); @@ -83,9 +82,8 @@ public class EmailConfigurationApiResource { return this.toApiJsonSerializer.serialize(settings, configuration); } - @PUT - public String updateConfiguration(@Context final UriInfo uriInfo, final String apiRequestBodyAsJson){ + public String updateConfiguration(@Context final UriInfo uriInfo, final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateEmailConfiguration().withJson(apiRequestBodyAsJson).build(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailBusinessRulesData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailBusinessRulesData.java index 88c158564..fd480b081 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailBusinessRulesData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailBusinessRulesData.java @@ -38,12 +38,10 @@ public class EmailBusinessRulesData { private final String reportDescription; @SuppressWarnings("unused") - private final Map reportParamName; + private final Map reportParamName; - - - public EmailBusinessRulesData(final Long reportId, final String reportName,final String reportType, final Map reportParamName, - final String reportSubType, final String reportDescription) { + public EmailBusinessRulesData(final Long reportId, final String reportName, final String reportType, + final Map reportParamName, final String reportSubType, final String reportDescription) { this.reportId = reportId; this.reportName = reportName; this.reportType = reportType; @@ -52,10 +50,9 @@ public class EmailBusinessRulesData { this.reportSubType = reportSubType; } - - public static EmailBusinessRulesData instance(final Long reportId, final String reportName, final String reportType, final Map reportParamName, - final String reportSubType, final String reportDescription){ - return new EmailBusinessRulesData(reportId,reportName,reportType,reportParamName,reportSubType,reportDescription); + public static EmailBusinessRulesData instance(final Long reportId, final String reportName, final String reportType, + final Map reportParamName, final String reportSubType, final String reportDescription) { + return new EmailBusinessRulesData(reportId, reportName, reportType, reportParamName, reportSubType, reportDescription); } public Map getReportParamName() { @@ -80,12 +77,8 @@ public class EmailBusinessRulesData { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || !(o instanceof EmailBusinessRulesData)) { - return false; - } + if (this == o) { return true; } + if (o == null || !(o instanceof EmailBusinessRulesData)) { return false; } EmailBusinessRulesData that = (EmailBusinessRulesData) o; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignData.java index 3bf8b3046..76984ce2c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignData.java @@ -59,47 +59,46 @@ public class EmailCampaignData { private final String recurrence; private EmailCampaignData(final Long id, final String campaignName, final Integer campaignType, final Long businessRuleId, - final String paramValue, final EnumOptionData campaignStatus, final String emailSubject, - final String message, final String emailAttachmentFileFormat, final Long stretchyReportId, - final String stretchyReportParamMap, final DateTime nextTriggerDate, final LocalDate lastTriggerDate, - final EmailCampaignTimeLine emailCampaignTimeLine, final DateTime recurrenceStartDate, final String recurrence) { + final String paramValue, final EnumOptionData campaignStatus, final String emailSubject, final String message, + final String emailAttachmentFileFormat, final Long stretchyReportId, final String stretchyReportParamMap, + final DateTime nextTriggerDate, final LocalDate lastTriggerDate, final EmailCampaignTimeLine emailCampaignTimeLine, + final DateTime recurrenceStartDate, final String recurrence) { this.id = id; this.campaignName = campaignName; this.campaignType = campaignType; this.businessRuleId = businessRuleId; this.paramValue = paramValue; - this.campaignStatus =campaignStatus; + this.campaignStatus = campaignStatus; this.emailSubject = emailSubject; this.emailMessage = message; this.emailAttachmentFileFormat = emailAttachmentFileFormat; this.stretchyReportId = stretchyReportId; this.stretchyReportParamMap = stretchyReportParamMap; - if(nextTriggerDate !=null){ + if (nextTriggerDate != null) { this.nextTriggerDate = nextTriggerDate; - }else{ + } else { this.nextTriggerDate = null; } - if(lastTriggerDate !=null){ + if (lastTriggerDate != null) { this.lastTriggerDate = lastTriggerDate; - }else{ + } else { this.lastTriggerDate = null; } - this.emailCampaignTimeLine =emailCampaignTimeLine; + this.emailCampaignTimeLine = emailCampaignTimeLine; this.recurrenceStartDate = recurrenceStartDate; - this.recurrence = recurrence; + this.recurrence = recurrence; } public static EmailCampaignData instance(final Long id, final String campaignName, final Integer campaignType, final Long runReportId, - final String paramValue, final EnumOptionData campaignStatus, final String emailSubject, - final String message, final String emailAttachmentFileFormat, final Long stretchyReportId, - final String stretchyReportParamMap, final DateTime nextTriggerDate, final LocalDate lastTriggerDate, - final EmailCampaignTimeLine emailCampaignTimeLine, - final DateTime recurrenceStartDate, final String recurrence){ - return new EmailCampaignData(id,campaignName,campaignType,runReportId,paramValue, - campaignStatus,emailSubject,message,emailAttachmentFileFormat,stretchyReportId,stretchyReportParamMap,nextTriggerDate,lastTriggerDate,emailCampaignTimeLine,recurrenceStartDate,recurrence); + final String paramValue, final EnumOptionData campaignStatus, final String emailSubject, final String message, + final String emailAttachmentFileFormat, final Long stretchyReportId, final String stretchyReportParamMap, + final DateTime nextTriggerDate, final LocalDate lastTriggerDate, final EmailCampaignTimeLine emailCampaignTimeLine, + final DateTime recurrenceStartDate, final String recurrence) { + return new EmailCampaignData(id, campaignName, campaignType, runReportId, paramValue, campaignStatus, emailSubject, message, + emailAttachmentFileFormat, stretchyReportId, stretchyReportParamMap, nextTriggerDate, lastTriggerDate, + emailCampaignTimeLine, recurrenceStartDate, recurrence); } - public Long getId() { return id; } @@ -124,7 +123,9 @@ public class EmailCampaignData { return this.campaignStatus; } - public String getEmailSubject() { return this.emailSubject; } + public String getEmailSubject() { + return this.emailSubject; + } public String getMessage() { return this.emailMessage; @@ -138,7 +139,11 @@ public class EmailCampaignData { return this.lastTriggerDate; } - public String getRecurrence() {return this.recurrence;} + public String getRecurrence() { + return this.recurrence; + } - public DateTime getRecurrenceStartDate() {return this.recurrenceStartDate;} + public DateTime getRecurrenceStartDate() { + return this.recurrenceStartDate; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignTimeLine.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignTimeLine.java index 920462690..30e856b70 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignTimeLine.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignTimeLine.java @@ -21,6 +21,7 @@ package org.apache.fineract.infrastructure.campaigns.email.data; import org.joda.time.LocalDate; public class EmailCampaignTimeLine { + private final LocalDate submittedOnDate; private final String submittedByUsername; private final LocalDate activatedOnDate; @@ -28,8 +29,8 @@ public class EmailCampaignTimeLine { private final LocalDate closedOnDate; private final String closedByUsername; - public EmailCampaignTimeLine(final LocalDate submittedOnDate, final String submittedByUsername, - final LocalDate activatedOnDate, final String activatedByUsername, final LocalDate closedOnDate, final String closedByUsername) { + public EmailCampaignTimeLine(final LocalDate submittedOnDate, final String submittedByUsername, final LocalDate activatedOnDate, + final String activatedByUsername, final LocalDate closedOnDate, final String closedByUsername) { this.submittedOnDate = submittedOnDate; this.submittedByUsername = submittedByUsername; this.activatedOnDate = activatedOnDate; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignValidator.java index 8228c984b..df79954be 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailCampaignValidator.java @@ -41,17 +41,15 @@ import org.springframework.stereotype.Component; @Component public class EmailCampaignValidator { - - public static final String RESOURCE_NAME = "email"; - public static final String campaignName = "campaignName"; + public static final String campaignName = "campaignName"; public static final String campaignType = "campaignType"; public static final String businessRuleId = "businessRuleId"; public static final String stretchyReportId = "stretchyReportId"; public static final String stretchyReportParamMap = "stretchyReportParamMap"; public static final String paramValue = "paramValue"; public static final String emailSubject = "emailSubject"; - public static final String emailMessage = "emailMessage"; + public static final String emailMessage = "emailMessage"; public static final String emailAttachmentFileFormatId = "emailAttachmentFileFormatId"; public static final String activationDateParamName = "activationDate"; public static final String recurrenceStartDate = "recurrenceStartDate"; @@ -63,32 +61,31 @@ public class EmailCampaignValidator { public static final String localeParamName = "locale"; public static final String dateFormatParamName = "dateFormat"; - private final FromJsonHelper fromApiJsonHelper; + public static final Set supportedParams = new HashSet( + Arrays.asList(campaignName, campaignType, localeParamName, dateFormatParamName, businessRuleId, paramValue, emailMessage, + recurrenceStartDate, activationDateParamName, submittedOnDateParamName, closureDateParamName, recurrenceParamName, + emailSubject, stretchyReportId, stretchyReportParamMap, emailAttachmentFileFormatId)); - public static final Set supportedParams = new HashSet(Arrays.asList(campaignName, campaignType,localeParamName,dateFormatParamName, - businessRuleId,paramValue,emailMessage,recurrenceStartDate,activationDateParamName,submittedOnDateParamName,closureDateParamName,recurrenceParamName, - emailSubject,stretchyReportId,stretchyReportParamMap,emailAttachmentFileFormatId)); + public static final Set supportedParamsForUpdate = new HashSet<>( + Arrays.asList(campaignName, campaignType, localeParamName, dateFormatParamName, businessRuleId, paramValue, emailMessage, + recurrenceStartDate, activationDateParamName, recurrenceParamName)); - public static final Set supportedParamsForUpdate = new HashSet<>(Arrays.asList(campaignName, campaignType,localeParamName,dateFormatParamName, - businessRuleId,paramValue,emailMessage,recurrenceStartDate,activationDateParamName,recurrenceParamName)); + public static final Set ACTIVATION_REQUEST_DATA_PARAMETERS = new HashSet( + Arrays.asList(localeParamName, dateFormatParamName, activationDateParamName)); - public static final Set ACTIVATION_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(localeParamName, - dateFormatParamName, activationDateParamName)); + public static final Set CLOSE_REQUEST_DATA_PARAMETERS = new HashSet( + Arrays.asList(localeParamName, dateFormatParamName, closureDateParamName)); - public static final Set CLOSE_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(localeParamName, - dateFormatParamName, closureDateParamName)); - - public static final Set PREVIEW_REQUEST_DATA_PARAMETERS= new HashSet(Arrays.asList(paramValue,emailMessage)); + public static final Set PREVIEW_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(paramValue, emailMessage)); @Autowired public EmailCampaignValidator(FromJsonHelper fromApiJsonHelper) { this.fromApiJsonHelper = fromApiJsonHelper; } - - public void validateCreate(String json){ + public void validateCreate(String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); @@ -101,22 +98,23 @@ public class EmailCampaignValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(EmailCampaignValidator.RESOURCE_NAME); - final String campaignName = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.campaignName,element); + final String campaignName = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.campaignName, element); baseDataValidator.reset().parameter(EmailCampaignValidator.campaignName).value(campaignName).notBlank().notExceedingLengthOf(100); - - final Long campaignType = this.fromApiJsonHelper.extractLongNamed(EmailCampaignValidator.campaignType,element); + final Long campaignType = this.fromApiJsonHelper.extractLongNamed(EmailCampaignValidator.campaignType, element); baseDataValidator.reset().parameter(EmailCampaignValidator.campaignType).value(campaignType).notNull().integerGreaterThanZero(); - if(campaignType.intValue() == EmailCampaignType.SCHEDULE.getValue()){ - final String recurrenceParamName = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.recurrenceParamName, element); + if (campaignType.intValue() == EmailCampaignType.SCHEDULE.getValue()) { + final String recurrenceParamName = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.recurrenceParamName, + element); baseDataValidator.reset().parameter(EmailCampaignValidator.recurrenceParamName).value(recurrenceParamName).notBlank(); - final String recurrenceStartDate = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.recurrenceStartDate, element); + final String recurrenceStartDate = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.recurrenceStartDate, + element); baseDataValidator.reset().parameter(EmailCampaignValidator.recurrenceStartDate).value(recurrenceStartDate).notBlank(); } - final Long businessRuleId = this.fromApiJsonHelper.extractLongNamed(EmailCampaignValidator.businessRuleId,element); + final Long businessRuleId = this.fromApiJsonHelper.extractLongNamed(EmailCampaignValidator.businessRuleId, element); baseDataValidator.reset().parameter(EmailCampaignValidator.businessRuleId).value(businessRuleId).notNull().integerGreaterThanZero(); final String emailSubject = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.emailSubject, element); @@ -128,21 +126,17 @@ public class EmailCampaignValidator { final String paramValue = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.paramValue, element); baseDataValidator.reset().parameter(EmailCampaignValidator.paramValue).value(paramValue).notBlank(); - - if (this.fromApiJsonHelper.parameterExists(EmailCampaignValidator.submittedOnDateParamName, element)) { final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(EmailCampaignValidator.submittedOnDateParamName, element); baseDataValidator.reset().parameter(EmailCampaignValidator.submittedOnDateParamName).value(submittedOnDate).notNull(); } - - throwExceptionIfValidationWarningsExist(dataValidationErrors); } - public void validateForUpdate(String json){ + public void validateForUpdate(String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, EmailCampaignValidator.supportedParamsForUpdate); @@ -153,22 +147,23 @@ public class EmailCampaignValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(EmailCampaignValidator.RESOURCE_NAME); - final String campaignName = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.campaignName,element); + final String campaignName = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.campaignName, element); baseDataValidator.reset().parameter(EmailCampaignValidator.campaignName).value(campaignName).notBlank().notExceedingLengthOf(100); - - final Long campaignType = this.fromApiJsonHelper.extractLongNamed(EmailCampaignValidator.campaignType,element); + final Long campaignType = this.fromApiJsonHelper.extractLongNamed(EmailCampaignValidator.campaignType, element); baseDataValidator.reset().parameter(EmailCampaignValidator.campaignType).value(campaignType).notNull().integerGreaterThanZero(); - if(campaignType.intValue() == EmailCampaignType.SCHEDULE.getValue()){ - final String recurrenceParamName = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.recurrenceParamName, element); + if (campaignType.intValue() == EmailCampaignType.SCHEDULE.getValue()) { + final String recurrenceParamName = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.recurrenceParamName, + element); baseDataValidator.reset().parameter(EmailCampaignValidator.recurrenceParamName).value(recurrenceParamName).notBlank(); - final String recurrenceStartDate = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.recurrenceStartDate, element); + final String recurrenceStartDate = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.recurrenceStartDate, + element); baseDataValidator.reset().parameter(EmailCampaignValidator.recurrenceStartDate).value(recurrenceStartDate).notBlank(); } - final Long runReportId = this.fromApiJsonHelper.extractLongNamed(EmailCampaignValidator.businessRuleId,element); + final Long runReportId = this.fromApiJsonHelper.extractLongNamed(EmailCampaignValidator.businessRuleId, element); baseDataValidator.reset().parameter(EmailCampaignValidator.businessRuleId).value(runReportId).notNull().integerGreaterThanZero(); final String message = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.emailMessage, element); @@ -179,10 +174,9 @@ public class EmailCampaignValidator { throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - public void validatePreviewMessage(String json){ + public void validatePreviewMessage(String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, EmailCampaignValidator.PREVIEW_REQUEST_DATA_PARAMETERS); @@ -201,10 +195,9 @@ public class EmailCampaignValidator { throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - public void validateClosedDate(String json){ + public void validateClosedDate(String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); @@ -221,7 +214,8 @@ public class EmailCampaignValidator { throwExceptionIfValidationWarningsExist(dataValidationErrors); } - public void validateActivation(String json){ + + public void validateActivation(String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); @@ -233,13 +227,14 @@ public class EmailCampaignValidator { final JsonElement element = this.fromApiJsonHelper.parse(json); - final LocalDate activationDate = this.fromApiJsonHelper.extractLocalDateNamed(EmailCampaignValidator.activationDateParamName, element); + final LocalDate activationDate = this.fromApiJsonHelper.extractLocalDateNamed(EmailCampaignValidator.activationDateParamName, + element); baseDataValidator.reset().parameter(EmailCampaignValidator.activationDateParamName).value(activationDate).notNull(); throwExceptionIfValidationWarningsExist(dataValidationErrors); } - public void validateClosure(String json){ + public void validateClosure(String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailConfigurationData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailConfigurationData.java index 8026823d2..2cbc66ce3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailConfigurationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailConfigurationData.java @@ -22,6 +22,7 @@ package org.apache.fineract.infrastructure.campaigns.email.data; * Immutable data object representing an Email configuration. */ public class EmailConfigurationData { + @SuppressWarnings("unused") private final Long id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailConfigurationValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailConfigurationValidator.java index a302732ff..a84241f7b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailConfigurationValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailConfigurationValidator.java @@ -47,17 +47,15 @@ public class EmailConfigurationValidator { private static final String EMAIL_REGEX = "^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"; private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX); - public static final Set supportedParams = new HashSet(Arrays.asList(EmailApiConstants.SMTP_PORT,EmailApiConstants.SMTP_PASSWORD, - EmailApiConstants.SMTP_USERNAME,EmailApiConstants.SMTP_SERVER)); + public static final Set supportedParams = new HashSet(Arrays.asList(EmailApiConstants.SMTP_PORT, + EmailApiConstants.SMTP_PASSWORD, EmailApiConstants.SMTP_USERNAME, EmailApiConstants.SMTP_SERVER)); @Autowired private EmailConfigurationValidator(final FromJsonHelper fromApiJsonHelper) { this.fromApiJsonHelper = fromApiJsonHelper; } - - - public void validateUpdateConfiguration(String json){ + public void validateUpdateConfiguration(String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } @@ -70,23 +68,20 @@ public class EmailConfigurationValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(EmailApiConstants.RESOURCE_NAME); - final String smtpUsername = this.fromApiJsonHelper.extractStringNamed(EmailApiConstants.SMTP_USERNAME,element); + final String smtpUsername = this.fromApiJsonHelper.extractStringNamed(EmailApiConstants.SMTP_USERNAME, element); baseDataValidator.reset().parameter(EmailApiConstants.SMTP_USERNAME).value(smtpUsername).notBlank().notExceedingLengthOf(150); - - final String smtpPassword = this.fromApiJsonHelper.extractStringNamed(EmailApiConstants.SMTP_PASSWORD,element); + final String smtpPassword = this.fromApiJsonHelper.extractStringNamed(EmailApiConstants.SMTP_PASSWORD, element); baseDataValidator.reset().parameter(EmailApiConstants.SMTP_PASSWORD).value(smtpPassword).notBlank().notExceedingLengthOf(50); - final String smtpServer = this.fromApiJsonHelper.extractStringNamed(EmailApiConstants.SMTP_SERVER,element); + final String smtpServer = this.fromApiJsonHelper.extractStringNamed(EmailApiConstants.SMTP_SERVER, element); baseDataValidator.reset().parameter(EmailApiConstants.SMTP_SERVER).value(smtpServer).notBlank().notExceedingLengthOf(100); - final Long smtpPort = this.fromApiJsonHelper.extractLongNamed(EmailApiConstants.SMTP_PORT,element); + final Long smtpPort = this.fromApiJsonHelper.extractLongNamed(EmailApiConstants.SMTP_PORT, element); baseDataValidator.reset().parameter(EmailApiConstants.SMTP_PORT).value(smtpPort).notNull().integerGreaterThanZero(); this.throwExceptionIfValidationWarningsExist(dataValidationErrors); - - } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { @@ -97,17 +92,13 @@ public class EmailConfigurationValidator { // this is the easiest check if (email == null) { return false; - }else if (email.endsWith(".")) { - return false; - } + } else if (email.endsWith(".")) { return false; } // Check the whole email address structure Matcher emailMatcher = EMAIL_PATTERN.matcher(email); // check if the Matcher matches the email pattern - if (!emailMatcher.matches()) { - return false; - } + if (!emailMatcher.matches()) { return false; } return true; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailData.java index 061040012..54c1d63cf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailData.java @@ -45,21 +45,21 @@ public class EmailData { private final LocalDate sentDate; private final String errorMessage; - - public static EmailData instance(final Long id,final Long groupId, final Long clientId, final Long staffId, final EnumOptionData status, - final String emailAddress, final String emailSubject, - final String message, final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport, - final String stretchyReportParamMap, final List emailAttachmentFileFormatOptions, - final List stretchyReportParamDateOptions, final String campaignName, final LocalDate sentDate,final String errorMessage) { - return new EmailData(id, groupId, clientId, staffId, status, emailAddress, emailSubject, message, - emailAttachmentFileFormat,stretchyReport,stretchyReportParamMap,emailAttachmentFileFormatOptions, - stretchyReportParamDateOptions,campaignName,sentDate,errorMessage); + public static EmailData instance(final Long id, final Long groupId, final Long clientId, final Long staffId, + final EnumOptionData status, final String emailAddress, final String emailSubject, final String message, + final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport, final String stretchyReportParamMap, + final List emailAttachmentFileFormatOptions, final List stretchyReportParamDateOptions, + final String campaignName, final LocalDate sentDate, final String errorMessage) { + return new EmailData(id, groupId, clientId, staffId, status, emailAddress, emailSubject, message, emailAttachmentFileFormat, + stretchyReport, stretchyReportParamMap, emailAttachmentFileFormatOptions, stretchyReportParamDateOptions, campaignName, + sentDate, errorMessage); } - private EmailData(final Long id,final Long groupId, final Long clientId, final Long staffId, final EnumOptionData status, final String emailAddress, final String emailSubject, final String message, - final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport, final String stretchyReportParamMap, - final List emailAttachmentFileFormatOptions, final List stretchyReportParamDateOptions, - final String campaignName,final LocalDate sentDate,final String errorMessage) { + private EmailData(final Long id, final Long groupId, final Long clientId, final Long staffId, final EnumOptionData status, + final String emailAddress, final String emailSubject, final String message, final EnumOptionData emailAttachmentFileFormat, + final ReportData stretchyReport, final String stretchyReportParamMap, + final List emailAttachmentFileFormatOptions, final List stretchyReportParamDateOptions, + final String campaignName, final LocalDate sentDate, final String errorMessage) { this.id = id; this.groupId = groupId; this.clientId = clientId; @@ -113,7 +113,9 @@ public class EmailData { return status; } - public String getErrorMessage() {return this.errorMessage;} + public String getErrorMessage() { + return this.errorMessage; + } /** * @return the emailAddress @@ -129,9 +131,13 @@ public class EmailData { return emailMessage; } - public String getCampaignName() {return this.campaignName;} + public String getCampaignName() { + return this.campaignName; + } - public LocalDate getSentDate() { return this.sentDate; } + public LocalDate getSentDate() { + return this.sentDate; + } public String getEmailSubject() { return emailSubject; @@ -156,4 +162,4 @@ public class EmailData { public List getStretchyReportParamDateOptions() { return stretchyReportParamDateOptions; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailDataValidator.java index 2684d358e..7bc970db1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailDataValidator.java @@ -61,24 +61,22 @@ public final class EmailDataValidator { /** * validate the request to create a new report mailing job * - * @param jsonCommand -- the JSON command object (instance of the JsonCommand class) + * @param jsonCommand + * -- the JSON command object (instance of the JsonCommand class) * @return None **/ public void validateCreateRequest(final JsonCommand jsonCommand) { final String jsonString = jsonCommand.json(); final JsonElement jsonElement = jsonCommand.parsedJson(); - if (StringUtils.isBlank(jsonString)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(jsonString)) { throw new InvalidJsonException(); } final Type typeToken = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, - ScheduledEmailConstants.CREATE_REQUEST_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, ScheduledEmailConstants.CREATE_REQUEST_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors). - resource(StringUtils.lowerCase(ScheduledEmailConstants.SCHEDULED_EMAIL_ENTITY_NAME)); + final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors) + .resource(StringUtils.lowerCase(ScheduledEmailConstants.SCHEDULED_EMAIL_ENTITY_NAME)); final String name = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.NAME_PARAM_NAME, jsonElement); dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.NAME_PARAM_NAME).value(name).notBlank().notExceedingLengthOf(100); @@ -87,34 +85,37 @@ public final class EmailDataValidator { jsonElement); dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.START_DATE_TIME_PARAM_NAME).value(startDateTime).notBlank(); - final Integer stretchyReportId = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME, - jsonElement); - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME).value(stretchyReportId).notNull(). - integerGreaterThanZero(); + final Integer stretchyReportId = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement); + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME).value(stretchyReportId).notNull() + .integerGreaterThanZero(); - final String emailRecipients = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement); + final String emailRecipients = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME, + jsonElement); dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME).value(emailRecipients).notBlank(); - final String emailSubject = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement); - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME).value(emailSubject).notBlank().notExceedingLengthOf(100); + final String emailSubject = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME, + jsonElement); + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME).value(emailSubject).notBlank() + .notExceedingLengthOf(100); - final String emailMessage = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement); + final String emailMessage = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME, + jsonElement); dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME).value(emailMessage).notBlank(); if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME, jsonElement)) { - final Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME, - jsonElement); + final Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME, jsonElement); dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME).value(isActive).notNull(); } - final Integer emailAttachmentFileFormatId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement); - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME). - value(emailAttachmentFileFormatId).notNull(); + final Integer emailAttachmentFileFormatId = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement); + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME) + .value(emailAttachmentFileFormatId).notNull(); if (emailAttachmentFileFormatId != null) { - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME).value(emailAttachmentFileFormatId). - isOneOfTheseValues(ScheduledEmailAttachmentFileFormat.validValues()); + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME) + .value(emailAttachmentFileFormatId).isOneOfTheseValues(ScheduledEmailAttachmentFileFormat.validValues()); } final String dateFormat = jsonCommand.dateFormat(); @@ -129,8 +130,9 @@ public final class EmailDataValidator { LocalDateTime.parse(startDateTime, dateTimeFormatter); } - catch(IllegalArgumentException ex) { - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat).failWithCode("invalid.date.format"); + catch (IllegalArgumentException ex) { + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat) + .failWithCode("invalid.date.format"); } } @@ -140,67 +142,69 @@ public final class EmailDataValidator { /** * validate the request to update a report mailing job * - * @param jsonCommand -- the JSON command object (instance of the JsonCommand class) + * @param jsonCommand + * -- the JSON command object (instance of the JsonCommand class) * @return None **/ public void validateUpdateRequest(final JsonCommand jsonCommand) { final String jsonString = jsonCommand.json(); final JsonElement jsonElement = jsonCommand.parsedJson(); - if (StringUtils.isBlank(jsonString)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(jsonString)) { throw new InvalidJsonException(); } final Type typeToken = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, - ScheduledEmailConstants.UPDATE_REQUEST_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, ScheduledEmailConstants.UPDATE_REQUEST_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors). - resource(StringUtils.lowerCase(ScheduledEmailConstants.SCHEDULED_EMAIL_ENTITY_NAME)); + final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors) + .resource(StringUtils.lowerCase(ScheduledEmailConstants.SCHEDULED_EMAIL_ENTITY_NAME)); if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.NAME_PARAM_NAME, jsonElement)) { final String name = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.NAME_PARAM_NAME, jsonElement); - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.NAME_PARAM_NAME).value(name).notBlank().notExceedingLengthOf(100); + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.NAME_PARAM_NAME).value(name).notBlank() + .notExceedingLengthOf(100); } if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement)) { - final Integer stretchyReportId = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME, - jsonElement); - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME).value(stretchyReportId).notNull(). - integerGreaterThanZero(); + final Integer stretchyReportId = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement); + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME).value(stretchyReportId).notNull() + .integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement)) { - final String emailRecipients = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement); + final String emailRecipients = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME, + jsonElement); dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME).value(emailRecipients).notBlank(); } if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement)) { - final String emailSubject = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement); - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME).value(emailSubject).notBlank().notExceedingLengthOf(100); + final String emailSubject = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME, + jsonElement); + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME).value(emailSubject).notBlank() + .notExceedingLengthOf(100); } if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement)) { - final String emailMessage = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement); + final String emailMessage = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME, + jsonElement); dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME).value(emailMessage).notBlank(); } if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME, jsonElement)) { - final Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME, - jsonElement); + final Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME, jsonElement); dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME).value(isActive).notNull(); } if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement)) { - final Integer emailAttachmentFileFormatId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement); - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME). - value(emailAttachmentFileFormatId).notNull(); + final Integer emailAttachmentFileFormatId = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement); + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME) + .value(emailAttachmentFileFormatId).notNull(); if (emailAttachmentFileFormatId != null) { - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME).value(emailAttachmentFileFormatId). - isOneOfTheseValues(ScheduledEmailAttachmentFileFormat.validValues()); + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME) + .value(emailAttachmentFileFormatId).isOneOfTheseValues(ScheduledEmailAttachmentFileFormat.validValues()); } } @@ -215,14 +219,16 @@ public final class EmailDataValidator { if (StringUtils.isNotEmpty(dateFormat)) { try { - final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateFormat).withLocale(jsonCommand.extractLocale()); + final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateFormat) + .withLocale(jsonCommand.extractLocale()); // try to parse the date time string LocalDateTime.parse(startDateTime, dateTimeFormatter); } - catch(IllegalArgumentException ex) { - dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat).failWithCode("invalid.date.format"); + catch (IllegalArgumentException ex) { + dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat) + .failWithCode("invalid.date.format"); } } } @@ -233,27 +239,22 @@ public final class EmailDataValidator { /** * check if string is a valid email address * - * @param email -- string to be validated + * @param email + * -- string to be validated * @return true if string is a valid email address **/ public boolean isValidEmail(String email) { // this is the easiest check - if (email == null) { - return false; - } + if (email == null) { return false; } // this is another easy check - if (email.endsWith(".")) { - return false; - } + if (email.endsWith(".")) { return false; } // Check the whole email address structure Matcher emailMatcher = EMAIL_PATTERN.matcher(email); // check if the Matcher matches the email pattern - if (!emailMatcher.matches()) { - return false; - } + if (!emailMatcher.matches()) { return false; } return true; } @@ -261,7 +262,8 @@ public final class EmailDataValidator { /** * Validate the email recipients string * - * @param emailRecipients -- the email recipients string to be validated + * @param emailRecipients + * -- the email recipients string to be validated * @return a hashset containing valid email addresses **/ public Set validateEmailRecipients(String emailRecipients) { @@ -285,18 +287,20 @@ public final class EmailDataValidator { /** * validate the stretchy report param json string * - * @param stretchyReportParamMap -- json string to be validated + * @param stretchyReportParamMap + * -- json string to be validated * @return if string is valid or empty, a HashMap object, else null **/ - public HashMap validateStretchyReportParamMap(String stretchyReportParamMap) { - HashMap stretchyReportParamHashMap = new HashMap<>(); + public HashMap validateStretchyReportParamMap(String stretchyReportParamMap) { + HashMap stretchyReportParamHashMap = new HashMap<>(); if (!StringUtils.isEmpty(stretchyReportParamMap)) { try { - stretchyReportParamHashMap = new ObjectMapper().readValue(stretchyReportParamMap, new TypeReference>(){}); + stretchyReportParamHashMap = new ObjectMapper().readValue(stretchyReportParamMap, + new TypeReference>() {}); } - catch(Exception e) { + catch (Exception e) { stretchyReportParamHashMap = null; } } @@ -307,4 +311,4 @@ public final class EmailDataValidator { private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailMessageWithAttachmentData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailMessageWithAttachmentData.java index d80592ab1..066cb1122 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailMessageWithAttachmentData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/EmailMessageWithAttachmentData.java @@ -35,16 +35,22 @@ public class EmailMessageWithAttachmentData { this.attachments = attachments; } - - public static EmailMessageWithAttachmentData createNew (final String to, final String text, final String subject, final List attachments){ - return new EmailMessageWithAttachmentData(to,text,subject,attachments); + public static EmailMessageWithAttachmentData createNew(final String to, final String text, final String subject, + final List attachments) { + return new EmailMessageWithAttachmentData(to, text, subject, attachments); } - public String getTo() {return this.to;} + public String getTo() { + return this.to; + } - public String getText() {return this.text;} + public String getText() { + return this.text; + } - public String getSubject() {return this.subject;} + public String getSubject() { + return this.subject; + } public List getAttachments() { return this.attachments; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/ScheduledEmailEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/ScheduledEmailEnumerations.java index 25c36fd22..ef1cbbb04 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/ScheduledEmailEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/data/ScheduledEmailEnumerations.java @@ -23,6 +23,7 @@ import org.apache.fineract.infrastructure.campaigns.email.domain.ScheduledEmailS import org.apache.fineract.infrastructure.core.data.EnumOptionData; public class ScheduledEmailEnumerations { + public static EnumOptionData emailAttachementFileFormat(final Integer emailAttachementFileFormatId) { return emailAttachementFileFormat(ScheduledEmailAttachmentFileFormat.instance(emailAttachementFileFormatId)); } @@ -42,8 +43,8 @@ public class ScheduledEmailEnumerations { return enumOptionData; } - public static EnumOptionData stretchyReportDateOption(final ScheduledEmailStretchyReportParamDateOption - reportMailingJobStretchyReportParamDateOption) { + public static EnumOptionData stretchyReportDateOption( + final ScheduledEmailStretchyReportParamDateOption reportMailingJobStretchyReportParamDateOption) { EnumOptionData enumOptionData = null; if (reportMailingJobStretchyReportParamDateOption != null) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaign.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaign.java index 24b0cf10f..88f0d291c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaign.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaign.java @@ -60,7 +60,7 @@ public class EmailCampaign extends AbstractPersistableCustom { @ManyToOne @JoinColumn(name = "businessRule_id", nullable = false) - private Report businessRuleId ; + private Report businessRuleId; @Column(name = "param_value") private String paramValue; @@ -123,7 +123,7 @@ public class EmailCampaign extends AbstractPersistableCustom { @Temporal(TemporalType.TIMESTAMP) private Date recurrenceStartDate; - @Column(name="is_visible",nullable = true) + @Column(name = "is_visible", nullable = true) private boolean isVisible; @Column(name = "previous_run_status", nullable = true) @@ -135,20 +135,20 @@ public class EmailCampaign extends AbstractPersistableCustom { @Column(name = "previous_run_error_message", nullable = true) private String previousRunErrorMessage; - public EmailCampaign() { - } + public EmailCampaign() {} private EmailCampaign(final String campaignName, final Integer campaignType, final Report businessRuleId, final String paramValue, - final String emailSubject, final String emailMessage,final LocalDate submittedOnDate, final AppUser submittedBy, - final Report stretchyReport, final String stretchyReportParamMap, final ScheduledEmailAttachmentFileFormat emailAttachmentFileFormat, - final String recurrence, final LocalDateTime localDateTime) { + final String emailSubject, final String emailMessage, final LocalDate submittedOnDate, final AppUser submittedBy, + final Report stretchyReport, final String stretchyReportParamMap, + final ScheduledEmailAttachmentFileFormat emailAttachmentFileFormat, final String recurrence, + final LocalDateTime localDateTime) { this.campaignName = campaignName; this.campaignType = EmailCampaignType.fromInt(campaignType).getValue(); this.businessRuleId = businessRuleId; this.paramValue = paramValue; - this.status = EmailCampaignStatus.PENDING.getValue(); + this.status = EmailCampaignStatus.PENDING.getValue(); this.emailSubject = emailSubject; - this.emailMessage = emailMessage; + this.emailMessage = emailMessage; this.emailAttachmentFileFormat = emailAttachmentFileFormat.getValue(); this.stretchyReport = stretchyReport; this.stretchyReportParamMap = stretchyReportParamMap; @@ -157,50 +157,58 @@ public class EmailCampaign extends AbstractPersistableCustom { this.recurrence = recurrence; LocalDateTime recurrenceStartDate = new LocalDateTime(); this.isVisible = true; - if(localDateTime != null){ + if (localDateTime != null) { this.recurrenceStartDate = localDateTime.toDate(); - }else{ + } else { this.recurrenceStartDate = recurrenceStartDate.toDate(); } } - public static EmailCampaign instance(final AppUser submittedBy, final Report businessRuleId, final Report stretchyReport, final JsonCommand command){ + public static EmailCampaign instance(final AppUser submittedBy, final Report businessRuleId, final Report stretchyReport, + final JsonCommand command) { final String campaignName = command.stringValueOfParameterNamed(EmailCampaignValidator.campaignName); - final Long campaignType = command.longValueOfParameterNamed(EmailCampaignValidator.campaignType); + final Long campaignType = command.longValueOfParameterNamed(EmailCampaignValidator.campaignType); final String paramValue = command.stringValueOfParameterNamed(EmailCampaignValidator.paramValue); final String emailSubject = command.stringValueOfParameterNamed(EmailCampaignValidator.emailSubject); - final String emailMessage = command.stringValueOfParameterNamed(EmailCampaignValidator.emailMessage); - final String stretchyReportParamMap = command.stringValueOfParameterNamed(ScheduledEmailConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME); - final Integer emailAttachmentFileFormatId = command.integerValueOfParameterNamed(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME); + final String emailMessage = command.stringValueOfParameterNamed(EmailCampaignValidator.emailMessage); + final String stretchyReportParamMap = command + .stringValueOfParameterNamed(ScheduledEmailConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME); + final Integer emailAttachmentFileFormatId = command + .integerValueOfParameterNamed(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME); final ScheduledEmailAttachmentFileFormat emailAttachmentFileFormat; - if (emailAttachmentFileFormatId!=null) { + if (emailAttachmentFileFormatId != null) { emailAttachmentFileFormat = ScheduledEmailAttachmentFileFormat.instance(emailAttachmentFileFormatId); - }else{emailAttachmentFileFormat = ScheduledEmailAttachmentFileFormat.instance(2);} + } else { + emailAttachmentFileFormat = ScheduledEmailAttachmentFileFormat.instance(2); + } LocalDate submittedOnDate = new LocalDate(); if (command.hasParameter(EmailCampaignValidator.submittedOnDateParamName)) { submittedOnDate = command.localDateValueOfParameterNamed(EmailCampaignValidator.submittedOnDateParamName); } - final String recurrence = command.stringValueOfParameterNamed(EmailCampaignValidator.recurrenceParamName); + final String recurrence = command.stringValueOfParameterNamed(EmailCampaignValidator.recurrenceParamName); final Locale locale = command.extractLocale(); - final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); + final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); - LocalDateTime recurrenceStartDate = new LocalDateTime(); - if(EmailCampaignType.fromInt(campaignType.intValue()).isSchedule()) { - if(command.hasParameter(EmailCampaignValidator.recurrenceStartDate)){ - recurrenceStartDate = LocalDateTime.parse(command.stringValueOfParameterNamed(EmailCampaignValidator.recurrenceStartDate),fmt); + LocalDateTime recurrenceStartDate = new LocalDateTime(); + if (EmailCampaignType.fromInt(campaignType.intValue()).isSchedule()) { + if (command.hasParameter(EmailCampaignValidator.recurrenceStartDate)) { + recurrenceStartDate = LocalDateTime.parse(command.stringValueOfParameterNamed(EmailCampaignValidator.recurrenceStartDate), + fmt); } - } else{recurrenceStartDate = null;} + } else { + recurrenceStartDate = null; + } - - return new EmailCampaign(campaignName,campaignType.intValue(),businessRuleId,paramValue,emailSubject,emailMessage, - submittedOnDate,submittedBy,stretchyReport,stretchyReportParamMap,emailAttachmentFileFormat,recurrence,recurrenceStartDate); + return new EmailCampaign(campaignName, campaignType.intValue(), businessRuleId, paramValue, emailSubject, emailMessage, + submittedOnDate, submittedBy, stretchyReport, stretchyReportParamMap, emailAttachmentFileFormat, recurrence, + recurrenceStartDate); } - public Map update(JsonCommand command){ + public Map update(JsonCommand command) { final Map actualChanges = new LinkedHashMap<>(5); @@ -224,7 +232,8 @@ public class EmailCampaign extends AbstractPersistableCustom { actualChanges.put(EmailCampaignValidator.campaignType, EmailCampaignType.fromInt(newValue)); this.campaignType = EmailCampaignType.fromInt(newValue).getValue(); } - if (command.isChangeInLongParameterNamed(EmailCampaignValidator.businessRuleId, (this.businessRuleId != null) ? this.businessRuleId.getId() : null)) { + if (command.isChangeInLongParameterNamed(EmailCampaignValidator.businessRuleId, + (this.businessRuleId != null) ? this.businessRuleId.getId() : null)) { final String newValue = command.stringValueOfParameterNamed(EmailCampaignValidator.businessRuleId); actualChanges.put(EmailCampaignValidator.businessRuleId, newValue); } @@ -236,7 +245,7 @@ public class EmailCampaign extends AbstractPersistableCustom { final String dateFormatAsInput = command.dateFormat(); final String localeAsInput = command.locale(); final Locale locale = command.extractLocale(); - final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); + final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); if (command.isChangeInLocalDateParameterNamed(EmailCampaignValidator.recurrenceStartDate, getRecurrenceStartDate())) { final String valueAsInput = command.stringValueOfParameterNamed(EmailCampaignValidator.recurrenceStartDate); @@ -244,7 +253,7 @@ public class EmailCampaign extends AbstractPersistableCustom { actualChanges.put(ClientApiConstants.dateFormatParamName, dateFormatAsInput); actualChanges.put(ClientApiConstants.localeParamName, localeAsInput); - final LocalDateTime newValue = LocalDateTime.parse(valueAsInput, fmt); + final LocalDateTime newValue = LocalDateTime.parse(valueAsInput, fmt); this.recurrenceStartDate = newValue.toDate(); } @@ -252,11 +261,10 @@ public class EmailCampaign extends AbstractPersistableCustom { return actualChanges; } + public void activate(final AppUser currentUser, final DateTimeFormatter formatter, final LocalDate activationLocalDate) { - public void activate(final AppUser currentUser, final DateTimeFormatter formatter, final LocalDate activationLocalDate){ - - if(isActive()){ - //handle errors if already activated + if (isActive()) { + // handle errors if already activated final String defaultUserMessage = "Cannot activate campaign. Campaign is already active."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.campaign.already.active", defaultUserMessage, EmailCampaignValidator.activationDateParamName, activationLocalDate.toString(formatter)); @@ -270,12 +278,12 @@ public class EmailCampaign extends AbstractPersistableCustom { this.approvedBy = currentUser; this.status = EmailCampaignStatus.ACTIVE.getValue(); - validate(); + validate(); } - public void close(final AppUser currentUser,final DateTimeFormatter dateTimeFormatter, final LocalDate closureLocalDate){ - if(isClosed()){ - //handle errors if already activated + public void close(final AppUser currentUser, final DateTimeFormatter dateTimeFormatter, final LocalDate closureLocalDate) { + if (isClosed()) { + // handle errors if already activated final String defaultUserMessage = "Cannot close campaign. Campaign already in closed state."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.campaign.already.closed", defaultUserMessage, EmailCampaignValidator.statusParamName, EmailCampaignStatus.fromInt(this.status).getCode()); @@ -285,20 +293,20 @@ public class EmailCampaign extends AbstractPersistableCustom { throw new PlatformApiDataValidationException(dataValidationErrors); } - if(this.campaignType.intValue() == EmailCampaignType.SCHEDULE.getValue()){ + if (this.campaignType.intValue() == EmailCampaignType.SCHEDULE.getValue()) { this.nextTriggerDate = null; this.lastTriggerDate = null; } this.closedBy = currentUser; this.closureDate = closureLocalDate.toDate(); - this.status = EmailCampaignStatus.CLOSED.getValue(); + this.status = EmailCampaignStatus.CLOSED.getValue(); validateClosureDate(); } - public void reactivate(final AppUser currentUser, final DateTimeFormatter dateTimeFormat,final LocalDate reactivateLocalDate){ + public void reactivate(final AppUser currentUser, final DateTimeFormatter dateTimeFormat, final LocalDate reactivateLocalDate) { - if(!isClosed()){ - //handle errors if already activated + if (!isClosed()) { + // handle errors if already activated final String defaultUserMessage = "Cannot reactivate campaign. Campaign must be in closed state."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.campaign.must.be.closed", defaultUserMessage, EmailCampaignValidator.statusParamName, EmailCampaignStatus.fromInt(this.status).getCode()); @@ -310,8 +318,8 @@ public class EmailCampaign extends AbstractPersistableCustom { } this.approvedOnDate = reactivateLocalDate.toDate(); - this.status = EmailCampaignStatus.ACTIVE.getValue(); - this.approvedBy =currentUser; + this.status = EmailCampaignStatus.ACTIVE.getValue(); + this.approvedBy = currentUser; this.closureDate = null; this.isVisible = true; this.closedBy = null; @@ -319,9 +327,9 @@ public class EmailCampaign extends AbstractPersistableCustom { validateReactivate(); } - public void delete(){ - if(!isClosed()){ - //handle errors if already activated + public void delete() { + if (!isClosed()) { + // handle errors if already activated final String defaultUserMessage = "Cannot delete campaign. Campaign must be in closed state."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.campaign.must.be.closed", defaultUserMessage, EmailCampaignValidator.statusParamName, EmailCampaignStatus.fromInt(this.status).getCode()); @@ -334,26 +342,23 @@ public class EmailCampaign extends AbstractPersistableCustom { this.isVisible = false; } - - - - public boolean isActive(){ + public boolean isActive() { return EmailCampaignStatus.fromInt(this.status).isActive(); } - public boolean isPending(){ - return EmailCampaignStatus.fromInt(this.status).isPending(); + public boolean isPending() { + return EmailCampaignStatus.fromInt(this.status).isPending(); } - public boolean isClosed(){ + public boolean isClosed() { return EmailCampaignStatus.fromInt(this.status).isClosed(); } - public boolean isDirect(){ + public boolean isDirect() { return EmailCampaignType.fromInt(this.campaignType).isDirect(); } - public boolean isSchedule(){ + public boolean isSchedule() { return EmailCampaignType.fromInt(this.campaignType).isSchedule(); } @@ -363,13 +368,13 @@ public class EmailCampaign extends AbstractPersistableCustom { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - private void validateReactivate(){ + private void validateReactivate() { final List dataValidationErrors = new ArrayList(); validateReactivationDate(dataValidationErrors); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - private void validateClosureDate(){ + private void validateClosureDate() { final List dataValidationErrors = new ArrayList(); validateClosureDate(dataValidationErrors); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } @@ -406,7 +411,7 @@ public class EmailCampaign extends AbstractPersistableCustom { } - private void validateReactivationDate(final List dataValidationErrors){ + private void validateReactivationDate(final List dataValidationErrors) { if (getActivationLocalDate() != null && isDateInTheFuture(getActivationLocalDate())) { final String defaultUserMessage = "Activation date cannot be in the future."; @@ -434,7 +439,7 @@ public class EmailCampaign extends AbstractPersistableCustom { } - private void validateClosureDate(final List dataValidationErrors){ + private void validateClosureDate(final List dataValidationErrors) { if (getClosureDate() != null && isDateInTheFuture(getClosureDate())) { final String defaultUserMessage = "closure date cannot be in the future."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.campaign.closureDate.in.the.future", @@ -448,6 +453,7 @@ public class EmailCampaign extends AbstractPersistableCustom { return ObjectUtils.defaultIfNull(new LocalDate(this.submittedOnDate), null); } + public LocalDate getClosureDate() { return ObjectUtils.defaultIfNull(new LocalDate(this.closureDate), null); } @@ -459,6 +465,7 @@ public class EmailCampaign extends AbstractPersistableCustom { } return activationLocalDate; } + private boolean isDateInTheFuture(final LocalDate localDate) { return localDate.isAfter(DateUtils.getLocalDateOfTenant()); } @@ -471,7 +478,9 @@ public class EmailCampaign extends AbstractPersistableCustom { return this.campaignName; } - public String getEmailSubject() { return this.emailSubject; } + public String getEmailSubject() { + return this.emailSubject; + } public String getEmailMessage() { return this.emailMessage; @@ -488,12 +497,11 @@ public class EmailCampaign extends AbstractPersistableCustom { public LocalDate getRecurrenceStartDate() { return ObjectUtils.defaultIfNull(new LocalDate(this.recurrenceStartDate), null); } + public LocalDateTime getRecurrenceStartDateTime() { return ObjectUtils.defaultIfNull(new LocalDateTime(this.recurrenceStartDate), null); } - - public void setLastTriggerDate(Date lastTriggerDate) { this.lastTriggerDate = lastTriggerDate; } @@ -507,7 +515,7 @@ public class EmailCampaign extends AbstractPersistableCustom { } - public Date getNextTriggerDateInDate(){ + public Date getNextTriggerDateInDate() { return this.nextTriggerDate; } @@ -519,7 +527,7 @@ public class EmailCampaign extends AbstractPersistableCustom { this.isVisible = isVisible; } - public void updateBusinessRuleId(final Report report){ + public void updateBusinessRuleId(final Report report) { this.businessRuleId = report; } @@ -539,7 +547,9 @@ public class EmailCampaign extends AbstractPersistableCustom { this.stretchyReportParamMap = stretchyReportParamMap; } - public AppUser getApprovedBy() {return this.approvedBy;} + public AppUser getApprovedBy() { + return this.approvedBy; + } public AppUser getClosedBy() { return this.closedBy; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignRepository.java index 480ecca7d..291698b91 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignRepository.java @@ -21,5 +21,4 @@ package org.apache.fineract.infrastructure.campaigns.email.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface EmailCampaignRepository extends JpaRepository, JpaSpecificationExecutor { -} +public interface EmailCampaignRepository extends JpaRepository, JpaSpecificationExecutor {} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignStatus.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignStatus.java index 8e396a3fe..4119a6638 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignStatus.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignStatus.java @@ -39,13 +39,13 @@ public enum EmailCampaignStatus { switch (statusValue) { case 100: enumeration = EmailCampaignStatus.PENDING; - break; + break; case 300: enumeration = EmailCampaignStatus.ACTIVE; - break; + break; case 600: enumeration = EmailCampaignStatus.CLOSED; - break; + break; } return enumeration; } @@ -57,15 +57,16 @@ public enum EmailCampaignStatus { public String getCode() { return code; } - public boolean isActive(){ + + public boolean isActive() { return this.value.equals(EmailCampaignStatus.ACTIVE.getValue()); } - public boolean isPending(){ + public boolean isPending() { return this.value.equals(EmailCampaignStatus.PENDING.getValue()); } - public boolean isClosed(){ - return this.value.equals(EmailCampaignStatus.CLOSED.getValue()); + public boolean isClosed() { + return this.value.equals(EmailCampaignStatus.CLOSED.getValue()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignStatusEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignStatusEnumerations.java index c7fe791c8..0fd6a2f21 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignStatusEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignStatusEnumerations.java @@ -21,6 +21,7 @@ package org.apache.fineract.infrastructure.campaigns.email.domain; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public class EmailCampaignStatusEnumerations { + public static EnumOptionData status(final Integer statusId) { return status(EmailCampaignStatus.fromInt(statusId)); } @@ -30,21 +31,21 @@ public class EmailCampaignStatusEnumerations { EmailCampaignStatus.INVALID.getCode(), "Invalid"); switch (status) { case INVALID: - optionData = new EnumOptionData(EmailCampaignStatus.INVALID.getValue().longValue(), - EmailCampaignStatus.INVALID.getCode(), "Invalid"); - break; + optionData = new EnumOptionData(EmailCampaignStatus.INVALID.getValue().longValue(), EmailCampaignStatus.INVALID.getCode(), + "Invalid"); + break; case PENDING: - optionData = new EnumOptionData(EmailCampaignStatus.PENDING.getValue().longValue(), - EmailCampaignStatus.PENDING.getCode(), "Pending"); - break; + optionData = new EnumOptionData(EmailCampaignStatus.PENDING.getValue().longValue(), EmailCampaignStatus.PENDING.getCode(), + "Pending"); + break; case ACTIVE: optionData = new EnumOptionData(EmailCampaignStatus.ACTIVE.getValue().longValue(), EmailCampaignStatus.ACTIVE.getCode(), "active"); - break; + break; case CLOSED: - optionData = new EnumOptionData(EmailCampaignStatus.CLOSED.getValue().longValue(), - EmailCampaignStatus.CLOSED.getCode(), "closed"); - break; + optionData = new EnumOptionData(EmailCampaignStatus.CLOSED.getValue().longValue(), EmailCampaignStatus.CLOSED.getCode(), + "closed"); + break; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignType.java index 8d613a957..95c36ce00 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailCampaignType.java @@ -19,8 +19,8 @@ package org.apache.fineract.infrastructure.campaigns.email.domain; public enum EmailCampaignType { - DIRECT(1,"emailCampaignStatusType.direct"), - SCHEDULE(2,"emailCampaignStatusType.schedule"); + + DIRECT(1, "emailCampaignStatusType.direct"), SCHEDULE(2, "emailCampaignStatusType.schedule"); private final Integer value; private final String code; @@ -43,19 +43,19 @@ public enum EmailCampaignType { switch (typeValue) { case 1: type = DIRECT; - break; + break; case 2: type = SCHEDULE; - break; + break; } return type; } - public boolean isDirect(){ + public boolean isDirect() { return this.value.equals(EmailCampaignType.DIRECT.getValue()); } - public boolean isSchedule(){ + public boolean isSchedule() { return this.value.equals(EmailCampaignType.SCHEDULE.getValue()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailConfiguration.java index 5f06f487f..8153b2371 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailConfiguration.java @@ -26,6 +26,7 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity @Table(name = "scheduled_email_configuration") public class EmailConfiguration extends AbstractPersistableCustom { + @Column(name = "name", nullable = false) private String name; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailConfigurationRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailConfigurationRepository.java index a96c1cd80..23db88177 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailConfigurationRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailConfigurationRepository.java @@ -21,6 +21,8 @@ package org.apache.fineract.infrastructure.campaigns.email.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface EmailConfigurationRepository extends JpaRepository, JpaSpecificationExecutor { +public interface EmailConfigurationRepository + extends JpaRepository, JpaSpecificationExecutor { + EmailConfiguration findByName(String name); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessage.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessage.java index ddea71721..d15aed560 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessage.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessage.java @@ -79,23 +79,25 @@ public class EmailMessage extends AbstractPersistableCustom { @Column(name = "error_message") private String errorMessage; - - public static EmailMessage pendingEmail(final Group group, final Client client, final Staff staff,final EmailCampaign emailCampaign, final String emailSubject, final String message, - final String emailAddress, final String campaignName) { - return new EmailMessage(group, client, staff,emailCampaign,EmailMessageStatusType.PENDING, emailSubject, message, emailAddress,campaignName); + public static EmailMessage pendingEmail(final Group group, final Client client, final Staff staff, final EmailCampaign emailCampaign, + final String emailSubject, final String message, final String emailAddress, final String campaignName) { + return new EmailMessage(group, client, staff, emailCampaign, EmailMessageStatusType.PENDING, emailSubject, message, emailAddress, + campaignName); } - public static EmailMessage instance(final Group group, final Client client, final Staff staff, final EmailCampaign emailCampaign, final EmailMessageStatusType statusType, - final String emailSubject, final String message, final String sourceAddress, final String emailAddress, final String campaignName) { - return new EmailMessage(group, client, staff,emailCampaign, statusType, emailSubject, message, emailAddress, campaignName); + public static EmailMessage instance(final Group group, final Client client, final Staff staff, final EmailCampaign emailCampaign, + final EmailMessageStatusType statusType, final String emailSubject, final String message, final String sourceAddress, + final String emailAddress, final String campaignName) { + return new EmailMessage(group, client, staff, emailCampaign, statusType, emailSubject, message, emailAddress, campaignName); } protected EmailMessage() { // } - private EmailMessage(final Group group, final Client client, final Staff staff, final EmailCampaign emailCampaign, final EmailMessageStatusType statusType, - final String emailSubject, final String message, final String emailAddress, final String campaignName) { + private EmailMessage(final Group group, final Client client, final Staff staff, final EmailCampaign emailCampaign, + final EmailMessageStatusType statusType, final String emailSubject, final String message, final String emailAddress, + final String campaignName) { this.group = group; this.client = client; this.staff = staff; @@ -121,7 +123,6 @@ public class EmailMessage extends AbstractPersistableCustom { return actualChanges; } - public Group getGroup() { return group; } @@ -138,16 +139,18 @@ public class EmailMessage extends AbstractPersistableCustom { return statusType; } + public String getEmailAddress() { + return this.emailAddress; + } - public String getEmailAddress() {return this.emailAddress;} - - public String getEmailSubject() {return emailSubject; } + public String getEmailSubject() { + return emailSubject; + } public String getMessage() { return message; } - public void setStatusType(final Integer statusType) { this.statusType = statusType; } @@ -160,10 +163,19 @@ public class EmailMessage extends AbstractPersistableCustom { return this.submittedOnDate; } - public EmailCampaign getEmailCampaign() {return this.emailCampaign;} + public EmailCampaign getEmailCampaign() { + return this.emailCampaign; + } - public void updateErrorMessage(final String errorMessage) {this.errorMessage = errorMessage;} + public void updateErrorMessage(final String errorMessage) { + this.errorMessage = errorMessage; + } - public boolean isPending(){ return EmailMessageStatusType.fromInt(this.statusType).isPending();} - public boolean isSent(){ return EmailMessageStatusType.fromInt(this.statusType).isSent();} -} \ No newline at end of file + public boolean isPending() { + return EmailMessageStatusType.fromInt(this.statusType).isPending(); + } + + public boolean isSent() { + return EmailMessageStatusType.fromInt(this.statusType).isSent(); + } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageAssembler.java index 3142c035d..708c89432 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageAssembler.java @@ -43,8 +43,8 @@ public class EmailMessageAssembler { @Autowired public EmailMessageAssembler(final EmailMessageRepository emailMessageRepository, final GroupRepositoryWrapper groupRepositoryWrapper, - final ClientRepositoryWrapper clientRepository, final StaffRepositoryWrapper staffRepository, - final FromJsonHelper fromApiJsonHelper) { + final ClientRepositoryWrapper clientRepository, final StaffRepositoryWrapper staffRepository, + final FromJsonHelper fromApiJsonHelper) { this.emailMessageRepository = emailMessageRepository; this.groupRepository = groupRepositoryWrapper; this.clientRepository = clientRepository; @@ -81,11 +81,10 @@ public class EmailMessageAssembler { final String message = this.fromApiJsonHelper.extractStringNamed(EmailApiConstants.messageParamName, element); final String emailSubject = this.fromApiJsonHelper.extractStringNamed(EmailApiConstants.subjectParamName, element); - return EmailMessage.pendingEmail(group, client, staff,null,emailSubject, message,emailAddress,null); + return EmailMessage.pendingEmail(group, client, staff, null, emailSubject, message, emailAddress, null); } public EmailMessage assembleFromResourceId(final Long resourceId) { - return this.emailMessageRepository.findById(resourceId) - .orElseThrow(() -> new EmailNotFoundException(resourceId)); + return this.emailMessageRepository.findById(resourceId).orElseThrow(() -> new EmailNotFoundException(resourceId)); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageEnumerations.java index 76d9b6174..c9a6c55f9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageEnumerations.java @@ -47,12 +47,12 @@ public class EmailMessageEnumerations { EmailMessageStatusType.DELIVERED.getCode(), "Delivered"); break; case FAILED: - optionData = new EnumOptionData(EmailMessageStatusType.FAILED.getValue().longValue(), EmailMessageStatusType.FAILED.getCode(), - "Failed"); + optionData = new EnumOptionData(EmailMessageStatusType.FAILED.getValue().longValue(), + EmailMessageStatusType.FAILED.getCode(), "Failed"); break; } return optionData; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageRepository.java index c2cc98f9e..ab605597e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageRepository.java @@ -23,6 +23,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface EmailMessageRepository extends JpaRepository, JpaSpecificationExecutor { + // no extra behaviour List findByStatusType(Integer emailMessageStatus); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageStatusType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageStatusType.java index 54dec8b33..2cb5ae3cd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageStatusType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/EmailMessageStatusType.java @@ -62,11 +62,11 @@ public enum EmailMessageStatusType { return this.code; } - public boolean isPending(){ + public boolean isPending() { return this.value.equals(EmailMessageStatusType.PENDING.getValue()); } - public boolean isSent(){ + public boolean isSent() { return this.value.equals(EmailMessageStatusType.SENT.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/ScheduledEmailAttachmentFileFormat.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/ScheduledEmailAttachmentFileFormat.java index aa26a6fdc..a28dfeeeb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/ScheduledEmailAttachmentFileFormat.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/ScheduledEmailAttachmentFileFormat.java @@ -19,10 +19,9 @@ package org.apache.fineract.infrastructure.campaigns.email.domain; public enum ScheduledEmailAttachmentFileFormat { - INVALID(0, "EmailAttachmentFileFormat.invalid", "invalid"), - XLS(1, "EmailAttachmentFileFormat.xls", "xls"), - PDF(2, "EmailAttachmentFileFormat.pdf", "pdf"), - CSV(3, "EmailAttachmentFileFormat.csv", "csv"); + + INVALID(0, "EmailAttachmentFileFormat.invalid", "invalid"), XLS(1, "EmailAttachmentFileFormat.xls", "xls"), PDF(2, + "EmailAttachmentFileFormat.pdf", "pdf"), CSV(3, "EmailAttachmentFileFormat.csv", "csv"); private final String code; private final String value; @@ -40,18 +39,18 @@ public enum ScheduledEmailAttachmentFileFormat { switch (value) { case "xls": emailAttachmentFileFormat = XLS; - break; + break; case "pdf": emailAttachmentFileFormat = PDF; - break; + break; case "csv": emailAttachmentFileFormat = CSV; - break; + break; default: - break; + break; } return emailAttachmentFileFormat; @@ -63,18 +62,18 @@ public enum ScheduledEmailAttachmentFileFormat { switch (id) { case 1: emailAttachmentFileFormat = XLS; - break; + break; case 2: emailAttachmentFileFormat = PDF; - break; + break; case 3: emailAttachmentFileFormat = CSV; - break; + break; default: - break; + break; } return emailAttachmentFileFormat; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/ScheduledEmailStretchyReportParamDateOption.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/ScheduledEmailStretchyReportParamDateOption.java index d36557f09..68b28dee1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/ScheduledEmailStretchyReportParamDateOption.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/domain/ScheduledEmailStretchyReportParamDateOption.java @@ -19,9 +19,11 @@ package org.apache.fineract.infrastructure.campaigns.email.domain; public enum ScheduledEmailStretchyReportParamDateOption { - INVALID(0, "scheduledEmailStretchyReportParamDateOption.invalid", "invalid"), - TODAY(1, "scheduledEmailStretchyReportParamDateOption.today", "today"), - // YESTERDAY(2, "scheduledEmailStretchyReportParamDateOption.yesterday", "yesterday"), + + INVALID(0, "scheduledEmailStretchyReportParamDateOption.invalid", "invalid"), TODAY(1, + "scheduledEmailStretchyReportParamDateOption.today", "today"), + // YESTERDAY(2, "scheduledEmailStretchyReportParamDateOption.yesterday", + // "yesterday"), TOMORROW(3, "scheduledEmailStretchyReportParamDateOption.tomorrow", "tomorrow"); private final String code; @@ -49,15 +51,15 @@ public enum ScheduledEmailStretchyReportParamDateOption { switch (value) { case "today": scheduledEmailStretchyReportParamDateOption = TODAY; - break; + break; // case "yesterday": - // scheduledEmailStretchyReportParamDateOption = YESTERDAY; - // break; + // scheduledEmailStretchyReportParamDateOption = YESTERDAY; + // break; case "tomorrow": scheduledEmailStretchyReportParamDateOption = TOMORROW; - break; + break; } return scheduledEmailStretchyReportParamDateOption; @@ -73,15 +75,15 @@ public enum ScheduledEmailStretchyReportParamDateOption { switch (id) { case 1: scheduledEmailStretchyReportParamDateOption = TODAY; - break; + break; // case 2: - // scheduledEmailStretchyReportParamDateOption = YESTERDAY; - // break; + // scheduledEmailStretchyReportParamDateOption = YESTERDAY; + // break; case 3: scheduledEmailStretchyReportParamDateOption = TOMORROW; - break; + break; } return scheduledEmailStretchyReportParamDateOption; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailBusinessRuleNotFound.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailBusinessRuleNotFound.java index e8e3d3ff2..c29122e29 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailBusinessRuleNotFound.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailBusinessRuleNotFound.java @@ -23,6 +23,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class EmailBusinessRuleNotFound extends AbstractPlatformResourceNotFoundException { public EmailBusinessRuleNotFound(final Long resourceId) { - super("error.msg.email.business.rule.not.found", "Email business rule with identifier `" + resourceId + "` does not exist", resourceId); + super("error.msg.email.business.rule.not.found", "Email business rule with identifier `" + resourceId + "` does not exist", + resourceId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignMustBeClosedToBeDeletedException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignMustBeClosedToBeDeletedException.java index 4aef1bd7c..c533a2ed9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignMustBeClosedToBeDeletedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignMustBeClosedToBeDeletedException.java @@ -20,9 +20,10 @@ package org.apache.fineract.infrastructure.campaigns.email.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; -public class EmailCampaignMustBeClosedToBeDeletedException extends AbstractPlatformDomainRuleException { +public class EmailCampaignMustBeClosedToBeDeletedException extends AbstractPlatformDomainRuleException { public EmailCampaignMustBeClosedToBeDeletedException(final Long resourceId) { super("error.msg.email.campaign.cannot.be.deleted", - "Campaign with identifier " + resourceId + " cannot be deleted as it is not in `Closed` state.", resourceId); } + "Campaign with identifier " + resourceId + " cannot be deleted as it is not in `Closed` state.", resourceId); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignMustBeClosedToEditException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignMustBeClosedToEditException.java index 364468786..2b7eee113 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignMustBeClosedToEditException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignMustBeClosedToEditException.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.infrastructure.campaigns.email.exception; - import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; public class EmailCampaignMustBeClosedToEditException extends AbstractPlatformDomainRuleException { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignNotFound.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignNotFound.java index 0307fb1b3..0682e9324 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignNotFound.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailCampaignNotFound.java @@ -20,9 +20,10 @@ package org.apache.fineract.infrastructure.campaigns.email.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; -public class EmailCampaignNotFound extends AbstractPlatformResourceNotFoundException{ +public class EmailCampaignNotFound extends AbstractPlatformResourceNotFoundException { public EmailCampaignNotFound(final Long resourceId) { - super("error.msg.email.campaign.identifier.not.found", "EMAIL_CAMPAIGN with identifier `" + resourceId + "` does not exist", resourceId); + super("error.msg.email.campaign.identifier.not.found", "EMAIL_CAMPAIGN with identifier `" + resourceId + "` does not exist", + resourceId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailConfigurationSMTPUsernameNotValid.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailConfigurationSMTPUsernameNotValid.java index 55b46c044..aa36c9111 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailConfigurationSMTPUsernameNotValid.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailConfigurationSMTPUsernameNotValid.java @@ -20,11 +20,10 @@ package org.apache.fineract.infrastructure.campaigns.email.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; +public class EmailConfigurationSMTPUsernameNotValid extends AbstractPlatformDomainRuleException { -public class EmailConfigurationSMTPUsernameNotValid extends AbstractPlatformDomainRuleException { - - public EmailConfigurationSMTPUsernameNotValid(final String smtpUsername) { + public EmailConfigurationSMTPUsernameNotValid(final String smtpUsername) { super("error.msg.email.configuration.smtpusername.not.valid", - "SMTP username configuration with email " + "'"+smtpUsername+"'" + " is not a valid email address "); + "SMTP username configuration with email " + "'" + smtpUsername + "'" + " is not a valid email address "); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailNotFoundException.java index c3b63ffcc..6e726b36c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/exception/EmailNotFoundException.java @@ -28,4 +28,4 @@ public class EmailNotFoundException extends AbstractPlatformResourceNotFoundExce public EmailNotFoundException(final Long resourceId) { super("error.msg.email.identifier.not.found", "Email with identifier `" + resourceId + "` does not exist", resourceId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/ActivateEmailCampaignCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/ActivateEmailCampaignCommandHandler.java index 04286ae66..d775ef168 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/ActivateEmailCampaignCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/ActivateEmailCampaignCommandHandler.java @@ -30,6 +30,7 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "EMAIL_CAMPAIGN", action = "ACTIVATE") public class ActivateEmailCampaignCommandHandler implements NewCommandSourceHandler { + private EmailCampaignWritePlatformService emailCampaignWritePlatformService; @Autowired diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/CloseEmailCampaignCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/CloseEmailCampaignCommandHandler.java index 01db76644..0f25e94ba 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/CloseEmailCampaignCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/CloseEmailCampaignCommandHandler.java @@ -29,15 +29,16 @@ import org.springframework.stereotype.Service; @Service @CommandType(entity = "EMAIL_CAMPAIGN", action = "CLOSE") public class CloseEmailCampaignCommandHandler implements NewCommandSourceHandler { + private final EmailCampaignWritePlatformService emailCampaignWritePlatformService; - @Autowired + @Autowired public CloseEmailCampaignCommandHandler(final EmailCampaignWritePlatformService emailCampaignWritePlatformService) { this.emailCampaignWritePlatformService = emailCampaignWritePlatformService; } @Override public CommandProcessingResult processCommand(JsonCommand command) { - return this.emailCampaignWritePlatformService.closeEmailCampaign(command.entityId(), command); + return this.emailCampaignWritePlatformService.closeEmailCampaign(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/CreateEmailCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/CreateEmailCommandHandler.java index 998468166..652572fb5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/CreateEmailCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/CreateEmailCommandHandler.java @@ -44,4 +44,4 @@ public class CreateEmailCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.create(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/DeleteEmailCampaignCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/DeleteEmailCampaignCommandHandler.java index 11b076bdf..5477a1f64 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/DeleteEmailCampaignCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/DeleteEmailCampaignCommandHandler.java @@ -37,9 +37,10 @@ public class DeleteEmailCampaignCommandHandler implements NewCommandSourceHandle public DeleteEmailCampaignCommandHandler(EmailCampaignWritePlatformService emailCampaignWritePlatformService) { this.emailCampaignWritePlatformService = emailCampaignWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand command) { - return this.emailCampaignWritePlatformService.delete(command.entityId()); + return this.emailCampaignWritePlatformService.delete(command.entityId()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/DeleteEmailCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/DeleteEmailCommandHandler.java index 8f4ef02e5..b97a5cce1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/DeleteEmailCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/DeleteEmailCommandHandler.java @@ -44,4 +44,4 @@ public class DeleteEmailCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.delete(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/ReactivateEmailCampaignCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/ReactivateEmailCampaignCommandHandler.java index 707ad70bf..655070284 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/ReactivateEmailCampaignCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/ReactivateEmailCampaignCommandHandler.java @@ -37,9 +37,10 @@ public class ReactivateEmailCampaignCommandHandler implements NewCommandSourceHa public ReactivateEmailCampaignCommandHandler(EmailCampaignWritePlatformService emailCampaignWritePlatformService) { this.emailCampaignWritePlatformService = emailCampaignWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand command) { - return this.emailCampaignWritePlatformService.reactivateEmailCampaign(command.entityId(),command); + return this.emailCampaignWritePlatformService.reactivateEmailCampaign(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/UpdateEmailCampaignCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/UpdateEmailCampaignCommandHandler.java index 95634a5da..18afe4175 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/UpdateEmailCampaignCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/handler/UpdateEmailCampaignCommandHandler.java @@ -32,13 +32,15 @@ import org.springframework.transaction.annotation.Transactional; public class UpdateEmailCampaignCommandHandler implements NewCommandSourceHandler { private final EmailCampaignWritePlatformService emailCampaignWritePlatformService; + @Autowired public UpdateEmailCampaignCommandHandler(EmailCampaignWritePlatformService emailCampaignWritePlatformService) { this.emailCampaignWritePlatformService = emailCampaignWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand command) { - return this.emailCampaignWritePlatformService.update(command.entityId(),command); + return this.emailCampaignWritePlatformService.update(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailCampaignReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailCampaignReadPlatformServiceImpl.java index 017c61fd1..46a4ac07a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailCampaignReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailCampaignReadPlatformServiceImpl.java @@ -50,7 +50,6 @@ import org.springframework.stereotype.Service; @Service public class EmailCampaignReadPlatformServiceImpl implements EmailCampaignReadPlatformService { - private final JdbcTemplate jdbcTemplate; private final BusinessRuleMapper businessRuleMapper; @@ -64,8 +63,7 @@ public class EmailCampaignReadPlatformServiceImpl implements EmailCampaignReadPl this.emailCampaignMapper = new EmailCampaignMapper(); } - - private static final class EmailCampaignMapper implements RowMapper{ + private static final class EmailCampaignMapper implements RowMapper { final String schema; @@ -103,6 +101,7 @@ public class EmailCampaignReadPlatformServiceImpl implements EmailCampaignReadPl this.schema = sql.toString(); } + public String schema() { return this.schema; } @@ -133,41 +132,36 @@ public class EmailCampaignReadPlatformServiceImpl implements EmailCampaignReadPl final boolean useReport = rs.getBoolean("useReport"); /* - final ReportData stretchyReport = new ReportData(reportId, reportName, reportType, reportSubType, - reportCategory, - reportDescription, reportSql, coreReport, useReport, null); + * final ReportData stretchyReport = new ReportData(reportId, + * reportName, reportType, reportSubType, reportCategory, + * reportDescription, reportSql, coreReport, useReport, null); */ final Integer statusId = JdbcSupport.getInteger(rs, "statusEnum"); final EnumOptionData status = EmailCampaignStatusEnumerations.status(statusId); final DateTime nextTriggerDate = JdbcSupport.getDateTime(rs, "nextTriggerDate"); - final LocalDate lastTriggerDate = JdbcSupport.getLocalDate(rs, "lastTriggerDate"); - + final LocalDate lastTriggerDate = JdbcSupport.getLocalDate(rs, "lastTriggerDate"); final LocalDate closedOnDate = JdbcSupport.getLocalDate(rs, "closedOnDate"); final String closedByUsername = rs.getString("closedByUsername"); - final LocalDate submittedOnDate = JdbcSupport.getLocalDate(rs, "submittedOnDate"); final String submittedByUsername = rs.getString("submittedByUsername"); final LocalDate activatedOnDate = JdbcSupport.getLocalDate(rs, "activatedOnDate"); final String activatedByUsername = rs.getString("activatedByUsername"); - final String recurrence =rs.getString("recurrence"); + final String recurrence = rs.getString("recurrence"); final DateTime recurrenceStartDate = JdbcSupport.getDateTime(rs, "recurrenceStartDate"); - final EmailCampaignTimeLine emailCampaignTimeLine = new EmailCampaignTimeLine(submittedOnDate,submittedByUsername, - activatedOnDate,activatedByUsername,closedOnDate,closedByUsername); + final EmailCampaignTimeLine emailCampaignTimeLine = new EmailCampaignTimeLine(submittedOnDate, submittedByUsername, + activatedOnDate, activatedByUsername, closedOnDate, closedByUsername); - - - return EmailCampaignData.instance(id,campaignName,campaignType,businessRuleId,paramValue,status,emailSubject,emailMessage, - emailAttachmentFileFormatString,reportId,stretchyReportParamMap,nextTriggerDate,lastTriggerDate,emailCampaignTimeLine, - recurrenceStartDate,recurrence); + return EmailCampaignData.instance(id, campaignName, campaignType, businessRuleId, paramValue, status, emailSubject, + emailMessage, emailAttachmentFileFormatString, reportId, stretchyReportParamMap, nextTriggerDate, lastTriggerDate, + emailCampaignTimeLine, recurrenceStartDate, recurrence); } } - - private static final class BusinessRuleMapper implements ResultSetExtractor>{ + private static final class BusinessRuleMapper implements ResultSetExtractor> { final String schema; @@ -189,7 +183,7 @@ public class EmailCampaignReadPlatformServiceImpl implements EmailCampaignReadPl this.schema = sql.toString(); } - public String schema(){ + public String schema() { return this.schema; } @@ -199,33 +193,34 @@ public class EmailCampaignReadPlatformServiceImpl implements EmailCampaignReadPl EmailBusinessRulesData emailBusinessRulesData = null; - Map mapOfSameObjects = new HashMap(); + Map mapOfSameObjects = new HashMap(); - while(rs.next()){ + while (rs.next()) { final Long id = rs.getLong("id"); - emailBusinessRulesData = mapOfSameObjects.get(id); - if(emailBusinessRulesData == null){ - final String reportName = rs.getString("reportName") ; + emailBusinessRulesData = mapOfSameObjects.get(id); + if (emailBusinessRulesData == null) { + final String reportName = rs.getString("reportName"); final String reportType = rs.getString("reportType"); final String reportSubType = rs.getString("reportSubType"); - final String paramName = rs.getString("paramName"); + final String paramName = rs.getString("paramName"); final String paramLabel = rs.getString("paramLabel"); final String description = rs.getString("description"); - Map hashMap = new HashMap(); - hashMap.put(paramLabel,paramName); - emailBusinessRulesData = EmailBusinessRulesData.instance(id,reportName,reportType,hashMap,reportSubType,description); - mapOfSameObjects.put(id,emailBusinessRulesData); - //add to the list + Map hashMap = new HashMap(); + hashMap.put(paramLabel, paramName); + emailBusinessRulesData = EmailBusinessRulesData.instance(id, reportName, reportType, hashMap, reportSubType, + description); + mapOfSameObjects.put(id, emailBusinessRulesData); + // add to the list emailBusinessRulesDataList.add(emailBusinessRulesData); } - //add new paramType to the existing object - Map hashMap = new HashMap(); - final String paramName = rs.getString("paramName"); + // add new paramType to the existing object + Map hashMap = new HashMap(); + final String paramName = rs.getString("paramName"); final String paramLabel = rs.getString("paramLabel"); - hashMap.put(paramLabel,paramName); + hashMap.put(paramLabel, paramName); - //get existing map and add new items to it + // get existing map and add new items to it emailBusinessRulesData.getReportParamName().putAll(hashMap); } @@ -247,12 +242,11 @@ public class EmailCampaignReadPlatformServiceImpl implements EmailCampaignReadPl final String sql = "select " + this.businessRuleMapper.schema() + " where sr.report_type = ? and sr.id = ?"; - List retrieveOne = this.jdbcTemplate.query(sql, this.businessRuleMapper, searchType,resourceId); - try{ + List retrieveOne = this.jdbcTemplate.query(sql, this.businessRuleMapper, searchType, resourceId); + try { EmailBusinessRulesData emailBusinessRulesData = retrieveOne.get(0); return emailBusinessRulesData; - } - catch (final IndexOutOfBoundsException e){ + } catch (final IndexOutOfBoundsException e) { throw new EmailBusinessRuleNotFound(resourceId); } @@ -260,10 +254,10 @@ public class EmailCampaignReadPlatformServiceImpl implements EmailCampaignReadPl @Override public EmailCampaignData retrieveOne(Long resourceId) { - final Integer isVisible =1; - try{ + final Integer isVisible = 1; + try { final String sql = "select " + this.emailCampaignMapper.schema + " where ec.id = ? and ec.is_visible = ?"; - return this.jdbcTemplate.queryForObject(sql, this.emailCampaignMapper, resourceId,isVisible); + return this.jdbcTemplate.queryForObject(sql, this.emailCampaignMapper, resourceId, isVisible); } catch (final EmptyResultDataAccessException e) { throw new EmailCampaignNotFound(resourceId); } @@ -279,12 +273,11 @@ public class EmailCampaignReadPlatformServiceImpl implements EmailCampaignReadPl @Override public Collection retrieveAllScheduleActiveCampaign() { final Integer scheduleCampaignType = EmailCampaignType.SCHEDULE.getValue(); - final Integer statusEnum = EmailCampaignStatus.ACTIVE.getValue(); - final Integer visible = 1; - final String sql = "select " + this.emailCampaignMapper.schema() + " where ec.status_enum = ? and ec.campaign_type = ? and ec.is_visible = ?"; - return this.jdbcTemplate.query(sql,this.emailCampaignMapper, statusEnum,scheduleCampaignType,visible); + final Integer statusEnum = EmailCampaignStatus.ACTIVE.getValue(); + final Integer visible = 1; + final String sql = "select " + this.emailCampaignMapper.schema() + + " where ec.status_enum = ? and ec.campaign_type = ? and ec.is_visible = ?"; + return this.jdbcTemplate.query(sql, this.emailCampaignMapper, statusEnum, scheduleCampaignType, visible); } - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailCampaignWritePlatformCommandHandlerImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailCampaignWritePlatformCommandHandlerImpl.java index d878bb88f..d3bdc437c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailCampaignWritePlatformCommandHandlerImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailCampaignWritePlatformCommandHandlerImpl.java @@ -154,8 +154,7 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai final Long reportId = command.longValueOfParameterNamed(EmailCampaignValidator.stretchyReportId); - final Report report = this.reportRepository.findById(reportId) - .orElseThrow(() -> new ReportNotFoundException(reportId)); + final Report report = this.reportRepository.findById(reportId).orElseThrow(() -> new ReportNotFoundException(reportId)); // find all report parameters and store them as json string final Set reportParameterUsages = report.getReportParameterUsages(); @@ -192,8 +191,7 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai if (changes.containsKey(EmailCampaignValidator.businessRuleId)) { final Long newValue = command.longValueOfParameterNamed(EmailCampaignValidator.businessRuleId); - final Report reportId = this.reportRepository.findById(newValue) - .orElseThrow(() -> new ReportNotFoundException(newValue)); + final Report reportId = this.reportRepository.findById(newValue).orElseThrow(() -> new ReportNotFoundException(newValue)); emailCampaign.updateBusinessRuleId(reportId); } @@ -579,7 +577,8 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai if (isValidEmail(emailMessage.getEmailAddress())) { - final EmailCampaign emailCampaign = this.emailCampaignRepository.findById(emailMessage.getEmailCampaign().getId()).orElse(null); // + final EmailCampaign emailCampaign = this.emailCampaignRepository.findById(emailMessage.getEmailCampaign().getId()) + .orElse(null); // final ScheduledEmailAttachmentFileFormat emailAttachmentFileFormat = ScheduledEmailAttachmentFileFormat .instance(emailCampaign.getEmailAttachmentFileFormat()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationReadPlatformServiceImpl.java index eab1a1a15..9dfc55052 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationReadPlatformServiceImpl.java @@ -49,13 +49,13 @@ public class EmailConfigurationReadPlatformServiceImpl implements EmailConfigura final String schema; public EmailConfigurationRowMapper() { - final StringBuilder sql = new StringBuilder(300); - sql.append("cnf.id as id, "); - sql.append("cnf.name as name, "); - sql.append("cnf.value as value "); - sql.append("from scheduled_email_configuration cnf"); + final StringBuilder sql = new StringBuilder(300); + sql.append("cnf.id as id, "); + sql.append("cnf.name as name, "); + sql.append("cnf.value as value "); + sql.append("from scheduled_email_configuration cnf"); - this.schema = sql.toString(); + this.schema = sql.toString(); } public String schema() { @@ -89,7 +89,7 @@ public class EmailConfigurationReadPlatformServiceImpl implements EmailConfigura return this.jdbcTemplate.queryForObject(sql, this.emailConfigurationRowMapper, name); } - catch(final EmptyResultDataAccessException e) { + catch (final EmptyResultDataAccessException e) { throw new EmailConfigurationNotFoundException(name); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationWritePlatformService.java index 3afa8d3e5..eb21094a0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationWritePlatformService.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.infrastructure.campaigns.email.service; - import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationWritePlatformServiceImpl.java index 9c517e3c4..7720d8b7d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailConfigurationWritePlatformServiceImpl.java @@ -42,7 +42,7 @@ public class EmailConfigurationWritePlatformServiceImpl implements EmailConfigur @Autowired public EmailConfigurationWritePlatformServiceImpl(final PlatformSecurityContext context, final EmailConfigurationRepository repository, - final EmailConfigurationValidator emailConfigurationValidator) { + final EmailConfigurationValidator emailConfigurationValidator) { this.context = context; this.repository = repository; this.emailConfigurationValidator = emailConfigurationValidator; @@ -51,36 +51,33 @@ public class EmailConfigurationWritePlatformServiceImpl implements EmailConfigur @Override public CommandProcessingResult update(final JsonCommand command) { - final AppUser currentUser = this.context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); - this.emailConfigurationValidator.validateUpdateConfiguration(command.json()); - final String smtpUsername = command.stringValueOfParameterNamed("SMTP_USERNAME"); + this.emailConfigurationValidator.validateUpdateConfiguration(command.json()); + final String smtpUsername = command.stringValueOfParameterNamed("SMTP_USERNAME"); - if(!this.emailConfigurationValidator.isValidEmail(smtpUsername)){ - throw new EmailConfigurationSMTPUsernameNotValid(smtpUsername); + if (!this.emailConfigurationValidator.isValidEmail(smtpUsername)) { + throw new EmailConfigurationSMTPUsernameNotValid(smtpUsername); + } + + final Map changes = new HashMap<>(4); + + Collection configurations = this.repository.findAll(); + /** + * Default SMTP configuration added to flyway + */ + for (EmailConfiguration config : configurations) { + if (config.getName() != null) { + String value = command.stringValueOfParameterNamed(config.getName()); + config.setValue(value); + changes.put(config.getName(), value); + this.repository.saveAndFlush(config); } + } - - final Map changes = new HashMap<>(4); - - Collection configurations = this.repository.findAll(); - /** - *Default SMTP configuration added to flyway - */ - for (EmailConfiguration config : configurations) { - if(config.getName() !=null){ - String value = command.stringValueOfParameterNamed(config.getName()); - config.setValue(value); - changes.put(config.getName(),value); - this.repository.saveAndFlush(config); - } - } - - return new CommandProcessingResultBuilder() // - .with(changes) - .build(); + return new CommandProcessingResultBuilder() // + .with(changes).build(); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailMessageJobEmailService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailMessageJobEmailService.java index 37b193b2a..b8c150623 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailMessageJobEmailService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailMessageJobEmailService.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.infrastructure.campaigns.email.service; - import org.apache.fineract.infrastructure.campaigns.email.data.EmailMessageWithAttachmentData; public interface EmailMessageJobEmailService { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailMessageJobEmailServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailMessageJobEmailServiceImpl.java index 375abc668..9dd8b8d4b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailMessageJobEmailServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailMessageJobEmailServiceImpl.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.infrastructure.campaigns.email.service; - import java.io.File; import java.util.List; import java.util.Properties; @@ -37,6 +36,7 @@ import org.springframework.stereotype.Service; @Service public class EmailMessageJobEmailServiceImpl implements EmailMessageJobEmailService { + private final static Logger LOG = LoggerFactory.getLogger(EmailMessageJobEmailServiceImpl.class); private EmailConfigurationRepository emailConfigurationRepository; @@ -47,7 +47,7 @@ public class EmailMessageJobEmailServiceImpl implements EmailMessageJobEmailServ @Override public void sendEmailWithAttachment(EmailMessageWithAttachmentData emailMessageWithAttachmentData) { - try{ + try { JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl(); javaMailSenderImpl.setHost(this.getGmailSmtpServer()); javaMailSenderImpl.setPort(this.getGmailSmtpPort()); @@ -64,39 +64,40 @@ public class EmailMessageJobEmailServiceImpl implements EmailMessageJobEmailServ mimeMessageHelper.setText(emailMessageWithAttachmentData.getText()); mimeMessageHelper.setSubject(emailMessageWithAttachmentData.getSubject()); final List attachments = emailMessageWithAttachmentData.getAttachments(); - if(attachments !=null && attachments.size() > 0){ - for(final File attachment : attachments){ - if(attachment !=null){ - mimeMessageHelper.addAttachment(attachment.getName(),attachment); + if (attachments != null && attachments.size() > 0) { + for (final File attachment : attachments) { + if (attachment != null) { + mimeMessageHelper.addAttachment(attachment.getName(), attachment); } } } javaMailSenderImpl.send(mimeMessage); - }catch(MessagingException e){ - LOG.error("Could not send emai Problem occurred in sendEmailWithAttachment function",e); + } catch (MessagingException e) { + LOG.error("Could not send emai Problem occurred in sendEmailWithAttachment function", e); } } - - private String getGmailSmtpServer(){ + private String getGmailSmtpServer() { final EmailConfiguration gmailSmtpServer = this.emailConfigurationRepository.findByName(EmailApiConstants.SMTP_SERVER); - return (gmailSmtpServer !=null) ? gmailSmtpServer.getValue() : null; - } - private Integer getGmailSmtpPort(){ - final EmailConfiguration gmailSmtpPort = this.emailConfigurationRepository.findByName(EmailApiConstants.SMTP_PORT); - return (gmailSmtpPort !=null) ? Integer.parseInt(gmailSmtpPort.getValue()) : null; - } - private String getGmailSmtpUsername(){ - final EmailConfiguration gmailSmtpUsername = this.emailConfigurationRepository.findByName(EmailApiConstants.SMTP_USERNAME); - return (gmailSmtpUsername !=null) ? gmailSmtpUsername.getValue() : null; + return (gmailSmtpServer != null) ? gmailSmtpServer.getValue() : null; } - private String getGmailSmtpPassword(){ + private Integer getGmailSmtpPort() { + final EmailConfiguration gmailSmtpPort = this.emailConfigurationRepository.findByName(EmailApiConstants.SMTP_PORT); + return (gmailSmtpPort != null) ? Integer.parseInt(gmailSmtpPort.getValue()) : null; + } + + private String getGmailSmtpUsername() { + final EmailConfiguration gmailSmtpUsername = this.emailConfigurationRepository.findByName(EmailApiConstants.SMTP_USERNAME); + return (gmailSmtpUsername != null) ? gmailSmtpUsername.getValue() : null; + } + + private String getGmailSmtpPassword() { final EmailConfiguration gmailSmtpPassword = this.emailConfigurationRepository.findByName(EmailApiConstants.SMTP_PASSWORD); - return (gmailSmtpPassword !=null) ? gmailSmtpPassword.getValue() : null; + return (gmailSmtpPassword != null) ? gmailSmtpPassword.getValue() : null; } private Properties getJavaMailProperties() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailReadPlatformServiceImpl.java index 170e9a507..e7fd91674 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailReadPlatformServiceImpl.java @@ -49,7 +49,6 @@ public class EmailReadPlatformServiceImpl implements EmailReadPlatformService { private final EmailMapper emailRowMapper = new EmailMapper(); private final PaginationHelper paginationHelper = new PaginationHelper<>(); - @Autowired public EmailReadPlatformServiceImpl(final RoutingDataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); @@ -104,8 +103,8 @@ public class EmailReadPlatformServiceImpl implements EmailReadPlatformService { final EnumOptionData status = EmailMessageEnumerations.status(statusId); - return EmailData.instance(id,groupId, clientId, staffId, status, emailAddress, emailSubject, - message,null,null,null,null,null,campaignName,sentDate,errorMessage); + return EmailData.instance(id, groupId, clientId, staffId, status, emailAddress, emailSubject, message, null, null, null, null, + null, campaignName, sentDate, errorMessage); } } @@ -140,8 +139,8 @@ public class EmailReadPlatformServiceImpl implements EmailReadPlatformService { @Override public Collection retrieveAllSent(final SearchParameters searchParameters) { final String sqlPlusLimit = (searchParameters.getLimit() > 0) ? " limit 0, " + searchParameters.getLimit() : ""; - final String sql = "select " + this.emailRowMapper.schema() + " where emo.status_enum = " - + EmailMessageStatusType.SENT.getValue() + sqlPlusLimit; + final String sql = "select " + this.emailRowMapper.schema() + " where emo.status_enum = " + EmailMessageStatusType.SENT.getValue() + + sqlPlusLimit; return this.jdbcTemplate.query(sql, this.emailRowMapper, new Object[] {}); } @@ -167,33 +166,34 @@ public class EmailReadPlatformServiceImpl implements EmailReadPlatformService { @Override public Collection retrieveAllFailed(final SearchParameters searchParameters) { final String sqlPlusLimit = (searchParameters.getLimit() > 0) ? " limit 0, " + searchParameters.getLimit() : ""; - final String sql = "select " + this.emailRowMapper.schema() + " where emo.status_enum = " - + EmailMessageStatusType.FAILED.getValue() + sqlPlusLimit; + final String sql = "select " + this.emailRowMapper.schema() + " where emo.status_enum = " + EmailMessageStatusType.FAILED.getValue() + + sqlPlusLimit; return this.jdbcTemplate.query(sql, this.emailRowMapper, new Object[] {}); } @Override - public Page retrieveEmailByStatus(final Integer limit, final Integer status,final Date dateFrom, final Date dateTo) { + public Page retrieveEmailByStatus(final Integer limit, final Integer status, final Date dateFrom, final Date dateTo) { final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); sqlBuilder.append(this.emailRowMapper.schema()); - if(status !=null){ + if (status != null) { sqlBuilder.append(" where emo.status_enum= ? "); } String fromDateString = null; String toDateString = null; - if(dateFrom !=null && dateTo !=null){ + if (dateFrom != null && dateTo != null) { final DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); fromDateString = df.format(dateFrom); - toDateString = df.format(dateTo); + toDateString = df.format(dateTo); sqlBuilder.append(" and emo.submittedon_date >= ? and emo.submittedon_date <= ? "); } final String sqlPlusLimit = (limit > 0) ? " limit 0, " + limit : ""; - if(!sqlPlusLimit.isEmpty()){ + if (!sqlPlusLimit.isEmpty()) { sqlBuilder.append(sqlPlusLimit); } final String sqlCountRows = "SELECT FOUND_ROWS()"; - return this.paginationHelper.fetchPage(this.jdbcTemplate,sqlCountRows,sqlBuilder.toString(),new Object[]{status,fromDateString,toDateString},this.emailRowMapper); + return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), + new Object[] { status, fromDateString, toDateString }, this.emailRowMapper); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailWritePlatformService.java index 233427c23..4930518dc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailWritePlatformService.java @@ -28,4 +28,4 @@ public interface EmailWritePlatformService { CommandProcessingResult update(Long resourceId, JsonCommand command); CommandProcessingResult delete(Long resourceId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailWritePlatformServiceJpaRepositoryImpl.java index b3182c805..98ae878c8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/email/service/EmailWritePlatformServiceJpaRepositoryImpl.java @@ -120,14 +120,17 @@ public class EmailWritePlatformServiceJpaRepositoryImpl implements EmailWritePla * Guaranteed to throw an exception no matter what the data integrity issue * is. */ - private void handleDataIntegrityIssues(@SuppressWarnings("unused") final JsonCommand command, final DataIntegrityViolationException dve) { + private void handleDataIntegrityIssues(@SuppressWarnings("unused") final JsonCommand command, + final DataIntegrityViolationException dve) { final Throwable realCause = dve.getMostSpecificCause(); - if (realCause.getMessage().contains("email_address")) { throw new PlatformDataIntegrityException("error.msg.email.no.email.address.exists", - "The group, client or staff provided has no email address.", "id"); } + if (realCause.getMessage().contains("email_address")) { + throw new PlatformDataIntegrityException("error.msg.email.no.email.address.exists", + "The group, client or staff provided has no email address.", "id"); + } LOG.error("Error occured.", dve); throw new PlatformDataIntegrityException("error.msg.email.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + realCause.getMessage()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/helper/SmsConfigUtils.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/helper/SmsConfigUtils.java index 8e3183eae..3ff3a2bdc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/helper/SmsConfigUtils.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/helper/SmsConfigUtils.java @@ -37,9 +37,10 @@ import org.springframework.stereotype.Component; public class SmsConfigUtils { @Autowired - private ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService; + private ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService; - //This method will return uri and HttpEntry objects with keys as uri and entity + // This method will return uri and HttpEntry objects with keys as uri and + // entity public Map getMessageGateWayRequestURI(final String apiEndPoint, String apiQueueResourceDatas) { Map httpRequestdetails = new HashMap<>(); MessageGatewayConfigurationData messageGatewayConfigurationData = this.propertiesReadPlatformService.getSMSGateway(); @@ -49,15 +50,18 @@ public class SmsConfigUtils { headers.add(SmsCampaignConstants.FINERACT_PLATFORM_TENANT_ID, tenant.getTenantIdentifier()); headers.add(SmsCampaignConstants.FINERACT_TENANT_APP_KEY, messageGatewayConfigurationData.getTenantAppKey()); StringBuilder pathBuilder = new StringBuilder(); - String endPoint = messageGatewayConfigurationData.getEndPoint() == null || messageGatewayConfigurationData.getEndPoint().equals( - "/") ? "" : messageGatewayConfigurationData.getEndPoint(); - pathBuilder = messageGatewayConfigurationData.getEndPoint() == null || messageGatewayConfigurationData.getEndPoint().equals("/") ? pathBuilder - .append("{apiEndPoint}") : pathBuilder.append("{endPoint}/{apiEndPoint}"); + String endPoint = messageGatewayConfigurationData.getEndPoint() == null || messageGatewayConfigurationData.getEndPoint().equals("/") + ? "" + : messageGatewayConfigurationData.getEndPoint(); + pathBuilder = messageGatewayConfigurationData.getEndPoint() == null || messageGatewayConfigurationData.getEndPoint().equals("/") + ? pathBuilder.append("{apiEndPoint}") + : pathBuilder.append("{endPoint}/{apiEndPoint}"); // pathBuilder.append("{endPoint}/{apiEndPoint}") ; UriBuilder builder = UriBuilder.fromPath(pathBuilder.toString()).host(messageGatewayConfigurationData.getHostName()).scheme("http") .port(messageGatewayConfigurationData.getPortNumber()); - URI uri = messageGatewayConfigurationData.getEndPoint() == null || messageGatewayConfigurationData.getEndPoint().equals("/") ? builder - .build(apiEndPoint) : builder.build(endPoint, apiEndPoint); + URI uri = messageGatewayConfigurationData.getEndPoint() == null || messageGatewayConfigurationData.getEndPoint().equals("/") + ? builder.build(apiEndPoint) + : builder.build(endPoint, apiEndPoint); HttpEntity entity = null; if (apiQueueResourceDatas != null) { entity = new HttpEntity<>(apiQueueResourceDatas, headers); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/api/SmsCampaignApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/api/SmsCampaignApiResource.java index ba592502d..00001057e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/api/SmsCampaignApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/api/SmsCampaignApiResource.java @@ -100,7 +100,8 @@ public class SmsCampaignApiResource { @GET @Path("template") - @ApiOperation(value = "Retrieve a SMS Campaign", notes = "Example Requests:\n" + "\n" + "smscampaigns/1\n" + "\n" + "\n" + "smscampaigns/1?template=true\n" + "\n" + "\n" + "smscampaigns/template") + @ApiOperation(value = "Retrieve a SMS Campaign", notes = "Example Requests:\n" + "\n" + "smscampaigns/1\n" + "\n" + "\n" + + "smscampaigns/1?template=true\n" + "\n" + "\n" + "smscampaigns/template") @ApiResponse(code = 200, message = "", response = SmsCampaignData.class) public String template(@Context final UriInfo uriInfo) { this.platformSecurityContext.authenticatedUser().validateHasReadPermission(SmsCampaignConstants.RESOURCE_NAME); @@ -112,8 +113,11 @@ public class SmsCampaignApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a SMS Campaign", notes = "Mandatory Fields\n" + "campaignName, campaignType, triggerType, providerId, runReportId, message\n" + "\n" + "Mandatory Fields for Cash based on selected report id\n" + "paramValue in json format") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass =CommandWrapper.class)}) + @ApiOperation(value = "Create a SMS Campaign", notes = "Mandatory Fields\n" + + "campaignName, campaignType, triggerType, providerId, runReportId, message\n" + "\n" + + "Mandatory Fields for Cash based on selected report id\n" + "paramValue in json format") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CommandWrapper.class) }) @ApiResponse(code = 200, message = "", response = CommandProcessingResult.class) public String createCampaign(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { this.platformSecurityContext.authenticatedUser(); @@ -139,9 +143,9 @@ public class SmsCampaignApiResource { @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "List SMS Campaigns", notes = "Example Requests:\n" + "\n" + "smscampaigns") @ApiResponse(code = 200, message = "", response = SmsCampaignData.class) - public String retrieveAllEmails(@QueryParam("sqlSearch") final String sqlSearch, - @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, - @QueryParam("orderBy") final String orderBy, @QueryParam("sortOrder") final String sortOrder, @Context final UriInfo uriInfo) { + public String retrieveAllEmails(@QueryParam("sqlSearch") final String sqlSearch, @QueryParam("offset") final Integer offset, + @QueryParam("limit") final Integer limit, @QueryParam("orderBy") final String orderBy, + @QueryParam("sortOrder") final String sortOrder, @Context final UriInfo uriInfo) { this.platformSecurityContext.authenticatedUser().validateHasReadPermission(SmsCampaignConstants.RESOURCE_NAME); final SearchParameters searchParameters = SearchParameters.forSMSCampaign(sqlSearch, offset, limit, orderBy, sortOrder); Page smsCampaignDataCollection = this.smsCampaignReadPlatformService.retrieveAll(searchParameters); @@ -154,9 +158,11 @@ public class SmsCampaignApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Campaign") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CommandWrapper.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CommandWrapper.class) }) @ApiResponse(code = 200, message = "", response = CommandProcessingResult.class) - public String updateCampaign(@PathParam("campaignId") final Long campaignId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + public String updateCampaign(@PathParam("campaignId") final Long campaignId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateSmsCampaign(campaignId).withJson(apiRequestBodyAsJson) .build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/constants/SmsCampaignEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/constants/SmsCampaignEnumerations.java index 9691becca..2689cc460 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/constants/SmsCampaignEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/constants/SmsCampaignEnumerations.java @@ -25,10 +25,8 @@ import org.apache.fineract.infrastructure.campaigns.constants.CampaignType; import org.apache.fineract.infrastructure.core.data.EnumOptionData; import org.apache.fineract.portfolio.common.domain.PeriodFrequencyType; - public class SmsCampaignEnumerations { - public static EnumOptionData smscampaignTriggerType(final SmsCampaignTriggerType type) { EnumOptionData optionData = new EnumOptionData(SmsCampaignTriggerType.INVALID.getValue().longValue(), SmsCampaignTriggerType.INVALID.getCode(), "Invalid"); @@ -61,7 +59,8 @@ public class SmsCampaignEnumerations { optionData = new EnumOptionData(CampaignType.SMS.getValue().longValue(), CampaignType.SMS.getCode(), "SMS"); break; case NOTIFICATION: - optionData = new EnumOptionData(CampaignType.NOTIFICATION.getValue().longValue(), CampaignType.NOTIFICATION.getCode(), "NOTIFICATION"); + optionData = new EnumOptionData(CampaignType.NOTIFICATION.getValue().longValue(), CampaignType.NOTIFICATION.getCode(), + "NOTIFICATION"); break; } return optionData; @@ -75,7 +74,10 @@ public class SmsCampaignEnumerations { public static List calendarMonthType() { final List optionDatas = new ArrayList<>(); for (final Month monthType : Month.values()) { - if (Month.DECEMBER.compareTo(monthType) != 0) { //We are removing December because we are adding yearly frequency + if (Month.DECEMBER.compareTo(monthType) != 0) { // We are removing + // December because + // we are adding + // yearly frequency optionDatas.add(calendarMonthType(monthType)); } } @@ -85,9 +87,9 @@ public class SmsCampaignEnumerations { public static List calendarPeriodFrequencyTypes(final PeriodFrequencyType[] periodFrequencyTypes) { final List optionDatas = new ArrayList<>(); for (final PeriodFrequencyType periodFrequencyType : periodFrequencyTypes) { - if(!periodFrequencyType.getValue().equals(PeriodFrequencyType.INVALID.getValue())) { - final EnumOptionData optionData = new EnumOptionData(periodFrequencyType.getValue().longValue(), periodFrequencyType.getCode(), - periodFrequencyType.toString()); + if (!periodFrequencyType.getValue().equals(PeriodFrequencyType.INVALID.getValue())) { + final EnumOptionData optionData = new EnumOptionData(periodFrequencyType.getValue().longValue(), + periodFrequencyType.getCode(), periodFrequencyType.toString()); optionDatas.add(optionData); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/constants/SmsCampaignTriggerType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/constants/SmsCampaignTriggerType.java index 18d9d1089..cc992417c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/constants/SmsCampaignTriggerType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/constants/SmsCampaignTriggerType.java @@ -21,6 +21,7 @@ package org.apache.fineract.infrastructure.campaigns.sms.constants; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public enum SmsCampaignTriggerType { + INVALID(-1, "triggerType.invalid"), DIRECT(1, "triggerType.direct"), SCHEDULE(2, "triggerType.schedule"), TRIGGERED(3, "triggerType.triggered"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsBusinessRulesData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsBusinessRulesData.java index 6b621bf94..1af8b39dc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsBusinessRulesData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsBusinessRulesData.java @@ -75,18 +75,12 @@ public class SmsBusinessRulesData { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || !(o instanceof SmsBusinessRulesData)) { - return false; - } + if (this == o) { return true; } + if (o == null || !(o instanceof SmsBusinessRulesData)) { return false; } SmsBusinessRulesData that = (SmsBusinessRulesData) o; - if (reportId != null ? !reportId.equals(that.reportId) : that.reportId != null) { - return false; - } + if (reportId != null ? !reportId.equals(that.reportId) : that.reportId != null) { return false; } return true; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsCampaignData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsCampaignData.java index d1ec6d00a..d22b14c97 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsCampaignData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsCampaignData.java @@ -43,7 +43,6 @@ public class SmsCampaignData { private final Long providerId; private final boolean isNotification; - private final Collection smsProviderOptions; private final Collection campaignTypeOptions; @@ -61,8 +60,7 @@ public class SmsCampaignData { private final Collection periodFrequencyOptions; private SmsCampaignData(final Long id, final String campaignName, final EnumOptionData campaignType, final EnumOptionData triggerType, - final Long runReportId, - final String reportName, final String paramValue, final EnumOptionData campaignStatus, + final Long runReportId, final String reportName, final String paramValue, final EnumOptionData campaignStatus, final String message, final DateTime nextTriggerDate, final LocalDate lastTriggerDate, final SmsCampaignTimeLine smsCampaignTimeLine, final DateTime recurrenceStartDate, final String recurrence, final Long providerId, final Collection businessRulesOptions, @@ -105,9 +103,8 @@ public class SmsCampaignData { } public static SmsCampaignData instance(final Long id, final String campaignName, final EnumOptionData campaignType, - final EnumOptionData triggerType, - final Long runReportId, final String reportName, final String paramValue, final EnumOptionData campaignStatus, - final String message, final DateTime nextTriggerDate, final LocalDate lastTriggerDate, + final EnumOptionData triggerType, final Long runReportId, final String reportName, final String paramValue, + final EnumOptionData campaignStatus, final String message, final DateTime nextTriggerDate, final LocalDate lastTriggerDate, final SmsCampaignTimeLine smsCampaignTimeLine, final DateTime recurrenceStartDate, final String recurrence, final Long providerId, final boolean isNotification) { final Collection businessRulesOptions = null; @@ -119,10 +116,10 @@ public class SmsCampaignData { final Collection frequencyTypeOptions = null; final Collection periodFrequencyOptions = null; - return new SmsCampaignData(id, campaignName, campaignType, triggerType, runReportId, - reportName, paramValue, campaignStatus, message, nextTriggerDate, lastTriggerDate, smsCampaignTimeLine, - recurrenceStartDate, recurrence, providerId, businessRulesOptions, smsProviderOptions, campaignTypeOptions, - triggerTypeOptions, months, weekDays, frequencyTypeOptions, periodFrequencyOptions, isNotification); + return new SmsCampaignData(id, campaignName, campaignType, triggerType, runReportId, reportName, paramValue, campaignStatus, + message, nextTriggerDate, lastTriggerDate, smsCampaignTimeLine, recurrenceStartDate, recurrence, providerId, + businessRulesOptions, smsProviderOptions, campaignTypeOptions, triggerTypeOptions, months, weekDays, frequencyTypeOptions, + periodFrequencyOptions, isNotification); } public static SmsCampaignData template(final Collection smsProviderOptions, @@ -146,10 +143,10 @@ public class SmsCampaignData { final String reportName = null; final Long providerId = null; final boolean isNotification = false; - return new SmsCampaignData(id, campaignName, campaignType, triggerType, runReportId, - reportName, paramValue, campaignStatus, message, nextTriggerDate, lastTriggerDate, smsCampaignTimeLine, - recurrenceStartDate, recurrence, providerId, businessRulesOptions, smsProviderOptions, campaignTypeOptions, - triggerTypeOptions, months, weekDays, frequencyTypeOptions, periodFrequencyOptions, isNotification); + return new SmsCampaignData(id, campaignName, campaignType, triggerType, runReportId, reportName, paramValue, campaignStatus, + message, nextTriggerDate, lastTriggerDate, smsCampaignTimeLine, recurrenceStartDate, recurrence, providerId, + businessRulesOptions, smsProviderOptions, campaignTypeOptions, triggerTypeOptions, months, weekDays, frequencyTypeOptions, + periodFrequencyOptions, isNotification); } public Long getId() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsProviderData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsProviderData.java index a7fcfe20e..5cc24c7cf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsProviderData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/data/SmsProviderData.java @@ -32,8 +32,8 @@ public class SmsProviderData { private String providerDescription; - public SmsProviderData(final Long id, final String providerAppKey, final String providerName, final String providerDescription, final String tenantId, - final String phoneNo) { + public SmsProviderData(final Long id, final String providerAppKey, final String providerName, final String providerDescription, + final String tenantId, final String phoneNo) { this.id = id; this.providerAppKey = providerAppKey; this.providerName = providerName; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaign.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaign.java index ef1c0090b..5039b42b1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaign.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaign.java @@ -53,19 +53,19 @@ import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; @Entity -@Table(name = "sms_campaign", uniqueConstraints = {@UniqueConstraint(columnNames = { "campaign_name" }, name = "campaign_name_UNIQUE")}) +@Table(name = "sms_campaign", uniqueConstraints = { @UniqueConstraint(columnNames = { "campaign_name" }, name = "campaign_name_UNIQUE") }) public class SmsCampaign extends AbstractPersistableCustom { @Column(name = "campaign_name", nullable = false) private String campaignName; @Column(name = "campaign_type", nullable = false) - private Integer campaignType ; //defines email or sms, etc.. + private Integer campaignType; // defines email or sms, etc.. @Column(name = "campaign_trigger_type", nullable = false) - private Integer triggerType; //defines direct, scheduled, transaction + private Integer triggerType; // defines direct, scheduled, transaction - @Column(name = "provider_id", nullable = true)//null for notifications + @Column(name = "provider_id", nullable = true) // null for notifications private Long providerId; // defined provider details @ManyToOne @@ -128,10 +128,9 @@ public class SmsCampaign extends AbstractPersistableCustom { public SmsCampaign() {} - private SmsCampaign(final String campaignName, final Integer campaignType, - final Integer triggerType, final Report businessRuleId, final Long providerId, final String paramValue, - final String message, final LocalDate submittedOnDate, final AppUser submittedBy, final String recurrence, - final LocalDateTime localDateTime, final boolean isNotification) { + private SmsCampaign(final String campaignName, final Integer campaignType, final Integer triggerType, final Report businessRuleId, + final Long providerId, final String paramValue, final String message, final LocalDate submittedOnDate, + final AppUser submittedBy, final String recurrence, final LocalDateTime localDateTime, final boolean isNotification) { this.campaignName = campaignName; this.campaignType = campaignType; this.triggerType = SmsCampaignTriggerType.fromInt(triggerType).getValue(); @@ -159,11 +158,11 @@ public class SmsCampaign extends AbstractPersistableCustom { final Long campaignType = command.longValueOfParameterNamed(SmsCampaignValidator.campaignType); final Long triggerType = command.longValueOfParameterNamed(SmsCampaignValidator.triggerType); boolean isNotification = false; - if(command.parameterExists(SmsCampaignValidator.isNotificationParamName)){ + if (command.parameterExists(SmsCampaignValidator.isNotificationParamName)) { isNotification = command.booleanPrimitiveValueOfParameterNamed(SmsCampaignValidator.isNotificationParamName); } Long providerId = null; - if(!isNotification){ + if (!isNotification) { providerId = command.longValueOfParameterNamed(SmsCampaignValidator.providerId); } @@ -176,7 +175,6 @@ public class SmsCampaign extends AbstractPersistableCustom { } String recurrence = null; - LocalDateTime recurrenceStartDate = new LocalDateTime(); if (SmsCampaignTriggerType.fromInt(triggerType.intValue()).isSchedule()) { final Locale locale = command.extractLocale(); @@ -185,8 +183,8 @@ public class SmsCampaign extends AbstractPersistableCustom { dateTimeFormat = command.stringValueOfParameterNamed(SmsCampaignValidator.dateTimeFormat); final DateTimeFormatter fmt = DateTimeFormat.forPattern(dateTimeFormat).withLocale(locale); if (command.hasParameter(SmsCampaignValidator.recurrenceStartDate)) { - recurrenceStartDate = LocalDateTime.parse( - command.stringValueOfParameterNamed(SmsCampaignValidator.recurrenceStartDate), fmt); + recurrenceStartDate = LocalDateTime.parse(command.stringValueOfParameterNamed(SmsCampaignValidator.recurrenceStartDate), + fmt); } recurrence = constructRecurrence(command); } @@ -194,8 +192,8 @@ public class SmsCampaign extends AbstractPersistableCustom { recurrenceStartDate = null; } - return new SmsCampaign(campaignName, campaignType.intValue(), triggerType.intValue(), report, - providerId, paramValue, message, submittedOnDate, submittedBy, recurrence, recurrenceStartDate, isNotification); + return new SmsCampaign(campaignName, campaignType.intValue(), triggerType.intValue(), report, providerId, paramValue, message, + submittedOnDate, submittedBy, recurrence, recurrenceStartDate, isNotification); } public Map update(JsonCommand command) { @@ -554,7 +552,8 @@ public class SmsCampaign extends AbstractPersistableCustom { return constructRecurrence(frequencyType, interval, repeatsOnDay); } - private static String constructRecurrence(final CalendarFrequencyType frequencyType, final Integer interval, final Integer repeatsOnDay) { + private static String constructRecurrence(final CalendarFrequencyType frequencyType, final Integer interval, + final Integer repeatsOnDay) { final StringBuilder recurrenceBuilder = new StringBuilder(200); recurrenceBuilder.append("FREQ="); @@ -583,5 +582,4 @@ public class SmsCampaign extends AbstractPersistableCustom { this.isNotification = isNotification; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaignRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaignRepository.java index 3a8409e06..32f562dbc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaignRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaignRepository.java @@ -34,8 +34,9 @@ public interface SmsCampaignRepository extends JpaRepository, Collection findByTriggerTypeAndStatus(final Integer triggerType, final Integer status); - Collection findByTriggerType(final Integer triggerType) ; + Collection findByTriggerType(final Integer triggerType); @Query("SELECT campaign FROM SmsCampaign campaign WHERE campaign.paramValue LIKE :reportPattern AND campaign.triggerType=:triggerType AND campaign.status=300") - List findActiveSmsCampaigns(@Param("reportPattern") final String reportPattern, @Param("triggerType") final Integer triggerType) ; + List findActiveSmsCampaigns(@Param("reportPattern") final String reportPattern, + @Param("triggerType") final Integer triggerType); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaignStatusEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaignStatusEnumerations.java index 9147a29f5..aa4ae5291 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaignStatusEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/domain/SmsCampaignStatusEnumerations.java @@ -22,6 +22,7 @@ import org.apache.fineract.infrastructure.campaigns.sms.constants.SmsCampaignSta import org.apache.fineract.infrastructure.core.data.EnumOptionData; public class SmsCampaignStatusEnumerations { + public static EnumOptionData status(final Integer statusId) { return status(SmsCampaignStatus.fromInt(statusId)); } @@ -31,22 +32,21 @@ public class SmsCampaignStatusEnumerations { SmsCampaignStatus.INVALID.getCode(), "Invalid"); switch (status) { case INVALID: - optionData = new EnumOptionData - (SmsCampaignStatus.INVALID.getValue().longValue(), - SmsCampaignStatus.INVALID.getCode(), "Invalid"); - break; + optionData = new EnumOptionData(SmsCampaignStatus.INVALID.getValue().longValue(), SmsCampaignStatus.INVALID.getCode(), + "Invalid"); + break; case PENDING: - optionData = new EnumOptionData(SmsCampaignStatus.PENDING.getValue().longValue(), - SmsCampaignStatus.PENDING.getCode(), "Pending"); - break; + optionData = new EnumOptionData(SmsCampaignStatus.PENDING.getValue().longValue(), SmsCampaignStatus.PENDING.getCode(), + "Pending"); + break; case ACTIVE: optionData = new EnumOptionData(SmsCampaignStatus.ACTIVE.getValue().longValue(), SmsCampaignStatus.ACTIVE.getCode(), "active"); - break; + break; case CLOSED: - optionData = new EnumOptionData(SmsCampaignStatus.CLOSED.getValue().longValue(), - SmsCampaignStatus.CLOSED.getCode(), "closed"); - break; + optionData = new EnumOptionData(SmsCampaignStatus.CLOSED.getValue().longValue(), SmsCampaignStatus.CLOSED.getCode(), + "closed"); + break; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/ConnectionFailureException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/ConnectionFailureException.java index b7d9d976c..0a37f881c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/ConnectionFailureException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/ConnectionFailureException.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformService public class ConnectionFailureException extends AbstractPlatformServiceUnavailableException { public ConnectionFailureException(final String connectionName) { - super("error.msg.unable.to.connect.to.intermediate.server", "Unable to connect to the server with connection name - " - + connectionName, connectionName); + super("error.msg.unable.to.connect.to.intermediate.server", + "Unable to connect to the server with connection name - " + connectionName, connectionName); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/SmsCampaignMustBeClosedToBeDeletedException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/SmsCampaignMustBeClosedToBeDeletedException.java index 96fd8d3d7..7e0b926ff 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/SmsCampaignMustBeClosedToBeDeletedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/SmsCampaignMustBeClosedToBeDeletedException.java @@ -20,9 +20,10 @@ package org.apache.fineract.infrastructure.campaigns.sms.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; -public class SmsCampaignMustBeClosedToBeDeletedException extends AbstractPlatformDomainRuleException { +public class SmsCampaignMustBeClosedToBeDeletedException extends AbstractPlatformDomainRuleException { public SmsCampaignMustBeClosedToBeDeletedException(final Long resourceId) { super("error.msg.sms.campaign.cannot.be.deleted", - "Campaign with identifier " + resourceId + " cannot be deleted as it is not in `Closed` state.", resourceId); } + "Campaign with identifier " + resourceId + " cannot be deleted as it is not in `Closed` state.", resourceId); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/SmsCampaignNotFound.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/SmsCampaignNotFound.java index 6bf0f4746..a51bccf82 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/SmsCampaignNotFound.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/exception/SmsCampaignNotFound.java @@ -20,9 +20,10 @@ package org.apache.fineract.infrastructure.campaigns.sms.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; -public class SmsCampaignNotFound extends AbstractPlatformResourceNotFoundException{ +public class SmsCampaignNotFound extends AbstractPlatformResourceNotFoundException { public SmsCampaignNotFound(final Long resourceId) { - super("error.msg.sms.campaign.identifier.not.found", "Sms Campaign with identifier `" + resourceId + "` does not exist", resourceId); + super("error.msg.sms.campaign.identifier.not.found", "Sms Campaign with identifier `" + resourceId + "` does not exist", + resourceId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/CloseSmsCampaignCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/CloseSmsCampaignCommandHandler.java index 0f1217e11..427e416d1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/CloseSmsCampaignCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/CloseSmsCampaignCommandHandler.java @@ -29,15 +29,16 @@ import org.springframework.stereotype.Service; @Service @CommandType(entity = "SMSCAMPAIGN", action = "CLOSE") public class CloseSmsCampaignCommandHandler implements NewCommandSourceHandler { + private final SmsCampaignWritePlatformService smsCampaignWritePlatformService; - @Autowired + @Autowired public CloseSmsCampaignCommandHandler(final SmsCampaignWritePlatformService smsCampaignWritePlatformService) { this.smsCampaignWritePlatformService = smsCampaignWritePlatformService; } @Override public CommandProcessingResult processCommand(JsonCommand command) { - return this.smsCampaignWritePlatformService.closeSmsCampaign(command.entityId(), command); + return this.smsCampaignWritePlatformService.closeSmsCampaign(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/DeleteSmsCampaignCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/DeleteSmsCampaignCommandHandler.java index ebb5ca505..b48c7a18b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/DeleteSmsCampaignCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/DeleteSmsCampaignCommandHandler.java @@ -37,9 +37,10 @@ public class DeleteSmsCampaignCommandHandler implements NewCommandSourceHandler public DeleteSmsCampaignCommandHandler(SmsCampaignWritePlatformService smsCampaignWritePlatformService) { this.smsCampaignWritePlatformService = smsCampaignWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand command) { - return this.smsCampaignWritePlatformService.delete(command.entityId()); + return this.smsCampaignWritePlatformService.delete(command.entityId()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/ReactivateSmsCampaignCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/ReactivateSmsCampaignCommandHandler.java index aa8bebe6f..c50aed400 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/ReactivateSmsCampaignCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/handler/ReactivateSmsCampaignCommandHandler.java @@ -37,9 +37,10 @@ public class ReactivateSmsCampaignCommandHandler implements NewCommandSourceHand public ReactivateSmsCampaignCommandHandler(SmsCampaignWritePlatformService smsCampaignWritePlatformService) { this.smsCampaignWritePlatformService = smsCampaignWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand command) { - return this.smsCampaignWritePlatformService.reactivateSmsCampaign(command.entityId(),command); + return this.smsCampaignWritePlatformService.reactivateSmsCampaign(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/serialization/SmsCampaignValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/serialization/SmsCampaignValidator.java index 017b07833..175aa3107 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/serialization/SmsCampaignValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/serialization/SmsCampaignValidator.java @@ -74,24 +74,20 @@ public class SmsCampaignValidator { private final FromJsonHelper fromApiJsonHelper; private final DeviceRegistrationRepositoryWrapper deviceRegistrationRepository; - protected static final Set supportedParams = new HashSet<>(Arrays.asList(campaignName, campaignType, - localeParamName, + protected static final Set supportedParams = new HashSet<>(Arrays.asList(campaignName, campaignType, localeParamName, dateFormatParamName, runReportId, paramValue, message, recurrenceStartDate, activationDateParamName, submittedOnDateParamName, closureDateParamName, recurrenceParamName, providerId, triggerType, frequencyParamName, intervalParamName, repeatsOnDayParamName, triggerEntityType, triggerActionType, dateTimeFormat, isNotificationParamName)); - protected static final Set supportedParamsForUpdate = new HashSet<>(Arrays.asList(campaignName, campaignType, - localeParamName, + protected static final Set supportedParamsForUpdate = new HashSet<>(Arrays.asList(campaignName, campaignType, localeParamName, dateFormatParamName, runReportId, paramValue, message, recurrenceStartDate, activationDateParamName, recurrenceParamName, providerId, triggerType, triggerEntityType, triggerActionType, dateTimeFormat, isNotificationParamName)); - protected static final Set ACTIVATION_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(localeParamName, - dateFormatParamName, - activationDateParamName)); + protected static final Set ACTIVATION_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(localeParamName, dateFormatParamName, activationDateParamName)); - protected static final Set CLOSE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(localeParamName, - dateFormatParamName, - closureDateParamName)); + protected static final Set CLOSE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(localeParamName, dateFormatParamName, closureDateParamName)); protected static final Set PREVIEW_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(paramValue, message)); @@ -207,7 +203,7 @@ public class SmsCampaignValidator { } } - if(this.fromApiJsonHelper.parameterExists(SmsCampaignValidator.runReportId, element)) { + if (this.fromApiJsonHelper.parameterExists(SmsCampaignValidator.runReportId, element)) { final Long runReportId = this.fromApiJsonHelper.extractLongNamed(SmsCampaignValidator.runReportId, element); baseDataValidator.reset().parameter(SmsCampaignValidator.runReportId).value(runReportId).notNull().integerGreaterThanZero(); } @@ -290,8 +286,8 @@ public class SmsCampaignValidator { final JsonElement element = this.fromApiJsonHelper.parse(json); - final LocalDate activationDate = this.fromApiJsonHelper - .extractLocalDateNamed(SmsCampaignValidator.activationDateParamName, element); + final LocalDate activationDate = this.fromApiJsonHelper.extractLocalDateNamed(SmsCampaignValidator.activationDateParamName, + element); baseDataValidator.reset().parameter(SmsCampaignValidator.activationDateParamName).value(activationDate).notNull(); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -322,8 +318,7 @@ public class SmsCampaignValidator { public boolean isValidNotificationOrSms(Client client, SmsCampaign smsCampaign, Object mobileNo) { if (smsCampaign.isNotification()) { if (client != null) { - DeviceRegistration deviceRegistration = this.deviceRegistrationRepository - .findDeviceRegistrationByClientId(client.getId()); + DeviceRegistration deviceRegistration = this.deviceRegistrationRepository.findDeviceRegistrationByClientId(client.getId()); return deviceRegistration != null; } return false; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDomainService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDomainService.java index 11faeb314..f2f3aca47 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDomainService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDomainService.java @@ -21,5 +21,4 @@ package org.apache.fineract.infrastructure.campaigns.sms.service; /** * Created by Stefan on 4-7-2016. */ -public interface SmsCampaignDomainService { -} +public interface SmsCampaignDomainService {} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDomainServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDomainServiceImpl.java index 8c9c59522..e128b56e5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDomainServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDomainServiceImpl.java @@ -66,7 +66,7 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { private static final Logger LOG = LoggerFactory.getLogger(SmsCampaignDomainServiceImpl.class); - //private final static int POOL_SIZE = 5 ; + // private final static int POOL_SIZE = 5 ; private final SmsCampaignRepository smsCampaignRepository; private final SmsMessageRepository smsMessageRepository; @@ -80,18 +80,16 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { @Autowired public SmsCampaignDomainServiceImpl(final SmsCampaignRepository smsCampaignRepository, final SmsMessageRepository smsMessageRepository, - final BusinessEventNotifierService businessEventNotifierService, final OfficeRepository officeRepository, - final SmsCampaignWritePlatformService smsCampaignWritePlatformCommandHandler, - final GroupRepository groupRepository, - final SmsMessageScheduledJobService smsMessageScheduledJobService, - final SmsCampaignValidator smsCampaignValidator){ + final BusinessEventNotifierService businessEventNotifierService, final OfficeRepository officeRepository, + final SmsCampaignWritePlatformService smsCampaignWritePlatformCommandHandler, final GroupRepository groupRepository, + final SmsMessageScheduledJobService smsMessageScheduledJobService, final SmsCampaignValidator smsCampaignValidator) { this.smsCampaignRepository = smsCampaignRepository; this.smsMessageRepository = smsMessageRepository; this.businessEventNotifierService = businessEventNotifierService; this.officeRepository = officeRepository; this.smsCampaignWritePlatformCommandHandler = smsCampaignWritePlatformCommandHandler; this.groupRepository = groupRepository; - this.smsMessageScheduledJobService = smsMessageScheduledJobService ; + this.smsMessageScheduledJobService = smsMessageScheduledJobService; this.smsCampaignValidator = smsCampaignValidator; } @@ -102,10 +100,13 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { this.businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_MAKE_REPAYMENT, new SendSmsOnLoanRepayment()); this.businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.CLIENTS_ACTIVATE, new ClientActivatedListener()); this.businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.CLIENTS_REJECT, new ClientRejectedListener()); - this.businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_ACTIVATE, new SavingsAccountActivatedListener()); + this.businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_ACTIVATE, + new SavingsAccountActivatedListener()); this.businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_REJECT, new SavingsAccountRejectedListener()); - this.businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_DEPOSIT, new SavingsAccountTransactionListener(true)); - this.businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_WITHDRAWAL, new SavingsAccountTransactionListener(false)); + this.businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_DEPOSIT, + new SavingsAccountTransactionListener(true)); + this.businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_WITHDRAWAL, + new SavingsAccountTransactionListener(false)); } private void notifyRejectedLoanOwner(Loan loan) { @@ -113,8 +114,8 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { if (smsCampaigns.size() > 0) { for (SmsCampaign campaign : smsCampaigns) { if (campaign.isActive()) { - SmsCampaignDomainServiceImpl.this.smsCampaignWritePlatformCommandHandler - .insertDirectCampaignIntoSmsOutboundTable(loan, campaign); + SmsCampaignDomainServiceImpl.this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(loan, + campaign); } } } @@ -122,39 +123,38 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { private void notifyAcceptedLoanOwner(Loan loan) { List smsCampaigns = retrieveSmsCampaigns("Loan Approved"); - if(smsCampaigns.size()>0){ - for (SmsCampaign campaign:smsCampaigns){ + if (smsCampaigns.size() > 0) { + for (SmsCampaign campaign : smsCampaigns) { this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(loan, campaign); } } } private void notifyClientActivated(final Client client) { - List smsCampaigns = retrieveSmsCampaigns("Client Activated"); - if(smsCampaigns.size()>0){ - for (SmsCampaign campaign:smsCampaigns){ - this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(client, campaign); - } - } + List smsCampaigns = retrieveSmsCampaigns("Client Activated"); + if (smsCampaigns.size() > 0) { + for (SmsCampaign campaign : smsCampaigns) { + this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(client, campaign); + } + } } private void notifyClientRejected(final Client client) { List smsCampaigns = retrieveSmsCampaigns("Client Rejected"); - if(smsCampaigns.size()>0){ - for (SmsCampaign campaign:smsCampaigns){ + if (smsCampaigns.size() > 0) { + for (SmsCampaign campaign : smsCampaigns) { this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(client, campaign); } } - } + } private void notifySavingsAccountActivated(final SavingsAccount savingsAccount) { List smsCampaigns = retrieveSmsCampaigns("Savings Activated"); if (smsCampaigns.size() > 0) { for (SmsCampaign campaign : smsCampaigns) { - this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount, - campaign); + this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount, campaign); } } @@ -164,8 +164,7 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { List smsCampaigns = retrieveSmsCampaigns("Savings Rejected"); if (smsCampaigns.size() > 0) { for (SmsCampaign campaign : smsCampaigns) { - this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount, - campaign); + this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount, campaign); } } @@ -179,8 +178,7 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { Loan loan = loanTransaction.getLoan(); final Set groupClients = new HashSet<>(); if (loan.hasInvalidLoanType()) { - throw new InvalidLoanTypeException( - "Loan Type cannot be Invalid for the Triggered Sms Campaign"); + throw new InvalidLoanTypeException("Loan Type cannot be Invalid for the Triggered Sms Campaign"); } if (loan.isGroupLoan()) { Group group = this.groupRepository.findById(loan.getGroupId()).orElse(null); @@ -189,8 +187,7 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { groupClients.add(loan.client()); } HashMap campaignParams = new ObjectMapper().readValue(smsCampaign.getParamValue(), - new TypeReference>() { - }); + new TypeReference>() {}); if (groupClients.size() > 0) { for (Client client : groupClients) { @@ -205,27 +202,24 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { if (spkeycheck && !(value.equals("-1") || spvalue.equals(value))) { if (key.equals("officeId")) { Office campaignOffice = this.officeRepository.findById(Long.valueOf(value)).orElse(null); - if (campaignOffice - .doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) { - throw new SmsRuntimeException("error.msg.no.office", - "Office not found for the id"); + if (campaignOffice.doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) { + throw new SmsRuntimeException("error.msg.no.office", "Office not found for the id"); } } else { - throw new SmsRuntimeException("error.msg.no.id.attribute", - "Office Id attribute is notfound"); + throw new SmsRuntimeException("error.msg.no.id.attribute", "Office Id attribute is notfound"); } } } - String message = this.smsCampaignWritePlatformCommandHandler.compileSmsTemplate( - smsCampaign.getMessage(), smsCampaign.getCampaignName(), smsParams); + String message = this.smsCampaignWritePlatformCommandHandler.compileSmsTemplate(smsCampaign.getMessage(), + smsCampaign.getCampaignName(), smsParams); Object mobileNo = smsParams.get("mobileNo"); if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) { String mobileNumber = null; - if(mobileNo != null){ + if (mobileNo != null) { mobileNumber = mobileNo.toString(); } - SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message, - mobileNumber, smsCampaign, smsCampaign.isNotification()); + SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message, mobileNumber, smsCampaign, + smsCampaign.isNotification()); Collection messages = new ArrayList<>(); messages.add(smsMessage); Map> smsDataMap = new HashMap<>(); @@ -252,8 +246,7 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { final SavingsAccount savingsAccount = savingsTransaction.getSavingsAccount(); final Client client = savingsAccount.getClient(); HashMap campaignParams = new ObjectMapper().readValue(smsCampaign.getParamValue(), - new TypeReference>() { - }); + new TypeReference>() {}); HashMap smsParams = processSavingsTransactionDataForSms(savingsTransaction, client); for (String key : campaignParams.keySet()) { String value = campaignParams.get(key); @@ -266,25 +259,23 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { if (key.equals("officeId")) { Office campaignOffice = this.officeRepository.findById(Long.valueOf(value)).orElse(null); if (campaignOffice.doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) { - throw new SmsRuntimeException("error.msg.no.office", - "Office not found for the id"); + throw new SmsRuntimeException("error.msg.no.office", "Office not found for the id"); } } else { - throw new SmsRuntimeException("error.msg.no.id.attribute", - "Office Id attribute is notfound"); + throw new SmsRuntimeException("error.msg.no.id.attribute", "Office Id attribute is notfound"); } } } - String message = this.smsCampaignWritePlatformCommandHandler - .compileSmsTemplate(smsCampaign.getMessage(), smsCampaign.getCampaignName(), smsParams); + String message = this.smsCampaignWritePlatformCommandHandler.compileSmsTemplate(smsCampaign.getMessage(), + smsCampaign.getCampaignName(), smsParams); Object mobileNo = smsParams.get("mobileNo"); if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) { String mobileNumber = null; - if(mobileNo != null){ + if (mobileNo != null) { mobileNumber = mobileNo.toString(); } - SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message, - mobileNumber, smsCampaign, smsCampaign.isNotification()); + SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message, mobileNumber, smsCampaign, + smsCampaign.isNotification()); this.smsMessageRepository.save(smsMessage); Collection messages = new ArrayList<>(); messages.add(smsMessage); @@ -301,89 +292,93 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { } } - private List retrieveSmsCampaigns(String paramValue){ - List smsCampaigns = smsCampaignRepository.findActiveSmsCampaigns("%"+paramValue+"%", SmsCampaignTriggerType.TRIGGERED.getValue()); + private List retrieveSmsCampaigns(String paramValue) { + List smsCampaigns = smsCampaignRepository.findActiveSmsCampaigns("%" + paramValue + "%", + SmsCampaignTriggerType.TRIGGERED.getValue()); return smsCampaigns; } - private HashMap processRepaymentDataForSms(final LoanTransaction loanTransaction, Client groupClient){ + private HashMap processRepaymentDataForSms(final LoanTransaction loanTransaction, Client groupClient) { HashMap smsParams = new HashMap(); Loan loan = loanTransaction.getLoan(); final Client client; - if(loan.isGroupLoan() && groupClient != null){ + if (loan.isGroupLoan() && groupClient != null) { client = groupClient; - }else if(loan.isIndividualLoan()){ + } else if (loan.isIndividualLoan()) { client = loan.getClient(); - }else{ + } else { throw new InvalidParameterException(""); } DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("HH:mm"); DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("MMM:d:yyyy"); - smsParams.put("id",loanTransaction.getLoan().getClientId()); - smsParams.put("firstname",client.getFirstname()); - smsParams.put("middlename",client.getMiddlename()); - smsParams.put("lastname",client.getLastname()); - smsParams.put("FullName",client.getDisplayName()); - smsParams.put("mobileNo",client.mobileNo()); - smsParams.put("LoanAmount",loan.getPrincpal()); - smsParams.put("LoanOutstanding",loanTransaction.getOutstandingLoanBalance()); - smsParams.put("loanId",loan.getId()); + smsParams.put("id", loanTransaction.getLoan().getClientId()); + smsParams.put("firstname", client.getFirstname()); + smsParams.put("middlename", client.getMiddlename()); + smsParams.put("lastname", client.getLastname()); + smsParams.put("FullName", client.getDisplayName()); + smsParams.put("mobileNo", client.mobileNo()); + smsParams.put("LoanAmount", loan.getPrincpal()); + smsParams.put("LoanOutstanding", loanTransaction.getOutstandingLoanBalance()); + smsParams.put("loanId", loan.getId()); smsParams.put("LoanAccountId", loan.getAccountNumber()); smsParams.put("officeId", client.getOffice().getId()); - if(client.getStaff() != null) { + if (client.getStaff() != null) { smsParams.put("loanOfficerId", client.getStaff().getId()); - }else { - smsParams.put("loanOfficerId", -1); + } else { + smsParams.put("loanOfficerId", -1); } smsParams.put("repaymentAmount", loanTransaction.getAmount(loan.getCurrency())); smsParams.put("RepaymentDate", loanTransaction.getCreatedDateTime().toLocalDate().toString(dateFormatter)); smsParams.put("RepaymentTime", loanTransaction.getCreatedDateTime().toLocalTime().toString(timeFormatter)); - if(loanTransaction.getPaymentDetail() != null) { + if (loanTransaction.getPaymentDetail() != null) { smsParams.put("receiptNumber", loanTransaction.getPaymentDetail().getReceiptNumber()); - }else { + } else { smsParams.put("receiptNumber", -1); } return smsParams; } - private HashMap processSavingsTransactionDataForSms(final SavingsAccountTransaction savingsAccountTransaction, Client client){ + private HashMap processSavingsTransactionDataForSms(final SavingsAccountTransaction savingsAccountTransaction, + Client client) { - // {{savingsId}} {{id}} {{firstname}} {{middlename}} {{lastname}} {{FullName}} {{mobileNo}} {{savingsAccountId}} {{depositAmount}} {{balance}} + // {{savingsId}} {{id}} {{firstname}} {{middlename}} {{lastname}} + // {{FullName}} {{mobileNo}} {{savingsAccountId}} {{depositAmount}} + // {{balance}} - //transactionDate + // transactionDate HashMap smsParams = new HashMap(); - SavingsAccount savingsAccount = savingsAccountTransaction.getSavingsAccount() ; + SavingsAccount savingsAccount = savingsAccountTransaction.getSavingsAccount(); DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("MMM:d:yyyy"); - smsParams.put("clientId",client.getId()); - smsParams.put("firstname",client.getFirstname()); - smsParams.put("middlename",client.getMiddlename()); - smsParams.put("lastname",client.getLastname()); - smsParams.put("FullName",client.getDisplayName()); - smsParams.put("mobileNo",client.mobileNo()); - smsParams.put("savingsId", savingsAccount.getId()) ; - smsParams.put("savingsAccountNo",savingsAccount.getAccountNumber()); - smsParams.put("withdrawAmount",savingsAccountTransaction.getAmount(savingsAccount.getCurrency())); - smsParams.put("depositAmount",savingsAccountTransaction.getAmount(savingsAccount.getCurrency())); - smsParams.put("balance",savingsAccount.getWithdrawableBalance()); + smsParams.put("clientId", client.getId()); + smsParams.put("firstname", client.getFirstname()); + smsParams.put("middlename", client.getMiddlename()); + smsParams.put("lastname", client.getLastname()); + smsParams.put("FullName", client.getDisplayName()); + smsParams.put("mobileNo", client.mobileNo()); + smsParams.put("savingsId", savingsAccount.getId()); + smsParams.put("savingsAccountNo", savingsAccount.getAccountNumber()); + smsParams.put("withdrawAmount", savingsAccountTransaction.getAmount(savingsAccount.getCurrency())); + smsParams.put("depositAmount", savingsAccountTransaction.getAmount(savingsAccount.getCurrency())); + smsParams.put("balance", savingsAccount.getWithdrawableBalance()); smsParams.put("officeId", client.getOffice().getId()); - smsParams.put("transactionDate", savingsAccountTransaction.getTransactionLocalDate().toString(dateFormatter)) ; - smsParams.put("savingsTransactionId", savingsAccountTransaction.getId()) ; + smsParams.put("transactionDate", savingsAccountTransaction.getTransactionLocalDate().toString(dateFormatter)); + smsParams.put("savingsTransactionId", savingsAccountTransaction.getId()); - if(client.getStaff() != null) { + if (client.getStaff() != null) { smsParams.put("loanOfficerId", client.getStaff().getId()); - }else { - smsParams.put("loanOfficerId", -1); + } else { + smsParams.put("loanOfficerId", -1); } - if(savingsAccountTransaction.getPaymentDetail() != null) { + if (savingsAccountTransaction.getPaymentDetail() != null) { smsParams.put("receiptNumber", savingsAccountTransaction.getPaymentDetail().getReceiptNumber()); - }else { + } else { smsParams.put("receiptNumber", -1); } return smsParams; @@ -393,11 +388,11 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { @Override public void businessEventToBeExecuted(Map businessEventEntity) { - //Nothing to do + // Nothing to do } } - private class SendSmsOnLoanApproved extends SmsBusinessEventAdapter{ + private class SendSmsOnLoanApproved extends SmsBusinessEventAdapter { @Override public void businessEventWasExecuted(Map businessEventEntity) { @@ -409,7 +404,7 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { } } - private class SendSmsOnLoanRejected extends SmsBusinessEventAdapter{ + private class SendSmsOnLoanRejected extends SmsBusinessEventAdapter { @Override public void businessEventWasExecuted(Map businessEventEntity) { @@ -421,7 +416,7 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { } } - private class SendSmsOnLoanRepayment extends SmsBusinessEventAdapter{ + private class SendSmsOnLoanRepayment extends SmsBusinessEventAdapter { @Override public void businessEventWasExecuted(Map businessEventEntity) { @@ -438,8 +433,8 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { @Override public void businessEventWasExecuted(Map businessEventEntity) { Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BusinessEntity.CLIENT); - if(entity instanceof Client) { - notifyClientActivated((Client)entity); + if (entity instanceof Client) { + notifyClientActivated((Client) entity); } } } @@ -449,20 +444,20 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { @Override public void businessEventWasExecuted(Map businessEventEntity) { Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BusinessEntity.CLIENT); - if(entity instanceof Client) { - notifyClientRejected((Client)entity); + if (entity instanceof Client) { + notifyClientRejected((Client) entity); } } } - private class SavingsAccountActivatedListener extends SmsBusinessEventAdapter{ + private class SavingsAccountActivatedListener extends SmsBusinessEventAdapter { @Override public void businessEventWasExecuted(Map businessEventEntity) { Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BusinessEntity.SAVING); - if(entity instanceof SavingsAccount) { - notifySavingsAccountActivated((SavingsAccount)entity); + if (entity instanceof SavingsAccount) { + notifySavingsAccountActivated((SavingsAccount) entity); } } @@ -473,41 +468,40 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService { @Override public void businessEventWasExecuted(Map businessEventEntity) { Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BusinessEntity.SAVING); - if(entity instanceof SavingsAccount) { - notifySavingsAccountRejected((SavingsAccount)entity); + if (entity instanceof SavingsAccount) { + notifySavingsAccountRejected((SavingsAccount) entity); } } } private class SavingsAccountTransactionListener extends SmsBusinessEventAdapter { - final boolean isDeposit ; + final boolean isDeposit; public SavingsAccountTransactionListener(final boolean isDeposit) { - this.isDeposit = isDeposit ; + this.isDeposit = isDeposit; } @Override public void businessEventWasExecuted(Map businessEventEntity) { Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BusinessEntity.SAVINGS_TRANSACTION); - if(entity instanceof SavingsAccountTransaction) { - sendSmsForSavingsTransaction((SavingsAccountTransaction)entity, this.isDeposit); + if (entity instanceof SavingsAccountTransaction) { + sendSmsForSavingsTransaction((SavingsAccountTransaction) entity, this.isDeposit); } } } - /*private abstract class Task implements Runnable { - - protected final FineractPlatformTenant tenant; - - protected final String reportName ; - - private final Object entity ; - - public Task(final FineractPlatformTenant tenant, final String reportName, final Object entity) { - this.tenant = tenant; - this.reportName = reportName ; - this.entity = entity ; - } - }*/ + /* + * private abstract class Task implements Runnable { + * + * protected final FineractPlatformTenant tenant; + * + * protected final String reportName ; + * + * private final Object entity ; + * + * public Task(final FineractPlatformTenant tenant, final String reportName, + * final Object entity) { this.tenant = tenant; this.reportName = reportName + * ; this.entity = entity ; } } + */ } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDropdownReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDropdownReadPlatformServiceImpl.java index bf85fbfb4..45353d2dd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDropdownReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignDropdownReadPlatformServiceImpl.java @@ -47,15 +47,16 @@ import org.springframework.web.client.RestTemplate; @Service public class SmsCampaignDropdownReadPlatformServiceImpl implements SmsCampaignDropdownReadPlatformService { + private final static Logger LOG = LoggerFactory.getLogger(SmsCampaignDropdownReadPlatformServiceImpl.class); private final RestTemplate restTemplate; - private final SmsConfigUtils smsConfigUtils ; + private final SmsConfigUtils smsConfigUtils; @Autowired public SmsCampaignDropdownReadPlatformServiceImpl(final SmsConfigUtils smsConfigUtils) { this.restTemplate = new RestTemplate(); - this.smsConfigUtils = smsConfigUtils ; + this.smsConfigUtils = smsConfigUtils; } @Override @@ -64,7 +65,7 @@ public class SmsCampaignDropdownReadPlatformServiceImpl implements SmsCampaignDr SmsCampaignEnumerations.smscampaignTriggerType(SmsCampaignTriggerType.DIRECT), // SmsCampaignEnumerations.smscampaignTriggerType(SmsCampaignTriggerType.SCHEDULE), // SmsCampaignEnumerations.smscampaignTriggerType(SmsCampaignTriggerType.TRIGGERED) // - ); + ); return triggerTypeCodeValues; } @@ -72,26 +73,26 @@ public class SmsCampaignDropdownReadPlatformServiceImpl implements SmsCampaignDr @Override public Collection retrieveSmsProviders() { Collection smsProviderOptions = new ArrayList<>(); - String hostName = "" ; - Map hostConfig = this.smsConfigUtils.getMessageGateWayRequestURI("smsbridges", null); - URI uri = (URI) hostConfig.get("uri"); - hostName = uri.getHost() ; - HttpEntity entity = (HttpEntity) hostConfig.get("entity"); - ResponseEntity> responseOne = restTemplate.exchange(uri, HttpMethod.GET, entity, - new ParameterizedTypeReference>() {}); - if (!responseOne.getStatusCode().equals(HttpStatus.OK)) { - throw new PlatformDataIntegrityException("error.msg.mobile.service.provider.not.available", - "Mobile service provider not available."); - } - smsProviderOptions = responseOne.getBody(); - return smsProviderOptions; + String hostName = ""; + Map hostConfig = this.smsConfigUtils.getMessageGateWayRequestURI("smsbridges", null); + URI uri = (URI) hostConfig.get("uri"); + hostName = uri.getHost(); + HttpEntity entity = (HttpEntity) hostConfig.get("entity"); + ResponseEntity> responseOne = restTemplate.exchange(uri, HttpMethod.GET, entity, + new ParameterizedTypeReference>() {}); + if (!responseOne.getStatusCode().equals(HttpStatus.OK)) { + throw new PlatformDataIntegrityException("error.msg.mobile.service.provider.not.available", + "Mobile service provider not available."); + } + smsProviderOptions = responseOne.getBody(); + return smsProviderOptions; } @Override public Collection retrieveCampaignTypes() { final List campaignTypeCodeValues = Arrays.asList( // SmsCampaignEnumerations.smscampaignType(CampaignType.SMS)// - ); + ); return campaignTypeCodeValues; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignReadPlatformServiceImpl.java index e5512a069..6fde3c550 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignReadPlatformServiceImpl.java @@ -117,7 +117,9 @@ public class SmsCampaignReadPlatformServiceImpl implements SmsCampaignReadPlatfo final Collection frequencyTypeOptions = this.calendarDropdownReadPlatformService .retrieveCalendarFrequencyTypeOptions(); final Collection periodFrequencyOptions = this.smsCampaignDropdownReadPlatformService.retrivePeriodFrequencyTypes(); - //final Collection triggerTypeSubTypeOptions = this.smsCampaignDropdownReadPlatformService.getTriggerTypeAndSubTypes(); + // final Collection + // triggerTypeSubTypeOptions = + // this.smsCampaignDropdownReadPlatformService.getTriggerTypeAndSubTypes(); return SmsCampaignData.template(smsProviderOptions, campaignTypeOptions, businessRulesOptions, campaignTriggerTypeOptions, months, weekDays, frequencyTypeOptions, periodFrequencyOptions); } @@ -266,8 +268,9 @@ public class SmsCampaignReadPlatformServiceImpl implements SmsCampaignReadPlatfo final String reportName = rs.getString("reportName"); final Long providerId = rs.getLong("providerId"); final Boolean isNotification = rs.getBoolean("isNotification"); - return SmsCampaignData.instance(id, campaignName, campaignTypeEnum, triggerTypeEnum, runReportId, reportName, paramValue, status, message, nextTriggerDate, lastTriggerDate, - smsCampaignTimeLine, recurrenceStartDate, recurrence, providerId, isNotification); + return SmsCampaignData.instance(id, campaignName, campaignTypeEnum, triggerTypeEnum, runReportId, reportName, paramValue, + status, message, nextTriggerDate, lastTriggerDate, smsCampaignTimeLine, recurrenceStartDate, recurrence, providerId, + isNotification); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignWritePlatformService.java index 51d4b00c3..18520274a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignWritePlatformService.java @@ -51,8 +51,8 @@ public interface SmsCampaignWritePlatformService { public void storeTemplateMessageIntoSmsOutBoundTable() throws JobExecutionException; - public void insertDirectCampaignIntoSmsOutboundTable(final Client client, final SmsCampaign smsCampaign) ; + public void insertDirectCampaignIntoSmsOutboundTable(final Client client, final SmsCampaign smsCampaign); - public void insertDirectCampaignIntoSmsOutboundTable(final SavingsAccount savingsAccount, final SmsCampaign smsCampaign) ; + public void insertDirectCampaignIntoSmsOutboundTable(final SavingsAccount savingsAccount, final SmsCampaign smsCampaign); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignWritePlatformServiceJpaImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignWritePlatformServiceJpaImpl.java index ff22504d2..f85de108e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignWritePlatformServiceJpaImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/campaigns/sms/service/SmsCampaignWritePlatformServiceJpaImpl.java @@ -117,7 +117,8 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP final SmsMessageRepository smsMessageRepository, final ClientRepositoryWrapper clientRepositoryWrapper, final ReadReportingService readReportingService, final GenericDataService genericDataService, final FromJsonHelper fromJsonHelper, final GroupRepository groupRepository, - final SmsMessageScheduledJobService smsMessageScheduledJobService, final DeviceRegistrationRepositoryWrapper deviceRegistrationRepository) { + final SmsMessageScheduledJobService smsMessageScheduledJobService, + final DeviceRegistrationRepositoryWrapper deviceRegistrationRepository) { this.context = context; this.smsCampaignRepository = smsCampaignRepository; this.smsCampaignValidator = smsCampaignValidator; @@ -128,7 +129,7 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP this.genericDataService = genericDataService; this.fromJsonHelper = fromJsonHelper; this.groupRepository = groupRepository; - this.smsMessageScheduledJobService = smsMessageScheduledJobService ; + this.smsMessageScheduledJobService = smsMessageScheduledJobService; this.deviceRegistrationRepository = deviceRegistrationRepository; } @@ -139,12 +140,13 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP final AppUser currentUser = this.context.authenticatedUser(); this.smsCampaignValidator.validateCreate(command.json()); final Long runReportId = command.longValueOfParameterNamed(SmsCampaignValidator.runReportId); - Report report = this.reportRepository.findById(runReportId) - .orElseThrow(() -> new ReportNotFoundException(runReportId)); + Report report = this.reportRepository.findById(runReportId).orElseThrow(() -> new ReportNotFoundException(runReportId)); SmsCampaign smsCampaign = SmsCampaign.instance(currentUser, report, command); - if (smsCampaign.getRecurrenceStartDate() != null && smsCampaign.getRecurrenceStartDate().isBefore(DateUtils.getLocalDateOfTenant())) { throw new GeneralPlatformDomainRuleException( - "error.msg.campaign.recurrenceStartDate.in.the.past", "Recurrence start date cannot be the past date.", - smsCampaign.getRecurrenceStartDate()); } + if (smsCampaign.getRecurrenceStartDate() != null + && smsCampaign.getRecurrenceStartDate().isBefore(DateUtils.getLocalDateOfTenant())) { + throw new GeneralPlatformDomainRuleException("error.msg.campaign.recurrenceStartDate.in.the.past", + "Recurrence start date cannot be the past date.", smsCampaign.getRecurrenceStartDate()); + } this.smsCampaignRepository.save(smsCampaign); return new CommandProcessingResultBuilder() // @@ -168,8 +170,7 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP if (changes.containsKey(SmsCampaignValidator.runReportId)) { final Long newValue = command.longValueOfParameterNamed(SmsCampaignValidator.runReportId); - final Report reportId = this.reportRepository.findById(newValue) - .orElseThrow(() -> new ReportNotFoundException(newValue)); + final Report reportId = this.reportRepository.findById(newValue).orElseThrow(() -> new ReportNotFoundException(newValue)); smsCampaign.updateBusinessRuleId(reportId); } @@ -228,25 +229,24 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId.longValue()); if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) { -// String countryCode = this.smsReadPlatformService.retrieveCountryCode(client.getOffice().getId()).getCountryCode(); + // String countryCode = + // this.smsReadPlatformService.retrieveCountryCode(client.getOffice().getId()).getCountryCode(); String mobileNumber = null; - if(mobileNo != null){ + if (mobileNo != null) { mobileNumber = mobileNo.toString(); } - SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, mobileNumber, - smsCampaign, smsCampaign.isNotification()); + SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, mobileNumber, smsCampaign, + smsCampaign.isNotification()); this.smsMessageRepository.save(smsMessage); } } } } catch (final IOException e) { - LOG.error("Error occured.", e) ; + LOG.error("Error occured.", e); } } - - @Override public void insertDirectCampaignIntoSmsOutboundTable(final Loan loan, final SmsCampaign smsCampaign) { try { @@ -285,26 +285,26 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) { String mobileNumber = null; - if(mobileNo != null){ + if (mobileNo != null) { mobileNumber = mobileNo.toString(); } - SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, mobileNumber, - smsCampaign, smsCampaign.isNotification()); + SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, mobileNumber, smsCampaign, + smsCampaign.isNotification()); smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); this.smsMessageRepository.save(smsMessage); - Collection messages = new ArrayList<>() ; - messages.add(smsMessage) ; - Map> smsDataMap = new HashMap<>() ; - smsDataMap.put(smsCampaign, messages) ; - this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap); + Collection messages = new ArrayList<>(); + messages.add(smsMessage); + Map> smsDataMap = new HashMap<>(); + smsDataMap.put(smsCampaign, messages); + this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap); } } } } } catch (final IOException e) { - LOG.error("Error occured.", e) ; + LOG.error("Error occured.", e); } catch (final RuntimeException e) { - LOG.error("Error occured.", e) ; + LOG.error("Error occured.", e); } } @@ -320,22 +320,21 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP campaignParams.put("clientId", client.getId().toString()); queryParamForRunReport.put("clientId", client.getId().toString()); - List> runReportObject = this - .getRunReportByServiceImpl(campaignParams.get("reportName"), queryParamForRunReport); + List> runReportObject = this.getRunReportByServiceImpl(campaignParams.get("reportName"), + queryParamForRunReport); if (runReportObject != null && runReportObject.size() > 0) { for (HashMap entry : runReportObject) { - String textMessage = this.compileSmsTemplate(smsCampaign.getMessage(), - smsCampaign.getCampaignName(), entry); + String textMessage = this.compileSmsTemplate(smsCampaign.getMessage(), smsCampaign.getCampaignName(), entry); Object mobileNo = entry.get("mobileNo"); if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) { String mobileNumber = null; - if(mobileNo != null){ + if (mobileNo != null) { mobileNumber = mobileNo.toString(); } - SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, - mobileNumber, smsCampaign, smsCampaign.isNotification()); + SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, mobileNumber, smsCampaign, + smsCampaign.isNotification()); smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); this.smsMessageRepository.save(smsMessage); Collection messages = new ArrayList<>(); @@ -347,9 +346,9 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP } } } catch (final IOException e) { - LOG.error("Error occured.", e) ; + LOG.error("Error occured.", e); } catch (final RuntimeException e) { - LOG.error("Error occured.", e) ; + LOG.error("Error occured.", e); } } @@ -363,23 +362,22 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP new TypeReference>() {}); queryParamForRunReport.put("savingsId", savingsAccount.getId().toString()); - Client client = savingsAccount.getClient() ; - List> runReportObject = this - .getRunReportByServiceImpl(campaignParams.get("reportName"), queryParamForRunReport); + Client client = savingsAccount.getClient(); + List> runReportObject = this.getRunReportByServiceImpl(campaignParams.get("reportName"), + queryParamForRunReport); if (runReportObject != null && runReportObject.size() > 0) { for (HashMap entry : runReportObject) { - String textMessage = this.compileSmsTemplate(smsCampaign.getMessage(), - smsCampaign.getCampaignName(), entry); + String textMessage = this.compileSmsTemplate(smsCampaign.getMessage(), smsCampaign.getCampaignName(), entry); Object mobileNo = entry.get("mobileNo"); if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) { String mobileNumber = null; - if(mobileNo != null){ + if (mobileNo != null) { mobileNumber = mobileNo.toString(); } - SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, - mobileNumber, smsCampaign, smsCampaign.isNotification()); + SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, mobileNumber, smsCampaign, + smsCampaign.isNotification()); smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); this.smsMessageRepository.save(smsMessage); Collection messages = new ArrayList<>(); @@ -391,9 +389,9 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP } } } catch (final IOException e) { - LOG.error("Error occured.", e) ; + LOG.error("Error occured.", e); } catch (final RuntimeException e) { - LOG.error("Error occured.", e) ; + LOG.error("Error occured.", e); } } @@ -408,8 +406,8 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP * next run time has to be in the future if not calculate a new future * date */ - LocalDate nextRuntime = CalendarUtils.getNextRecurringDate(smsCampaign.getRecurrence(), smsCampaign.getNextTriggerDate() - .toLocalDate(), nextTriggerDate.toLocalDate()); + LocalDate nextRuntime = CalendarUtils.getNextRecurringDate(smsCampaign.getRecurrence(), + smsCampaign.getNextTriggerDate().toLocalDate(), nextTriggerDate.toLocalDate()); if (nextRuntime.isBefore(DateUtils.getLocalDateOfTenant())) { // means // next // run @@ -506,7 +504,7 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP smsCampaign.close(currentUser, fmt, closureDate); this.smsCampaignRepository.saveAndFlush(smsCampaign); -// this.serviceui.sendMessagesToGateway(); + // this.serviceui.sendMessagesToGateway(); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -546,8 +544,8 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP String key = map.getKey(); Object ob = map.getValue(); if (ob instanceof ArrayList && ((ArrayList) ob).size() == 3) { - String changeArrayDateToStringDate = ((ArrayList) ob).get(2).toString() + "-" + ((ArrayList) ob).get(1).toString() - + "-" + ((ArrayList) ob).get(0).toString(); + String changeArrayDateToStringDate = ((ArrayList) ob).get(2).toString() + "-" + ((ArrayList) ob).get(1).toString() + "-" + + ((ArrayList) ob).get(0).toString(); entry.put(key, changeArrayDateToStringDate); } } @@ -563,8 +561,8 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP // final String smsParams = // this.fromJsonHelper.extractJsonObjectNamed("paramValue", // query.parsedJson()).getAsString(); - final JsonElement smsParamsElement = this.fromJsonHelper - .extractJsonObjectNamed(SmsCampaignValidator.paramValue, query.parsedJson()); + final JsonElement smsParamsElement = this.fromJsonHelper.extractJsonObjectNamed(SmsCampaignValidator.paramValue, + query.parsedJson()); String smsParams = smsParamsElement.toString(); final String textMessageTemplate = this.fromJsonHelper.extractStringNamed("message", query.parsedJson()); @@ -649,15 +647,15 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP @Override @CronTarget(jobName = JobName.UPDATE_SMS_OUTBOUND_WITH_CAMPAIGN_MESSAGE) public void storeTemplateMessageIntoSmsOutBoundTable() throws JobExecutionException { - final Collection smsCampaignDataCollection = this.smsCampaignRepository.findByTriggerTypeAndStatus( - SmsCampaignTriggerType.SCHEDULE.getValue(), SmsCampaignStatus.ACTIVE.getValue()); + final Collection smsCampaignDataCollection = this.smsCampaignRepository + .findByTriggerTypeAndStatus(SmsCampaignTriggerType.SCHEDULE.getValue(), SmsCampaignStatus.ACTIVE.getValue()); if (smsCampaignDataCollection != null) { for (SmsCampaign smsCampaign : smsCampaignDataCollection) { LocalDateTime tenantDateNow = tenantDateTime(); LocalDateTime nextTriggerDate = smsCampaign.getNextTriggerDate(); LOG.info("tenant time {} trigger time {} {}", - new Object[] { tenantDateNow, nextTriggerDate, JobName.UPDATE_SMS_OUTBOUND_WITH_CAMPAIGN_MESSAGE.name() }); + new Object[] { tenantDateNow, nextTriggerDate, JobName.UPDATE_SMS_OUTBOUND_WITH_CAMPAIGN_MESSAGE.name() }); if (nextTriggerDate.isBefore(tenantDateNow)) { insertDirectCampaignIntoSmsOutboundTable(smsCampaign); this.updateTriggerDates(smsCampaign.getId()); @@ -686,20 +684,22 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP return today; } -// private String formatDestinationPhoneNumber(String phoneNumber, String countryCallingCode) { -// StringBuilder formatedPhoneNumber = new StringBuilder("+"); -// -// try { -// Long phoneNumberToLong = Long.parseLong(phoneNumber); -// Long countryCallingCodeToLong = Long.parseLong(countryCallingCode); -// formatedPhoneNumber.append(Long.toString(countryCallingCodeToLong)); -// formatedPhoneNumber.append(Long.toString(phoneNumberToLong)); -// } -// -// catch (Exception e) { -// LOG.error("Invalid phone number or country calling code, must contain only numbers", e); -// } -// -// return formatedPhoneNumber.toString(); -// } + // private String formatDestinationPhoneNumber(String phoneNumber, String + // countryCallingCode) { + // StringBuilder formatedPhoneNumber = new StringBuilder("+"); + // + // try { + // Long phoneNumberToLong = Long.parseLong(phoneNumber); + // Long countryCallingCodeToLong = Long.parseLong(countryCallingCode); + // formatedPhoneNumber.append(Long.toString(countryCallingCodeToLong)); + // formatedPhoneNumber.append(Long.toString(phoneNumberToLong)); + // } + // + // catch (Exception e) { + // LOG.error("Invalid phone number or country calling code, must contain + // only numbers", e); + // } + // + // return formatedPhoneNumber.toString(); + // } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/CodeConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/CodeConstants.java index 66520a183..307b269bb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/CodeConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/CodeConstants.java @@ -28,8 +28,9 @@ public class CodeConstants { * value ***/ public static enum CodevalueJSONinputParams { - CODEVALUE_ID("id"), NAME("name"), POSITION("position"), DESCRIPTION("description"), IS_ACTIVE("isActive"), - IS_MANDATORY("isMandatory"); + + CODEVALUE_ID("id"), NAME("name"), POSITION("position"), DESCRIPTION("description"), IS_ACTIVE("isActive"), IS_MANDATORY( + "isMandatory"); private final String value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodeValuesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodeValuesApiResource.java index 38d2112a1..75c162ce4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodeValuesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodeValuesApiResource.java @@ -61,20 +61,19 @@ import org.springframework.stereotype.Component; @Path("/codes/{codeId}/codevalues") @Component @Scope("singleton") -@Api(tags = {"Code Values"}) +@Api(tags = { "Code Values" }) @SwaggerDefinition(tags = { - @Tag(name = "Code Values", description = "Code and code values: Codes represent a specific category of data, their code values are a specific instance of that category.\n" + "\n" + "Codes are mostly system defined which means the code itself comes out of the box and cannot be modified however its code values can be. e.g. 'Customer Identifier', it defaults to a code value of 'Passport' but could be 'Drivers License, National Id' etc") -}) + @Tag(name = "Code Values", description = "Code and code values: Codes represent a specific category of data, their code values are a specific instance of that category.\n" + + "\n" + + "Codes are mostly system defined which means the code itself comes out of the box and cannot be modified however its code values can be. e.g. 'Customer Identifier', it defaults to a code value of 'Passport' but could be 'Drivers License, National Id' etc") }) public class CodeValuesApiResource { /** * The set of parameters that are supported in response for {@link CodeData} */ - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(CodevalueJSONinputParams.CODEVALUE_ID.getValue(), - CodevalueJSONinputParams.NAME.getValue(), CodevalueJSONinputParams.POSITION.getValue(), - CodevalueJSONinputParams.IS_MANDATORY.getValue(), - CodevalueJSONinputParams.DESCRIPTION.getValue())); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(CodevalueJSONinputParams.CODEVALUE_ID.getValue(), + CodevalueJSONinputParams.NAME.getValue(), CodevalueJSONinputParams.POSITION.getValue(), + CodevalueJSONinputParams.IS_MANDATORY.getValue(), CodevalueJSONinputParams.DESCRIPTION.getValue())); private final String resourceNameForPermissions = "CODEVALUE"; private final PlatformSecurityContext context; @@ -97,9 +96,12 @@ public class CodeValuesApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Code Values", notes = "Returns the list of Code Values for a given Code\n" + "\n" + "Example Requests:\n" + "\n" + "codes/1/codevalues") - @ApiResponses({@ApiResponse(code = 200, message = "A List of Given response", response = CodeValuesApiResourceSwagger.GetCodeValuesDataResponse.class, responseContainer = "list")}) - public String retrieveAllCodeValues(@Context final UriInfo uriInfo, @PathParam("codeId") @ApiParam(value = "codeId") final Long codeId) { + @ApiOperation(value = "List Code Values", notes = "Returns the list of Code Values for a given Code\n" + "\n" + "Example Requests:\n" + + "\n" + "codes/1/codevalues") + @ApiResponses({ + @ApiResponse(code = 200, message = "A List of Given response", response = CodeValuesApiResourceSwagger.GetCodeValuesDataResponse.class, responseContainer = "list") }) + public String retrieveAllCodeValues(@Context final UriInfo uriInfo, + @PathParam("codeId") @ApiParam(value = "codeId") final Long codeId) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -113,9 +115,11 @@ public class CodeValuesApiResource { @Path("{codeValueId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Code Value", notes = "Returns the details of a Code Value\n" + "\n" + "Example Requests:\n" + "\n" + "codes/1/codevalues/1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = CodeValuesApiResourceSwagger.GetCodeValuesDataResponse.class)}) - public String retrieveCodeValue(@Context final UriInfo uriInfo, @PathParam("codeValueId") @ApiParam(value = "codeValueId") final Long codeValueId) { + @ApiOperation(value = "Retrieve a Code Value", notes = "Returns the details of a Code Value\n" + "\n" + "Example Requests:\n" + "\n" + + "codes/1/codevalues/1") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CodeValuesApiResourceSwagger.GetCodeValuesDataResponse.class) }) + public String retrieveCodeValue(@Context final UriInfo uriInfo, + @PathParam("codeValueId") @ApiParam(value = "codeValueId") final Long codeValueId) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -129,9 +133,11 @@ public class CodeValuesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create a Code Value", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CodeValuesApiResourceSwagger.PostCodeValuesDataRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = CodeValuesApiResourceSwagger.PostCodeValueDataResponse.class)}) - public String createCodeValue(@PathParam("codeId") @ApiParam(value = "codeId") final Long codeId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CodeValuesApiResourceSwagger.PostCodeValuesDataRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CodeValuesApiResourceSwagger.PostCodeValueDataResponse.class) }) + public String createCodeValue(@PathParam("codeId") @ApiParam(value = "codeId") final Long codeId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createCodeValue(codeId).withJson(apiRequestBodyAsJson).build(); @@ -146,9 +152,11 @@ public class CodeValuesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Code Value", notes = "Updates the details of a code value.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CodeValuesApiResourceSwagger.PutCodeValuesDataRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = CodeValuesApiResourceSwagger.PutCodeValueDataResponse.class)}) - public String updateCodeValue(@PathParam("codeId") @ApiParam(value = "codeId") final Long codeId, @PathParam("codeValueId") @ApiParam(value = "codeValueId") final Long codeValueId, + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CodeValuesApiResourceSwagger.PutCodeValuesDataRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CodeValuesApiResourceSwagger.PutCodeValueDataResponse.class) }) + public String updateCodeValue(@PathParam("codeId") @ApiParam(value = "codeId") final Long codeId, + @PathParam("codeValueId") @ApiParam(value = "codeValueId") final Long codeValueId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCodeValue(codeId, codeValueId) @@ -164,8 +172,9 @@ public class CodeValuesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Code Value", notes = "Deletes a code value") - @ApiResponses({@ApiResponse(code = 200, message = "", response = CodeValuesApiResourceSwagger.DeleteCodeValueDataResponse.class)}) - public String deleteCodeValue(@PathParam("codeId") @ApiParam(value = "codeId") final Long codeId, @PathParam("codeValueId") @ApiParam(value = "codeValueId") final Long codeValueId) { + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CodeValuesApiResourceSwagger.DeleteCodeValueDataResponse.class) }) + public String deleteCodeValue(@PathParam("codeId") @ApiParam(value = "codeId") final Long codeId, + @PathParam("codeValueId") @ApiParam(value = "codeValueId") final Long codeValueId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteCodeValue(codeId, codeValueId).build(); @@ -173,4 +182,4 @@ public class CodeValuesApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodeValuesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodeValuesApiResourceSwagger.java index 636577492..9035061b9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodeValuesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodeValuesApiResourceSwagger.java @@ -25,15 +25,18 @@ import io.swagger.annotations.ApiModelProperty; * Created by sanyam on 30/7/17. */ final class CodeValuesApiResourceSwagger { + private CodeValuesApiResourceSwagger() { } @ApiModel(value = "GetCodeValuesDataResponse") public static final class GetCodeValuesDataResponse { + private GetCodeValuesDataResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Passport") @@ -46,9 +49,11 @@ final class CodeValuesApiResourceSwagger { @ApiModel(value = "PostCodeValuesDataRequest") public static final class PostCodeValuesDataRequest { + private PostCodeValuesDataRequest() { } + @ApiModelProperty(example = "Passport") public String name; @ApiModelProperty(example = "Passport information") @@ -59,18 +64,22 @@ final class CodeValuesApiResourceSwagger { @ApiModel(value = "PostCodeValueDataResponse") public static final class PostCodeValueDataResponse { + private PostCodeValueDataResponse() { } + @ApiModelProperty(example = "4") public Long resourceId; } @ApiModel(value = "PutCodeValuesDataRequest") public static final class PutCodeValuesDataRequest { + private PutCodeValuesDataRequest() { } + @ApiModelProperty(example = "Passport") public String name; @ApiModelProperty(example = "Passport information") @@ -81,11 +90,15 @@ final class CodeValuesApiResourceSwagger { @ApiModel(value = "PutCodeValueDataResponse") public static final class PutCodeValueDataResponse { + private PutCodeValueDataResponse() { } - private final class PutCodeValuechangesSwagger{ + + private final class PutCodeValuechangesSwagger { + private PutCodeValuechangesSwagger() {} + @ApiModelProperty(example = "Passport") public String name; @ApiModelProperty(example = "Passport information") @@ -93,6 +106,7 @@ final class CodeValuesApiResourceSwagger { @ApiModelProperty(example = "0") public Integer position; } + @ApiModelProperty(example = "4") public Long resourceId; public PutCodeValuechangesSwagger changes; @@ -100,9 +114,11 @@ final class CodeValuesApiResourceSwagger { @ApiModel(value = "DeleteCodeValueDataResponse") public static final class DeleteCodeValueDataResponse { + private DeleteCodeValueDataResponse() { } + @ApiModelProperty(example = "4") public Long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodesApiResource.java index 3dd42e0bd..5f59030ee 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodesApiResource.java @@ -59,10 +59,11 @@ import org.springframework.stereotype.Component; @Path("/codes") @Component @Scope("singleton") -@Api(tags = {"Codes"}) +@Api(tags = { "Codes" }) @SwaggerDefinition(tags = { - @Tag(name = "Codes", description = "Code and code values: Codes represent a specific category of data, their code values are a specific instance of that category.\n" + "\n" + "Codes are mostly system defined which means the code itself comes out of the box and cannot be modified however its code values can be. e.g. 'Customer Identifier', it defaults to a code value of 'Passport' but could be 'Drivers License, National Id' etc") -}) + @Tag(name = "Codes", description = "Code and code values: Codes represent a specific category of data, their code values are a specific instance of that category.\n" + + "\n" + + "Codes are mostly system defined which means the code itself comes out of the box and cannot be modified however its code values can be. e.g. 'Customer Identifier', it defaults to a code value of 'Passport' but could be 'Drivers License, National Id' etc") }) public class CodesApiResource { /** @@ -92,7 +93,8 @@ public class CodesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieve Codes", notes = "Returns the list of codes.\n" + "\n" + "Example Requests:\n" + "\n" + "codes") - @ApiResponses({@ApiResponse(code = 200, message = "", response = CodesApiResourceSwagger.GetCodesResponse.class, responseContainer = "list")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = CodesApiResourceSwagger.GetCodesResponse.class, responseContainer = "list") }) public String retrieveCodes(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -107,8 +109,9 @@ public class CodesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create a Code", notes = "Creates a code. Codes created through api are always 'user defined' and so system defined is marked as false.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CodesApiResourceSwagger.PostCodesRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = CodesApiResourceSwagger.PostCodesResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CodesApiResourceSwagger.PostCodesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CodesApiResourceSwagger.PostCodesResponse.class) }) public String createCode(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createCode().withJson(apiRequestBodyAsJson).build(); @@ -123,7 +126,7 @@ public class CodesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieve a Code", notes = "Returns the details of a Code.\n" + "\n" + "Example Requests:\n" + "\n" + "codes/1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = CodesApiResourceSwagger.GetCodesResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CodesApiResourceSwagger.GetCodesResponse.class) }) public String retrieveCode(@PathParam("codeId") @ApiParam(value = "codeId") final Long codeId, @Context final UriInfo uriInfo) { final CodeData code = this.readPlatformService.retrieveCode(codeId); @@ -137,9 +140,11 @@ public class CodesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Code", notes = "Updates the details of a code if it is not system defined.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CodesApiResourceSwagger.PutCodesRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = CodesApiResourceSwagger.PutCodesResponse.class)}) - public String updateCode(@PathParam("codeId") @ApiParam(value = "codeId") final Long codeId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CodesApiResourceSwagger.PutCodesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CodesApiResourceSwagger.PutCodesResponse.class) }) + public String updateCode(@PathParam("codeId") @ApiParam(value = "codeId") final Long codeId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCode(codeId).withJson(apiRequestBodyAsJson).build(); @@ -153,7 +158,7 @@ public class CodesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Code", notes = "Deletes a code if it is not system defined.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = CodesApiResourceSwagger.DeleteCodesResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CodesApiResourceSwagger.DeleteCodesResponse.class) }) public String deleteCode(@PathParam("codeId") @ApiParam(value = "codeId") final Long codeId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteCode(codeId).build(); @@ -162,4 +167,4 @@ public class CodesApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodesApiResourceSwagger.java index 69ce81676..bdf18208b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/api/CodesApiResourceSwagger.java @@ -25,15 +25,18 @@ import io.swagger.annotations.ApiModelProperty; * Created by sanyam on 29/7/17. */ final class CodesApiResourceSwagger { + private CodesApiResourceSwagger() { // this class is only for Swagger Live Documentation } @ApiModel(value = "GetCodesResponse") public static final class GetCodesResponse { + private GetCodesResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Education") @@ -44,41 +47,52 @@ final class CodesApiResourceSwagger { @ApiModel(value = "PostCodesRequest") public static final class PostCodesRequest { + private PostCodesRequest() { } + @ApiModelProperty(example = "MyNewCode") public String name; } @ApiModel(value = "PostCodesResponse") public static final class PostCodesResponse { + private PostCodesResponse() { } + @ApiModelProperty(example = "4") public Long resourceId; } @ApiModel(value = "PutCodesRequest") public static final class PutCodesRequest { + private PutCodesRequest() { } + @ApiModelProperty(example = "MyNewCode(changed)") public String name; } @ApiModel(value = "PutCodesResponse") public static final class PutCodesResponse { + private PutCodesResponse() { } - private final class PutCodesApichangesSwagger{ + + private final class PutCodesApichangesSwagger { + private PutCodesApichangesSwagger() {} + @ApiModelProperty(example = "MyNewCode(changed)") public String name; } + @ApiModelProperty(example = "4") public Long resourceId; public PutCodesApichangesSwagger changes; @@ -86,9 +100,11 @@ final class CodesApiResourceSwagger { @ApiModel(value = "DeleteCodesResponse") public static final class DeleteCodesResponse { + private DeleteCodesResponse() { } + @ApiModelProperty(example = "4") public Long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/data/CodeData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/data/CodeData.java index 4709392cf..f1088e842 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/data/CodeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/data/CodeData.java @@ -44,4 +44,4 @@ public class CodeData implements Serializable { public Long getCodeId() { return this.id; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/data/CodeValueData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/data/CodeValueData.java index 3ff438b2f..db97f3656 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/data/CodeValueData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/data/CodeValueData.java @@ -37,7 +37,7 @@ public class CodeValueData implements Serializable { private final boolean active; private final boolean mandatory; - public CodeValueData( final Long id){ + public CodeValueData(final Long id) { this.id = id; this.name = null; this.position = null; @@ -46,20 +46,19 @@ public class CodeValueData implements Serializable { this.mandatory = false; } - public static CodeValueData instance(final Long id, final String name, final Integer position, - final boolean isActive, final boolean mandatory) { + public static CodeValueData instance(final Long id, final String name, final Integer position, final boolean isActive, + final boolean mandatory) { String description = null; return new CodeValueData(id, name, position, description, isActive, mandatory); } - public static CodeValueData instance(final Long id, final String name, final String description, - final boolean isActive, final boolean mandatory) { + public static CodeValueData instance(final Long id, final String name, final String description, final boolean isActive, + final boolean mandatory) { Integer position = null; return new CodeValueData(id, name, position, description, isActive, mandatory); } - public static CodeValueData instance(final Long id, final String name, final String description, - final boolean isActive) { + public static CodeValueData instance(final Long id, final String name, final String description, final boolean isActive) { Integer position = null; boolean mandatory = false; @@ -75,13 +74,13 @@ public class CodeValueData implements Serializable { return new CodeValueData(id, name, position, description, isActive, mandatory); } - public static CodeValueData instance(final Long id, final String name, final Integer position, - final String description, final boolean isActive, final boolean mandatory) { + public static CodeValueData instance(final Long id, final String name, final Integer position, final String description, + final boolean isActive, final boolean mandatory) { return new CodeValueData(id, name, position, description, isActive, mandatory); } - private CodeValueData(final Long id, final String name, final Integer position, final String description, - final boolean active, final boolean mandatory) { + private CodeValueData(final Long id, final String name, final Integer position, final String description, final boolean active, + final boolean mandatory) { this.id = id; this.name = name; this.position = position; @@ -111,4 +110,4 @@ public class CodeValueData implements Serializable { public boolean isActive() { return active; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/Code.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/Code.java index 724cd1936..624a22cd7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/Code.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/Code.java @@ -91,4 +91,4 @@ public class Code extends AbstractPersistableCustom { public boolean remove(final CodeValue codeValueToDelete) { return this.values.remove(codeValueToDelete); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeRepository.java index b02590bba..f20559e39 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeRepository.java @@ -24,4 +24,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface CodeRepository extends JpaRepository, JpaSpecificationExecutor { Code findOneByName(String name); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeValue.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeValue.java index 93b9d63e8..0032efeda 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeValue.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeValue.java @@ -33,7 +33,8 @@ import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity -@Table(name = "m_code_value", uniqueConstraints = { @UniqueConstraint(columnNames = { "code_id", "code_value" }, name = "code_value_duplicate") }) +@Table(name = "m_code_value", uniqueConstraints = { + @UniqueConstraint(columnNames = { "code_id", "code_value" }, name = "code_value_duplicate") }) public class CodeValue extends AbstractPersistableCustom { @Column(name = "code_value", length = 100) @@ -64,8 +65,8 @@ public class CodeValue extends AbstractPersistableCustom { // } - private CodeValue(final Code code, final String label, final int position, final String description, - final boolean isActive, final boolean mandatory) { + private CodeValue(final Code code, final String label, final int position, final String description, final boolean isActive, + final boolean mandatory) { this.code = code; this.label = StringUtils.defaultIfEmpty(label, null); this.position = position; @@ -96,8 +97,7 @@ public class CodeValue extends AbstractPersistableCustom { position = 0; } - Boolean mandatory = command.booleanPrimitiveValueOfParameterNamed( - CodevalueJSONinputParams.IS_MANDATORY.getValue()); + Boolean mandatory = command.booleanPrimitiveValueOfParameterNamed(CodevalueJSONinputParams.IS_MANDATORY.getValue()); return new CodeValue(code, label, position, description, isActive, mandatory); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeValueRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeValueRepository.java index cae081e3e..60ba58e54 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeValueRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/domain/CodeValueRepository.java @@ -25,5 +25,5 @@ public interface CodeValueRepository extends JpaRepository, Jpa CodeValue findByCodeNameAndId(String codeName, Long id); - CodeValue findByCodeNameAndLabel (String codeName, String label); + CodeValue findByCodeNameAndLabel(String codeName, String label); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/exception/CodeNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/exception/CodeNotFoundException.java index 4dfdbe770..b277c6182 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/exception/CodeNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/exception/CodeNotFoundException.java @@ -32,4 +32,4 @@ public class CodeNotFoundException extends AbstractPlatformResourceNotFoundExcep public CodeNotFoundException(final Long codeId) { super("error.msg.code.identifier.not.found", "Code with identifier `" + codeId + "` does not exist", codeId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/exception/CodeValueNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/exception/CodeValueNotFoundException.java index 3b276a8eb..ef5f10fcd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/exception/CodeValueNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/exception/CodeValueNotFoundException.java @@ -30,12 +30,12 @@ public class CodeValueNotFoundException extends AbstractPlatformResourceNotFound } public CodeValueNotFoundException(final String codeName, final Long id) { - super("error.msg.codevalue.codename.id.combination.invalid", "Code value with identifier " + id - + " does not exist for a code with name " + codeName, id, codeName); + super("error.msg.codevalue.codename.id.combination.invalid", + "Code value with identifier " + id + " does not exist for a code with name " + codeName, id, codeName); } public CodeValueNotFoundException(final String codeName, final String label) { - super("error.msg.codevalue.codename.id.combination.invalid", "Code value with label " + label - + " does not exist for a code with name " + codeName, label, codeName); + super("error.msg.codevalue.codename.id.combination.invalid", + "Code value with label " + label + " does not exist for a code with name " + codeName, label, codeName); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/CreateCodeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/CreateCodeCommandHandler.java index 7a18de11a..8f783a766 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/CreateCodeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/CreateCodeCommandHandler.java @@ -44,4 +44,4 @@ public class CreateCodeCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createCode(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/CreateCodeValueCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/CreateCodeValueCommandHandler.java index 4654ff6ca..ab3f60a17 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/CreateCodeValueCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/CreateCodeValueCommandHandler.java @@ -44,4 +44,4 @@ public class CreateCodeValueCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createCodeValue(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/DeleteCodeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/DeleteCodeCommandHandler.java index 930f0e23c..718231470 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/DeleteCodeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/DeleteCodeCommandHandler.java @@ -44,4 +44,4 @@ public class DeleteCodeCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.deleteCode(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/DeleteCodeValueCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/DeleteCodeValueCommandHandler.java index 1227df416..910b76156 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/DeleteCodeValueCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/DeleteCodeValueCommandHandler.java @@ -44,4 +44,4 @@ public class DeleteCodeValueCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.deleteCodeValue(command.entityId(), command.subentityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/UpdateCodeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/UpdateCodeCommandHandler.java index ad77c90cc..def7a818f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/UpdateCodeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/UpdateCodeCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateCodeCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.updateCode(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/UpdateCodeValueCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/UpdateCodeValueCommandHandler.java index 9f2e0615d..8ba6da8d6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/UpdateCodeValueCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/handler/UpdateCodeValueCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateCodeValueCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.updateCodeValue(command.subentityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/serialization/CodeCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/serialization/CodeCommandFromApiJsonDeserializer.java index 469717ba4..8bc840d45 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/serialization/CodeCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/serialization/CodeCommandFromApiJsonDeserializer.java @@ -89,7 +89,9 @@ public final class CodeCommandFromApiJsonDeserializer { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/serialization/CodeValueCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/serialization/CodeValueCommandFromApiJsonDeserializer.java index 43da690a5..331802ee4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/serialization/CodeValueCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/serialization/CodeValueCommandFromApiJsonDeserializer.java @@ -67,8 +67,7 @@ public final class CodeValueCommandFromApiJsonDeserializer { baseDataValidator.reset().parameter(CodevalueJSONinputParams.NAME.getValue()).value(name).notBlank().notExceedingLengthOf(100); if (this.fromApiJsonHelper.parameterExists(CodevalueJSONinputParams.DESCRIPTION.getValue(), element)) { - final String description = this.fromApiJsonHelper.extractStringNamed(CodevalueJSONinputParams.DESCRIPTION.getValue(), - element); + final String description = this.fromApiJsonHelper.extractStringNamed(CodevalueJSONinputParams.DESCRIPTION.getValue(), element); baseDataValidator.reset().parameter(CodevalueJSONinputParams.DESCRIPTION.getValue()).value(description) .notExceedingLengthOf(500); } @@ -99,12 +98,10 @@ public final class CodeValueCommandFromApiJsonDeserializer { if (this.fromApiJsonHelper.parameterExists(CodevalueJSONinputParams.NAME.getValue(), element)) { final String name = this.fromApiJsonHelper.extractStringNamed(CodevalueJSONinputParams.NAME.getValue(), element); - baseDataValidator.reset().parameter(CodevalueJSONinputParams.NAME.getValue()).value(name).notBlank() - .notExceedingLengthOf(100); + baseDataValidator.reset().parameter(CodevalueJSONinputParams.NAME.getValue()).value(name).notBlank().notExceedingLengthOf(100); } if (this.fromApiJsonHelper.parameterExists(CodevalueJSONinputParams.DESCRIPTION.getValue(), element)) { - final String description = this.fromApiJsonHelper.extractStringNamed(CodevalueJSONinputParams.DESCRIPTION.getValue(), - element); + final String description = this.fromApiJsonHelper.extractStringNamed(CodevalueJSONinputParams.DESCRIPTION.getValue(), element); baseDataValidator.reset().parameter(CodevalueJSONinputParams.DESCRIPTION.getValue()).value(description) .notExceedingLengthOf(500); } @@ -123,7 +120,9 @@ public final class CodeValueCommandFromApiJsonDeserializer { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeReadPlatformServiceImpl.java index f5a7070a6..19bc39c18 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeReadPlatformServiceImpl.java @@ -99,4 +99,4 @@ public class CodeReadPlatformServiceImpl implements CodeReadPlatformService { throw new CodeNotFoundException(codeName); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueReadPlatformService.java index d1040d571..d6674fc0f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueReadPlatformService.java @@ -47,4 +47,4 @@ public interface CodeValueReadPlatformService { Collection retrieveAllCodeValues(final Long codeId); CodeValueData retrieveCodeValue(final Long codeValueId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueWritePlatformService.java index 841ead04f..829ba9cbd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueWritePlatformService.java @@ -28,4 +28,4 @@ public interface CodeValueWritePlatformService { CommandProcessingResult updateCodeValue(Long codeValueId, JsonCommand command); CommandProcessingResult deleteCodeValue(Long codeId, Long codeValueId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueWritePlatformServiceJpaRepositoryImpl.java index cc4d88a45..2deffd211 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeValueWritePlatformServiceJpaRepositoryImpl.java @@ -72,8 +72,7 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue this.fromApiJsonDeserializer.validateForCreate(command.json()); final Long codeId = command.entityId(); - final Code code = this.codeRepository.findById(codeId) - .orElseThrow(() -> new CodeNotFoundException(codeId)); + final Code code = this.codeRepository.findById(codeId).orElseThrow(() -> new CodeNotFoundException(codeId)); final CodeValue codeValue = CodeValue.fromJson(code, command); this.codeValueRepository.save(codeValue); @@ -98,8 +97,8 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("code_value")) { final String name = command.stringValueOfParameterNamed("name"); - throw new PlatformDataIntegrityException("error.msg.code.value.duplicate.label", "A code value with lable '" + name - + "' already exists", "name", name); + throw new PlatformDataIntegrityException("error.msg.code.value.duplicate.label", + "A code value with lable '" + name + "' already exists", "name", name); } LOG.error("Error occured.", dve); @@ -146,8 +145,7 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue try { this.context.authenticatedUser(); - final Code code = this.codeRepository.findById(codeId) - .orElseThrow(() -> new CodeNotFoundException(codeId)); + final Code code = this.codeRepository.findById(codeId).orElseThrow(() -> new CodeNotFoundException(codeId)); final CodeValue codeValueToDelete = this.codeValueRepositoryWrapper.findOneWithNotFoundDetection(codeValueId); @@ -163,8 +161,9 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue } catch (final DataIntegrityViolationException dve) { LOG.error("Error occured.", dve); final Throwable realCause = dve.getMostSpecificCause(); - if (realCause.getMessage().contains("code_value")) { throw new PlatformDataIntegrityException("error.msg.codeValue.in.use", - "This code value is in use", codeValueId); } + if (realCause.getMessage().contains("code_value")) { + throw new PlatformDataIntegrityException("error.msg.codeValue.in.use", "This code value is in use", codeValueId); + } throw new PlatformDataIntegrityException("error.msg.code.value.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + dve.getMostSpecificCause().getMessage()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeWritePlatformService.java index 40ec6832c..c9d287ec8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeWritePlatformService.java @@ -28,4 +28,4 @@ public interface CodeWritePlatformService { CommandProcessingResult updateCode(Long codeId, JsonCommand command); CommandProcessingResult deleteCode(Long codeId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java index 686a4654d..9b12cd505 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java @@ -73,8 +73,8 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf } catch (final DataIntegrityViolationException dve) { handleCodeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + } catch (final PersistenceException ee) { + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()); handleCodeDataIntegrityIssues(command, throwable, ee); return CommandProcessingResult.empty(); } @@ -105,8 +105,8 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf } catch (final DataIntegrityViolationException dve) { handleCodeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException ee) { - Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ; + } catch (final PersistenceException ee) { + Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()); handleCodeDataIntegrityIssues(command, throwable, ee); return CommandProcessingResult.empty(); } @@ -133,8 +133,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf } private Code retrieveCodeBy(final Long codeId) { - return this.codeRepository.findById(codeId) - .orElseThrow(() -> new CodeNotFoundException(codeId.toString())); + return this.codeRepository.findById(codeId).orElseThrow(() -> new CodeNotFoundException(codeId.toString())); } /* diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServiceConfigurationApiConstant.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServiceConfigurationApiConstant.java index f517fbb12..95d446dbc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServiceConfigurationApiConstant.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServiceConfigurationApiConstant.java @@ -28,6 +28,5 @@ public class ExternalServiceConfigurationApiConstant { public static final String VALUE = "value"; public static final String EXTERNAL_SERVICE_RESOURCE_NAME = "externalServiceConfiguration"; - protected static final Set EXTERNAL_SERVICE_CONFIGURATION_DATA_PARAMETERS = new HashSet<>(Arrays.asList - (NAME, VALUE)); + protected static final Set EXTERNAL_SERVICE_CONFIGURATION_DATA_PARAMETERS = new HashSet<>(Arrays.asList(NAME, VALUE)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServicesConfigurationApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServicesConfigurationApiResource.java index 3b7688726..bddbbc2bb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServicesConfigurationApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServicesConfigurationApiResource.java @@ -54,10 +54,11 @@ import org.springframework.stereotype.Component; @Path("/externalservice") @Component @Scope("singleton") -@Api(tags = {"External Services"}) +@Api(tags = { "External Services" }) @SwaggerDefinition(tags = { - @Tag(name = "External Services", description = "External Services Configuration related to set of supported configurations for third party services like Amazon S3 and SMTP:\n" + "\n" + "S3 (Amazon S3):\n" + "s3_access_key -\n" + "s3_bucket_name -\n" + "s3_secret_key -\n" + "\n" + "\n" + "SMTP (Email Service):\n" + "username -\n" + "password -\n" + "host -\n" + "port -\n" + "useTLS -") -}) + @Tag(name = "External Services", description = "External Services Configuration related to set of supported configurations for third party services like Amazon S3 and SMTP:\n" + + "\n" + "S3 (Amazon S3):\n" + "s3_access_key -\n" + "s3_bucket_name -\n" + "s3_secret_key -\n" + "\n" + "\n" + + "SMTP (Email Service):\n" + "username -\n" + "password -\n" + "host -\n" + "port -\n" + "useTLS -") }) public class ExternalServicesConfigurationApiResource { private final PlatformSecurityContext context; @@ -86,9 +87,11 @@ public class ExternalServicesConfigurationApiResource { @Path("{servicename}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve External Services Configuration", notes = "Returns a external Service configurations based on the Service Name.\n" + "\n" + "Service Names supported are S3 and SMTP.\n" + "\n" + "Example Requests:\n" + "\n" + "externalservice/SMTP") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ExternalServicesPropertiesData.class)}) - public String retrieveOne(@PathParam("servicename") @ApiParam(value = "servicename") final String serviceName, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve External Services Configuration", notes = "Returns a external Service configurations based on the Service Name.\n" + + "\n" + "Service Names supported are S3 and SMTP.\n" + "\n" + "Example Requests:\n" + "\n" + "externalservice/SMTP") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = ExternalServicesPropertiesData.class) }) + public String retrieveOne(@PathParam("servicename") @ApiParam(value = "servicename") final String serviceName, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(ExternalServiceConfigurationApiConstant.EXTERNAL_SERVICE_RESOURCE_NAME); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final Collection externalServiceNVPs = this.externalServicePropertiesReadPlatformService @@ -101,11 +104,13 @@ public class ExternalServicesConfigurationApiResource { @Path("{servicename}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Update External Service", notes = "Updates the external Service Configuration for a Service Name.\n" + "\n" + "Example: \n" + "\n" + "externalservice/S3") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ExternalServicesConfigurationApiResourceSwagger.PutExternalServiceRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "")}) + @ApiOperation(value = "Update External Service", notes = "Updates the external Service Configuration for a Service Name.\n" + "\n" + + "Example: \n" + "\n" + "externalservice/S3") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ExternalServicesConfigurationApiResourceSwagger.PutExternalServiceRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "") }) public String updateExternalServiceProperties(@PathParam("servicename") @ApiParam(value = "servicename") final String serviceName, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { // ExternalServicesData external = // this.externalServiceReadPlatformService.getExternalServiceDetailsByServiceName(serviceName); final CommandWrapper commandRequest = new CommandWrapperBuilder().updateExternalServiceProperties(serviceName) diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServicesConfigurationApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServicesConfigurationApiResourceSwagger.java index 8db296ed5..e43519104 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServicesConfigurationApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/ExternalServicesConfigurationApiResourceSwagger.java @@ -25,15 +25,18 @@ import io.swagger.annotations.ApiModelProperty; * Created by sanyam on 30/7/17. */ final class ExternalServicesConfigurationApiResourceSwagger { + private ExternalServicesConfigurationApiResourceSwagger() { } @ApiModel(value = "PutExternalServiceRequest") - public static final class PutExternalServiceRequest{ + public static final class PutExternalServiceRequest { + private PutExternalServiceRequest() { } + @ApiModelProperty(example = "test@mifos.org") public String username; @ApiModelProperty(example = "XXXX") diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/GlobalConfigurationApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/GlobalConfigurationApiResource.java index dfdb37c99..6d65348eb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/GlobalConfigurationApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/GlobalConfigurationApiResource.java @@ -59,10 +59,17 @@ import org.springframework.stereotype.Component; @Path("/configurations") @Component @Scope("singleton") -@Api(tags = {"Global Configuration"}) +@Api(tags = { "Global Configuration" }) @SwaggerDefinition(tags = { - @Tag(name = "Global Configuration", description = "Global configuration related to set of supported enable/disable configurations:\n" + "\n" + "maker-checker - defaults to false - if true turns on maker-checker functionality\n" + "reschedule-future-repayments - defaults to false - if true reschedules repayemnts which falls on a non-working day to configured repayment rescheduling rule\n" + "allow-transactions-on-non_workingday - defaults to false - if true allows transactions on non-working days\n" + "reschedule-repayments-on-holidays - defaults to false - if true reschedules repayemnts which falls on a non-working day to defined reschedule date\n" + "allow-transactions-on-holiday - defaults to false - if true allows transactions on holidays\n" + "savings-interest-posting-current-period-end - Set it at the database level before any savings interest is posted. When set as false(default), interest will be posted on the first date of next period. If set as true, interest will be posted on last date of current period. There is no difference in the interest amount posted.\n" + "financial-year-beginning-month - Set it at the database level before any savings interest is posted. Allowed values 1 - 12 (January - December). Interest posting periods are evaluated based on this configuration.\n" + "meetings-mandatory-for-jlg-loans - if set to true, enforces all JLG loans to follow a meeting schedule belonging to either the parent group or Center.") -}) + @Tag(name = "Global Configuration", description = "Global configuration related to set of supported enable/disable configurations:\n" + + "\n" + "maker-checker - defaults to false - if true turns on maker-checker functionality\n" + + "reschedule-future-repayments - defaults to false - if true reschedules repayemnts which falls on a non-working day to configured repayment rescheduling rule\n" + + "allow-transactions-on-non_workingday - defaults to false - if true allows transactions on non-working days\n" + + "reschedule-repayments-on-holidays - defaults to false - if true reschedules repayemnts which falls on a non-working day to defined reschedule date\n" + + "allow-transactions-on-holiday - defaults to false - if true allows transactions on holidays\n" + + "savings-interest-posting-current-period-end - Set it at the database level before any savings interest is posted. When set as false(default), interest will be posted on the first date of next period. If set as true, interest will be posted on last date of current period. There is no difference in the interest amount posted.\n" + + "financial-year-beginning-month - Set it at the database level before any savings interest is posted. Allowed values 1 - 12 (January - December). Interest posting periods are evaluated based on this configuration.\n" + + "meetings-mandatory-for-jlg-loans - if set to true, enforces all JLG loans to follow a meeting schedule belonging to either the parent group or Center.") }) public class GlobalConfigurationApiResource { private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("globalConfiguration")); @@ -77,8 +84,7 @@ public class GlobalConfigurationApiResource { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public GlobalConfigurationApiResource(final PlatformSecurityContext context, - final ConfigurationReadPlatformService readPlatformService, + public GlobalConfigurationApiResource(final PlatformSecurityContext context, final ConfigurationReadPlatformService readPlatformService, final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, @@ -94,9 +100,14 @@ public class GlobalConfigurationApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Global Configuration | Retrieve Global Configuration for surveys", notes = "Returns the list global enable/disable configurations.\n" + "\n" + "Example Requests:\n" + "\n" + "configurations\n\n" + "\n" + "Returns the list global enable/disable survey configurations.\n" + "\n" + "Example Requests:\n" + "\n" + "configurations/survey") - @ApiResponses({@ApiResponse(code = 200, message = "List of example \n response \nsurveys response \ngiven below", response = GlobalConfigurationApiResourceSwagger.GetGlobalConfigurationsResponse.class, responseContainer = "list")}) - public String retrieveConfiguration(@Context final UriInfo uriInfo,@DefaultValue("false") @QueryParam("survey") @ApiParam(value = "survey") final boolean survey) { + @ApiOperation(value = "Retrieve Global Configuration | Retrieve Global Configuration for surveys", notes = "Returns the list global enable/disable configurations.\n" + + "\n" + "Example Requests:\n" + "\n" + "configurations\n\n" + "\n" + + "Returns the list global enable/disable survey configurations.\n" + "\n" + "Example Requests:\n" + "\n" + + "configurations/survey") + @ApiResponses({ + @ApiResponse(code = 200, message = "List of example \n response \nsurveys response \ngiven below", response = GlobalConfigurationApiResourceSwagger.GetGlobalConfigurationsResponse.class, responseContainer = "list") }) + public String retrieveConfiguration(@Context final UriInfo uriInfo, + @DefaultValue("false") @QueryParam("survey") @ApiParam(value = "survey") final boolean survey) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -110,8 +121,10 @@ public class GlobalConfigurationApiResource { @Path("{configId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Global Configuration", notes = "Returns a global enable/disable configurations.\n" + "\n" + "Example Requests:\n" + "\n" + "configurations/1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = GlobalConfigurationApiResourceSwagger.GetGlobalConfigurationsResponse.class)}) + @ApiOperation(value = "Retrieve Global Configuration", notes = "Returns a global enable/disable configurations.\n" + "\n" + + "Example Requests:\n" + "\n" + "configurations/1") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = GlobalConfigurationApiResourceSwagger.GetGlobalConfigurationsResponse.class) }) public String retrieveOne(@PathParam("configId") @ApiParam(value = "configId") final Long configId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -122,15 +135,17 @@ public class GlobalConfigurationApiResource { return this.propertyDataJsonSerializer.serialize(settings, configurationData, this.RESPONSE_DATA_PARAMETERS); } - @PUT @Path("{configId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update Global Configuration", notes = "Updates an enable/disable global configuration item.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = GlobalConfigurationApiResourceSwagger.PutGlobalConfigurationsRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = GlobalConfigurationApiResourceSwagger.PutGlobalConfigurationsResponse.class)}) - public String updateConfiguration(@PathParam("configId") @ApiParam(value = "configId") final Long configId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = GlobalConfigurationApiResourceSwagger.PutGlobalConfigurationsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = GlobalConfigurationApiResourceSwagger.PutGlobalConfigurationsResponse.class) }) + public String updateConfiguration(@PathParam("configId") @ApiParam(value = "configId") final Long configId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .updateGlobalConfiguration(configId) // @@ -141,4 +156,4 @@ public class GlobalConfigurationApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/GlobalConfigurationApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/GlobalConfigurationApiResourceSwagger.java index 52835f9d1..18e4ef8d7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/GlobalConfigurationApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/GlobalConfigurationApiResourceSwagger.java @@ -27,19 +27,24 @@ import org.apache.fineract.infrastructure.configuration.data.GlobalConfiguration * Created by sanyam on 30/7/17. */ final class GlobalConfigurationApiResourceSwagger { + private GlobalConfigurationApiResourceSwagger() { } @ApiModel(value = "GetGlobalConfigurationsResponse") public static final class GetGlobalConfigurationsResponse { - private GetGlobalConfigurationsResponse(){} + + private GetGlobalConfigurationsResponse() {} + public List globalConfiguration; } @ApiModel(value = "PutGlobalConfigurationsRequest") public static final class PutGlobalConfigurationsRequest { - private PutGlobalConfigurationsRequest(){} + + private PutGlobalConfigurationsRequest() {} + @ApiModelProperty(example = "true") public boolean enabled; @ApiModelProperty(example = "2") @@ -48,12 +53,17 @@ final class GlobalConfigurationApiResourceSwagger { @ApiModel(value = "PutGlobalConfigurationsResponse") public static final class PutGlobalConfigurationsResponse { - private PutGlobalConfigurationsResponse(){} - final class PutGlobalConfigurationsResponsechangesSwagger{ + + private PutGlobalConfigurationsResponse() {} + + final class PutGlobalConfigurationsResponsechangesSwagger { + private PutGlobalConfigurationsResponsechangesSwagger() {} + @ApiModelProperty(example = "true") public boolean enabled; } + @ApiModelProperty(example = "4") public Long resourceId; public PutGlobalConfigurationsResponsechangesSwagger changes; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/command/UpdateGlobalConfigurationCommand.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/command/UpdateGlobalConfigurationCommand.java index d85519638..7e190e0e9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/command/UpdateGlobalConfigurationCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/command/UpdateGlobalConfigurationCommand.java @@ -34,4 +34,4 @@ public class UpdateGlobalConfigurationCommand { public Map getGlobalConfiguration() { return this.globalConfiguration; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationData.java index 9ab45cc08..57314a0b9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationData.java @@ -31,4 +31,4 @@ public class GlobalConfigurationData { public GlobalConfigurationData(final List globalConfiguration) { this.globalConfiguration = globalConfiguration; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationDataValidator.java index 04c7723ce..9eb87234c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationDataValidator.java @@ -43,10 +43,9 @@ import org.springframework.stereotype.Component; public class GlobalConfigurationDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set UPDATE_CONFIGURATION_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(GlobalConfigurationApiConstant.localeParamName, - GlobalConfigurationApiConstant.dateFormatParamName, GlobalConfigurationApiConstant.ENABLED, - GlobalConfigurationApiConstant.VALUE, GlobalConfigurationApiConstant.DATE_VALUE)); + private static final Set UPDATE_CONFIGURATION_DATA_PARAMETERS = new HashSet<>(Arrays.asList( + GlobalConfigurationApiConstant.localeParamName, GlobalConfigurationApiConstant.dateFormatParamName, + GlobalConfigurationApiConstant.ENABLED, GlobalConfigurationApiConstant.VALUE, GlobalConfigurationApiConstant.DATE_VALUE)); @Autowired public GlobalConfigurationDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -66,22 +65,17 @@ public class GlobalConfigurationDataValidator { final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.ENABLED, element)) { - final boolean enabledBool = this.fromApiJsonHelper - .extractBooleanNamed(GlobalConfigurationApiConstant.ENABLED, element); - baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.ENABLED).value(enabledBool) - .validateForBooleanValue(); + final boolean enabledBool = this.fromApiJsonHelper.extractBooleanNamed(GlobalConfigurationApiConstant.ENABLED, element); + baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.ENABLED).value(enabledBool).validateForBooleanValue(); } if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.VALUE, element)) { - final Long valueStr = this.fromApiJsonHelper.extractLongNamed(GlobalConfigurationApiConstant.VALUE, - element); - baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.ENABLED).value(valueStr) - .zeroOrPositiveAmount(); + final Long valueStr = this.fromApiJsonHelper.extractLongNamed(GlobalConfigurationApiConstant.VALUE, element); + baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.ENABLED).value(valueStr).zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.DATE_VALUE, element)) { - final LocalDate dateValue = this.fromApiJsonHelper - .extractLocalDateNamed(GlobalConfigurationApiConstant.DATE_VALUE, element); + final LocalDate dateValue = this.fromApiJsonHelper.extractLocalDateNamed(GlobalConfigurationApiConstant.DATE_VALUE, element); baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.DATE_VALUE).value(dateValue).notNull(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationPropertyData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationPropertyData.java old mode 100755 new mode 100644 index dd4428b9a..a893b9373 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationPropertyData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/GlobalConfigurationPropertyData.java @@ -17,6 +17,7 @@ * under the License. */ package org.apache.fineract.infrastructure.configuration.data; + import java.util.Date; /** @@ -39,8 +40,8 @@ public class GlobalConfigurationPropertyData { @SuppressWarnings("unused") private final boolean trapDoor; - public GlobalConfigurationPropertyData(final String name, final boolean enabled, final Long value, final Date dateValue, final String description, - final boolean trapDoor) { + public GlobalConfigurationPropertyData(final String name, final boolean enabled, final Long value, final Date dateValue, + final String description, final boolean trapDoor) { this.name = name; this.enabled = enabled; this.value = value; @@ -89,5 +90,4 @@ public class GlobalConfigurationPropertyData { return this.trapDoor; } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/SMTPCredentialsData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/SMTPCredentialsData.java index d6493b876..2dcdc5f28 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/SMTPCredentialsData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/data/SMTPCredentialsData.java @@ -28,7 +28,8 @@ public class SMTPCredentialsData { private final String fromEmail; private final String fromName; - public SMTPCredentialsData(final String username, final String password, final String host, final String port, final boolean useTLS, String fromEmail, String fromName) { + public SMTPCredentialsData(final String username, final String password, final String host, final String port, final boolean useTLS, + String fromEmail, String fromName) { this.username = username; this.password = password; this.host = host; @@ -59,10 +60,10 @@ public class SMTPCredentialsData { } public String getFromEmail() { - return fromEmail != null ?fromEmail :username; + return fromEmail != null ? fromEmail : username; } public String getFromName() { - return fromName != null ?fromName :username; + return fromName != null ? fromName : username; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ConfigurationDomainService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ConfigurationDomainService.java index 7c66561bb..65663b0c6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ConfigurationDomainService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ConfigurationDomainService.java @@ -94,4 +94,4 @@ public interface ConfigurationDomainService { Integer retrieveOTPLiveTime(); boolean isSubRatesEnabled(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ConfigurationDomainServiceJpa.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ConfigurationDomainServiceJpa.java index e75f2307f..123946654 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ConfigurationDomainServiceJpa.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ConfigurationDomainServiceJpa.java @@ -168,9 +168,7 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService public Integer retrieveFinancialYearBeginningMonth() { final String propertyName = "financial-year-beginning-month"; final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(propertyName); - if (property.isEnabled()) { - return property.getValue().intValue(); - } + if (property.isEnabled()) { return property.getValue().intValue(); } return 1; } @@ -204,9 +202,7 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(propertyName); if (property.isEnabled()) { int value = property.getValue().intValue(); - if (value < 0 || value > 6) { - return defaultValue; - } + if (value < 0 || value > 6) { return defaultValue; } return value; } return defaultValue; @@ -308,9 +304,7 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(propertyName); int defaultValue = 6; int value = property.getValue().intValue(); - if(value < 1) { - return defaultValue; - } + if (value < 1) { return defaultValue; } return value; } @@ -320,9 +314,7 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(propertyName); int defaultValue = 300; int value = property.getValue().intValue(); - if(value < 1) { - return defaultValue; - } + if (value < 1) { return defaultValue; } return value; } @@ -339,9 +331,9 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService @Override public boolean isSubRatesEnabled() { GlobalConfigurationPropertyData configuration = getGlobalConfigurationPropertyData("sub-rates"); - if (configuration==null){ + if (configuration == null) { return false; - }else{ + } else { return configuration.isEnabled(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalService.java index 31b4ac669..aa4188def 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalService.java @@ -17,6 +17,7 @@ * under the License. */ package org.apache.fineract.infrastructure.configuration.domain; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @@ -50,4 +51,4 @@ public class ExternalService extends AbstractPersistableCustom { return this.name; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicePropertiesPK.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicePropertiesPK.java index 104547756..b7d4f53f3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicePropertiesPK.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicePropertiesPK.java @@ -52,15 +52,9 @@ public class ExternalServicePropertiesPK implements Serializable { @Override public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (!(obj instanceof ExternalServicePropertiesPK)) { - return false; - } + if (obj == null) { return false; } + if (obj == this) { return true; } + if (!(obj instanceof ExternalServicePropertiesPK)) { return false; } final ExternalServicePropertiesPK rhs = (ExternalServicePropertiesPK) obj; return new EqualsBuilder() // .append(this.externalServiceId, rhs.externalServiceId) // diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesProperties.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesProperties.java index 25b7b5e67..812508aa8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesProperties.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesProperties.java @@ -50,6 +50,7 @@ public class ExternalServicesProperties { this.value = value; } + public static ExternalServicesProperties fromJson(final ExternalService externalService, final JsonCommand command) { final String name = command.stringValueOfParameterNamed(ExternalservicePropertiesJSONinputParams.NAME.getValue()); final String value = command.stringValueOfParameterNamed(ExternalservicePropertiesJSONinputParams.VALUE.getValue()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesPropertiesRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesPropertiesRepository.java index e5fc15b57..fe82a2a90 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesPropertiesRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesPropertiesRepository.java @@ -27,5 +27,6 @@ public interface ExternalServicesPropertiesRepository extends JpaRepository { @Query("SELECT ep from ExternalServicesProperties ep where ep.externalServicePropertiesPK.name=:name and ep.externalServicePropertiesPK.externalServiceId=:externalServiceId") - ExternalServicesProperties findOneByExternalServicePropertiesPK(@Param("name") String name, @Param("externalServiceId") Long externalServiceId); -} \ No newline at end of file + ExternalServicesProperties findOneByExternalServicePropertiesPK(@Param("name") String name, + @Param("externalServiceId") Long externalServiceId); +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesPropertiesRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesPropertiesRepositoryWrapper.java index fc1d8eb9b..565636e31 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesPropertiesRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ExternalServicesPropertiesRepositoryWrapper.java @@ -33,11 +33,8 @@ public class ExternalServicesPropertiesRepositoryWrapper { } public ExternalServicesProperties findOneByIdAndName(Long id, String name, String externalServiceName) { - final ExternalServicesProperties externalServicesProperties = this.repository - .findOneByExternalServicePropertiesPK(name,id); - if (externalServicesProperties == null) { - throw new ExternalServiceConfigurationNotFoundException(externalServiceName, name); - } + final ExternalServicesProperties externalServicesProperties = this.repository.findOneByExternalServicePropertiesPK(name, id); + if (externalServicesProperties == null) { throw new ExternalServiceConfigurationNotFoundException(externalServiceName, name); } return externalServicesProperties; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationProperty.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationProperty.java old mode 100755 new mode 100644 index 6eb0ed46f..aef7121b2 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationProperty.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationProperty.java @@ -61,8 +61,8 @@ public class GlobalConfigurationProperty extends AbstractPersistableCustom { this.isTrapDoor = false; } - public GlobalConfigurationProperty(final String name, final boolean enabled, final Long value, final Date dateValue ,final String description, - final boolean isTrapDoor) { + public GlobalConfigurationProperty(final String name, final boolean enabled, final Long value, final Date dateValue, + final String description, final boolean isTrapDoor) { this.name = name; this.enabled = enabled; this.value = value; @@ -79,11 +79,10 @@ public class GlobalConfigurationProperty extends AbstractPersistableCustom { return this.value; } - public Date getDateValue(){ + public Date getDateValue() { return this.dateValue; } - public Map update(final JsonCommand command) { final Map actualChanges = new LinkedHashMap<>(7); @@ -106,7 +105,7 @@ public class GlobalConfigurationProperty extends AbstractPersistableCustom { } final String dateValueParamName = "dateValue"; - if(command.isChangeInDateParameterNamed(dateValueParamName, this.dateValue)){ + if (command.isChangeInDateParameterNamed(dateValueParamName, this.dateValue)) { final Date newDateValue = command.dateValueOfParameterNamed(dateValueParamName); actualChanges.put(dateValueParamName, newDateValue); this.dateValue = newDateValue; @@ -114,8 +113,10 @@ public class GlobalConfigurationProperty extends AbstractPersistableCustom { final String passwordPropertyName = "force-password-reset-days"; if (this.name.equalsIgnoreCase(passwordPropertyName)) { - if ((this.enabled == true && command.hasParameter(valueParamName) && (this.value == 0)) || (this.enabled == true - && !command.hasParameter(valueParamName) && (previousValue == 0))) { throw new ForcePasswordResetException(); } + if ((this.enabled == true && command.hasParameter(valueParamName) && (this.value == 0)) + || (this.enabled == true && !command.hasParameter(valueParamName) && (previousValue == 0))) { + throw new ForcePasswordResetException(); + } } return actualChanges; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationRepository.java index faeaffa00..f86b36c7f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationRepository.java @@ -21,8 +21,8 @@ package org.apache.fineract.infrastructure.configuration.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface GlobalConfigurationRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface GlobalConfigurationRepository + extends JpaRepository, JpaSpecificationExecutor { GlobalConfigurationProperty findOneByName(String name); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationRepositoryWrapper.java index 563a5ade9..b874ea54c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/GlobalConfigurationRepositoryWrapper.java @@ -45,8 +45,7 @@ public class GlobalConfigurationRepositoryWrapper { } public GlobalConfigurationProperty findOneWithNotFoundDetection(final Long configId) { - return this.repository.findById(configId) - .orElseThrow(() -> new GlobalConfigurationPropertyNotFoundException(configId)); + return this.repository.findById(configId).orElseThrow(() -> new GlobalConfigurationPropertyNotFoundException(configId)); } public void save(final GlobalConfigurationProperty globalConfigurationProperty) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/exception/GlobalConfigurationPropertyCannotBeModfied.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/exception/GlobalConfigurationPropertyCannotBeModfied.java index 0a8964a66..cbffa5145 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/exception/GlobalConfigurationPropertyCannotBeModfied.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/exception/GlobalConfigurationPropertyCannotBeModfied.java @@ -20,10 +20,11 @@ package org.apache.fineract.infrastructure.configuration.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; -public class GlobalConfigurationPropertyCannotBeModfied extends AbstractPlatformDomainRuleException{ +public class GlobalConfigurationPropertyCannotBeModfied extends AbstractPlatformDomainRuleException { public GlobalConfigurationPropertyCannotBeModfied(final Long configId) { - super("error.msg.configuration.id.not.modifiable", "Configuration identifier `" + configId + "` cannot be modified", new Object[] {configId}); + super("error.msg.configuration.id.not.modifiable", "Configuration identifier `" + configId + "` cannot be modified", + new Object[] { configId }); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/exception/GlobalConfigurationPropertyNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/exception/GlobalConfigurationPropertyNotFoundException.java index 3ac90519b..b92926f16 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/exception/GlobalConfigurationPropertyNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/exception/GlobalConfigurationPropertyNotFoundException.java @@ -33,4 +33,4 @@ public class GlobalConfigurationPropertyNotFoundException extends AbstractPlatfo public GlobalConfigurationPropertyNotFoundException(final Long configId) { super("error.msg.configuration.id.invalid", "Configuration identifier `" + configId + "` does not exist", configId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/handler/UpdateGlobalConfigurationCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/handler/UpdateGlobalConfigurationCommandHandler.java index 990e58a6a..561508e17 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/handler/UpdateGlobalConfigurationCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/handler/UpdateGlobalConfigurationCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateGlobalConfigurationCommandHandler implements NewCommandSource return this.writePlatformService.update(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/serialization/GlobalConfigurationCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/serialization/GlobalConfigurationCommandFromApiJsonDeserializer.java index 31e4e2922..f8b1725fe 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/serialization/GlobalConfigurationCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/serialization/GlobalConfigurationCommandFromApiJsonDeserializer.java @@ -38,8 +38,8 @@ import org.springframework.stereotype.Component; * {@link UpdateGlobalConfigurationCommand}'s. */ @Component -public final class GlobalConfigurationCommandFromApiJsonDeserializer extends - AbstractFromApiJsonDeserializer { +public final class GlobalConfigurationCommandFromApiJsonDeserializer + extends AbstractFromApiJsonDeserializer { /** * The parameters supported for this command. @@ -62,4 +62,4 @@ public final class GlobalConfigurationCommandFromApiJsonDeserializer extends return this.fromApiJsonHelper.fromJson(json, UpdateGlobalConfigurationCommand.class); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ConfigurationReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ConfigurationReadPlatformService.java index 9f35e38fa..e6ae44fec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ConfigurationReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ConfigurationReadPlatformService.java @@ -29,4 +29,4 @@ public interface ConfigurationReadPlatformService { GlobalConfigurationData retrieveGlobalConfiguration(boolean survey); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java old mode 100755 new mode 100644 index e2c55464d..1034401de --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java @@ -66,8 +66,6 @@ public class ConfigurationReadPlatformServiceImpl implements ConfigurationReadPl return new GlobalConfigurationData(globalConfiguration); } - - @Override public GlobalConfigurationPropertyData retrieveGlobalConfiguration(String name) { @@ -75,8 +73,7 @@ public class ConfigurationReadPlatformServiceImpl implements ConfigurationReadPl final String sql = "SELECT c.id, c.name, c.enabled, c.value, c.date_value, c.description, c.is_trap_door FROM " + "c_configuration c where c.name=? order by c.id"; - final GlobalConfigurationPropertyData globalConfiguration = this.jdbcTemplate.queryForObject(sql, this.rm, - new Object[] { name }); + final GlobalConfigurationPropertyData globalConfiguration = this.jdbcTemplate.queryForObject(sql, this.rm, new Object[] { name }); return globalConfiguration; } @@ -94,7 +91,6 @@ public class ConfigurationReadPlatformServiceImpl implements ConfigurationReadPl return globalConfiguration; } - private static final class GlobalConfigurationRowMapper implements RowMapper { @Override @@ -112,4 +108,4 @@ public class ConfigurationReadPlatformServiceImpl implements ConfigurationReadPl } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesConstants.java old mode 100755 new mode 100644 index 6e831c750..f44076201 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesConstants.java @@ -49,6 +49,7 @@ public class ExternalServicesConstants { public static final String NOTIFICATION_FCM_END_POINT = "fcm_end_point"; public static enum ExternalservicePropertiesJSONinputParams { + EXTERNAL_SERVICE_ID("external_service_id"), NAME("name"), VALUE("value"); private final String value; @@ -80,7 +81,9 @@ public class ExternalServicesConstants { } public static enum SMTPJSONinputParams { - USERNAME("username"), PASSWORD("password"), HOST("host"), PORT("port"), USETLS("useTLS"), FROM_EMAIL("fromEmail"), FROM_NAME("fromName"); + + USERNAME("username"), PASSWORD("password"), HOST("host"), PORT("port"), USETLS("useTLS"), FROM_EMAIL("fromEmail"), FROM_NAME( + "fromName"); private final String value; @@ -111,6 +114,7 @@ public class ExternalServicesConstants { } public static enum SMSJSONinputParams { + HASTNAME("host_name"), PORT("port_number"), END_POINT("end_point"), TENANT_APP_KEY("tenant_app_key"); private final String value; @@ -142,6 +146,7 @@ public class ExternalServicesConstants { } public static enum S3JSONinputParams { + S3_ACCESS_KEY("s3_access_key"), S3_BUCKET_NAME("s3_bucket_name"), S3_SECRET_KEY("s3_secret_key"); private final String value; @@ -173,6 +178,7 @@ public class ExternalServicesConstants { } public static enum NotificationJSONinputParams { + SERVER_KEY("server_key"), GCM_END_POINT("gcm_end_point"), FCM_END_POINT("fcm_end_point"); private final String value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesPropertiesReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesPropertiesReadPlatformService.java index f159df833..1faa7551a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesPropertiesReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesPropertiesReadPlatformService.java @@ -37,4 +37,4 @@ public interface ExternalServicesPropertiesReadPlatformService { NotificationConfigurationData getNotificationConfiguration(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesPropertiesReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesPropertiesReadPlatformServiceImpl.java index 12e9d73ee..2b8e5b733 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesPropertiesReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/ExternalServicesPropertiesReadPlatformServiceImpl.java @@ -165,7 +165,8 @@ public class ExternalServicesPropertiesReadPlatformServiceImpl implements Extern final ResultSetExtractor resultSetExtractor = new MessageGatewayDataExtractor(); final String sql = "SELECT esp.name, esp.value FROM c_external_service_properties esp inner join c_external_service es on esp.external_service_id = es.id where es.name = '" + ExternalServicesConstants.SMS_SERVICE_NAME + "'"; - final MessageGatewayConfigurationData messageGatewayConfigurationData = this.jdbcTemplate.query(sql, resultSetExtractor, new Object[] {}); + final MessageGatewayConfigurationData messageGatewayConfigurationData = this.jdbcTemplate.query(sql, resultSetExtractor, + new Object[] {}); return messageGatewayConfigurationData; } @@ -207,11 +208,11 @@ public class ExternalServicesPropertiesReadPlatformServiceImpl implements Extern String gcmEndPoint = null; String fcmEndPoint = null; while (rs.next()) { - if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.NOTIFICATION_SERVER_KEY )) { + if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.NOTIFICATION_SERVER_KEY)) { serverKey = rs.getString("value"); - } else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.NOTIFICATION_GCM_END_POINT )) { + } else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.NOTIFICATION_GCM_END_POINT)) { gcmEndPoint = rs.getString("value"); - } else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.NOTIFICATION_FCM_END_POINT )) { + } else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.NOTIFICATION_FCM_END_POINT)) { fcmEndPoint = rs.getString("value"); } } @@ -219,13 +220,13 @@ public class ExternalServicesPropertiesReadPlatformServiceImpl implements Extern } } - @Override public NotificationConfigurationData getNotificationConfiguration() { final ResultSetExtractor resultSetExtractor = new NotificationDataExtractor(); final String sql = "SELECT esp.name, esp.value FROM c_external_service_properties esp inner join c_external_service es on esp.external_service_id = es.id where es.name = '" + ExternalServicesConstants.NOTIFICATION_SERVICE_NAME + "'"; - final NotificationConfigurationData notificationConfigurationData = this.jdbcTemplate.query(sql, resultSetExtractor, new Object[] {}); + final NotificationConfigurationData notificationConfigurationData = this.jdbcTemplate.query(sql, resultSetExtractor, + new Object[] {}); return notificationConfigurationData; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java index 1eb96820c..4d673c45d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/GlobalConfigurationWritePlatformService.java @@ -24,5 +24,6 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public interface GlobalConfigurationWritePlatformService { CommandProcessingResult update(Long configId, JsonCommand command); + void addSurveyConfig(String name); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java index bf35eda06..c6e1fe96c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java @@ -85,21 +85,16 @@ public class GlobalConfigurationWritePlatformServiceJpaRepositoryImpl implements @Transactional @Override - public void addSurveyConfig(final String name) - { - try{ + public void addSurveyConfig(final String name) { + try { final GlobalConfigurationProperty ppi = GlobalConfigurationProperty.newSurveyConfiguration(name); this.repository.save(ppi); - } - catch (final DataIntegrityViolationException dve) - { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(dve); } } - - /* * Guaranteed to throw an exception no matter what the data integrity issue * is. @@ -111,4 +106,4 @@ public class GlobalConfigurationWritePlatformServiceJpaRepositoryImpl implements throw new PlatformDataIntegrityException("error.msg.globalConfiguration.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + realCause.getMessage()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ApiParameterHelper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ApiParameterHelper.java index 4c7792093..78b140b58 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ApiParameterHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ApiParameterHelper.java @@ -169,7 +169,6 @@ public class ApiParameterHelper { return singleQuote + StringUtils.replace(str, singleQuote, twoSingleQuotes, -1) + singleQuote; } - public static Map asMap(final MultivaluedMap queryParameters) { final Map map = new HashMap<>(queryParameters.size()); @@ -181,4 +180,4 @@ public class ApiParameterHelper { return map; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ApiRequestParameterHelper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ApiRequestParameterHelper.java index a6d7bc3ec..88fb3ec90 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ApiRequestParameterHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ApiRequestParameterHelper.java @@ -62,4 +62,4 @@ public class ApiRequestParameterHelper { return ApiRequestJsonSerializationSettings.from(prettyPrint, responseParameters, template, makerCheckerable, includeJson); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/DateAdapter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/DateAdapter.java index e5bd9e9ef..937ff081f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/DateAdapter.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/DateAdapter.java @@ -27,7 +27,8 @@ import java.time.format.DateTimeFormatter; import java.util.Date; /** - * GSON Serializer for JUL Dates (java.util.Date) in ISO-8601 format using {@link DateTimeFormatter#ISO_INSTANT} (see FINERACT-926). + * GSON Serializer for JUL Dates (java.util.Date) in ISO-8601 format using + * {@link DateTimeFormatter#ISO_INSTANT} (see FINERACT-926). * * @author Michael Vorburger.ch */ @@ -38,9 +39,7 @@ public class DateAdapter implements JsonSerializer { @Override @SuppressWarnings("unused") public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { - if (src == null) { - return null; - } + if (src == null) { return null; } return new JsonPrimitive(formatter.format(src.toInstant())); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JodaLocalDateAdapter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JodaLocalDateAdapter.java index 85acb8d99..0e9381eb5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JodaLocalDateAdapter.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JodaLocalDateAdapter.java @@ -27,8 +27,8 @@ import java.lang.reflect.Type; import org.joda.time.LocalDate; /** - * Serializer for Joda Time {@link LocalDate} that returns the date in array format - * to match previous Jackson functionality. + * Serializer for Joda Time {@link LocalDate} that returns the date in array + * format to match previous Jackson functionality. */ public class JodaLocalDateAdapter implements JsonSerializer { @@ -44,4 +44,4 @@ public class JodaLocalDateAdapter implements JsonSerializer { } return array; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JodaMonthDayAdapter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JodaMonthDayAdapter.java index 3ff290b86..f8d9724a9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JodaMonthDayAdapter.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JodaMonthDayAdapter.java @@ -27,8 +27,8 @@ import java.lang.reflect.Type; import org.joda.time.MonthDay; /** - * Serializer for Joda Time {@link MonthDay} that returns the date in array format - * to match previous Jackson functionality. + * Serializer for Joda Time {@link MonthDay} that returns the date in array + * format to match previous Jackson functionality. */ public class JodaMonthDayAdapter implements JsonSerializer { @@ -43,4 +43,4 @@ public class JodaMonthDayAdapter implements JsonSerializer { } return array; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JsonCommand.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JsonCommand.java index ce6872e27..e61a23960 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JsonCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/JsonCommand.java @@ -68,25 +68,25 @@ public final class JsonCommand { public static JsonCommand from(final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper, final String entityName, final Long resourceId, final Long subresourceId, final Long groupId, final Long clientId, final Long loanId, final Long savingsId, final String transactionId, final String url, final Long productId, - final Long creditBureauId,final Long organisationCreditBureauId) { + final Long creditBureauId, final Long organisationCreditBureauId) { return new JsonCommand(null, jsonCommand, parsedCommand, fromApiJsonHelper, entityName, resourceId, subresourceId, groupId, - clientId, loanId, savingsId, transactionId, url, productId,creditBureauId,organisationCreditBureauId); + clientId, loanId, savingsId, transactionId, url, productId, creditBureauId, organisationCreditBureauId); } public static JsonCommand fromExistingCommand(final Long commandId, final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper, final String entityName, final Long resourceId, final Long subresourceId, - final String url, final Long productId,final Long creditBureauId,final Long organisationCreditBureauId) { + final String url, final Long productId, final Long creditBureauId, final Long organisationCreditBureauId) { return new JsonCommand(commandId, jsonCommand, parsedCommand, fromApiJsonHelper, entityName, resourceId, subresourceId, null, null, - null, null, null, url, productId,creditBureauId,organisationCreditBureauId); + null, null, null, url, productId, creditBureauId, organisationCreditBureauId); } public static JsonCommand fromExistingCommand(final Long commandId, final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper, final String entityName, final Long resourceId, final Long subresourceId, final Long groupId, final Long clientId, final Long loanId, final Long savingsId, final String transactionId, final String url, - final Long productId,Long creditBureauId,final Long organisationCreditBureauId) { + final Long productId, Long creditBureauId, final Long organisationCreditBureauId) { return new JsonCommand(commandId, jsonCommand, parsedCommand, fromApiJsonHelper, entityName, resourceId, subresourceId, groupId, - clientId, loanId, savingsId, transactionId, url, productId,creditBureauId,organisationCreditBureauId); + clientId, loanId, savingsId, transactionId, url, productId, creditBureauId, organisationCreditBureauId); } @@ -94,20 +94,20 @@ public final class JsonCommand { final String jsonCommand = command.fromApiJsonHelper.toJson(parsedCommand); return new JsonCommand(command.commandId, jsonCommand, parsedCommand, command.fromApiJsonHelper, command.entityName, command.resourceId, command.subresourceId, command.groupId, command.clientId, command.loanId, command.savingsId, - command.transactionId, command.url, command.productId,command.creditBureauId,command.organisationCreditBureauId); + command.transactionId, command.url, command.productId, command.creditBureauId, command.organisationCreditBureauId); } - public static JsonCommand fromExistingCommand(JsonCommand command, final JsonElement parsedCommand,final Long clientId) { + public static JsonCommand fromExistingCommand(JsonCommand command, final JsonElement parsedCommand, final Long clientId) { final String jsonCommand = command.fromApiJsonHelper.toJson(parsedCommand); return new JsonCommand(command.commandId, jsonCommand, parsedCommand, command.fromApiJsonHelper, command.entityName, command.resourceId, command.subresourceId, command.groupId, clientId, command.loanId, command.savingsId, - command.transactionId, command.url, command.productId,command.creditBureauId,command.organisationCreditBureauId); + command.transactionId, command.url, command.productId, command.creditBureauId, command.organisationCreditBureauId); } public JsonCommand(final Long commandId, final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper, final String entityName, final Long resourceId, final Long subresourceId, final Long groupId, final Long clientId, final Long loanId, final Long savingsId, final String transactionId, final String url, - final Long productId,final Long creditBureauId, final Long organisationCreditBureauId) { + final Long productId, final Long creditBureauId, final Long organisationCreditBureauId) { this.commandId = commandId; this.jsonCommand = jsonCommand; @@ -123,15 +123,16 @@ public final class JsonCommand { this.transactionId = transactionId; this.url = url; this.productId = productId; - this.creditBureauId=creditBureauId; - this.organisationCreditBureauId=organisationCreditBureauId; + this.creditBureauId = creditBureauId; + this.organisationCreditBureauId = organisationCreditBureauId; } public static JsonCommand fromJsonElement(final Long resourceId, final JsonElement parsedCommand) { return new JsonCommand(resourceId, parsedCommand); } - public static JsonCommand fromJsonElement(final Long resourceId, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper) { + public static JsonCommand fromJsonElement(final Long resourceId, final JsonElement parsedCommand, + final FromJsonHelper fromApiJsonHelper) { return new JsonCommand(resourceId, parsedCommand, fromApiJsonHelper); } @@ -150,8 +151,8 @@ public final class JsonCommand { this.transactionId = null; this.url = null; this.productId = null; - this.creditBureauId=null; - this.organisationCreditBureauId=null; + this.creditBureauId = null; + this.organisationCreditBureauId = null; } public JsonCommand(final Long resourceId, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper) { @@ -169,8 +170,8 @@ public final class JsonCommand { this.transactionId = null; this.url = null; this.productId = null; - this.creditBureauId=null; - this.organisationCreditBureauId=null; + this.creditBureauId = null; + this.organisationCreditBureauId = null; } public Long getOrganisationCreditBureauId() { @@ -190,9 +191,7 @@ public final class JsonCommand { } public JsonElement jsonElement(final String paramName) { - if (this.parsedCommand.getAsJsonObject().has(paramName)) { - return this.parsedCommand.getAsJsonObject().get(paramName); - } + if (this.parsedCommand.getAsJsonObject().has(paramName)) { return this.parsedCommand.getAsJsonObject().get(paramName); } return null; } @@ -372,7 +371,7 @@ public final class JsonCommand { return isChangeInLocalDateParameterNamed(parameterName, localDate); } - public boolean isChangeInTimeParameterNamed(final String parameterName, final Date existingValue,final String timeFormat) { + public boolean isChangeInTimeParameterNamed(final String parameterName, final Date existingValue, final String timeFormat) { LocalDateTime time = null; if (existingValue != null) { DateTimeFormatter timeFormtter = DateTimeFormat.forPattern(timeFormat); @@ -402,6 +401,7 @@ public final class JsonCommand { public LocalDate localDateValueOfParameterNamed(final String parameterName) { return this.fromApiJsonHelper.extractLocalDateNamed(parameterName, this.parsedCommand); } + public LocalDateTime localTimeValueOfParameterNamed(final String parameterName) { return this.fromApiJsonHelper.extractLocalTimeNamed(parameterName, this.parsedCommand); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ParameterListExclusionStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ParameterListExclusionStrategy.java index 40bed7215..22d5a03b8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ParameterListExclusionStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ParameterListExclusionStrategy.java @@ -44,4 +44,4 @@ public class ParameterListExclusionStrategy implements ExclusionStrategy { public boolean shouldSkipClass(final Class clazz) { return false; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ParameterListInclusionStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ParameterListInclusionStrategy.java index 9eb70e8f6..78e5b10d5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ParameterListInclusionStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/api/ParameterListInclusionStrategy.java @@ -40,4 +40,4 @@ public class ParameterListInclusionStrategy implements ExclusionStrategy { public boolean shouldSkipClass(final Class clazz) { return false; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/AbstractApplicationConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/AbstractApplicationConfiguration.java index c846b3279..c9eef4fc0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/AbstractApplicationConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/AbstractApplicationConfiguration.java @@ -45,16 +45,13 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; * and MariaDB4j (because those differ in the subclasses). */ @Configuration -@Import({ WebXmlConfiguration.class, WebXmlOauthConfiguration.class, WebFrontEndConfiguration.class, - MessagingConfiguration.class, WebTwoFactorXmlConfiguration.class }) +@Import({ WebXmlConfiguration.class, WebXmlOauthConfiguration.class, WebFrontEndConfiguration.class, MessagingConfiguration.class, + WebTwoFactorXmlConfiguration.class }) @ImportResource({ "classpath*:META-INF/spring/appContext.xml" }) -@PropertySource(value="classpath:META-INF/spring/jdbc.properties") -@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - FlywayAutoConfiguration.class, - GsonAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class}) +@PropertySource(value = "classpath:META-INF/spring/jdbc.properties") +@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, FlywayAutoConfiguration.class, GsonAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class }) @EnableWebSecurity @EnableTransactionManagement public abstract class AbstractApplicationConfiguration { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/ApplicationExitUtil.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/ApplicationExitUtil.java index 5c34994a9..a23c129e7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/ApplicationExitUtil.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/ApplicationExitUtil.java @@ -26,9 +26,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ConfigurableApplicationContext; - public abstract class ApplicationExitUtil { + private final static Logger LOG = LoggerFactory.getLogger(ApplicationExitUtil.class); + private ApplicationExitUtil() {} public static void waitForKeyPressToCleanlyExit(ConfigurableApplicationContext ctx) throws IOException { @@ -46,4 +47,4 @@ public abstract class ApplicationExitUtil { ctx.stop(); ctx.close(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/JDBCDriverConfig.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/JDBCDriverConfig.java index 2a216f856..95ea516fe 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/JDBCDriverConfig.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/JDBCDriverConfig.java @@ -35,7 +35,8 @@ public class JDBCDriverConfig { private String protocol; private String subProtocol; - @Autowired ApplicationContext context; + @Autowired + ApplicationContext context; @PostConstruct protected void init() { @@ -50,8 +51,8 @@ public class JDBCDriverConfig { } public String constructProtocol(String schemaServer, String schemaServerPort, String schemaName) { - final String url = new StringBuilder(protocol).append(":").append(subProtocol).append("://").append(schemaServer).append(':').append(schemaServerPort) - .append('/').append(schemaName).toString(); + final String url = new StringBuilder(protocol).append(":").append(subProtocol).append("://").append(schemaServer).append(':') + .append(schemaServerPort).append('/').append(schemaName).toString(); return url; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebFrontEndConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebFrontEndConfiguration.java index 06c6b9741..ef1e0808c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebFrontEndConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebFrontEndConfiguration.java @@ -27,15 +27,12 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebFrontEndConfiguration implements WebMvcConfigurer { - private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { - "classpath:/static/", "classpath:/public/" - }; + private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/static/", "classpath:/public/" }; - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - if (!registry.hasMappingForPattern("/**")) { - registry.addResourceHandler("/**").addResourceLocations( - CLASSPATH_RESOURCE_LOCATIONS); + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + if (!registry.hasMappingForPattern("/**")) { + registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS); + } } - } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebTwoFactorXmlConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebTwoFactorXmlConfiguration.java index fe570bdbd..086ffe521 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebTwoFactorXmlConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebTwoFactorXmlConfiguration.java @@ -23,13 +23,13 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; - @Configuration public class WebTwoFactorXmlConfiguration { @Bean public FilterRegistrationBean twoFactorFilterBean(TwoFactorAuthenticationFilter filter) { - FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter); + FilterRegistrationBean registrationBean = new FilterRegistrationBean( + filter); registrationBean.setEnabled(false); return registrationBean; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebXmlConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebXmlConfiguration.java index 50a2584fb..5b46a0033 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebXmlConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebXmlConfiguration.java @@ -31,8 +31,8 @@ import org.springframework.context.annotation.Profile; /** * This Configuration replaces what formerly was in web.xml. * - * @see #howto-convert-an-existing-application-to-spring-boot + * @see #howto-convert-an-existing-application-to-spring-boot */ @Configuration @Profile("basicauth") diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebXmlOauthConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebXmlOauthConfiguration.java index 792d8d2d4..6338789ed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebXmlOauthConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/boot/WebXmlOauthConfiguration.java @@ -26,10 +26,11 @@ import org.springframework.context.annotation.Profile; import org.springframework.web.servlet.DispatcherServlet; /** - * This Configuration replaces what formerly was in web.xml. Beans are loaded only when "oauth" Profile is enabled. + * This Configuration replaces what formerly was in web.xml. Beans are loaded + * only when "oauth" Profile is enabled. * - * @see #howto-convert-an-existing-application-to-spring-boot + * @see #howto-convert-an-existing-application-to-spring-boot */ @Configuration @Profile("oauth") @@ -43,8 +44,8 @@ public class WebXmlOauthConfiguration { jerseyServletRegistration.setName("jersey-servlet"); jerseyServletRegistration.setLoadOnStartup(1); jerseyServletRegistration.addInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true"); -// jerseyServletRegistration.addInitParameter("com.sun.jersey.spi.container.ContainerResponseFilters", -// ResponseCorsFilter.class.getName()); + // jerseyServletRegistration.addInitParameter("com.sun.jersey.spi.container.ContainerResponseFilters", + // ResponseCorsFilter.class.getName()); jerseyServletRegistration.addInitParameter("com.sun.jersey.config.feature.DisableWADL", "true"); // debugging for development: // jerseyServletRegistration.addInitParameter("com.sun.jersey.spi.container.ContainerRequestFilters", diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiErrorMessageArg.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiErrorMessageArg.java index ff374162a..a4fd77b7a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiErrorMessageArg.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiErrorMessageArg.java @@ -44,4 +44,4 @@ public class ApiErrorMessageArg { public void setValue(final Object value) { this.value = value; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiGlobalErrorResponse.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiGlobalErrorResponse.java index 96c43f21f..15b972037 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiGlobalErrorResponse.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiGlobalErrorResponse.java @@ -83,8 +83,8 @@ public class ApiGlobalErrorResponse { public static ApiGlobalErrorResponse unAuthorized(final String defaultUserMessage) { final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("403"); - globalErrorResponse - .setDeveloperMessage("The user associated with credentials passed on this request does not have sufficient privileges to perform this action."); + globalErrorResponse.setDeveloperMessage( + "The user associated with credentials passed on this request does not have sufficient privileges to perform this action."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.not.authorized"); globalErrorResponse.setDefaultUserMessage("Insufficient privileges to perform this action."); @@ -238,4 +238,4 @@ public class ApiGlobalErrorResponse { public void setUserMessageGlobalisationCode(final String userMessageGlobalisationCode) { this.userMessageGlobalisationCode = userMessageGlobalisationCode; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiParameterError.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiParameterError.java index 75a7ae0e2..5535c0e2a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiParameterError.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/ApiParameterError.java @@ -82,7 +82,8 @@ public class ApiParameterError { // } - private ApiParameterError(final String globalisationMessageCode, final String defaultUserMessage, final Object[] defaultUserMessageArgs) { + private ApiParameterError(final String globalisationMessageCode, final String defaultUserMessage, + final Object[] defaultUserMessageArgs) { this.userMessageGlobalisationCode = globalisationMessageCode; this.developerMessage = defaultUserMessage; this.defaultUserMessage = defaultUserMessage; @@ -90,7 +91,7 @@ public class ApiParameterError { final List messageArgs = new ArrayList<>(); if (defaultUserMessageArgs != null) { for (final Object object : defaultUserMessageArgs) { - if(object instanceof Date){ + if (object instanceof Date) { final String formattedDate = dateFormatter.format(object); messageArgs.add(ApiErrorMessageArg.from(formattedDate)); } else { @@ -150,4 +151,4 @@ public class ApiParameterError { public void setArgs(final List args) { this.args = args; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/CommandProcessingResult.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/CommandProcessingResult.java index d9ce6fb19..f45690284 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/CommandProcessingResult.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/CommandProcessingResult.java @@ -46,8 +46,9 @@ public class CommandProcessingResult implements Serializable { private Boolean rollbackTransaction; public static CommandProcessingResult fromDetails(final Long commandId, final Long officeId, final Long groupId, final Long clientId, - final Long loanId, final Long savingsId, final String resourceIdentifier, final Long entityId, final Long gsimId, final Long glimId, final String transactionId, - final Map changes, final Long productId, final Boolean rollbackTransaction, final Long subResourceId) { + final Long loanId, final Long savingsId, final String resourceIdentifier, final Long entityId, final Long gsimId, + final Long glimId, final String transactionId, final Map changes, final Long productId, + final Boolean rollbackTransaction, final Long subResourceId) { return new CommandProcessingResult(commandId, officeId, groupId, clientId, loanId, savingsId, resourceIdentifier, entityId, transactionId, changes, productId, gsimId, glimId, rollbackTransaction, subResourceId); } @@ -99,14 +100,15 @@ public class CommandProcessingResult implements Serializable { this.transactionId = null; this.changes = new HashMap<>(); this.productId = null; - this.gsimId=null; - this.glimId=null; + this.gsimId = null; + this.glimId = null; this.subResourceId = null; } private CommandProcessingResult(final Long commandId, final Long officeId, final Long groupId, final Long clientId, final Long loanId, final Long savingsId, final String resourceIdentifier, final Long resourceId, final String transactionId, - final Map changesOnly, final Long productId, final Long gsimId, final Long glimId, Boolean rollbackTransaction, final Long subResourceId) { + final Map changesOnly, final Long productId, final Long gsimId, final Long glimId, Boolean rollbackTransaction, + final Long subResourceId) { this.commandId = commandId; this.officeId = officeId; this.groupId = groupId; @@ -118,13 +120,14 @@ public class CommandProcessingResult implements Serializable { this.changes = changesOnly; this.transactionId = transactionId; this.productId = productId; - this.gsimId=gsimId; - this.glimId=glimId; + this.gsimId = gsimId; + this.glimId = glimId; this.rollbackTransaction = rollbackTransaction; this.subResourceId = subResourceId; } - protected CommandProcessingResult(final Long resourceId, final Long officeId, final Long commandId, final Map changesOnly) { + protected CommandProcessingResult(final Long resourceId, final Long officeId, final Long commandId, + final Map changesOnly) { if (resourceId != null) { this.resourceIdentifier = resourceId.toString(); } else { @@ -140,8 +143,8 @@ public class CommandProcessingResult implements Serializable { this.commandId = commandId; this.changes = changesOnly; this.productId = null; - this.gsimId=null; - this.glimId=null; + this.gsimId = null; + this.glimId = null; this.subResourceId = null; } @@ -217,4 +220,4 @@ public class CommandProcessingResult implements Serializable { public Long getSubResourceId() { return subResourceId; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/CommandProcessingResultBuilder.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/CommandProcessingResultBuilder.java index 335c31a3f..606a6d2e6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/CommandProcessingResultBuilder.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/CommandProcessingResultBuilder.java @@ -44,8 +44,8 @@ public class CommandProcessingResultBuilder { public CommandProcessingResult build() { return CommandProcessingResult.fromDetails(this.commandId, this.officeId, this.groupId, this.clientId, this.loanId, this.savingsId, - this.resourceIdentifier, this.entityId, this.gsimId, this.glimId, this.transactionId, this.changes, this.productId, this.rollbackTransaction, - this.subEntityId); + this.resourceIdentifier, this.entityId, this.gsimId, this.glimId, this.transactionId, this.changes, this.productId, + this.rollbackTransaction, this.subEntityId); } public CommandProcessingResultBuilder withCommandId(final Long withCommandId) { @@ -123,4 +123,4 @@ public class CommandProcessingResultBuilder { return this; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/DataValidatorBuilder.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/DataValidatorBuilder.java index f9200e6ad..ac430b5e5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/DataValidatorBuilder.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/DataValidatorBuilder.java @@ -161,8 +161,8 @@ public class DataValidatorBuilder { if (!trueOfFalseFieldProvided && !this.ignoreNullValue) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".must.be.true.or.false"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " must be set as true or false."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be set as true or false."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter); this.dataValidationErrors.add(error); @@ -170,25 +170,21 @@ public class DataValidatorBuilder { return this; } + public DataValidatorBuilder trueOrFalseRequired(final Object trueOfFalseField) { - public DataValidatorBuilder trueOrFalseRequired(final Object trueOfFalseField) - { - - if(trueOfFalseField!=null) - { - if(!trueOfFalseField.toString().equalsIgnoreCase("true") && !trueOfFalseField.toString().equalsIgnoreCase("false")) - { - final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") - .append(this.parameter).append(".must.be.true.or.false"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " must be set as true or false."); - final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), this.parameter); - this.dataValidationErrors.add(error); + if (trueOfFalseField != null) { + if (!trueOfFalseField.toString().equalsIgnoreCase("true") && !trueOfFalseField.toString().equalsIgnoreCase("false")) { + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".must.be.true.or.false"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be set as true or false."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter); + this.dataValidationErrors.add(error); } } - return this; + return this; } public DataValidatorBuilder notNull() { @@ -204,8 +200,8 @@ public class DataValidatorBuilder { } validationErrorCode.append(".cannot.be.blank"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(realParameterName).append( - " is mandatory."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(realParameterName) + .append(" is mandatory."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), realParameterName, this.arrayIndex); this.dataValidationErrors.add(error); @@ -227,8 +223,8 @@ public class DataValidatorBuilder { } validationErrorCode.append(".cannot.be.blank"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(realParameterName).append( - " is mandatory."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(realParameterName) + .append(" is mandatory."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), realParameterName, this.arrayIndex); this.dataValidationErrors.add(error); @@ -361,8 +357,8 @@ public class DataValidatorBuilder { if (number.compareTo(BigDecimal.ZERO) <= 0) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".not.greater.than.zero"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " must be greater than 0."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be greater than 0."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, number, 0); this.dataValidationErrors.add(error); @@ -382,8 +378,8 @@ public class DataValidatorBuilder { if (number.compareTo(BigDecimal.ZERO) < 0) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".not.zero.or.greater"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " must be greater than or equal to 0."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be greater than or equal to 0."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, number, 0); this.dataValidationErrors.add(error); @@ -403,8 +399,8 @@ public class DataValidatorBuilder { if (number < 0) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".not.zero.or.greater"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " must be zero or greater."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be zero or greater."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, number, 0); this.dataValidationErrors.add(error); @@ -424,8 +420,8 @@ public class DataValidatorBuilder { if (number < 1) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".not.greater.than.zero"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " must be greater than 0."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be greater than 0."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, number, 0); this.dataValidationErrors.add(error); @@ -517,8 +513,8 @@ public class DataValidatorBuilder { if (number < 1) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".not.greater.than.zero"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " must be greater than 0."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be greater than 0."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, number, 0); this.dataValidationErrors.add(error); @@ -538,8 +534,8 @@ public class DataValidatorBuilder { if (number < 0) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".not.equal.or.greater.than.zero"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " must be equal or greater than 0."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be equal or greater than 0."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, number, 0); this.dataValidationErrors.add(error); @@ -591,8 +587,8 @@ public class DataValidatorBuilder { if (ObjectUtils.isEmpty(array)) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".cannot.be.empty"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " cannot be empty. You must select at least one."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" cannot be empty. You must select at least one."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter); this.dataValidationErrors.add(error); @@ -607,8 +603,8 @@ public class DataValidatorBuilder { if (this.value != null && !array.iterator().hasNext()) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".cannot.be.empty"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " cannot be empty. You must select at least one."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" cannot be empty. You must select at least one."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter); this.dataValidationErrors.add(error); @@ -635,8 +631,8 @@ public class DataValidatorBuilder { } if (!hasData) { - final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append( - ".no.parameters.for.update"); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource) + .append(".no.parameters.for.update"); final StringBuilder defaultEnglishMessage = new StringBuilder("No parameters passed for update."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), "id"); @@ -648,8 +644,8 @@ public class DataValidatorBuilder { public DataValidatorBuilder inValidValue(final String parameterValueCode, final Object invalidValue) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".invalid.").append(parameterValueCode); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " has an invalid value."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" has an invalid value."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, invalidValue); this.dataValidationErrors.add(error); @@ -662,7 +658,9 @@ public class DataValidatorBuilder { if (this.value == null && parameterValue != null) { return this; } if (this.value != null && StringUtils.isBlank(this.value.toString()) && parameterValue != null - && StringUtils.isNotBlank(parameterValue.toString())) { return this; } + && StringUtils.isNotBlank(parameterValue.toString())) { + return this; + } final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".cannot.also.be.provided.when.").append(parameterName).append(".is.populated"); @@ -680,7 +678,9 @@ public class DataValidatorBuilder { if (this.value == null && parameterValue != null) { return this; } if (this.value != null && StringUtils.isBlank(this.value.toString()) && parameterValue != null - && StringUtils.isNotBlank(parameterValue.toString())) { return this; } + && StringUtils.isNotBlank(parameterValue.toString())) { + return this; + } final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".cannot.also.be.provided.when.").append(parameterName).append(".is.") @@ -894,8 +894,8 @@ public class DataValidatorBuilder { if (validationErr) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".value.should.true.or.false"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " value should true or false "); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" value should true or false "); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, this.value); this.dataValidationErrors.add(error); @@ -937,8 +937,8 @@ public class DataValidatorBuilder { if (this.value != null && !CronExpression.isValidExpression(this.value.toString().trim())) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") .append(this.parameter).append(".invalid"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( - " value is not a valid cron expression"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" value is not a valid cron expression"); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, this.value); this.dataValidationErrors.add(error); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/EnumOptionData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/EnumOptionData.java index 4b074e4fd..8303af4fd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/EnumOptionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/EnumOptionData.java @@ -52,20 +52,14 @@ public class EnumOptionData implements Serializable { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof EnumOptionData)) { - return false; - } + if (this == o) { return true; } + if (!(o instanceof EnumOptionData)) { return false; } EnumOptionData that = (EnumOptionData) o; - return id.equals(that.id) && - code.equals(that.code) && - value.equals(that.value); + return id.equals(that.id) && code.equals(that.code) && value.equals(that.value); } @Override public int hashCode() { return Objects.hash(id, code, value); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/PaginationParameters.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/PaginationParameters.java index 078b658dc..f80eaf587 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/PaginationParameters.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/PaginationParameters.java @@ -126,7 +126,7 @@ public class PaginationParameters { return sql.toString(); } - public String paginationSql(){ + public String paginationSql() { final StringBuilder sqlBuilder = new StringBuilder(50); if (this.isOrderByRequested()) { sqlBuilder.append(' ').append(this.orderBySql()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/PaginationParametersDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/PaginationParametersDataValidator.java index 0e08cfd23..9adc1e474 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/PaginationParametersDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/data/PaginationParametersDataValidator.java @@ -31,29 +31,30 @@ public class PaginationParametersDataValidator { private final Set sortOrderValues = new HashSet<>(Arrays.asList("ASC", "DESC")); - public void validateParameterValues(PaginationParameters parameters, final Set supportedOrdeByValues, final String resourceName) { + public void validateParameterValues(PaginationParameters parameters, final Set supportedOrdeByValues, + final String resourceName) { final List dataValidationErrors = new ArrayList<>(); - if (parameters.isOrderByRequested() && !supportedOrdeByValues.contains(parameters.getOrderBy())) { - final String defaultUserMessage = "The orderBy value '" + parameters.getOrderBy() - + "' is not supported. The supported orderBy values are " + supportedOrdeByValues.toString(); - final ApiParameterError error = ApiParameterError.parameterError("validation.msg." + resourceName - + ".orderBy.value.is.not.supported", defaultUserMessage, "orderBy", parameters.getOrderBy(), - supportedOrdeByValues.toString()); - dataValidationErrors.add(error); - } + if (parameters.isOrderByRequested() && !supportedOrdeByValues.contains(parameters.getOrderBy())) { + final String defaultUserMessage = "The orderBy value '" + parameters.getOrderBy() + + "' is not supported. The supported orderBy values are " + supportedOrdeByValues.toString(); + final ApiParameterError error = ApiParameterError.parameterError( + "validation.msg." + resourceName + ".orderBy.value.is.not.supported", defaultUserMessage, "orderBy", + parameters.getOrderBy(), supportedOrdeByValues.toString()); + dataValidationErrors.add(error); + } - if (parameters.isSortOrderProvided() && !sortOrderValues.contains(parameters.getSortOrder().toUpperCase())) { - final String defaultUserMessage = "The sortOrder value '" + parameters.getSortOrder() - + "' is not supported. The supported sortOrder values are " + sortOrderValues.toString(); - final ApiParameterError error = ApiParameterError.parameterError("validation.msg." + resourceName - + ".sortOrder.value.is.not.supported", defaultUserMessage, "sortOrder", parameters.getSortOrder(), - sortOrderValues.toString()); - dataValidationErrors.add(error); - } + if (parameters.isSortOrderProvided() && !sortOrderValues.contains(parameters.getSortOrder().toUpperCase())) { + final String defaultUserMessage = "The sortOrder value '" + parameters.getSortOrder() + + "' is not supported. The supported sortOrder values are " + sortOrderValues.toString(); + final ApiParameterError error = ApiParameterError.parameterError( + "validation.msg." + resourceName + ".sortOrder.value.is.not.supported", defaultUserMessage, "sortOrder", + parameters.getSortOrder(), sortOrderValues.toString()); + dataValidationErrors.add(error); + } throwExceptionIfValidationWarningsExist(dataValidationErrors); } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/AbstractAuditableCustom.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/AbstractAuditableCustom.java index db0cf9887..c674e9cf0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/AbstractAuditableCustom.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/AbstractAuditableCustom.java @@ -34,7 +34,8 @@ import org.springframework.data.jpa.domain.AbstractAuditable; /** * A custom copy of {@link AbstractAuditable} to override the column names used - * on database. It also uses Instant instead of LocalDateTime for created and modified. + * on database. It also uses Instant instead of LocalDateTime for created and + * modified. * * Abstract base class for auditable entities. Stores the audit values in * persistent fields. @@ -49,7 +50,7 @@ public abstract class AbstractAuditableCustom extends AbstractPersistableCustom private static final long serialVersionUID = 141481953116476081L; - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "createdby_id") private AppUser createdBy; @@ -57,7 +58,7 @@ public abstract class AbstractAuditableCustom extends AbstractPersistableCustom @Temporal(TemporalType.TIMESTAMP) private Date createdDate; - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "lastmodifiedby_id") private AppUser lastModifiedBy; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/AbstractPersistableCustom.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/AbstractPersistableCustom.java index c7e36633a..3b7976df7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/AbstractPersistableCustom.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/AbstractPersistableCustom.java @@ -29,13 +29,14 @@ import org.springframework.data.domain.Persistable; /** * Abstract base class for entities. * - * Inspired by {@link org.springframework.data.jpa.domain.AbstractPersistable}, but - * Id is always Long (and this class thus does not require generic parameterization), - * and auto-generation is of strategy {@link javax.persistence.GenerationType#IDENTITY}. + * Inspired by {@link org.springframework.data.jpa.domain.AbstractPersistable}, + * but Id is always Long (and this class thus does not require generic + * parameterization), and auto-generation is of strategy + * {@link javax.persistence.GenerationType#IDENTITY}. * - * The {@link #equals(Object)} and {@link #hashCode()} methods are NOT implemented here, - * which is untypical for JPA (it's usually implemented based on the Id), because - * "we end up with issues on OpenJPA" (TODO clarify this). + * The {@link #equals(Object)} and {@link #hashCode()} methods are NOT + * implemented here, which is untypical for JPA (it's usually implemented based + * on the Id), because "we end up with issues on OpenJPA" (TODO clarify this). */ @MappedSuperclass public abstract class AbstractPersistableCustom implements Persistable, Serializable { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/Base64EncodedImage.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/Base64EncodedImage.java index 2f6e17f03..eb99e1713 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/Base64EncodedImage.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/Base64EncodedImage.java @@ -35,4 +35,4 @@ public class Base64EncodedImage { public String getFileExtension() { return this.fileExtension; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/EmailDetail.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/EmailDetail.java index 83cad8ba5..f25fa6c1f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/EmailDetail.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/EmailDetail.java @@ -47,4 +47,4 @@ public class EmailDetail { public String getAddress() { return this.address; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/FineractPlatformTenant.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/FineractPlatformTenant.java index fb1c0c3fb..33f089f09 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/FineractPlatformTenant.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/FineractPlatformTenant.java @@ -26,8 +26,8 @@ public class FineractPlatformTenant { private final String timezoneId; private final FineractPlatformTenantConnection connection; - public FineractPlatformTenant(final Long id, final String tenantIdentifier, final String name, - final String timezoneId, final FineractPlatformTenantConnection connection) { + public FineractPlatformTenant(final Long id, final String tenantIdentifier, final String name, final String timezoneId, + final FineractPlatformTenantConnection connection) { this.id = id; this.tenantIdentifier = tenantIdentifier; this.name = name; @@ -54,4 +54,4 @@ public class FineractPlatformTenant { public FineractPlatformTenantConnection getConnection() { return connection; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/FineractPlatformTenantConnection.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/FineractPlatformTenantConnection.java index 54395765c..fac355480 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/FineractPlatformTenantConnection.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/FineractPlatformTenantConnection.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.infrastructure.core.domain; - /** * Holds Tenant's DB server connection connection details. */ @@ -47,13 +46,15 @@ public class FineractPlatformTenantConnection { private final int maxIntervalBetweenRetries; private final boolean testOnBorrow; - public FineractPlatformTenantConnection(final Long connectionId,final String schemaName, String schemaServer,final String schemaServerPort,final String schemaUsername,final String schemaPassword, - final boolean autoUpdateEnabled,final int initialSize,final long validationInterval,final boolean removeAbandoned,final int removeAbandonedTimeout, - final boolean logAbandoned,final int abandonWhenPercentageFull,final int maxActive,final int minIdle,final int maxIdle,final int suspectTimeout, - final int timeBetweenEvictionRunsMillis,final int minEvictableIdleTimeMillis,final int maxRetriesOnDeadlock,final int maxIntervalBetweenRetries,final boolean tesOnBorrow) { + public FineractPlatformTenantConnection(final Long connectionId, final String schemaName, String schemaServer, + final String schemaServerPort, final String schemaUsername, final String schemaPassword, final boolean autoUpdateEnabled, + final int initialSize, final long validationInterval, final boolean removeAbandoned, final int removeAbandonedTimeout, + final boolean logAbandoned, final int abandonWhenPercentageFull, final int maxActive, final int minIdle, final int maxIdle, + final int suspectTimeout, final int timeBetweenEvictionRunsMillis, final int minEvictableIdleTimeMillis, + final int maxRetriesOnDeadlock, final int maxIntervalBetweenRetries, final boolean tesOnBorrow) { this.connectionId = connectionId; - this.schemaName =schemaName; + this.schemaName = schemaName; this.schemaServer = schemaServer; this.schemaServerPort = schemaServerPort; this.schemaUsername = schemaUsername; @@ -73,7 +74,7 @@ public class FineractPlatformTenantConnection { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; this.maxRetriesOnDeadlock = maxRetriesOnDeadlock; this.maxIntervalBetweenRetries = maxIntervalBetweenRetries; - this.testOnBorrow=tesOnBorrow; + this.testOnBorrow = tesOnBorrow; } public String getSchemaServer() { @@ -163,6 +164,7 @@ public class FineractPlatformTenantConnection { public String getSchemaName() { return schemaName; } + @Override public String toString() { return this.schemaName + ":" + this.schemaServer + ":" + this.schemaServerPort; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/JdbcSupport.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/JdbcSupport.java index 89e96afff..cbb3bfae3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/JdbcSupport.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/JdbcSupport.java @@ -62,6 +62,7 @@ public class JdbcSupport { } return localDate; } + public static LocalTime getLocalTime(final ResultSet rs, final String columnName) throws SQLException { LocalTime localTime = null; final Date timeValue = rs.getTime(columnName); @@ -70,6 +71,7 @@ public class JdbcSupport { } return localTime; } + public static Long getLong(final ResultSet rs, final String columnName) throws SQLException { return (Long) JdbcUtils.getResultSetValue(rs, rs.findColumn(columnName), Long.class); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/LocalDateInterval.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/LocalDateInterval.java index d09b290ca..a867a6322 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/LocalDateInterval.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/LocalDateInterval.java @@ -77,4 +77,4 @@ public class LocalDateInterval { public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/MySQLDictionaryCustom.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/MySQLDictionaryCustom.java index 973ca4f77..24de015b6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/MySQLDictionaryCustom.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/MySQLDictionaryCustom.java @@ -26,21 +26,21 @@ import org.apache.openjpa.jdbc.sql.MySQLDictionary; @SuppressWarnings("unchecked") public class MySQLDictionaryCustom extends MySQLDictionary { - public MySQLDictionaryCustom(){ - super(); - this.supportsSubselect = true; - this.booleanRepresentation = BooleanRepresentationFactory.BOOLEAN; - this.supportsGetGeneratedKeys = false ; - this.allowsAliasInBulkClause = true ; - this.useWildCardForCount = true ; - } + public MySQLDictionaryCustom() { + super(); + this.supportsSubselect = true; + this.booleanRepresentation = BooleanRepresentationFactory.BOOLEAN; + this.supportsGetGeneratedKeys = false; + this.allowsAliasInBulkClause = true; + this.useWildCardForCount = true; + } - @Override - public void connectedConfiguration(Connection conn) throws SQLException { - super.connectedConfiguration(conn); - this.supportsSubselect = true; - this.supportsGetGeneratedKeys = false ; - this.allowsAliasInBulkClause = true ; - this.useWildCardForCount = true ; - } + @Override + public void connectedConfiguration(Connection conn) throws SQLException { + super.connectedConfiguration(conn); + this.supportsSubselect = true; + this.supportsGetGeneratedKeys = false; + this.allowsAliasInBulkClause = true; + this.useWildCardForCount = true; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/Tenant.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/Tenant.java old mode 100755 new mode 100644 index 7fde855ce..79e85130e --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/Tenant.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/domain/Tenant.java @@ -74,4 +74,4 @@ public class Tenant { return this.timezoneId; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformDomainRuleException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformDomainRuleException.java index 314723f40..bb57263da 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformDomainRuleException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformDomainRuleException.java @@ -46,4 +46,4 @@ public abstract class AbstractPlatformDomainRuleException extends RuntimeExcepti public Object[] getDefaultUserMessageArgs() { return this.defaultUserMessageArgs; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformResourceNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformResourceNotFoundException.java index 64b9823c2..7f66684cf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformResourceNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformResourceNotFoundException.java @@ -46,4 +46,4 @@ public abstract class AbstractPlatformResourceNotFoundException extends RuntimeE public Object[] getDefaultUserMessageArgs() { return this.defaultUserMessageArgs; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformServiceUnavailableException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformServiceUnavailableException.java old mode 100755 new mode 100644 index e43b4d0ef..e718b9c73 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformServiceUnavailableException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/AbstractPlatformServiceUnavailableException.java @@ -46,4 +46,4 @@ public abstract class AbstractPlatformServiceUnavailableException extends Runtim public Object[] getDefaultUserMessageArgs() { return this.defaultUserMessageArgs; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/GeneralPlatformDomainRuleException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/GeneralPlatformDomainRuleException.java index e7e0bbebf..b5b9139eb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/GeneralPlatformDomainRuleException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/GeneralPlatformDomainRuleException.java @@ -28,4 +28,4 @@ public final class GeneralPlatformDomainRuleException extends AbstractPlatformDo final Object... defaultUserMessageArgs) { super(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/InvalidJsonException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/InvalidJsonException.java index 9a265ba57..2be934884 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/InvalidJsonException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/InvalidJsonException.java @@ -24,4 +24,4 @@ package org.apache.fineract.infrastructure.core.exception; */ public class InvalidJsonException extends RuntimeException { // -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/MultiException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/MultiException.java index a1cdc867f..4bb2f2d49 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/MultiException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/MultiException.java @@ -31,18 +31,24 @@ import org.slf4j.LoggerFactory; /** * Exception with multiple root causes. * - * Intended to be used in places where N operations are performed in a loop over something, - * each of which could fail, but where we don't want to fail immediately but continue, and - * then fail at end. + * Intended to be used in places where N operations are performed in a loop over + * something, each of which could fail, but where we don't want to fail + * immediately but continue, and then fail at end. * - *

The failures should typically also each be logged within the loop, as they occur; this exception is - * only thrown to propagate the failure, and the caller may or may not log this with the details. + *

+ * The failures should typically also each be logged within the loop, as they + * occur; this exception is only thrown to propagate the failure, and the caller + * may or may not log this with the details. * - *

Originally inspired by org.junit.runners.model.MultipleFailureException

. + *

+ * Originally inspired by org.junit.runners.model.MultipleFailureException + *

+ * . * * @author Michael Vorburger.ch */ public class MultiException extends Exception { + private final static Logger LOG = LoggerFactory.getLogger(MultiException.class); private final List throwables; @@ -78,7 +84,7 @@ public class MultiException extends Exception { LOG.info("{}", super.getMessage()); int i = 0; for (Throwable e : throwables) { - LOG.info("{}.",++i); + LOG.info("{}.", ++i); e.printStackTrace(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformApiDataValidationException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformApiDataValidationException.java index ee214b1a9..6e389e295 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformApiDataValidationException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformApiDataValidationException.java @@ -54,4 +54,4 @@ public class PlatformApiDataValidationException extends RuntimeException { public List getErrors() { return this.errors; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformDataIntegrityException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformDataIntegrityException.java index ec00f5d0d..0b58ae94e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformDataIntegrityException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformDataIntegrityException.java @@ -60,4 +60,4 @@ public class PlatformDataIntegrityException extends RuntimeException { public String getParameterName() { return this.parameterName; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformInternalServerException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformInternalServerException.java index e9fcdec52..fcf24aaab 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformInternalServerException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/PlatformInternalServerException.java @@ -45,4 +45,4 @@ public class PlatformInternalServerException extends RuntimeException { public Object[] getDefaultUserMessageArgs() { return this.defaultUserMessageArgs; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/UnrecognizedQueryParamException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/UnrecognizedQueryParamException.java index 76fba29e1..9e4084753 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/UnrecognizedQueryParamException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/UnrecognizedQueryParamException.java @@ -41,4 +41,4 @@ public class UnrecognizedQueryParamException extends RuntimeException { public Object[] getSupportedParams() { return this.supportedParams; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/UnsupportedParameterException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/UnsupportedParameterException.java index da0a62759..cb0fa114a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/UnsupportedParameterException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exception/UnsupportedParameterException.java @@ -35,4 +35,4 @@ public class UnsupportedParameterException extends RuntimeException { public List getUnsupportedParameters() { return this.unsupportedParameters; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/AccessDeniedExceptionMapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/AccessDeniedExceptionMapper.java index de8dbf841..41b8af829 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/AccessDeniedExceptionMapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/AccessDeniedExceptionMapper.java @@ -49,4 +49,4 @@ public class AccessDeniedExceptionMapper implements ExceptionMapper errors = new ArrayList<>(); errors.add(error); - final ApiGlobalErrorResponse invalidParameterError = ApiGlobalErrorResponse.badClientRequest( - "validation.msg.validation.errors.exist", "Validation errors exist.", errors); + final ApiGlobalErrorResponse invalidParameterError = ApiGlobalErrorResponse + .badClientRequest("validation.msg.validation.errors.exist", "Validation errors exist.", errors); return Response.status(Status.BAD_REQUEST).entity(invalidParameterError).type(MediaType.APPLICATION_JSON).build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/UnsupportedCommandExceptionMapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/UnsupportedCommandExceptionMapper.java index 754fbd73b..1d1f2a7ce 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/UnsupportedCommandExceptionMapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/UnsupportedCommandExceptionMapper.java @@ -46,16 +46,16 @@ public class UnsupportedCommandExceptionMapper implements ExceptionMapper errors = new ArrayList<>(); final StringBuilder validationErrorCode = new StringBuilder("error.msg.command.unsupported"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The command ").append(exception.getUnsupportedCommandName()).append( - " is not supported."); + final StringBuilder defaultEnglishMessage = new StringBuilder("The command ").append(exception.getUnsupportedCommandName()) + .append(" is not supported."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), exception.getUnsupportedCommandName(), exception.getUnsupportedCommandName()); errors.add(error); - final ApiGlobalErrorResponse invalidParameterError = ApiGlobalErrorResponse.badClientRequest( - "validation.msg.validation.errors.exist", "Validation errors exist.", errors); + final ApiGlobalErrorResponse invalidParameterError = ApiGlobalErrorResponse + .badClientRequest("validation.msg.validation.errors.exist", "Validation errors exist.", errors); return Response.status(Status.BAD_REQUEST).entity(invalidParameterError).type(MediaType.APPLICATION_JSON).build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/UnsupportedParameterExceptionMapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/UnsupportedParameterExceptionMapper.java index 4918d7d76..21cb4fdbd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/UnsupportedParameterExceptionMapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/UnsupportedParameterExceptionMapper.java @@ -47,17 +47,17 @@ public class UnsupportedParameterExceptionMapper implements ExceptionMapper implements FromApiJsonD @Override public abstract T commandFromApiJson(final String json); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/AbstractFromCommandJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/AbstractFromCommandJsonDeserializer.java index 6723c1194..63ff3c65b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/AbstractFromCommandJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/AbstractFromCommandJsonDeserializer.java @@ -33,4 +33,4 @@ public abstract class AbstractFromCommandJsonDeserializer implements FromComm public T commandFromCommandJson(final Long codeId, final String commandAsJson) { return commandFromCommandJson(codeId, commandAsJson, false); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ApiRequestJsonSerializationSettings.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ApiRequestJsonSerializationSettings.java index a66ebe23a..7f1b501e7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ApiRequestJsonSerializationSettings.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ApiRequestJsonSerializationSettings.java @@ -73,4 +73,4 @@ public class ApiRequestJsonSerializationSettings { public boolean isPartialResponseRequired() { return !this.parametersForPartialResponse.isEmpty(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandProcessingResultJsonSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandProcessingResultJsonSerializer.java index 36c744927..99c3f37f7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandProcessingResultJsonSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandProcessingResultJsonSerializer.java @@ -47,4 +47,4 @@ public final class CommandProcessingResultJsonSerializer { } return returnedResult; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandSerializer.java index b3af0d1e8..b06b1f433 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandSerializer.java @@ -30,4 +30,4 @@ package org.apache.fineract.infrastructure.core.serialization; public interface CommandSerializer { String serializeCommandToJson(Object command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandSerializerDefaultToJson.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandSerializerDefaultToJson.java index f01b5045c..301f9d824 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandSerializerDefaultToJson.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/CommandSerializerDefaultToJson.java @@ -40,4 +40,4 @@ public class CommandSerializerDefaultToJson implements CommandSerializer { public String serializeCommandToJson(final Object command) { return this.excludeNothingWithPrettyPrintingOff.serialize(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/DatatableCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/DatatableCommandFromApiJsonDeserializer.java index 3018a4878..8c53a3319 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/DatatableCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/DatatableCommandFromApiJsonDeserializer.java @@ -45,16 +45,16 @@ public class DatatableCommandFromApiJsonDeserializer { /** * The parameters supported for this command. */ - private final Set supportedParametersForCreate = new HashSet<>(Arrays.asList("datatableName", "apptableName", "multiRow", - "columns")); - private final Set supportedParametersForCreateColumns = new HashSet<>(Arrays.asList("name", "type", "length", - "mandatory", "code")); - private final Set supportedParametersForUpdate = new HashSet<>(Arrays.asList("apptableName", "changeColumns", - "addColumns", "dropColumns")); - private final Set supportedParametersForAddColumns = new HashSet<>(Arrays.asList("name", "type", "length", "mandatory", - "after", "code")); - private final Set supportedParametersForChangeColumns = new HashSet<>(Arrays.asList("name", "newName", "length", - "mandatory", "after", "code", "newCode")); + private final Set supportedParametersForCreate = new HashSet<>( + Arrays.asList("datatableName", "apptableName", "multiRow", "columns")); + private final Set supportedParametersForCreateColumns = new HashSet<>( + Arrays.asList("name", "type", "length", "mandatory", "code")); + private final Set supportedParametersForUpdate = new HashSet<>( + Arrays.asList("apptableName", "changeColumns", "addColumns", "dropColumns")); + private final Set supportedParametersForAddColumns = new HashSet<>( + Arrays.asList("name", "type", "length", "mandatory", "after", "code")); + private final Set supportedParametersForChangeColumns = new HashSet<>( + Arrays.asList("name", "newName", "length", "mandatory", "after", "code", "newCode")); private final Set supportedParametersForDropColumns = new HashSet<>(Arrays.asList("name")); private final Object[] supportedColumnTypes = { "string", "number", "boolean", "decimal", "date", "datetime", "text", "dropdown" }; private final Object[] supportedApptableNames = { "m_loan", "m_savings_account", "m_client", "m_group", "m_center", "m_office", @@ -152,8 +152,10 @@ public class DatatableCommandFromApiJsonDeserializer { // parameter // has been specified is necessary in order to avoid JSON requests with // no parameters - if (!json.matches("(?s)\\A\\{.*?(\\\".*?\\\"\\s*?:\\s*?)+.*?\\}\\z")) { throw new PlatformDataIntegrityException( - "error.msg.invalid.request.body.no.parameters", "Provided JSON request body does not have any parameters."); } + if (!json.matches("(?s)\\A\\{.*?(\\\".*?\\\"\\s*?:\\s*?)+.*?\\}\\z")) { + throw new PlatformDataIntegrityException("error.msg.invalid.request.body.no.parameters", + "Provided JSON request body does not have any parameters."); + } final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForUpdate); @@ -250,7 +252,9 @@ public class DatatableCommandFromApiJsonDeserializer { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/DefaultToApiJsonSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/DefaultToApiJsonSerializer.java index 2a45be08b..df21a88d0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/DefaultToApiJsonSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/DefaultToApiJsonSerializer.java @@ -38,8 +38,7 @@ public final class DefaultToApiJsonSerializer implements ToApiJsonSerializer< private final GoogleGsonSerializerHelper helper; @Autowired - public DefaultToApiJsonSerializer( - final ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson excludeNothingWithPrettyPrintingOff, + public DefaultToApiJsonSerializer(final ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson excludeNothingWithPrettyPrintingOff, final ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson excludeNothingWithPrettyPrintingOn, final CommandProcessingResultJsonSerializer commandProcessingResultSerializer, final GoogleGsonSerializerHelper helper) { this.excludeNothingWithPrettyPrintingOff = excludeNothingWithPrettyPrintingOff; @@ -137,7 +136,8 @@ public final class DefaultToApiJsonSerializer implements ToApiJsonSerializer< return json; } - private Gson findAppropriateSerializer(final ApiRequestJsonSerializationSettings settings, final Set supportedResponseParameters) { + private Gson findAppropriateSerializer(final ApiRequestJsonSerializationSettings settings, + final Set supportedResponseParameters) { Gson gson = null; if (settings.isPartialResponseRequired()) { gson = this.helper.createGsonBuilderWithParameterExclusionSerializationStrategy(supportedResponseParameters, @@ -154,4 +154,4 @@ public final class DefaultToApiJsonSerializer implements ToApiJsonSerializer< } return gson; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson.java index a5d13440d..d7ef20342 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson.java @@ -47,4 +47,4 @@ public final class ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson { } return returnedResult; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson.java index 93bf9d26b..45cf00a16 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson.java @@ -43,4 +43,4 @@ public final class ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson { public String serialize(final Object result) { return this.gson.toJson(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromApiJsonDeserializer.java index 20d460f2b..405372960 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromApiJsonDeserializer.java @@ -24,4 +24,4 @@ package org.apache.fineract.infrastructure.core.serialization; public interface FromApiJsonDeserializer { T commandFromApiJson(final String json); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromCommandJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromCommandJsonDeserializer.java index 87cd8018d..a763700ec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromCommandJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromCommandJsonDeserializer.java @@ -28,4 +28,4 @@ public interface FromCommandJsonDeserializer { T commandFromCommandJson(final Long resourceId, final String json); T commandFromCommandJson(final Long resourceId, final String json, final boolean makerCheckerApproval); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromJsonHelper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromJsonHelper.java index 17ac9bf23..669851203 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromJsonHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/FromJsonHelper.java @@ -201,7 +201,7 @@ public class FromJsonHelper { } public LocalDateTime extractLocalTimeNamed(final String parameterName, final JsonElement element, final String dateFormat, - final Locale locale) { + final Locale locale) { return this.helperDelegator.extractLocalTimeNamed(parameterName, element, dateFormat, locale, new HashSet<>()); } @@ -211,8 +211,7 @@ public class FromJsonHelper { public LocalDate extractLocalDateNamed(final String parameterName, final JsonElement element, final String dateFormat, final Locale locale) { - return this.helperDelegator.extractLocalDateNamed(parameterName, element.getAsJsonObject(), dateFormat, locale, - new HashSet<>()); + return this.helperDelegator.extractLocalDateNamed(parameterName, element.getAsJsonObject(), dateFormat, locale, new HashSet<>()); } public LocalDate extractLocalDateNamed(final String parameterName, final JsonElement element, diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/GoogleGsonSerializerHelper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/GoogleGsonSerializerHelper.java index 1a4834f5f..86833d596 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/GoogleGsonSerializerHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/GoogleGsonSerializerHelper.java @@ -73,8 +73,9 @@ public final class GoogleGsonSerializerHelper { final Set differentParametersDetectedSet = new HashSet<>(responseParameters); differentParametersDetectedSet.removeAll(supportedParameters); - if (!differentParametersDetectedSet.isEmpty()) { throw new UnsupportedParameterException(new ArrayList<>( - differentParametersDetectedSet)); } + if (!differentParametersDetectedSet.isEmpty()) { + throw new UnsupportedParameterException(new ArrayList<>(differentParametersDetectedSet)); + } parameterNamesToSkip.addAll(supportedParameters); parameterNamesToSkip.removeAll(responseParameters); @@ -104,4 +105,4 @@ public final class GoogleGsonSerializerHelper { builder.registerTypeAdapter(DateTime.class, new JodaDateTimeAdapter()); builder.registerTypeAdapter(MonthDay.class, new JodaMonthDayAdapter()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/JsonParserHelper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/JsonParserHelper.java index 8dffee02d..e328a5746 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/JsonParserHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/JsonParserHelper.java @@ -126,7 +126,8 @@ public class JsonParserHelper { return value; } - public Integer extractIntegerWithLocaleNamed(final String parameterName, final JsonElement element, final Set modifiedParameters) { + public Integer extractIntegerWithLocaleNamed(final String parameterName, final JsonElement element, + final Set modifiedParameters) { Integer value = null; if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); @@ -340,8 +341,8 @@ public class JsonParserHelper { final List dataValidationErrors = new ArrayList<>(); final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.month.day", "The parameter " + parameterName + " is invalid based on the monthDayFormat: '" + dateFormat - + "' and locale: '" + clientApplicationLocale + "' provided:", parameterName, valueAsString, - dateFormat); + + "' and locale: '" + clientApplicationLocale + "' provided:", + parameterName, valueAsString, dateFormat); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", @@ -397,24 +398,23 @@ public class JsonParserHelper { public LocalDateTime extractLocalTimeNamed(final String parameterName, final JsonElement element, final String timeFormat, final Locale clientApplicationLocale, final Set parametersPassedInCommand) { LocalDateTime value = null; - String timeValueAsString=null; + String timeValueAsString = null; if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { parametersPassedInCommand.add(parameterName); - try{ + try { DateTimeFormatter timeFormtter = DateTimeFormat.forPattern(timeFormat); final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); - timeValueAsString = primitive.getAsString(); + timeValueAsString = primitive.getAsString(); if (StringUtils.isNotBlank(timeValueAsString)) { value = LocalDateTime.parse(timeValueAsString, timeFormtter); } - } - catch(IllegalArgumentException e ){ + } catch (IllegalArgumentException e) { final List dataValidationErrors = new ArrayList<>(); - final String defaultMessage = new StringBuilder("The parameter '" + timeValueAsString - + "' is not in correct format.").toString(); + final String defaultMessage = new StringBuilder("The parameter '" + timeValueAsString + "' is not in correct format.") + .toString(); final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.TimeFormat", defaultMessage, parameterName); dataValidationErrors.add(error); @@ -451,12 +451,11 @@ public class JsonParserHelper { public static LocalDate convertFrom(final String dateAsString, final String parameterName, final String dateFormat, final Locale clientApplicationLocale) { - return convertDateTimeFrom(dateAsString, parameterName, - dateFormat, clientApplicationLocale).toLocalDate(); + return convertDateTimeFrom(dateAsString, parameterName, dateFormat, clientApplicationLocale).toLocalDate(); } - public static LocalDateTime convertDateTimeFrom(final String dateTimeAsString, final String parameterName, - final String dateTimeFormat, final Locale clientApplicationLocale) { + public static LocalDateTime convertDateTimeFrom(final String dateTimeAsString, final String parameterName, final String dateTimeFormat, + final Locale clientApplicationLocale) { validateDateFormatAndLocale(parameterName, dateTimeFormat, clientApplicationLocale); LocalDateTime eventLocalDateTime = null; @@ -466,9 +465,11 @@ public class JsonParserHelper { .parseLocalDateTime(dateTimeAsString.toLowerCase(clientApplicationLocale)); } catch (final IllegalArgumentException e) { final List dataValidationErrors = new ArrayList<>(); - final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.dateFormat.format", "The parameter " - + parameterName + " is invalid based on the dateFormat: '" + dateTimeFormat + "' and locale: '" - + clientApplicationLocale + "' provided:", parameterName, eventLocalDateTime, dateTimeFormat); + final ApiParameterError error = ApiParameterError + .parameterError("validation.msg.invalid.dateFormat.format", + "The parameter " + parameterName + " is invalid based on the dateFormat: '" + dateTimeFormat + + "' and locale: '" + clientApplicationLocale + "' provided:", + parameterName, eventLocalDateTime, dateTimeFormat); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", @@ -480,20 +481,20 @@ public class JsonParserHelper { } private static void validateDateFormatAndLocale(final String parameterName, final String dateFormat, - final Locale clientApplicationLocale) { + final Locale clientApplicationLocale) { if (StringUtils.isBlank(dateFormat) || clientApplicationLocale == null) { final List dataValidationErrors = new ArrayList<>(); if (StringUtils.isBlank(dateFormat)) { - final String defaultMessage = new StringBuilder("The parameter '" + parameterName - + "' requires a 'dateFormat' parameter to be passed with it.").toString(); + final String defaultMessage = new StringBuilder( + "The parameter '" + parameterName + "' requires a 'dateFormat' parameter to be passed with it.").toString(); final ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.dateFormat.parameter", defaultMessage, parameterName); dataValidationErrors.add(error); } if (clientApplicationLocale == null) { - final String defaultMessage = new StringBuilder("The parameter '" + parameterName - + "' requires a 'locale' parameter to be passed with it.").toString(); + final String defaultMessage = new StringBuilder( + "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.").toString(); final ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); dataValidationErrors.add(error); @@ -504,13 +505,14 @@ public class JsonParserHelper { } - public Integer convertToInteger(final String numericalValueFormatted, final String parameterName, final Locale clientApplicationLocale) { + public Integer convertToInteger(final String numericalValueFormatted, final String parameterName, + final Locale clientApplicationLocale) { if (clientApplicationLocale == null) { final List dataValidationErrors = new ArrayList<>(); - final String defaultMessage = new StringBuilder("The parameter '" + parameterName - + "' requires a 'locale' parameter to be passed with it.").toString(); + final String defaultMessage = new StringBuilder( + "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.").toString(); final ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); dataValidationErrors.add(error); @@ -544,8 +546,9 @@ public class JsonParserHelper { if (source.contains(Character.toString(symbols.getDecimalSeparator()))) { throw new ParseException(source, 0); } - if (!Double.valueOf(parsedNumberDouble).equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) { throw new ParseException( - source, 0); } + if (!Double.valueOf(parsedNumberDouble).equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) { + throw new ParseException(source, 0); + } number = parsedNumber.intValue(); } @@ -554,9 +557,10 @@ public class JsonParserHelper { } catch (final ParseException e) { final List dataValidationErrors = new ArrayList<>(); - final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.integer.format", "The parameter " - + parameterName + " has value: " + numericalValueFormatted + " which is invalid integer value for provided locale of [" - + clientApplicationLocale.toString() + "].", parameterName, numericalValueFormatted, clientApplicationLocale); + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.integer.format", + "The parameter " + parameterName + " has value: " + numericalValueFormatted + + " which is invalid integer value for provided locale of [" + clientApplicationLocale.toString() + "].", + parameterName, numericalValueFormatted, clientApplicationLocale); error.setValue(numericalValueFormatted); dataValidationErrors.add(error); @@ -578,9 +582,9 @@ public class JsonParserHelper { } catch (final NumberFormatException e) { final List dataValidationErrors = new ArrayList<>(); - final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.integer", "The parameter " - + parameterName + " has value: " + numericalValueFormatted + " which is invalid integer.", parameterName, - numericalValueFormatted); + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.integer", + "The parameter " + parameterName + " has value: " + numericalValueFormatted + " which is invalid integer.", + parameterName, numericalValueFormatted); error.setValue(numericalValueFormatted); dataValidationErrors.add(error); @@ -594,8 +598,8 @@ public class JsonParserHelper { if (clientApplicationLocale == null) { final List dataValidationErrors = new ArrayList<>(); - final String defaultMessage = new StringBuilder("The parameter '" + parameterName - + "' requires a 'locale' parameter to be passed with it.").toString(); + final String defaultMessage = new StringBuilder( + "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.").toString(); final ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); dataValidationErrors.add(error); @@ -633,9 +637,10 @@ public class JsonParserHelper { } catch (final ParseException e) { final List dataValidationErrors = new ArrayList<>(); - final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.decimal.format", "The parameter " - + parameterName + " has value: " + numericalValueFormatted + " which is invalid decimal value for provided locale of [" - + clientApplicationLocale.toString() + "].", parameterName, numericalValueFormatted, clientApplicationLocale); + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.decimal.format", + "The parameter " + parameterName + " has value: " + numericalValueFormatted + + " which is invalid decimal value for provided locale of [" + clientApplicationLocale.toString() + "].", + parameterName, numericalValueFormatted, clientApplicationLocale); error.setValue(numericalValueFormatted); dataValidationErrors.add(error); @@ -644,7 +649,9 @@ public class JsonParserHelper { } } - /*** TODO: Vishwas move all Locale related code to a separate Utils class ***/ + /*** + * TODO: Vishwas move all Locale related code to a separate Utils class + ***/ public static Locale localeFromString(final String localeAsString) { if (StringUtils.isBlank(localeAsString)) { @@ -701,8 +708,10 @@ public class JsonParserHelper { } } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } return new Locale(languageCode.toLowerCase(), courntryCode.toUpperCase(), variantCode); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ToApiJsonSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ToApiJsonSerializer.java index 02351de73..1252af28e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ToApiJsonSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/serialization/ToApiJsonSerializer.java @@ -46,4 +46,4 @@ public interface ToApiJsonSerializer { String serialize(ApiRequestJsonSerializationSettings settings, T single, Set supportedResponseParameters); String serialize(ApiRequestJsonSerializationSettings settings, Page singleObject, Set supportedResponseParameters); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/AbandonedConnectionCleanupShutdownListener.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/AbandonedConnectionCleanupShutdownListener.java index 1d87f2c2a..b39558434 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/AbandonedConnectionCleanupShutdownListener.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/AbandonedConnectionCleanupShutdownListener.java @@ -43,13 +43,16 @@ public class AbandonedConnectionCleanupShutdownListener implements ApplicationLi } private void shutDowncleanUpThreadAndDeregisterJDBCDriver() { - /*try { - - AbandonedConnectionCleanupThread.shutdown(); tomcat memoroy leak with mysql connector. With Drizzle not required - LOG.info("Shut-down of AbandonedConnectionCleanupThread successful"); - } catch (Throwable t) { - LOG.error("Exception occurred while shut-down of AbandonedConnectionCleanupThread", t); - }*/ + /* + * try { + * + * AbandonedConnectionCleanupThread.shutdown(); tomcat memoroy leak with + * mysql connector. With Drizzle not required + * LOG.info("Shut-down of AbandonedConnectionCleanupThread successful"); + * } catch (Throwable t) { LOG. + * error("Exception occurred while shut-down of AbandonedConnectionCleanupThread" + * , t); } + */ // This manually deregisters JDBC driver, which prevents Tomcat 7 from // complaining about memory leaks @@ -69,4 +72,4 @@ public class AbandonedConnectionCleanupShutdownListener implements ApplicationLi LOG.error("Exception Occcured while trying to sleep.", e); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/DateUtils.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/DateUtils.java index ecef6ee8d..9360771bc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/DateUtils.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/DateUtils.java @@ -91,8 +91,8 @@ public class DateUtils { return dateTime.toLocalDate(); } catch (final IllegalArgumentException e) { final List dataValidationErrors = new ArrayList<>(); - final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.date.pattern", "The parameter date (" - + stringDate + ") is invalid w.r.t. pattern " + pattern, "date", stringDate, pattern); + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.date.pattern", + "The parameter date (" + stringDate + ") is invalid w.r.t. pattern " + pattern, "date", stringDate, pattern); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/GmailBackedPlatformEmailService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/GmailBackedPlatformEmailService.java index 23789778b..e5e49c2eb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/GmailBackedPlatformEmailService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/GmailBackedPlatformEmailService.java @@ -34,22 +34,19 @@ public class GmailBackedPlatformEmailService implements PlatformEmailService { private final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService; @Autowired - public GmailBackedPlatformEmailService(final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService){ + public GmailBackedPlatformEmailService(final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService) { this.externalServicesReadPlatformService = externalServicesReadPlatformService; } @Override - public void sendToUserAccount(String organisationName, String contactName, - String address, String username, String unencodedPassword) { + public void sendToUserAccount(String organisationName, String contactName, String address, String username, String unencodedPassword) { final String subject = "Welcome " + contactName + " to " + organisationName; - final String body = "You are receiving this email as your email account: " + - address + " has being used to create a user account for an organisation named [" + - organisationName + "] on Mifos.\n" + - "You can login using the following credentials:\nusername: " + username + "\n" + - "password: " + unencodedPassword + "\n" + - "You must change this password upon first log in using Uppercase, Lowercase, number and character.\n" + - "Thank you and welcome to the organisation."; + final String body = "You are receiving this email as your email account: " + address + + " has being used to create a user account for an organisation named [" + organisationName + "] on Mifos.\n" + + "You can login using the following credentials:\nusername: " + username + "\n" + "password: " + unencodedPassword + "\n" + + "You must change this password upon first log in using Uppercase, Lowercase, number and character.\n" + + "Thank you and welcome to the organisation."; final EmailDetail emailDetail = new EmailDetail(subject, body, address, contactName); sendDefinedEmail(emailDetail); @@ -70,7 +67,7 @@ public class GmailBackedPlatformEmailService implements PlatformEmailService { email.setHostName(smtpCredentialsData.getHost()); try { - if(smtpCredentialsData.isUseTLS()){ + if (smtpCredentialsData.isUseTLS()) { email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true"); } email.setFrom(smtpCredentialsData.getFromEmail(), smtpCredentialsData.getFromName()); @@ -84,4 +81,4 @@ public class GmailBackedPlatformEmailService implements PlatformEmailService { throw new PlatformEmailSendException(e); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/Page.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/Page.java index 4f4768bdb..f6c2d7189 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/Page.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/Page.java @@ -38,4 +38,4 @@ public class Page implements Serializable { public List getPageItems() { return this.pageItems; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/PlatformEmailService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/PlatformEmailService.java index 86453a877..b2f0d1bb4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/PlatformEmailService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/PlatformEmailService.java @@ -22,8 +22,7 @@ import org.apache.fineract.infrastructure.core.domain.EmailDetail; public interface PlatformEmailService { - void sendToUserAccount(String organisationName,String contactName, - String address, String username, String unencodedPassword); + void sendToUserAccount(String organisationName, String contactName, String address, String username, String unencodedPassword); void sendDefinedEmail(EmailDetail emailDetails); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/RoutingDataSource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/RoutingDataSource.java index fbe32e861..fb2117cb9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/RoutingDataSource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/RoutingDataSource.java @@ -55,4 +55,4 @@ public class RoutingDataSource extends AbstractDataSource { public Connection getConnection(final String username, final String password) throws SQLException { return determineTargetDataSource().getConnection(username, password); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/RoutingDataSourceService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/RoutingDataSourceService.java index a279aec90..dff9b53a7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/RoutingDataSourceService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/RoutingDataSourceService.java @@ -27,4 +27,4 @@ import javax.sql.DataSource; public interface RoutingDataSourceService { DataSource retrieveDataSource(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/SearchParameters.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/SearchParameters.java old mode 100755 new mode 100644 index 7b586eb87..72b36a1a5 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/SearchParameters.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/SearchParameters.java @@ -225,7 +225,8 @@ public final class SearchParameters { staffId, accountNo, loanId, savingsId, orphansOnly, isSelfUser); } - public static SearchParameters forEmailCampaign(final String sqlSearch, final Integer offset, final Integer limit, final String orderBy, final String sortOrder) { + public static SearchParameters forEmailCampaign(final String sqlSearch, final Integer offset, final Integer limit, final String orderBy, + final String sortOrder) { final String externalId = null; final Integer maxLimitAllowed = getCheckedLimit(limit); @@ -294,10 +295,10 @@ public final class SearchParameters { } - public SearchParameters(final String sqlSearch, final Long officeId, final String externalId, final String name, - final String hierarchy, final String firstname, final String lastname, final Integer offset, final Integer limit, - final String orderBy, final String sortOrder, final Long staffId, final String accountNo, final Long loanId, - final Long savingsId, final Boolean orphansOnly, final String currencyCode) { + public SearchParameters(final String sqlSearch, final Long officeId, final String externalId, final String name, final String hierarchy, + final String firstname, final String lastname, final Integer offset, final Integer limit, final String orderBy, + final String sortOrder, final Long staffId, final String accountNo, final Long loanId, final Long savingsId, + final Boolean orphansOnly, final String currencyCode) { this.sqlSearch = sqlSearch; this.officeId = officeId; this.externalId = externalId; @@ -475,28 +476,30 @@ public final class SearchParameters { } /** - * creates an instance of the SearchParameters from a request for the report mailing job run history + * creates an instance of the SearchParameters from a request for the report + * mailing job run history * * @return SearchParameters object **/ - public static SearchParameters fromReportMailingJobRunHistory(final Integer offset, - final Integer limit, final String orderBy, final String sortOrder) { + public static SearchParameters fromReportMailingJobRunHistory(final Integer offset, final Integer limit, final String orderBy, + final String sortOrder) { final Integer maxLimitAllowed = getCheckedLimit(limit); - return new SearchParameters(null, null, null, null, null, null, null, offset, maxLimitAllowed, orderBy, - sortOrder, null, null, null, null, null, false); + return new SearchParameters(null, null, null, null, null, null, null, offset, maxLimitAllowed, orderBy, sortOrder, null, null, null, + null, null, false); } /** - * creates an instance of the {@link SearchParameters} from a request for the report mailing job + * creates an instance of the {@link SearchParameters} from a request for + * the report mailing job * * @return {@link SearchParameters} object */ - public static SearchParameters fromReportMailingJob(final Integer offset, - final Integer limit, final String orderBy, final String sortOrder) { + public static SearchParameters fromReportMailingJob(final Integer offset, final Integer limit, final String orderBy, + final String sortOrder) { final Integer maxLimitAllowed = getCheckedLimit(limit); - return new SearchParameters(null, null, null, null, null, null, null, offset, maxLimitAllowed, orderBy, - sortOrder, null, null, null, null, null, false); + return new SearchParameters(null, null, null, null, null, null, null, offset, maxLimitAllowed, orderBy, sortOrder, null, null, null, + null, null, false); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/TenantDatabaseUpgradeService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/TenantDatabaseUpgradeService.java index a1197206f..35cb09621 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/TenantDatabaseUpgradeService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/TenantDatabaseUpgradeService.java @@ -49,10 +49,12 @@ public class TenantDatabaseUpgradeService { private final TenantDetailsService tenantDetailsService; protected final DataSource tenantDataSource; - @Autowired private JDBCDriverConfig driverConfig; + @Autowired + private JDBCDriverConfig driverConfig; @Autowired - public TenantDatabaseUpgradeService(final TenantDetailsService detailsService, @Qualifier("hikariTenantDataSource") final DataSource dataSource) { + public TenantDatabaseUpgradeService(final TenantDetailsService detailsService, + @Qualifier("hikariTenantDataSource") final DataSource dataSource) { this.tenantDetailsService = detailsService; this.tenantDataSource = dataSource; } @@ -65,19 +67,18 @@ public class TenantDatabaseUpgradeService { final FineractPlatformTenantConnection connection = tenant.getConnection(); if (connection.isAutoUpdateEnabled()) { - String connectionProtocol = driverConfig.constructProtocol(connection.getSchemaServer(), connection.getSchemaServerPort(), connection.getSchemaName()) ; - DriverDataSource source = new DriverDataSource(Thread.currentThread().getContextClassLoader(), driverConfig.getDriverClassName(), connectionProtocol, connection.getSchemaUsername(), connection.getSchemaPassword()); + String connectionProtocol = driverConfig.constructProtocol(connection.getSchemaServer(), connection.getSchemaServerPort(), + connection.getSchemaName()); + DriverDataSource source = new DriverDataSource(Thread.currentThread().getContextClassLoader(), + driverConfig.getDriverClassName(), connectionProtocol, connection.getSchemaUsername(), + connection.getSchemaPassword()); - final Flyway flyway = Flyway.configure() - .dataSource(source) - .locations("sql/migrations/core_db") - .outOfOrder(true) - .placeholderReplacement(false) - .configuration(Map.of( - "flyway.table", "schema_version")) // FINERACT-979 + final Flyway flyway = Flyway.configure().dataSource(source).locations("sql/migrations/core_db").outOfOrder(true) + .placeholderReplacement(false).configuration(Map.of("flyway.table", "schema_version")) // FINERACT-979 .load(); - //Should be removed later when all instances are stabilized :FINERACT-1008 + // Should be removed later when all instances are stabilized + // :FINERACT-1008 repairFlywayVersionSkip(flyway.getConfiguration().getDataSource()); try { @@ -85,7 +86,7 @@ public class TenantDatabaseUpgradeService { flyway.migrate(); } catch (FlywayException e) { String betterMessage = e.getMessage() + "; for Tenant DB URL: " + connectionProtocol + ", username: " - + connection.getSchemaUsername(); + + connection.getSchemaUsername(); throw new FlywayException(betterMessage, e.getCause()); } } @@ -103,71 +104,59 @@ public class TenantDatabaseUpgradeService { String dbPwd = getEnvVar("FINERACT_DEFAULT_TENANTDB_PWD", "mysql"); LOG.info("upgradeTenantDB: FINERACT_DEFAULT_TENANTDB_HOSTNAME = {}, FINERACT_DEFAULT_TENANTDB_PORT = {}", dbHostname, dbPort); - - - final Flyway flyway = Flyway.configure() - .dataSource(tenantDataSource) - .locations("sql/migrations/list_db") - .outOfOrder(true) + final Flyway flyway = Flyway.configure().dataSource(tenantDataSource).locations("sql/migrations/list_db").outOfOrder(true) .placeholders(Map.of( // FINERACT-773 - "fineract_default_tenantdb_hostname", dbHostname, - "fineract_default_tenantdb_port", dbPort, - "fineract_default_tenantdb_uid", dbUid, - "fineract_default_tenantdb_pwd", dbPwd)) - .configuration(Map.of( - "flyway.table", "schema_version")) // FINERACT-979 + "fineract_default_tenantdb_hostname", dbHostname, "fineract_default_tenantdb_port", dbPort, + "fineract_default_tenantdb_uid", dbUid, "fineract_default_tenantdb_pwd", dbPwd)) + .configuration(Map.of("flyway.table", "schema_version")) // FINERACT-979 .load(); - //Should be removed later when all instances are stabilized :FINERACT-1008 + // Should be removed later when all instances are stabilized + // :FINERACT-1008 repairFlywayVersionSkip(flyway.getConfiguration().getDataSource()); flyway.repair(); flyway.migrate(); } - - private String getEnvVar(String name, String defaultValue) { String value = System.getenv(name); - if (value == null) { - return defaultValue; - } + if (value == null) { return defaultValue; } return value; } - private void repairFlywayVersionSkip(DataSource source) { JdbcTemplate template = new JdbcTemplate(source); LOG.info("repairFlywayVersionSkip: Check whether the version table is in old format "); SqlRowSet ts = template.queryForRowSet("SHOW TABLES LIKE 'schema_version';"); - if(ts.next()){ - SqlRowSet rs = template.queryForRowSet("SHOW COLUMNS FROM `schema_version` LIKE 'version_rank';"); - if(rs.next()) { + if (ts.next()) { + SqlRowSet rs = template.queryForRowSet("SHOW COLUMNS FROM `schema_version` LIKE 'version_rank';"); + if (rs.next()) { LOG.info("repairFlywayVersionSkip: The schema_version table is in old format, executing repair "); - template.execute("CREATE TABLE `schema_version_history` ( `version_rank` int(11) NOT NULL, " + - " `installed_rank` int(11) NOT NULL, `version` varchar(50) NOT NULL, `description` varchar(200) NOT NULL, " + - "`type` varchar(20) NOT NULL, `script` varchar(1000) NOT NULL, `checksum` int(11) DEFAULT NULL, " + - " `installed_by` varchar(100) NOT NULL, `installed_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, " + - " `execution_time` int(11) NOT NULL, `success` tinyint(1) NOT NULL, PRIMARY KEY (`version`), " + - " KEY `schema_version_vr_idx` (`version_rank`), KEY `schema_version_ir_idx` (`installed_rank`), " + - " KEY `schema_version_s_idx` (`success`));"); + template.execute("CREATE TABLE `schema_version_history` ( `version_rank` int(11) NOT NULL, " + + " `installed_rank` int(11) NOT NULL, `version` varchar(50) NOT NULL, `description` varchar(200) NOT NULL, " + + "`type` varchar(20) NOT NULL, `script` varchar(1000) NOT NULL, `checksum` int(11) DEFAULT NULL, " + + " `installed_by` varchar(100) NOT NULL, `installed_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, " + + " `execution_time` int(11) NOT NULL, `success` tinyint(1) NOT NULL, PRIMARY KEY (`version`), " + + " KEY `schema_version_vr_idx` (`version_rank`), KEY `schema_version_ir_idx` (`installed_rank`), " + + " KEY `schema_version_s_idx` (`success`));"); template.execute("INSERT INTO schema_version_history select * from schema_version;"); template.execute("DROP TABLE schema_version;"); - template.execute("CREATE TABLE `schema_version` ( `installed_rank` int(11) NOT NULL, " + - " `version` varchar(50) DEFAULT NULL, `description` varchar(200) NOT NULL, `type` varchar(20) NOT NULL, " + - " `script` varchar(1000) NOT NULL, `checksum` int(11) DEFAULT NULL, `installed_by` varchar(100) NOT NULL, " + - " `installed_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `execution_time` int(11) NOT NULL, " + - " `success` tinyint(1) NOT NULL, PRIMARY KEY (`installed_rank`), KEY `flyway_schema_history_s_idx` (`success`) );"); - template.execute("INSERT INTO schema_version (installed_rank, version, description, type, script, checksum, " + - "installed_by, installed_on, execution_time, success) SELECT installed_rank, version, description, type, " + - "script, checksum, installed_by, installed_on, execution_time, success FROM schema_version_history;"); + template.execute("CREATE TABLE `schema_version` ( `installed_rank` int(11) NOT NULL, " + + " `version` varchar(50) DEFAULT NULL, `description` varchar(200) NOT NULL, `type` varchar(20) NOT NULL, " + + " `script` varchar(1000) NOT NULL, `checksum` int(11) DEFAULT NULL, `installed_by` varchar(100) NOT NULL, " + + " `installed_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `execution_time` int(11) NOT NULL, " + + " `success` tinyint(1) NOT NULL, PRIMARY KEY (`installed_rank`), KEY `flyway_schema_history_s_idx` (`success`) );"); + template.execute("INSERT INTO schema_version (installed_rank, version, description, type, script, checksum, " + + "installed_by, installed_on, execution_time, success) SELECT installed_rank, version, description, type, " + + "script, checksum, installed_by, installed_on, execution_time, success FROM schema_version_history;"); template.execute("DROP TABLE schema_version_history;"); LOG.info("repairFlywayVersionSkip: The schema_version repair completed."); - }else{ + } else { LOG.info("repairFlywayVersionSkip: The schema_version table format is new, aborting repair"); } - }else{ + } else { LOG.info("repairFlywayVersionSkip: The schema_version table does not exist, aborting repair"); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/ThreadLocalContextUtil.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/ThreadLocalContextUtil.java index 2228a9bc7..ec98c3e6c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/ThreadLocalContextUtil.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/ThreadLocalContextUtil.java @@ -67,4 +67,4 @@ public class ThreadLocalContextUtil { return authTokenContext.get(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/TomcatJdbcDataSourcePerTenantService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/TomcatJdbcDataSourcePerTenantService.java index 3b6fb7dca..c363ceb29 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/TomcatJdbcDataSourcePerTenantService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/service/TomcatJdbcDataSourcePerTenantService.java @@ -31,9 +31,9 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; /** - * Implementation that returns a new or existing connection pool - * datasource based on the tenant details stored in a {@link ThreadLocal} - * variable for this request. + * Implementation that returns a new or existing connection pool datasource + * based on the tenant details stored in a {@link ThreadLocal} variable for this + * request. * * {@link ThreadLocalContextUtil} is used to retrieve the * {@link FineractPlatformTenant} for the request. @@ -62,7 +62,8 @@ public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceSe final FineractPlatformTenantConnection tenantConnection = tenant.getConnection(); synchronized (this.tenantToDataSourceMap) { - // if tenantConnection information available switch to the appropriate datasource for that tenant. + // if tenantConnection information available switch to the + // appropriate datasource for that tenant. DataSource possibleDS = this.tenantToDataSourceMap.get(tenantConnection.getConnectionId()); if (possibleDS != null) { tenantDataSource = possibleDS; @@ -78,7 +79,8 @@ public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceSe // creates the tenant data source for the oltp and report database private DataSource createNewDataSourceFor(final FineractPlatformTenantConnection tenantConnectionObj) { - String jdbcUrl = this.driverConfig.constructProtocol(tenantConnectionObj.getSchemaServer(), tenantConnectionObj.getSchemaServerPort(), tenantConnectionObj.getSchemaName()); + String jdbcUrl = this.driverConfig.constructProtocol(tenantConnectionObj.getSchemaServer(), + tenantConnectionObj.getSchemaServerPort(), tenantConnectionObj.getSchemaName()); HikariConfig config = new HikariConfig(); config.setDriverClassName(this.driverConfig.getDriverClassName()); @@ -96,7 +98,9 @@ public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceSe config.setRegisterMbeans(true); // https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration - // These are the properties for each Tenant DB; the same configuration is also in src/main/resources/META-INF/spring/hikariDataSource.xml for the all Tenants DB --> + // These are the properties for each Tenant DB; the same configuration + // is also in src/main/resources/META-INF/spring/hikariDataSource.xml + // for the all Tenants DB --> config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); @@ -109,10 +113,11 @@ public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceSe config.addDataSourceProperty("maintainTimeStats", "false"); // https://github.com/brettwooldridge/HikariCP/wiki/JDBC-Logging#mysql-connectorj - // TODO FINERACT-890: config.addDataSourceProperty("logger", "com.mysql.cj.log.Slf4JLogger"); + // TODO FINERACT-890: config.addDataSourceProperty("logger", + // "com.mysql.cj.log.Slf4JLogger"); config.addDataSourceProperty("logSlowQueries", "true"); config.addDataSourceProperty("dumpQueriesOnException", "true"); return new HikariDataSource(config); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/api/CreditBureauConfigurationAPI.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/api/CreditBureauConfigurationAPI.java index 511947c44..a7993969d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/api/CreditBureauConfigurationAPI.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/api/CreditBureauConfigurationAPI.java @@ -59,6 +59,7 @@ import org.springframework.stereotype.Component; @Scope("singleton") @Api(value = "CreditBureau Configuration") public class CreditBureauConfigurationAPI { + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( Arrays.asList("creditBureauId", "alias", "country", "creditBureauProductId", "startDate", "endDate", "isActive")); private final String resourceNameForPermissions = "CreditBureau"; @@ -75,8 +76,7 @@ public class CreditBureauConfigurationAPI { private final CreditBureauReadConfigurationService creditBureauConfiguration; @Autowired - public CreditBureauConfigurationAPI(final PlatformSecurityContext context, - final CreditBureauReadPlatformService readPlatformService, + public CreditBureauConfigurationAPI(final PlatformSecurityContext context, final CreditBureauReadPlatformService readPlatformService, final DefaultToApiJsonSerializer toApiJsonSerializer, final CreditBureauLoanProductMappingReadPlatformService readPlatformServiceCreditBureauLoanProduct, final DefaultToApiJsonSerializer toApiJsonSerializerCreditBureauLoanProduct, @@ -108,8 +108,7 @@ public class CreditBureauConfigurationAPI { final Collection creditBureau = this.readPlatformService.retrieveCreditBureau(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, creditBureau, this.RESPONSE_DATA_PARAMETERS); } @@ -124,9 +123,9 @@ public class CreditBureauConfigurationAPI { final Collection creditBureauLoanProductMapping = this.readPlatformServiceCreditBureauLoanProduct .readCreditBureauLoanProductMapping(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping, this.RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping, + this.RESPONSE_DATA_PARAMETERS); } @@ -140,8 +139,7 @@ public class CreditBureauConfigurationAPI { final Collection organisationCreditBureau = this.readPlatformServiceOrganisationCreditBureau .retrieveOrgCreditBureau(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializerOrganisationCreditBureau.serialize(settings, organisationCreditBureau, this.RESPONSE_DATA_PARAMETERS); @@ -151,7 +149,8 @@ public class CreditBureauConfigurationAPI { @Path("/config/{organisationCreditBureauId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String getConfiguration(@PathParam("organisationCreditBureauId") final Long organisationCreditBureauId, @Context final UriInfo uriInfo) { + public String getConfiguration(@PathParam("organisationCreditBureauId") final Long organisationCreditBureauId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -161,7 +160,6 @@ public class CreditBureauConfigurationAPI { return this.toApiJsonSerializerReport.serialize(configurationData); } - @GET @Path("/loanProduct") @Consumes({ MediaType.APPLICATION_JSON }) @@ -172,9 +170,9 @@ public class CreditBureauConfigurationAPI { final Collection creditBureauLoanProductMapping = this.readPlatformServiceCreditBureauLoanProduct .fetchLoanProducts(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping, this.RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping, + this.RESPONSE_DATA_PARAMETERS); } @PUT @@ -183,8 +181,7 @@ public class CreditBureauConfigurationAPI { @Produces({ MediaType.APPLICATION_JSON }) public String updateCreditBureau(final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCreditBureau() - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCreditBureau().withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -209,7 +206,8 @@ public class CreditBureauConfigurationAPI { @Path("/organisationCreditBureau/{organisationCreditBureauId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String addOrganisationCreditBureau(@PathParam("organisationCreditBureauId") final Long organisationCreditBureauId, final String apiRequestBodyAsJson) { + public String addOrganisationCreditBureau(@PathParam("organisationCreditBureauId") final Long organisationCreditBureauId, + final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().addOrganisationCreditBureau(organisationCreditBureauId) .withJson(apiRequestBodyAsJson).build(); @@ -223,7 +221,8 @@ public class CreditBureauConfigurationAPI { @Path("/mappings/{CreditBureauId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String createCreditBureauLoanProductMapping(@PathParam("CreditBureauId") final Long CreditBureauId, final String apiRequestBodyAsJson) { + public String createCreditBureauLoanProductMapping(@PathParam("CreditBureauId") final Long CreditBureauId, + final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createCreditBureauLoanProductMapping(CreditBureauId) .withJson(apiRequestBodyAsJson).build(); @@ -233,6 +232,4 @@ public class CreditBureauConfigurationAPI { return this.toApiJsonSerializer.serialize(result); } - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauConfigurationData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauConfigurationData.java index 868707190..a54ea9ba9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauConfigurationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauConfigurationData.java @@ -19,6 +19,7 @@ package org.apache.fineract.infrastructure.creditbureau.data; public class CreditBureauConfigurationData { + private final long creditBureauConfigurationId; private final String configurationKey; @@ -29,8 +30,8 @@ public class CreditBureauConfigurationData { private final String description; - private CreditBureauConfigurationData(final long creditBureauConfigurationId, final String configurationKey, - final String value, final long organizationCreditBureauId, final String description) { + private CreditBureauConfigurationData(final long creditBureauConfigurationId, final String configurationKey, final String value, + final long organizationCreditBureauId, final String description) { this.creditBureauConfigurationId = creditBureauConfigurationId; this.configurationKey = configurationKey; this.value = value; @@ -41,8 +42,8 @@ public class CreditBureauConfigurationData { public static CreditBureauConfigurationData instance(final long creditBureauConfigurationId, final String configurationKey, final String value, final long organizationCreditBureauId, final String description) { - return new CreditBureauConfigurationData(creditBureauConfigurationId, configurationKey, value, - organizationCreditBureauId, description); + return new CreditBureauConfigurationData(creditBureauConfigurationId, configurationKey, value, organizationCreditBureauId, + description); } public long getCreditBureauConfigurationId() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java index 9106d53ff..31382af3c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java @@ -32,8 +32,8 @@ public class CreditBureauData { private final long implementationKey; - private CreditBureauData(final long creditBureauId, final String creditBureauName, final String country, - final String productName, final String creditBureauSummary, final long implementationKey) { + private CreditBureauData(final long creditBureauId, final String creditBureauName, final String country, final String productName, + final String creditBureauSummary, final long implementationKey) { this.creditBureauId = creditBureauId; this.creditBureauName = creditBureauName; this.country = country; @@ -43,11 +43,10 @@ public class CreditBureauData { } - public static CreditBureauData instance(final long creditBureauId, final String creditBureauName, - final String country, final String productName, final String creditBureauSummary, final long implementationKey) { + public static CreditBureauData instance(final long creditBureauId, final String creditBureauName, final String country, + final String productName, final String creditBureauSummary, final long implementationKey) { - return new CreditBureauData(creditBureauId, creditBureauName, country, productName, creditBureauSummary, - implementationKey); + return new CreditBureauData(creditBureauId, creditBureauName, country, productName, creditBureauSummary, implementationKey); } public String getCreditBureauSummary() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauLoanProductMappingData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauLoanProductMappingData.java index 2969010da..9eb08ac40 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauLoanProductMappingData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauLoanProductMappingData.java @@ -40,10 +40,9 @@ public class CreditBureauLoanProductMappingData { private final boolean is_active; - private CreditBureauLoanProductMappingData(final long creditbureauLoanProductMappingId, - final long organisationCreditBureauId, final String alias, final String creditbureauSummary, - final String loanProductName, final long loanProductId, final boolean isCreditCheckMandatory, - final boolean skipCrediCheckInFailure, final long stalePeriod, final boolean is_active) { + private CreditBureauLoanProductMappingData(final long creditbureauLoanProductMappingId, final long organisationCreditBureauId, + final String alias, final String creditbureauSummary, final String loanProductName, final long loanProductId, + final boolean isCreditCheckMandatory, final boolean skipCrediCheckInFailure, final long stalePeriod, final boolean is_active) { this.creditbureauLoanProductMappingId = creditbureauLoanProductMappingId; this.organisationCreditBureauId = organisationCreditBureauId; this.alias = alias; @@ -57,12 +56,12 @@ public class CreditBureauLoanProductMappingData { } public static CreditBureauLoanProductMappingData instance(final long creditbureauLoanProductMappingId, - final long organisationCreditBureauId, final String alias, final String creditbureauSummary, - final String loanProductName, final long loanProductId, final boolean isCreditCheckMandatory, - final boolean skipCrediCheckInFailure, final long stalePeriod, final boolean is_active) { + final long organisationCreditBureauId, final String alias, final String creditbureauSummary, final String loanProductName, + final long loanProductId, final boolean isCreditCheckMandatory, final boolean skipCrediCheckInFailure, final long stalePeriod, + final boolean is_active) { return new CreditBureauLoanProductMappingData(creditbureauLoanProductMappingId, organisationCreditBureauId, alias, - creditbureauSummary, loanProductName, loanProductId, isCreditCheckMandatory, skipCrediCheckInFailure, - stalePeriod, is_active); + creditbureauSummary, loanProductName, loanProductId, isCreditCheckMandatory, skipCrediCheckInFailure, stalePeriod, + is_active); } public static CreditBureauLoanProductMappingData instance1(final String loanProductName, final long loanProductId) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauProduct.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauProduct.java index 253be4296..c2c42dd4b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauProduct.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauProduct.java @@ -26,8 +26,7 @@ public class CreditBureauProduct { private final long creditBureauMasterId; - private CreditBureauProduct(final long creditBureauProductId, final String creditBureauProductName, - final long creditBureauMasterId) { + private CreditBureauProduct(final long creditBureauProductId, final String creditBureauProductName, final long creditBureauMasterId) { this.creditBureauProductId = creditBureauProductId; this.creditBureauProductName = creditBureauProductName; this.creditBureauMasterId = creditBureauMasterId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/OrganisationCreditBureauData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/OrganisationCreditBureauData.java index 1bc9ac6e2..409bc0ebf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/OrganisationCreditBureauData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/OrganisationCreditBureauData.java @@ -36,9 +36,9 @@ public class OrganisationCreditBureauData { private final boolean is_active; - private OrganisationCreditBureauData(final long organisationCreditBureauId, final String alias, - final long creditBureauId, final String creditBureauName, final String creditBureauProduct, - final String creditBureauCountry, final String creditBureauSummary, final boolean is_active) { + private OrganisationCreditBureauData(final long organisationCreditBureauId, final String alias, final long creditBureauId, + final String creditBureauName, final String creditBureauProduct, final String creditBureauCountry, + final String creditBureauSummary, final boolean is_active) { this.organisationCreditBureauId = organisationCreditBureauId; this.alias = alias; this.creditBureauId = creditBureauId; @@ -50,10 +50,10 @@ public class OrganisationCreditBureauData { } public static OrganisationCreditBureauData instance(final long organisationCreditBureauId, final String alias, - final long creditBureauId, final String creditBureauName, final String creditBureauProduct, - final String creditBureauCountry, final String creditBureauSummary, final boolean is_active) { - return new OrganisationCreditBureauData(organisationCreditBureauId, alias, creditBureauId, creditBureauName, - creditBureauProduct, creditBureauCountry, creditBureauSummary, is_active); + final long creditBureauId, final String creditBureauName, final String creditBureauProduct, final String creditBureauCountry, + final String creditBureauSummary, final boolean is_active) { + return new OrganisationCreditBureauData(organisationCreditBureauId, alias, creditBureauId, creditBureauName, creditBureauProduct, + creditBureauCountry, creditBureauSummary, is_active); } public long getOrganisationCreditBureauId() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureau.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureau.java index b46d46a44..a891b35c7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureau.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureau.java @@ -31,7 +31,6 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "m_creditbureau") public class CreditBureau extends AbstractPersistableCustom { - private String name; private String product; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauConfiguration.java index d6f819112..a4982b794 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauConfiguration.java @@ -29,6 +29,7 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity @Table(name = "m_creditbureau_configuration") public class CreditBureauConfiguration extends AbstractPersistableCustom { + @Column(name = "configkey") private String configurationKey; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauLoanProductMapping.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauLoanProductMapping.java index 7a697fa59..98756a1a7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauLoanProductMapping.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauLoanProductMapping.java @@ -47,7 +47,7 @@ public class CreditBureauLoanProductMapping extends AbstractPersistableCustom { private OrganisationCreditBureau organisation_creditbureau; @OneToOne - @JoinColumn(name="loan_product_id") + @JoinColumn(name = "loan_product_id") private LoanProduct loanProduct; public CreditBureauLoanProductMapping() { @@ -64,32 +64,27 @@ public class CreditBureauLoanProductMapping extends AbstractPersistableCustom { this.loanProduct = loanProduct; } - public static CreditBureauLoanProductMapping fromJson(final JsonCommand command, - OrganisationCreditBureau organisation_creditbureau, LoanProduct loanProduct) { - Boolean isCreditCheckMandatory=false; - Boolean skipCreditCheckInFailure=false; - Integer stalePeriod=-1; - Boolean is_active=false; - if((Boolean)command.booleanPrimitiveValueOfParameterNamed("isCreditcheckMandatory")!=null) - { - isCreditCheckMandatory = command.booleanPrimitiveValueOfParameterNamed("isCreditcheckMandatory"); - } + public static CreditBureauLoanProductMapping fromJson(final JsonCommand command, OrganisationCreditBureau organisation_creditbureau, + LoanProduct loanProduct) { + Boolean isCreditCheckMandatory = false; + Boolean skipCreditCheckInFailure = false; + Integer stalePeriod = -1; + Boolean is_active = false; + if ((Boolean) command.booleanPrimitiveValueOfParameterNamed("isCreditcheckMandatory") != null) { + isCreditCheckMandatory = command.booleanPrimitiveValueOfParameterNamed("isCreditcheckMandatory"); + } - if((Boolean)command.booleanPrimitiveValueOfParameterNamed("skipCreditcheckInFailure")!=null) - { - skipCreditCheckInFailure = command.booleanPrimitiveValueOfParameterNamed("skipCreditcheckInFailure"); - } + if ((Boolean) command.booleanPrimitiveValueOfParameterNamed("skipCreditcheckInFailure") != null) { + skipCreditCheckInFailure = command.booleanPrimitiveValueOfParameterNamed("skipCreditcheckInFailure"); + } - if(command.integerValueOfParameterNamed("stalePeriod")!=null) - { - stalePeriod = command.integerValueOfParameterNamed("stalePeriod"); - } - - if((Boolean) command.booleanPrimitiveValueOfParameterNamed("is_active")) - { - is_active = command.booleanPrimitiveValueOfParameterNamed("is_active"); - } + if (command.integerValueOfParameterNamed("stalePeriod") != null) { + stalePeriod = command.integerValueOfParameterNamed("stalePeriod"); + } + if ((Boolean) command.booleanPrimitiveValueOfParameterNamed("is_active")) { + is_active = command.booleanPrimitiveValueOfParameterNamed("is_active"); + } return new CreditBureauLoanProductMapping(isCreditCheckMandatory, skipCreditCheckInFailure, stalePeriod, is_active, organisation_creditbureau, loanProduct); @@ -144,6 +139,4 @@ public class CreditBureauLoanProductMapping extends AbstractPersistableCustom { this.loanProduct = loanProduct; } - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauRepository.java index 26287ef35..1b0c93fcb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/CreditBureauRepository.java @@ -19,11 +19,11 @@ package org.apache.fineract.infrastructure.creditbureau.domain; //import org.apache.fineract.infrastructure.jobs.domain.ScheduledJobDetail; + import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface CreditBureauRepository - extends JpaRepository, JpaSpecificationExecutor { +public interface CreditBureauRepository extends JpaRepository, JpaSpecificationExecutor { // CreditBureau findOne(long id); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/OrganisationCreditBureau.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/OrganisationCreditBureau.java index 25a08b35d..cbe8bc024 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/OrganisationCreditBureau.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/domain/OrganisationCreditBureau.java @@ -93,6 +93,4 @@ public class OrganisationCreditBureau extends AbstractPersistableCustom { this.creditBureauLoanProductMapping = creditBureauLoanProductMapping; } - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/CreateCreditBureauLoanProductMappingCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/CreateCreditBureauLoanProductMappingCommandHandler.java index a96e62f8d..3d883d3e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/CreateCreditBureauLoanProductMappingCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/CreateCreditBureauLoanProductMappingCommandHandler.java @@ -33,7 +33,8 @@ public class CreateCreditBureauLoanProductMappingCommandHandler implements NewCo private final CreditBureauLoanProductMappingWritePlatformService writePlatformService; @Autowired - public CreateCreditBureauLoanProductMappingCommandHandler(final CreditBureauLoanProductMappingWritePlatformService writePlatformService) { + public CreateCreditBureauLoanProductMappingCommandHandler( + final CreditBureauLoanProductMappingWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/UpdateCreditBureauLoanProductMappingCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/UpdateCreditBureauLoanProductMappingCommandHandler.java index a7ed740e1..b708ac2b8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/UpdateCreditBureauLoanProductMappingCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/handler/UpdateCreditBureauLoanProductMappingCommandHandler.java @@ -34,7 +34,8 @@ public class UpdateCreditBureauLoanProductMappingCommandHandler implements NewCo private final CreditBureauLoanProductMappingWritePlatformService writePlatformService; @Autowired - public UpdateCreditBureauLoanProductMappingCommandHandler(final CreditBureauLoanProductMappingWritePlatformService writePlatformService) { + public UpdateCreditBureauLoanProductMappingCommandHandler( + final CreditBureauLoanProductMappingWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/serialization/CreditBureauCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/serialization/CreditBureauCommandFromApiJsonDeserializer.java index 5459643b4..e048dfef9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/serialization/CreditBureauCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/serialization/CreditBureauCommandFromApiJsonDeserializer.java @@ -39,7 +39,7 @@ import org.springframework.stereotype.Component; @Component public class CreditBureauCommandFromApiJsonDeserializer { - private final Set supportedParameters = new HashSet<>(Arrays.asList("alias", "is_active","creditBureauId")); + private final Set supportedParameters = new HashSet<>(Arrays.asList("alias", "is_active", "creditBureauId")); private final FromJsonHelper fromApiJsonHelper; @@ -49,17 +49,13 @@ public class CreditBureauCommandFromApiJsonDeserializer { } public void validateForCreate(final String json, final Long creditBureauId) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource("CreditBureau"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("CreditBureau"); final JsonElement element = this.fromApiJsonHelper.parse(json); @@ -77,25 +73,17 @@ public class CreditBureauCommandFromApiJsonDeserializer { throwExceptionIfValidationWarningsExist(dataValidationErrors); } + public void validateForUpdate(final String json) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - public void validateForUpdate(final String json) - { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - final Type typeOfMap = new TypeToken>() { - }.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource("CreditBureau"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("CreditBureau"); final JsonElement element = this.fromApiJsonHelper.parse(json); - final String creditBureauIdParameter = "creditBureauId"; if (this.fromApiJsonHelper.parameterExists(creditBureauIdParameter, element)) { final Long creditBureauId = this.fromApiJsonHelper.extractLongNamed("creditBureauId", element); @@ -108,15 +96,14 @@ public class CreditBureauCommandFromApiJsonDeserializer { baseDataValidator.reset().parameter("is_active").value(is_active).notNull().notBlank().trueOrFalseRequired(is_active); } - throwExceptionIfValidationWarningsExist(dataValidationErrors); } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/serialization/CreditBureauLoanProductCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/serialization/CreditBureauLoanProductCommandFromApiJsonDeserializer.java index 6a6b75322..42118eaf2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/serialization/CreditBureauLoanProductCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/serialization/CreditBureauLoanProductCommandFromApiJsonDeserializer.java @@ -38,8 +38,9 @@ import org.springframework.stereotype.Component; @Component public class CreditBureauLoanProductCommandFromApiJsonDeserializer { - private final Set supportedParameters = new HashSet<>(Arrays.asList("loanProductId", - "isCreditcheckMandatory", "skipCreditcheckInFailure", "stalePeriod", "is_active", "locale","creditbureauLoanProductMappingId")); + + private final Set supportedParameters = new HashSet<>(Arrays.asList("loanProductId", "isCreditcheckMandatory", + "skipCreditcheckInFailure", "stalePeriod", "is_active", "locale", "creditbureauLoanProductMappingId")); private final FromJsonHelper fromApiJsonHelper; @@ -49,12 +50,9 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer { } public void validateForCreate(final String json, final Long cb_id) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList<>(); @@ -66,51 +64,38 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer { baseDataValidator.reset().value(cb_id).notBlank().integerGreaterThanZero(); final long loanProductId = this.fromApiJsonHelper.extractLongNamed("loanProductId", element); - baseDataValidator.reset().parameter("loanProductId").value(loanProductId).notBlank() - .integerGreaterThanZero(); + baseDataValidator.reset().parameter("loanProductId").value(loanProductId).notBlank().integerGreaterThanZero(); - - if(this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory",element)!= null) - { - final boolean isCreditcheckMandatory = this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", - element); + if (this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element) != null) { + final boolean isCreditcheckMandatory = this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element); baseDataValidator.reset().parameter("isCreditcheckMandatory").value(isCreditcheckMandatory).notBlank() .trueOrFalseRequired(isCreditcheckMandatory); - } - else - { - baseDataValidator.reset().parameter("isCreditcheckMandatory").value(this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", - element)).notBlank() - .trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", - element)); + } else { + baseDataValidator.reset().parameter("isCreditcheckMandatory") + .value(this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element)).notBlank() + .trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element)); } - - if( this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element)!=null) - { + if (this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element) != null) { final boolean skipCreditcheckInFailure = this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element); - baseDataValidator.reset().parameter("skipCreditcheckInFailure").value(skipCreditcheckInFailure).notBlank().trueOrFalseRequired(skipCreditcheckInFailure); + baseDataValidator.reset().parameter("skipCreditcheckInFailure").value(skipCreditcheckInFailure).notBlank() + .trueOrFalseRequired(skipCreditcheckInFailure); - } - else - { - baseDataValidator.reset().parameter("skipCreditcheckInFailure").value(this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element)).notBlank().trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element)); + } else { + baseDataValidator.reset().parameter("skipCreditcheckInFailure") + .value(this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element)).notBlank() + .trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element)); } - - if(this.fromApiJsonHelper.extractLongNamed("stalePeriod", element)!=null) - { + if (this.fromApiJsonHelper.extractLongNamed("stalePeriod", element) != null) { final long stalePeriod = this.fromApiJsonHelper.extractLongNamed("stalePeriod", element); baseDataValidator.reset().parameter("stalePeriod").value(stalePeriod).notBlank().integerGreaterThanZero(); - } - else - { - baseDataValidator.reset().parameter("stalePeriod").value(this.fromApiJsonHelper.extractLongNamed("stalePeriod", element)).notBlank().integerGreaterThanZero(); + } else { + baseDataValidator.reset().parameter("stalePeriod").value(this.fromApiJsonHelper.extractLongNamed("stalePeriod", element)) + .notBlank().integerGreaterThanZero(); } - - if(this.fromApiJsonHelper.extractBooleanNamed("is_active", element)!=null) - { + if (this.fromApiJsonHelper.extractBooleanNamed("is_active", element) != null) { Boolean is_active = this.fromApiJsonHelper.extractBooleanNamed("is_active", element); if (is_active == null) { is_active = false; @@ -120,22 +105,14 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer { } } - - throwExceptionIfValidationWarningsExist(dataValidationErrors); } + public void validateForUpdate(final String json) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - public void validateForUpdate(final String json) - { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - final Type typeOfMap = new TypeToken>() { - }.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList<>(); @@ -144,11 +121,12 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer { final JsonElement element = this.fromApiJsonHelper.parse(json); - final String creditbureauLoanProductMappingIdParameter = "creditbureauLoanProductMappingId"; if (this.fromApiJsonHelper.parameterExists(creditbureauLoanProductMappingIdParameter, element)) { - final Long creditbureauLoanProductMappingId = this.fromApiJsonHelper.extractLongNamed("creditbureauLoanProductMappingId", element); - baseDataValidator.reset().parameter("creditbureauLoanProductMappingId").value(creditbureauLoanProductMappingId).notNull().notBlank().longGreaterThanZero(); + final Long creditbureauLoanProductMappingId = this.fromApiJsonHelper.extractLongNamed("creditbureauLoanProductMappingId", + element); + baseDataValidator.reset().parameter("creditbureauLoanProductMappingId").value(creditbureauLoanProductMappingId).notNull() + .notBlank().longGreaterThanZero(); } final String is_activeParameter = "is_active"; @@ -157,15 +135,14 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer { baseDataValidator.reset().parameter("is_active").value(is_active).notNull().notBlank().trueOrFalseRequired(is_active); } - throwExceptionIfValidationWarningsExist(dataValidationErrors); } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingReadPlatformServiceImpl.java index 0dc726a76..7ec5544f7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingReadPlatformServiceImpl.java @@ -31,6 +31,7 @@ import org.springframework.stereotype.Service; @Service public class CreditBureauLoanProductMappingReadPlatformServiceImpl implements CreditBureauLoanProductMappingReadPlatformService { + private final JdbcTemplate jdbcTemplate; private final PlatformSecurityContext context; @@ -66,8 +67,8 @@ public class CreditBureauLoanProductMappingReadPlatformServiceImpl implements Cr final int stale_period = rs.getInt("staleperiod"); final boolean is_active = rs.getBoolean("is_active"); - return CreditBureauLoanProductMappingData.instance(mapping_id, orgcbID, alias, credit_bureau_name, loan_product_name, - lpId, is_creditcheck_mandatory, skip_credit_check_in_failure, stale_period, is_active); + return CreditBureauLoanProductMappingData.instance(mapping_id, orgcbID, alias, credit_bureau_name, loan_product_name, lpId, + is_creditcheck_mandatory, skip_credit_check_in_failure, stale_period, is_active); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingWritePlatformServiceImpl.java index c8d5b8fbe..03ce84968 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauLoanProductMappingWritePlatformServiceImpl.java @@ -76,8 +76,7 @@ public class CreditBureauLoanProductMappingWritePlatformServiceImpl implements C this.creditBureauLoanProductMappingRepository.save(cb_lp); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(cb_lp.getId()) - .build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(cb_lp.getId()).build(); } @@ -92,7 +91,6 @@ public class CreditBureauLoanProductMappingWritePlatformServiceImpl implements C final CreditBureauLoanProductMapping cblpmapping = this.creditBureauLoanProductMappingRepository.getOne(mappingid); cblpmapping.setIs_active(is_active); this.creditBureauLoanProductMappingRepository.saveAndFlush(cblpmapping); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(cblpmapping.getId()) - .build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(cblpmapping.getId()).build(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadConfigurationServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadConfigurationServiceImpl.java index adfd8871c..06fa01591 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadConfigurationServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadConfigurationServiceImpl.java @@ -39,13 +39,13 @@ public class CreditBureauReadConfigurationServiceImpl implements CreditBureauRea private final PlatformSecurityContext context; @Autowired - public CreditBureauReadConfigurationServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { + public CreditBureauReadConfigurationServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); } private static final class CbConfigMapper implements RowMapper { + public String schema() { return "cbconfig.id as configId,cbconfig.configkey,cbconfig.value as configValue," @@ -54,8 +54,7 @@ public class CreditBureauReadConfigurationServiceImpl implements CreditBureauRea } @Override - public CreditBureauConfigurationData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public CreditBureauConfigurationData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final long configId = rs.getLong("configId"); final String configkey = rs.getString("configkey"); final String configValue = rs.getString("configValue"); @@ -86,8 +85,7 @@ public class CreditBureauReadConfigurationServiceImpl implements CreditBureauRea final CbConfigMapper rm = new CbConfigMapper(); final String sql = "select " + rm.schema() + " where cbconfig.organisation_creditbureau_id= ?"; - List config = this.jdbcTemplate.query(sql, - rm, new Object[] {id}); + List config = this.jdbcTemplate.query(sql, rm, new Object[] { id }); Map configuration = new HashMap(); for (CreditBureauConfigurationData data : config) { configuration.put(data.getConfigurationKey(), data.getValue()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadPlatformServiceImpl.java index f4d1196cc..6ca410fc9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReadPlatformServiceImpl.java @@ -36,21 +36,20 @@ public class CreditBureauReadPlatformServiceImpl implements CreditBureauReadPlat private final PlatformSecurityContext context; @Autowired - public CreditBureauReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { + public CreditBureauReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); } private static final class CBMapper implements RowMapper { + public String schema() { return "cb.id as creditBureauID,cb.name as creditBureauName,cb.product as creditBureauProduct," + "cb.country as country,concat(cb.product,' - ',cb.name,' - ',cb.country) as cbSummary,cb.implementationKey as implementationKey from m_creditbureau cb"; } @Override - public CreditBureauData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public CreditBureauData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final long id = rs.getLong("creditBureauID"); final String name = rs.getString("creditBureauName"); final String product = rs.getString("creditBureauProduct"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauReadPlatformService.java index 3327b8aa5..04246a937 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauReadPlatformService.java @@ -22,6 +22,7 @@ import java.util.Collection; import org.apache.fineract.infrastructure.creditbureau.data.OrganisationCreditBureauData; public interface OrganisationCreditBureauReadPlatformService { + Collection retrieveOrgCreditBureau(); OrganisationCreditBureauData retrieveOrgCreditBureauById(long orgCbId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauReadPlatformServiceImpl.java index 3d88f62ef..f2e225cb0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauReadPlatformServiceImpl.java @@ -36,13 +36,13 @@ public class OrganisationCreditBureauReadPlatformServiceImpl implements Organisa private final PlatformSecurityContext context; @Autowired - public OrganisationCreditBureauReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { + public OrganisationCreditBureauReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); } private static final class OrganisationCreditBureauMapper implements RowMapper { + public String schema() { return "ocb.id as orgCbId,ocb.alias as orgCbAlias,cb.name as creditbureauName,cb.product as creditbureauProduct,cb.country as creditbureauCountry," + "concat(cb.product,' - ',cb.name,' - ',cb.country) as CreditBureauSummary," @@ -52,8 +52,7 @@ public class OrganisationCreditBureauReadPlatformServiceImpl implements Organisa } @Override - public OrganisationCreditBureauData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public OrganisationCreditBureauData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final long orgCbId = rs.getLong("orgCbId"); final String orgCbAlias = rs.getString("orgCbAlias"); final String creditbureauName = rs.getString("creditbureauName"); @@ -63,8 +62,8 @@ public class OrganisationCreditBureauReadPlatformServiceImpl implements Organisa final long cbid = rs.getLong("cbid"); final boolean is_active = rs.getBoolean("is_active"); - return OrganisationCreditBureauData.instance(orgCbId, orgCbAlias, cbid, creditbureauName, - creditbureauProduct, creditbureauCountry, CreditBureauSummary, is_active); + return OrganisationCreditBureauData.instance(orgCbId, orgCbAlias, cbid, creditbureauName, creditbureauProduct, + creditbureauCountry, CreditBureauSummary, is_active); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauWritePlatflormServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauWritePlatflormServiceImpl.java index 55e158c2e..d73070cd1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauWritePlatflormServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/OrganisationCreditBureauWritePlatflormServiceImpl.java @@ -32,8 +32,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -public class OrganisationCreditBureauWritePlatflormServiceImpl - implements OrganisationCreditBureauWritePlatflormService { +public class OrganisationCreditBureauWritePlatflormServiceImpl implements OrganisationCreditBureauWritePlatflormService { private final PlatformSecurityContext context; @@ -45,8 +44,8 @@ public class OrganisationCreditBureauWritePlatflormServiceImpl @Autowired public OrganisationCreditBureauWritePlatflormServiceImpl(final PlatformSecurityContext context, - final OrganisationCreditBureauRepository organisationCreditBureauRepository, final CreditBureauRepository creditBureauRepository, - final CreditBureauCommandFromApiJsonDeserializer fromApiJsonDeserializer) { + final OrganisationCreditBureauRepository organisationCreditBureauRepository, + final CreditBureauRepository creditBureauRepository, final CreditBureauCommandFromApiJsonDeserializer fromApiJsonDeserializer) { this.context = context; this.organisationCreditBureauRepository = organisationCreditBureauRepository; this.creditBureauRepository = creditBureauRepository; @@ -72,7 +71,7 @@ public class OrganisationCreditBureauWritePlatflormServiceImpl @Transactional @Override public CommandProcessingResult updateCreditBureau(JsonCommand command) { - this.context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); final long creditbureauID = command.longValueOfParameterNamed("creditBureauId"); @@ -85,8 +84,7 @@ public class OrganisationCreditBureauWritePlatflormServiceImpl organisationCreditBureauRepository.saveAndFlush(orgcb); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(orgcb.getId()) - .build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(orgcb.getId()).build(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DataTableApiConstant.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DataTableApiConstant.java index 655cfdbcb..f71468bcc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DataTableApiConstant.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DataTableApiConstant.java @@ -26,8 +26,8 @@ public class DataTableApiConstant { public static final Integer CATEGORY_PPI = 200; public static final Integer CATEGORY_DEFAULT = 100; - public static final String categoryParamName ="category"; + public static final String categoryParamName = "category"; public static final String localParamName = "locale"; - public static final String DATATABLE_RESOURCE_NAME ="dataTables"; + public static final String DATATABLE_RESOURCE_NAME = "dataTables"; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DatatablesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DatatablesApiResource.java index f53502b58..19d323fbb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DatatablesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DatatablesApiResource.java @@ -62,10 +62,11 @@ import org.springframework.stereotype.Component; @Path("/datatables") @Component @Scope("singleton") -@Api(tags = {"Data Tables"}) +@Api(tags = { "Data Tables" }) @SwaggerDefinition(tags = { - @Tag(name = "Data Tables", description = "The datatables API allows you to plug-in your own tables (MySql) that have a relationship to a Apache Fineract core table. For example, you might want to add some extra client fields and record information about each of the clients' family members. Via the API you can create, read, update and delete entries for each 'plugged-in' table. The API checks for permission and for 'data scoping' (only data within the users' office hierarchy can be managed by the user).\n" + "\n" + "The Apache Fineract Reference App uses a JQuery plug-in called stretchydatatables (which in turn uses this datatables resource) to provide a pretty flexible CRUD (Create, Read, Update, Delete) User Interface.") -}) + @Tag(name = "Data Tables", description = "The datatables API allows you to plug-in your own tables (MySql) that have a relationship to a Apache Fineract core table. For example, you might want to add some extra client fields and record information about each of the clients' family members. Via the API you can create, read, update and delete entries for each 'plugged-in' table. The API checks for permission and for 'data scoping' (only data within the users' office hierarchy can be managed by the user).\n" + + "\n" + + "The Apache Fineract Reference App uses a JQuery plug-in called stretchydatatables (which in turn uses this datatables resource) to provide a pretty flexible CRUD (Create, Read, Update, Delete) User Interface.") }) public class DatatablesApiResource { private final PlatformSecurityContext context; @@ -90,10 +91,14 @@ public class DatatablesApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Data Tables", notes = "Lists registered data tables and the Apache Fineract Core application table they are registered to.\n" + "\n" + "ARGUMENTS\n" + "\n" + "apptable - optional" + "\n"+ "The Apache Fineract core application table.\n" + "\n" + "Example Requests:\n" + "\n" + "datatables?apptable=m_client\n" + "\n" + "\n" + "datatables", - responseContainer = "List", response = DatatablesApiResourceSwagger.GetDataTablesResponse.class) - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.GetDataTablesResponse.class, responseContainer = "list")}) - public String getDatatables(@QueryParam("apptable") @ApiParam(value = "apptable") final String apptable, @Context final UriInfo uriInfo) { + @ApiOperation(value = "List Data Tables", notes = "Lists registered data tables and the Apache Fineract Core application table they are registered to.\n" + + "\n" + "ARGUMENTS\n" + "\n" + "apptable - optional" + "\n" + "The Apache Fineract core application table.\n" + "\n" + + "Example Requests:\n" + "\n" + "datatables?apptable=m_client\n" + "\n" + "\n" + + "datatables", responseContainer = "List", response = DatatablesApiResourceSwagger.GetDataTablesResponse.class) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.GetDataTablesResponse.class, responseContainer = "list") }) + public String getDatatables(@QueryParam("apptable") @ApiParam(value = "apptable") final String apptable, + @Context final UriInfo uriInfo) { final List result = this.readWriteNonCoreDataService.retrieveDatatableNames(apptable); @@ -104,12 +109,26 @@ public class DatatablesApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create Data Table", notes = "Create a new data table and registers it with the Apache Fineract Core application table.\n" + "\n" + "Field Descriptions\n" + "\n" + "Mandatory - datatableName : \n"+ "\nThe name of the Data Table.\n" + "\n" + "Mandatory - apptableName\n" + "\n" + "Application table name. Must be one of the following:\n" + "\n" + "m_client\n" + "\n" + "m_group" +"\n" + "\n" + "m_loan" + "\n" + "\n" + "m_office" + "\n" + "\n" + "m_saving_account" + "\n" + "\n" + "m_product_loan" + "\n" + "\n" + "m_savings_product" + "\n" + "\n" + "Mandatory - columns " + "\n" + "An array of columns in the new Data Table." + "\n" + "\n" + "Optional - multiRow" + "\n" + - "\n" + "Allows to create multiple entries in the Data Table. Optional, defaults to false. If this property is not provided Data Table will allow only one entry." + "\n" + "\n" + "Field Descriptions - columns" + "\n" + "\n" + "Mandatory - name" + "\n" + "\n" + "Name of the created column. Can contain only alphanumeric characters, underscores and spaces, but cannot start with a number. Cannot start or end with an underscore or space." + "\n" + "\n" + "Mandatory - type" + "\n" + "\n" + "Column type. Must be one of the following:" + "\n" + "\n" + "Boolean" + "\n" + "\n" + "Date" + "\n" + "\n" + "DateTime" + "\n" + "\n" + "Decimal" + "\n" + "\n" + "Dropdown" + "\n" + - "\n" + "\n" + "Number" + "\n" + "\n" + "String" + "\n" + "\n" + "Text" + "\n" + "\n" + "Mandatory [type = Dropdown] - code" + "\n" + "\n" + "Used in Code Value fields. Column name becomes: code_cd_name. Mandatory if using type Dropdown, otherwise an error is returned." + "\n" + "\n" + "Optional - mandatory" + "\n" + "\n" + - "Determines whether this column must have a value in every entry. Optional, defaults to false." + "\n" + "\n" + "Mandatory [type = String] - length" + "\n" + "\n" + "Length of the text field. Mandatory if type String is used, otherwise an error is returned.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PostDataTablesRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PostDataTablesResponse.class)}) + @ApiOperation(value = "Create Data Table", notes = "Create a new data table and registers it with the Apache Fineract Core application table.\n" + + "\n" + "Field Descriptions\n" + "\n" + "Mandatory - datatableName : \n" + "\nThe name of the Data Table.\n" + "\n" + + "Mandatory - apptableName\n" + "\n" + "Application table name. Must be one of the following:\n" + "\n" + "m_client\n" + "\n" + + "m_group" + "\n" + "\n" + "m_loan" + "\n" + "\n" + "m_office" + "\n" + "\n" + "m_saving_account" + "\n" + "\n" + + "m_product_loan" + "\n" + "\n" + "m_savings_product" + "\n" + "\n" + "Mandatory - columns " + "\n" + + "An array of columns in the new Data Table." + "\n" + "\n" + "Optional - multiRow" + "\n" + "\n" + + "Allows to create multiple entries in the Data Table. Optional, defaults to false. If this property is not provided Data Table will allow only one entry." + + "\n" + "\n" + "Field Descriptions - columns" + "\n" + "\n" + "Mandatory - name" + "\n" + "\n" + + "Name of the created column. Can contain only alphanumeric characters, underscores and spaces, but cannot start with a number. Cannot start or end with an underscore or space." + + "\n" + "\n" + "Mandatory - type" + "\n" + "\n" + "Column type. Must be one of the following:" + "\n" + "\n" + "Boolean" + "\n" + + "\n" + "Date" + "\n" + "\n" + "DateTime" + "\n" + "\n" + "Decimal" + "\n" + "\n" + "Dropdown" + "\n" + "\n" + "\n" + "Number" + + "\n" + "\n" + "String" + "\n" + "\n" + "Text" + "\n" + "\n" + "Mandatory [type = Dropdown] - code" + "\n" + "\n" + + "Used in Code Value fields. Column name becomes: code_cd_name. Mandatory if using type Dropdown, otherwise an error is returned." + + "\n" + "\n" + "Optional - mandatory" + "\n" + "\n" + + "Determines whether this column must have a value in every entry. Optional, defaults to false." + "\n" + "\n" + + "Mandatory [type = String] - length" + "\n" + "\n" + + "Length of the text field. Mandatory if type String is used, otherwise an error is returned.") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PostDataTablesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PostDataTablesResponse.class) }) public String createDatatable(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createDBDatatable(apiRequestBodyAsJson).build(); @@ -123,9 +142,11 @@ public class DatatablesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update Data Table", notes = "Modifies fields of a data table. If the apptableName parameter is passed, data table is deregistered and registered with the new application table.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PutDataTablesRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PutDataTablesResponse.class)}) - public String updateDatatable(@PathParam("datatableName") @ApiParam(value = "datatableName") final String datatableName, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PutDataTablesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PutDataTablesResponse.class) }) + public String updateDatatable(@PathParam("datatableName") @ApiParam(value = "datatableName") final String datatableName, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateDBDatatable(datatableName, apiRequestBodyAsJson).build(); @@ -138,8 +159,9 @@ public class DatatablesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete Data Table", notes = "Deletes a data table and deregisters it from the Apache Fineract Core application table.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.DeleteDataTablesResponse.class)}) - public String deleteDatatable(@PathParam("datatableName") @ApiParam(value = "datatableName") final String datatableName, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiResponses({ @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.DeleteDataTablesResponse.class) }) + public String deleteDatatable(@PathParam("datatableName") @ApiParam(value = "datatableName") final String datatableName, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteDBDatatable(datatableName, apiRequestBodyAsJson).build(); @@ -152,9 +174,11 @@ public class DatatablesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Register Data Table", notes = "Registers a data table with the Apache Fineract Core application table. This allows the data table to be maintained through the API. In case the datatable is a PPI (survey table), a parameter category should be pass along with the request. The API currently support one category (200)") - @ApiImplicitParams({@ApiImplicitParam(value = "body", paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PostDataTablesRegisterDatatableAppTable.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PutDataTablesResponse.class)}) - public String registerDatatable(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, @PathParam("apptable") @ApiParam(value = "apptable") final String apptable, + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PostDataTablesRegisterDatatableAppTable.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PutDataTablesResponse.class) }) + public String registerDatatable(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, + @PathParam("apptable") @ApiParam(value = "apptable") final String apptable, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().registerDBDatatable(datatable, apptable) @@ -170,7 +194,7 @@ public class DatatablesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Deregister Data Table", notes = "Deregisters a data table. It will no longer be available through the API.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PutDataTablesResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PutDataTablesResponse.class) }) public String deregisterDatatable(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable) { this.readWriteNonCoreDataService.deregisterDatatable(datatable); @@ -185,8 +209,9 @@ public class DatatablesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieve Data Table Details", notes = "Lists a registered data table details and the Apache Fineract Core application table they are registered to.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.GetDataTablesResponse.class)}) - public String getDatatable(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, @Context final UriInfo uriInfo) { + @ApiResponses({ @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.GetDataTablesResponse.class) }) + public String getDatatable(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, + @Context final UriInfo uriInfo) { final DatatableData result = this.readWriteNonCoreDataService.retrieveDatatable(datatable); @@ -198,9 +223,16 @@ public class DatatablesApiResource { @Path("{datatable}/{apptableId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Entry(s) from Data Table", notes = "Gets the entry (if it exists) for data tables that are one to one with the application table. \n" + "Gets the entries (if they exist) for data tables that are one to many with the application table.\n" + "\n" + "Note: The 'fields' parameter is not available for datatables.\n" + "\n" + "ARGUMENTS\n" + "orderoptional Specifies the order in which data is returned.genericResultSetoptional, defaults to false If 'true' an optimised JSON format is returned suitable for tabular display of data. This format is used by the default data tables UI functionality.\n" + "Example Requests:\n" + "\n" + "datatables/extra_client_details/1\n" + "\n" + "\n" + "datatables/extra_family_details/1?order=`Date of Birth` desc\n" + "\n" + "\n" + "datatables/extra_client_details/1?genericResultSet=true") - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.GetDataTablesAppTableIdResponse.class)}) - public String getDatatable(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, + @ApiOperation(value = "Retrieve Entry(s) from Data Table", notes = "Gets the entry (if it exists) for data tables that are one to one with the application table. \n" + + "Gets the entries (if they exist) for data tables that are one to many with the application table.\n" + "\n" + + "Note: The 'fields' parameter is not available for datatables.\n" + "\n" + "ARGUMENTS\n" + + "orderoptional Specifies the order in which data is returned.genericResultSetoptional, defaults to false If 'true' an optimised JSON format is returned suitable for tabular display of data. This format is used by the default data tables UI functionality.\n" + + "Example Requests:\n" + "\n" + "datatables/extra_client_details/1\n" + "\n" + "\n" + + "datatables/extra_family_details/1?order=`Date of Birth` desc\n" + "\n" + "\n" + + "datatables/extra_client_details/1?genericResultSet=true") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.GetDataTablesAppTableIdResponse.class) }) + public String getDatatable(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, + @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, @QueryParam("order") @ApiParam(value = "order") final String order, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasDatatableReadPermission(datatable); @@ -250,11 +282,15 @@ public class DatatablesApiResource { @Path("{datatable}/{apptableId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create Entry in Data Table", notes = "Adds a row to the data table.\n" + "\n" + "Note that the default datatable UI functionality converts any field name containing spaces to underscores when using the API. This means the field name \"Business Description\" is considered the same as \"Business_Description\". So you shouldn't have both \"versions\" in any data table.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PostDataTablesAppTableIdRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PostDataTablesAppTableIdResponse.class)}) - public String createDatatableEntry(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Create Entry in Data Table", notes = "Adds a row to the data table.\n" + "\n" + + "Note that the default datatable UI functionality converts any field name containing spaces to underscores when using the API. This means the field name \"Business Description\" is considered the same as \"Business_Description\". So you shouldn't have both \"versions\" in any data table.") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PostDataTablesAppTableIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PostDataTablesAppTableIdResponse.class) }) + public String createDatatableEntry(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, + @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createDatatable(datatable, apptableId, null) // @@ -271,10 +307,12 @@ public class DatatablesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update Entry in Data Table (One to One)", notes = "Updates the row (if it exists) of the data table.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PutDataTablesAppTableIdRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PutDataTablesAppTableIdResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PutDataTablesAppTableIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PutDataTablesAppTableIdResponse.class) }) public String updateDatatableEntryOnetoOne(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, - @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .updateDatatable(datatable, apptableId, null) // @@ -291,10 +329,13 @@ public class DatatablesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update Entry in Data Table (One to Many)", notes = "Updates the row (if it exists) of the data table.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PutDataTablesAppTableIdDatatableIdRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PutDataTablesAppTableIdDatatableIdResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = DatatablesApiResourceSwagger.PutDataTablesAppTableIdDatatableIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.PutDataTablesAppTableIdDatatableIdResponse.class) }) public String updateDatatableEntryOneToMany(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, - @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, @PathParam("datatableId") @ApiParam(value = "datatableId") final Long datatableId, + @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, + @PathParam("datatableId") @ApiParam(value = "datatableId") final Long datatableId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -311,9 +352,12 @@ public class DatatablesApiResource { @Path("{datatable}/{apptableId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Delete Entry(s) in Data Table", notes = "Deletes the entry (if it exists) for data tables that are one-to-one with the application table. \n" + "Deletes the entries (if they exist) for data tables that are one-to-many with the application table.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.DeleteDataTablesDatatableAppTableIdResponse.class)}) - public String deleteDatatableEntries(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId) { + @ApiOperation(value = "Delete Entry(s) in Data Table", notes = "Deletes the entry (if it exists) for data tables that are one-to-one with the application table. \n" + + "Deletes the entries (if they exist) for data tables that are one-to-many with the application table.") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.DeleteDataTablesDatatableAppTableIdResponse.class) }) + public String deleteDatatableEntries(@PathParam("datatable") @ApiParam(value = "datatable") final String datatable, + @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .deleteDatatable(datatable, apptableId, null) // @@ -328,9 +372,13 @@ public class DatatablesApiResource { @Path("{datatable}/{apptableId}/{datatableId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Delete Entry in Datatable (One to Many)", notes = "Deletes the entry (if it exists) for data tables that are one to many with the application table.\n" + "\n") - @ApiResponses({@ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.DeleteDataTablesDatatableAppTableIdDatatableIdResponse.class)}) - public String deleteDatatableEntries(@PathParam("datatable") @ApiParam(value = "datatable", type = "body", example = "{}") final String datatable, @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, + @ApiOperation(value = "Delete Entry in Datatable (One to Many)", notes = "Deletes the entry (if it exists) for data tables that are one to many with the application table.\n" + + "\n") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = DatatablesApiResourceSwagger.DeleteDataTablesDatatableAppTableIdDatatableIdResponse.class) }) + public String deleteDatatableEntries( + @PathParam("datatable") @ApiParam(value = "datatable", type = "body", example = "{}") final String datatable, + @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, @PathParam("datatableId") @ApiParam(value = "datatableId") final Long datatableId) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -341,4 +389,4 @@ public class DatatablesApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DatatablesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DatatablesApiResourceSwagger.java index 801c31d0c..7bf0ac475 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DatatablesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/DatatablesApiResourceSwagger.java @@ -28,15 +28,18 @@ import org.apache.fineract.infrastructure.dataqueries.data.ResultsetRowData; * Created by sanyam on 31/7/17. */ final class DatatablesApiResourceSwagger { + private DatatablesApiResourceSwagger() { } @ApiModel(value = "GetDataTablesResponse") public static final class GetDataTablesResponse { + private GetDataTablesResponse() { } + @ApiModelProperty(example = "m_client") public String appTableName; @ApiModelProperty(example = "extra_client_details") @@ -45,10 +48,12 @@ final class DatatablesApiResourceSwagger { } @ApiModel(value = "PostDataTablesRequest") - public static final class PostDataTablesRequest{ + public static final class PostDataTablesRequest { + private PostDataTablesRequest() { } + @ApiModelProperty(example = "m_client") public String applicationTableName; @ApiModelProperty(example = "extra_client_details") @@ -59,27 +64,35 @@ final class DatatablesApiResourceSwagger { } @ApiModel(value = "PostDataTablesResponse") - public static final class PostDataTablesResponse{ + public static final class PostDataTablesResponse { + private PostDataTablesResponse() { } + @ApiModelProperty(example = "extra_client_details") public String resourceIdentifier; } @ApiModel(value = "PutDataTablesRequest") - public static final class PutDataTablesRequest{ + public static final class PutDataTablesRequest { + private PutDataTablesRequest() { } + final class PutDataTablesRequestDropColumns { + private PutDataTablesRequestDropColumns() {} + @ApiModelProperty(example = "Gender_cd_Question") public String name; } + final class PutDataTablesRequestAddColumns { - private PutDataTablesRequestAddColumns() { - } + + private PutDataTablesRequestAddColumns() {} + @ApiModelProperty(example = "Question") public String name; @ApiModelProperty(example = "Dropdown") @@ -89,9 +102,11 @@ final class DatatablesApiResourceSwagger { @ApiModelProperty(example = "true") public boolean mandatory; } + final class PutDataTablesRequestChangeColumns { - private PutDataTablesRequestChangeColumns() { - } + + private PutDataTablesRequestChangeColumns() {} + @ApiModelProperty(example = "Question") public String name; @ApiModelProperty(example = "Question 2") @@ -103,6 +118,7 @@ final class DatatablesApiResourceSwagger { @ApiModelProperty(example = "true") public boolean mandatory; } + @ApiModelProperty(example = "m_client") public String appTableName; public List dropColumns; @@ -111,33 +127,40 @@ final class DatatablesApiResourceSwagger { } @ApiModel(value = "PutDataTablesResponse") - public static final class PutDataTablesResponse{ + public static final class PutDataTablesResponse { + private PutDataTablesResponse() { } + @ApiModelProperty(example = "extra_client_details") public String resourceIdentifier; } @ApiModel(value = "DeleteDataTablesResponse") - public static final class DeleteDataTablesResponse{ + public static final class DeleteDataTablesResponse { + private DeleteDataTablesResponse() { } + @ApiModelProperty(example = "extra_client_details") public String resourceIdentifier; } @ApiModel(value = "PostDataTablesRegisterDatatableAppTable") public static final class PostDataTablesRegisterDatatableAppTable { - private PostDataTablesRegisterDatatableAppTable () {} + + private PostDataTablesRegisterDatatableAppTable() {} } @ApiModel(value = "PostDataTablesAppTableIdRequest") - public static final class PostDataTablesAppTableIdRequest{ + public static final class PostDataTablesAppTableIdRequest { + private PostDataTablesAppTableIdRequest() { } + @ApiModelProperty(example = "Livestock sales") public String BusinessDescription; @ApiModelProperty(example = "First comment made") @@ -160,51 +183,64 @@ final class DatatablesApiResourceSwagger { @ApiModel(value = "PostDataTablesAppTableIdResponse ") public static final class PostDataTablesAppTableIdResponse { - private PostDataTablesAppTableIdResponse () { + + private PostDataTablesAppTableIdResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "GetDataTablesAppTableIdResponse") public static final class GetDataTablesAppTableIdResponse { + private GetDataTablesAppTableIdResponse() { } + public List columnHeaders; public List data; } @ApiModel(value = "PutDataTablesAppTableIdRequest") - public static final class PutDataTablesAppTableIdRequest{ + public static final class PutDataTablesAppTableIdRequest { + private PutDataTablesAppTableIdRequest() { } + @ApiModelProperty(example = "Livestock sales updated") public String BusinessDescription; } @ApiModel(value = "PutDataTablesAppTableIdResponse") public static final class PutDataTablesAppTableIdResponse { + private PutDataTablesAppTableIdResponse() { } - final class PutDataTablesAppTableIdResponseChanges{ - private PutDataTablesAppTableIdResponseChanges () {} + + final class PutDataTablesAppTableIdResponseChanges { + + private PutDataTablesAppTableIdResponseChanges() {} + @ApiModelProperty(example = "Livestock sales updated") public String BusinessDescription; } + @ApiModelProperty(example = "1") public Long resourceId; public PutDataTablesAppTableIdResponseChanges changes; } @ApiModel(value = "PutDataTablesAppTableIdDatatableIdRequest") - public static final class PutDataTablesAppTableIdDatatableIdRequest{ + public static final class PutDataTablesAppTableIdDatatableIdRequest { + private PutDataTablesAppTableIdDatatableIdRequest() { } + @ApiModelProperty(example = "01 June 1982") public String DateOfBirth; @ApiModelProperty(example = "5") @@ -223,27 +259,33 @@ final class DatatablesApiResourceSwagger { @ApiModel(value = "PutDataTablesAppTableIdDatatableIdResponse ") public static final class PutDataTablesAppTableIdDatatableIdResponse { - private PutDataTablesAppTableIdDatatableIdResponse () { + + private PutDataTablesAppTableIdDatatableIdResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "DeleteDataTablesDatatableAppTableIdResponse ") public static final class DeleteDataTablesDatatableAppTableIdResponse { - private DeleteDataTablesDatatableAppTableIdResponse () { + + private DeleteDataTablesDatatableAppTableIdResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "DeleteDataTablesDatatableAppTableIdDatatableIdResponse ") public static final class DeleteDataTablesDatatableAppTableIdDatatableIdResponse { - private DeleteDataTablesDatatableAppTableIdDatatableIdResponse () { + + private DeleteDataTablesDatatableAppTableIdDatatableIdResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/EntityDatatableChecksApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/EntityDatatableChecksApiResource.java index f00651aff..f2d1f3cdc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/EntityDatatableChecksApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/EntityDatatableChecksApiResource.java @@ -60,10 +60,8 @@ import org.springframework.stereotype.Component; @Path("/entityDatatableChecks") @Component @Scope("singleton") -@Api(tags = {"Entity Datatable Check"}) -@SwaggerDefinition(tags = { - @Tag(name = "Entity Data Table", description = "This defines Entity-Datatable Check.") -}) +@Api(tags = { "Entity Datatable Check" }) +@SwaggerDefinition(tags = { @Tag(name = "Entity Data Table", description = "This defines Entity-Datatable Check.") }) public class EntityDatatableChecksApiResource { private final PlatformSecurityContext context; @@ -88,11 +86,17 @@ public class EntityDatatableChecksApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Entity-Datatable Checks", notes = "The list capability of Entity-Datatable Checks can support pagination.\n" + "\n" + "OPTIONAL ARGUMENTS\n" + "offset Integer optional, defaults to 0 Indicates the result from which pagination startslimit Integer optional, defaults to 200 Restricts the size of results returned. To override the default and return all entries you must explicitly pass a non-positive integer value for limit e.g. limit=0, or limit=-1\n" + "Example Request:\n" + "\n" + "entityDatatableChecks?offset=0&limit=15") - @ApiResponses({@ApiResponse(code = 200, message = "", response = EntityDatatableChecksApiResourceSwagger.GetEntityDatatableChecksResponse.class, responseContainer = "list")}) + @ApiOperation(value = "List Entity-Datatable Checks", notes = "The list capability of Entity-Datatable Checks can support pagination.\n" + + "\n" + "OPTIONAL ARGUMENTS\n" + + "offset Integer optional, defaults to 0 Indicates the result from which pagination startslimit Integer optional, defaults to 200 Restricts the size of results returned. To override the default and return all entries you must explicitly pass a non-positive integer value for limit e.g. limit=0, or limit=-1\n" + + "Example Request:\n" + "\n" + "entityDatatableChecks?offset=0&limit=15") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = EntityDatatableChecksApiResourceSwagger.GetEntityDatatableChecksResponse.class, responseContainer = "list") }) public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("status") @ApiParam(value = "status") final Long status, - @QueryParam("entity") @ApiParam(value = "entity") final String entity, @QueryParam("productId") @ApiParam(value = "productId") final Long productId, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit) { + @QueryParam("entity") @ApiParam(value = "entity") final String entity, + @QueryParam("productId") @ApiParam(value = "productId") final Long productId, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit) { final SearchParameters searchParameters = SearchParameters.forPagination(offset, limit); final Page result = this.readEntityDatatableChecksService.retrieveAll(searchParameters, status, entity, productId); @@ -105,8 +109,10 @@ public class EntityDatatableChecksApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Entity-Datatable Checks Template", notes = "This is a convenience resource useful for building maintenance user interface screens for Entity-Datatable Checks applications. The template data returned consists of:\n" + "\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "entityDatatableChecks/template") - @ApiResponses({@ApiResponse(code = 200, message = "", response = EntityDatatableChecksApiResourceSwagger.GetEntityDatatableChecksTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Entity-Datatable Checks Template", notes = "This is a convenience resource useful for building maintenance user interface screens for Entity-Datatable Checks applications. The template data returned consists of:\n" + + "\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "entityDatatableChecks/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = EntityDatatableChecksApiResourceSwagger.GetEntityDatatableChecksTemplateResponse.class) }) public String getTemplate(@Context final UriInfo uriInfo) { final EntityDataTableChecksTemplateData result = this.readEntityDatatableChecksService.retrieveTemplate(); @@ -118,9 +124,12 @@ public class EntityDatatableChecksApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create Entity-Datatable Checks", notes = "Mandatory Fields : \n" + "entity, status, datatableName\n" + "\n" + "Non-Mandatory Fields : \n" + "productId") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = EntityDatatableChecksApiResourceSwagger.PostEntityDatatableChecksTemplateRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = EntityDatatableChecksApiResourceSwagger.PostEntityDatatableChecksTemplateResponse.class)}) + @ApiOperation(value = "Create Entity-Datatable Checks", notes = "Mandatory Fields : \n" + "entity, status, datatableName\n" + "\n" + + "Non-Mandatory Fields : \n" + "productId") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = EntityDatatableChecksApiResourceSwagger.PostEntityDatatableChecksTemplateRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = EntityDatatableChecksApiResourceSwagger.PostEntityDatatableChecksTemplateResponse.class) }) public String createEntityDatatableCheck(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createEntityDatatableChecks(apiRequestBodyAsJson).build(); @@ -133,14 +142,17 @@ public class EntityDatatableChecksApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete Entity-Datatable Checks", notes = "Deletes an existing Entity-Datatable Check") - @ApiResponses({@ApiResponse(code = 200, message = "", response = EntityDatatableChecksApiResourceSwagger.DeleteEntityDatatableChecksTemplateResponse.class)}) - public String deleteDatatable(@PathParam("entityDatatableCheckId") @ApiParam(value = "entityDatatableCheckId") final long entityDatatableCheckId, final String apiRequestBodyAsJson) { + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = EntityDatatableChecksApiResourceSwagger.DeleteEntityDatatableChecksTemplateResponse.class) }) + public String deleteDatatable( + @PathParam("entityDatatableCheckId") @ApiParam(value = "entityDatatableCheckId") final long entityDatatableCheckId, + final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteEntityDatatableChecks(entityDatatableCheckId, - apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder() + .deleteEntityDatatableChecks(entityDatatableCheckId, apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/EntityDatatableChecksApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/EntityDatatableChecksApiResourceSwagger.java index 98a504156..aa2ef207c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/EntityDatatableChecksApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/EntityDatatableChecksApiResourceSwagger.java @@ -32,13 +32,15 @@ import org.apache.fineract.portfolio.savings.data.SavingsProductData; * Created by sanyam on 31/7/17. */ final class EntityDatatableChecksApiResourceSwagger { + private EntityDatatableChecksApiResourceSwagger() { } @ApiModel(value = "GetEntityDatatableChecksResponse") public static final class GetEntityDatatableChecksResponse { - private GetEntityDatatableChecksResponse(){} + + private GetEntityDatatableChecksResponse() {} public long id; public String entity; @@ -52,7 +54,8 @@ final class EntityDatatableChecksApiResourceSwagger { @ApiModel(value = "GetEntityDatatableChecksTemplateResponse") public static final class GetEntityDatatableChecksTemplateResponse { - private GetEntityDatatableChecksTemplateResponse(){} + + private GetEntityDatatableChecksTemplateResponse() {} public List entities; public List statusClient; @@ -65,10 +68,12 @@ final class EntityDatatableChecksApiResourceSwagger { } @ApiModel(value = "PostEntityDatatableChecksTemplateRequest") - public static final class PostEntityDatatableChecksTemplateRequest{ + public static final class PostEntityDatatableChecksTemplateRequest { + private PostEntityDatatableChecksTemplateRequest() { } + @ApiModelProperty(example = "m_loan") public String entity; @ApiModelProperty(example = "100") @@ -80,21 +85,24 @@ final class EntityDatatableChecksApiResourceSwagger { } @ApiModel(value = "PostEntityDatatableChecksTemplateResponse") - public static final class PostEntityDatatableChecksTemplateResponse{ + public static final class PostEntityDatatableChecksTemplateResponse { + private PostEntityDatatableChecksTemplateResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "DeleteEntityDatatableChecksTemplateResponse") - public static final class DeleteEntityDatatableChecksTemplateResponse{ + public static final class DeleteEntityDatatableChecksTemplateResponse { + private DeleteEntityDatatableChecksTemplateResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/ReportsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/ReportsApiResource.java index 31af52c3d..d244745b8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/ReportsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/ReportsApiResource.java @@ -59,10 +59,8 @@ import org.springframework.stereotype.Component; @Path("/reports") @Component @Scope("singleton") -@Api(tags = {"Reports"}) -@SwaggerDefinition(tags = { - @Tag(name = "Reports", description = "Non-core reports can be added, updated and deleted.") -}) +@Api(tags = { "Reports" }) +@SwaggerDefinition(tags = { @Tag(name = "Reports", description = "Non-core reports can be added, updated and deleted.") }) public class ReportsApiResource { private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "reportName", "reportType", "reportSubType", @@ -90,8 +88,9 @@ public class ReportsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Reports", notes = "Lists all reports and their parameters.\n" + "\n" + "Example Request:\n" + "\n" + "reports", responseContainer = "List", response = ReportsApiResourceSwagger.GetReportsResponse.class) - @ApiResponses({@ApiResponse(code = 200, message = "")}) + @ApiOperation(value = "List Reports", notes = "Lists all reports and their parameters.\n" + "\n" + "Example Request:\n" + "\n" + + "reports", responseContainer = "List", response = ReportsApiResourceSwagger.GetReportsResponse.class) + @ApiResponses({ @ApiResponse(code = 200, message = "") }) public String retrieveReportList(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -106,8 +105,9 @@ public class ReportsApiResource { @Path("{id}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Report\n", notes = "Example Requests:\n" + "\n" + "reports/1\n" + "\n" + "\n" + "reports/1?template=true") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportsApiResourceSwagger.GetReportsResponse.class)}) + @ApiOperation(value = "Retrieve a Report\n", notes = "Example Requests:\n" + "\n" + "reports/1\n" + "\n" + "\n" + + "reports/1?template=true") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = ReportsApiResourceSwagger.GetReportsResponse.class) }) public String retrieveReport(@PathParam("id") @ApiParam(value = "id") final Long id, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -126,8 +126,9 @@ public class ReportsApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Report Template", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "\n" + "Example Request : \n" + "\n" + "reports/template") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportsApiResourceSwagger.GetReportsTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Report Template", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "\n" + "Example Request : \n" + "\n" + "reports/template") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = ReportsApiResourceSwagger.GetReportsTemplateResponse.class) }) public String retrieveOfficeTemplate(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -143,8 +144,9 @@ public class ReportsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create a Report", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ReportsApiResourceSwagger.PostRepostRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportsApiResourceSwagger.PostReportsResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ReportsApiResourceSwagger.PostRepostRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = ReportsApiResourceSwagger.PostReportsResponse.class) }) public String createReport(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createReport().withJson(apiRequestBodyAsJson).build(); @@ -159,9 +161,11 @@ public class ReportsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Report", notes = "Only the useReport value can be updated for core reports.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ReportsApiResourceSwagger.PutReportRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportsApiResourceSwagger.PutReportResponse.class)}) - public String updateReport(@PathParam("id") @ApiParam(value = "id") final Long id, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ReportsApiResourceSwagger.PutReportRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = ReportsApiResourceSwagger.PutReportResponse.class) }) + public String updateReport(@PathParam("id") @ApiParam(value = "id") final Long id, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateReport(id).withJson(apiRequestBodyAsJson).build(); @@ -175,7 +179,7 @@ public class ReportsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Report", notes = "Only non-core reports can be deleted.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportsApiResourceSwagger.DeleteReportsResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = ReportsApiResourceSwagger.DeleteReportsResponse.class) }) public String deleteReport(@PathParam("id") @ApiParam(value = "id") final Long id) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteReport(id).build(); @@ -185,4 +189,4 @@ public class ReportsApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/ReportsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/ReportsApiResourceSwagger.java index 6f6da7218..d62dd9cdc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/ReportsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/ReportsApiResourceSwagger.java @@ -28,15 +28,18 @@ import org.apache.fineract.infrastructure.dataqueries.data.ReportParameterData; * Created by sanyam on 4/8/17. */ final class ReportsApiResourceSwagger { + private ReportsApiResourceSwagger() { } @ApiModel(value = "GetReportsResponse") public static final class GetReportsResponse { + private GetReportsResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Client Listing") @@ -60,7 +63,8 @@ final class ReportsApiResourceSwagger { @ApiModel(value = "GetReportsTemplateResponse") public static final class GetReportsTemplateResponse { - private GetReportsTemplateResponse(){ + + private GetReportsTemplateResponse() { } @@ -71,9 +75,11 @@ final class ReportsApiResourceSwagger { @ApiModel(value = "PostRepostRequest") public static final class PostRepostRequest { + private PostRepostRequest() { } + @ApiModelProperty(example = "Completely New Report") public String reportName; @ApiModelProperty(example = "Table") @@ -91,18 +97,22 @@ final class ReportsApiResourceSwagger { @ApiModel(value = "PostReportsResponse") public static final class PostReportsResponse { - private PostReportsResponse(){ + + private PostReportsResponse() { } + @ApiModelProperty(example = "132") public long resourceId; } @ApiModel(value = "PutReportRequest") public static final class PutReportRequest { + private PutReportRequest() { } + @ApiModelProperty(example = "Completely New Report") public String reportName; public Collection reportParameters; @@ -111,17 +121,22 @@ final class ReportsApiResourceSwagger { @ApiModel(value = "PutReportResponse") public static final class PutReportResponse { + private PutReportResponse() { } - final class PutReportResponseChanges{ + + final class PutReportResponseChanges { + private PutReportResponseChanges() { } + @ApiModelProperty(example = "Changed New Report") public String reportName; public Collection reportParameters; } + @ApiModelProperty(example = "132") public long resourceId; public PutReportResponseChanges changes; @@ -129,9 +144,11 @@ final class ReportsApiResourceSwagger { @ApiModel(value = "DeleteReportsResponse") public static final class DeleteReportsResponse { - private DeleteReportsResponse(){ + + private DeleteReportsResponse() { } + @ApiModelProperty(example = "132") public long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/RunreportsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/RunreportsApiResource.java index fb21f6b8d..7f83819ec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/RunreportsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/RunreportsApiResource.java @@ -62,10 +62,8 @@ import org.springframework.stereotype.Component; @Path("/runreports") @Component @Scope("singleton") -@Api(tags = {"Run Reports"}) -@SwaggerDefinition(tags = { - @Tag(name = "Run Reports", description = "") -}) +@Api(tags = { "Run Reports" }) +@SwaggerDefinition(tags = { @Tag(name = "Run Reports", description = "") }) public class RunreportsApiResource { private final PlatformSecurityContext context; @@ -89,9 +87,25 @@ public class RunreportsApiResource { @Path("{reportName}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON, "text/csv", "application/vnd.ms-excel", "application/pdf", "text/html" }) - @ApiOperation(value = "Running a Report", notes = "This resource allows you to run and receive output from pre-defined Apache Fineract reports.\n" + "\n" + "Reports can also be used to provide data for searching and workflow functionality.\n" + "\n" + "The default output is a JSON formatted \"Generic Resultset\". The Generic Resultset contains Column Heading as well as Data information. However, you can export to CSV format by simply adding \"&exportCSV=true\" to the end of your URL.\n" + "\n" + "If Pentaho reports have been pre-defined, they can also be run through this resource. Pentaho reports can return HTML, PDF or CSV formats.\n" + "\n" + "The Apache Fineract reference application uses a JQuery plugin called stretchy reporting which, itself, uses this reports resource to provide a pretty flexible reporting User Interface (UI).\n\n" + "\n" + - "\n" + "Example Requests:\n" + "\n" + "runreports/Client%20Listing?R_officeId=1\n" + "\n" + "\n" + "runreports/Client%20Listing?R_officeId=1&exportCSV=true\n" + "\n" + "\n" + "runreports/OfficeIdSelectOne?R_officeId=1¶meterType=true\n" + "\n" + "\n" + "runreports/OfficeIdSelectOne?R_officeId=1¶meterType=true&exportCSV=true\n" + "\n" + "\n" + "runreports/Expected%20Payments%20By%20Date%20-%20Formatted?R_endDate=2013-04-30&R_loanOfficerId=-1&R_officeId=1&R_startDate=2013-04-16&output-type=HTML&R_officeId=1\n" + "\n" + "\n" + "runreports/Expected%20Payments%20By%20Date%20-%20Formatted?R_endDate=2013-04-30&R_loanOfficerId=-1&R_officeId=1&R_startDate=2013-04-16&output-type=XLS&R_officeId=1\n" + "\n" + "\n" + "runreports/Expected%20Payments%20By%20Date%20-%20Formatted?R_endDate=2013-04-30&R_loanOfficerId=-1&R_officeId=1&R_startDate=2013-04-16&output-type=CSV&R_officeId=1\n" + "\n" + "\n" + "runreports/Expected%20Payments%20By%20Date%20-%20Formatted?R_endDate=2013-04-30&R_loanOfficerId=-1&R_officeId=1&R_startDate=2013-04-16&output-type=PDF&R_officeId=1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = RunreportsApiResourceSwagger.GetReportNameResponse.class)}) + @ApiOperation(value = "Running a Report", notes = "This resource allows you to run and receive output from pre-defined Apache Fineract reports.\n" + + "\n" + "Reports can also be used to provide data for searching and workflow functionality.\n" + "\n" + + "The default output is a JSON formatted \"Generic Resultset\". The Generic Resultset contains Column Heading as well as Data information. However, you can export to CSV format by simply adding \"&exportCSV=true\" to the end of your URL.\n" + + "\n" + + "If Pentaho reports have been pre-defined, they can also be run through this resource. Pentaho reports can return HTML, PDF or CSV formats.\n" + + "\n" + + "The Apache Fineract reference application uses a JQuery plugin called stretchy reporting which, itself, uses this reports resource to provide a pretty flexible reporting User Interface (UI).\n\n" + + "\n" + "\n" + "Example Requests:\n" + "\n" + "runreports/Client%20Listing?R_officeId=1\n" + "\n" + "\n" + + "runreports/Client%20Listing?R_officeId=1&exportCSV=true\n" + "\n" + "\n" + + "runreports/OfficeIdSelectOne?R_officeId=1¶meterType=true\n" + "\n" + "\n" + + "runreports/OfficeIdSelectOne?R_officeId=1¶meterType=true&exportCSV=true\n" + "\n" + "\n" + + "runreports/Expected%20Payments%20By%20Date%20-%20Formatted?R_endDate=2013-04-30&R_loanOfficerId=-1&R_officeId=1&R_startDate=2013-04-16&output-type=HTML&R_officeId=1\n" + + "\n" + "\n" + + "runreports/Expected%20Payments%20By%20Date%20-%20Formatted?R_endDate=2013-04-30&R_loanOfficerId=-1&R_officeId=1&R_startDate=2013-04-16&output-type=XLS&R_officeId=1\n" + + "\n" + "\n" + + "runreports/Expected%20Payments%20By%20Date%20-%20Formatted?R_endDate=2013-04-30&R_loanOfficerId=-1&R_officeId=1&R_startDate=2013-04-16&output-type=CSV&R_officeId=1\n" + + "\n" + "\n" + + "runreports/Expected%20Payments%20By%20Date%20-%20Formatted?R_endDate=2013-04-30&R_loanOfficerId=-1&R_officeId=1&R_startDate=2013-04-16&output-type=PDF&R_officeId=1") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = RunreportsApiResourceSwagger.GetReportNameResponse.class) }) public Response runReport(@PathParam("reportName") @ApiParam(value = "reportName") final String reportName, @Context final UriInfo uriInfo, @DefaultValue("false") @QueryParam("isSelfServiceUserReport") @ApiParam(value = "isSelfServiceUserReport") final boolean isSelfServiceUserReport) { @@ -119,8 +133,8 @@ public class RunreportsApiResource { if (exportPdf) { final Map reportParams = getReportParams(queryParams); - final String pdfFileName = this.readExtraDataAndReportingService - .retrieveReportPDF(reportName, parameterTypeValue, reportParams, isSelfServiceUserReport); + final String pdfFileName = this.readExtraDataAndReportingService.retrieveReportPDF(reportName, parameterTypeValue, reportParams, + isSelfServiceUserReport); final File file = new File(pdfFileName); @@ -156,8 +170,8 @@ public class RunreportsApiResource { // CSV Export final Map reportParams = getReportParams(queryParams); - final StreamingOutput result = this.readExtraDataAndReportingService - .retrieveReportCSV(reportName, parameterTypeValue, reportParams, isSelfServiceUserReport); + final StreamingOutput result = this.readExtraDataAndReportingService.retrieveReportCSV(reportName, parameterTypeValue, reportParams, + isSelfServiceUserReport); return Response.ok().entity(result).type("text/csv") .header("Content-Disposition", "attachment;filename=" + reportName.replaceAll(" ", "") + ".csv").build(); @@ -169,8 +183,9 @@ public class RunreportsApiResource { // (dropdown listbox) values. if (!parameterType) { final AppUser currentUser = this.context.authenticatedUser(); - if (currentUser.hasNotPermissionForReport(reportName)) { throw new NoAuthorizationException("Not authorised to run report: " - + reportName); } + if (currentUser.hasNotPermissionForReport(reportName)) { + throw new NoAuthorizationException("Not authorised to run report: " + reportName); + } } } @@ -191,4 +206,4 @@ public class RunreportsApiResource { } return reportParams; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/RunreportsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/RunreportsApiResourceSwagger.java index 1303fd160..7d4393afb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/RunreportsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/api/RunreportsApiResourceSwagger.java @@ -26,14 +26,18 @@ import org.apache.fineract.infrastructure.dataqueries.data.ResultsetRowData; * Created by sanyam on 5/8/17. */ final class RunreportsApiResourceSwagger { + private RunreportsApiResourceSwagger() { } + @ApiModel(value = "GetReportNameResponse") public static final class GetReportNameResponse { + private GetReportNameResponse() { } + public ResultsetColumnHeaderData columnHeaders; public ResultsetRowData row; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DataTableValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DataTableValidator.java index b87df94ee..94166118a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DataTableValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DataTableValidator.java @@ -53,7 +53,8 @@ public class DataTableValidator { this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, REGISTER_PARAMS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(DataTableApiConstant.DATATABLE_RESOURCE_NAME); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(DataTableApiConstant.DATATABLE_RESOURCE_NAME); final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists(DataTableApiConstant.categoryParamName, element)) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableData.java index 029855dca..d4d7a7bc7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/DatatableData.java @@ -33,7 +33,6 @@ public class DatatableData implements Serializable { @SuppressWarnings("unused") private final List columnHeaderData; - public static DatatableData create(final String applicationTableName, final String registeredTableName, final List columnHeaderData) { return new DatatableData(applicationTableName, registeredTableName, columnHeaderData); @@ -47,20 +46,18 @@ public class DatatableData implements Serializable { } - public boolean hasColumn(final String columnName){ + public boolean hasColumn(final String columnName) { - for(ResultsetColumnHeaderData c : this.columnHeaderData){ + for (ResultsetColumnHeaderData c : this.columnHeaderData) { - if(c.getColumnName().equals(columnName)) { - return true; - } + if (c.getColumnName().equals(columnName)) { return true; } } return false; } - public String getRegisteredTableName(){ + public String getRegisteredTableName() { return registeredTableName; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityDataTableChecksData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityDataTableChecksData.java index 18def1326..b573624a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityDataTableChecksData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityDataTableChecksData.java @@ -47,4 +47,4 @@ public class EntityDataTableChecksData implements Serializable { this.productName = productName; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityDataTableChecksTemplateData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityDataTableChecksTemplateData.java index 44d66fc88..4262f363f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityDataTableChecksTemplateData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityDataTableChecksTemplateData.java @@ -41,8 +41,8 @@ public class EntityDataTableChecksTemplateData implements Serializable { public EntityDataTableChecksTemplateData(final List entities, List statusClient, List statusGroup, List statusSavings, - List statusLoans, List datatables, - Collection loanProductDatas, Collection savingsProductDatas) { + List statusLoans, List datatables, Collection loanProductDatas, + Collection savingsProductDatas) { this.entities = entities; this.statusClient = statusClient; @@ -56,28 +56,21 @@ public class EntityDataTableChecksTemplateData implements Serializable { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } + if (this == o) { return true; } - if (!(o instanceof EntityDataTableChecksTemplateData)) { - return false; - } + if (!(o instanceof EntityDataTableChecksTemplateData)) { return false; } EntityDataTableChecksTemplateData that = (EntityDataTableChecksTemplateData) o; - return Objects.equals(entities, that.entities) && - Objects.equals(statusClient, that.statusClient) && - Objects.equals(statusGroup, that.statusGroup) && - Objects.equals(statusSavings, that.statusSavings) && - Objects.equals(statusLoans, that.statusLoans) && - Objects.equals(datatables, that.datatables) && - Objects.equals(loanProductDatas, that.loanProductDatas) && - Objects.equals(savingsProductDatas, that.savingsProductDatas); + return Objects.equals(entities, that.entities) && Objects.equals(statusClient, that.statusClient) + && Objects.equals(statusGroup, that.statusGroup) && Objects.equals(statusSavings, that.statusSavings) + && Objects.equals(statusLoans, that.statusLoans) && Objects.equals(datatables, that.datatables) + && Objects.equals(loanProductDatas, that.loanProductDatas) && Objects.equals(savingsProductDatas, that.savingsProductDatas); } @Override public int hashCode() { - return Objects.hash(entities, statusClient, statusGroup, statusSavings, statusLoans, datatables, loanProductDatas, savingsProductDatas); + return Objects.hash(entities, statusClient, statusGroup, statusSavings, statusLoans, datatables, loanProductDatas, + savingsProductDatas); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityTables.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityTables.java index 7a58093c8..815607e41 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityTables.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/EntityTables.java @@ -26,37 +26,23 @@ import java.util.Map; public enum EntityTables { - CLIENT("m_client", - ImmutableList.of(StatusEnum.CREATE.getCode(), - StatusEnum.ACTIVATE.getCode(), - StatusEnum.CLOSE.getCode()), - "client_id"), - LOAN("m_loan", - ImmutableList.of(StatusEnum.CREATE.getCode(), - StatusEnum.APPROVE.getCode(), - StatusEnum.DISBURSE.getCode(), - StatusEnum.WITHDRAWN.getCode(), - StatusEnum.REJECTED.getCode(), - StatusEnum.WRITE_OFF.getCode()), - "loan_id"), - GROUP("m_group", - ImmutableList.of(StatusEnum.CREATE.getCode(), - StatusEnum.ACTIVATE.getCode(), - StatusEnum.CLOSE.getCode()), - "group_id"), - SAVING("m_savings_account", - ImmutableList.of(StatusEnum.CREATE.getCode(), - StatusEnum.APPROVE.getCode(), - StatusEnum.ACTIVATE.getCode(), - StatusEnum.WITHDRAWN.getCode(), - StatusEnum.REJECTED.getCode(), - StatusEnum.CLOSE.getCode()), - "savings_account_id"); + CLIENT("m_client", ImmutableList.of(StatusEnum.CREATE.getCode(), StatusEnum.ACTIVATE.getCode(), StatusEnum.CLOSE.getCode()), + "client_id"), LOAN("m_loan", + ImmutableList.of(StatusEnum.CREATE.getCode(), StatusEnum.APPROVE.getCode(), StatusEnum.DISBURSE.getCode(), + StatusEnum.WITHDRAWN.getCode(), StatusEnum.REJECTED.getCode(), StatusEnum.WRITE_OFF.getCode()), + "loan_id"), GROUP("m_group", + ImmutableList.of(StatusEnum.CREATE.getCode(), StatusEnum.ACTIVATE.getCode(), StatusEnum.CLOSE.getCode()), + "group_id"), SAVING("m_savings_account", + ImmutableList.of(StatusEnum.CREATE.getCode(), StatusEnum.APPROVE.getCode(), + StatusEnum.ACTIVATE.getCode(), StatusEnum.WITHDRAWN.getCode(), StatusEnum.REJECTED.getCode(), + StatusEnum.CLOSE.getCode()), + "savings_account_id"); private static final Map lookup = new HashMap(); static { - for (EntityTables d : EntityTables.values()) - { lookup.put(d.getName(), d);} + for (EntityTables d : EntityTables.values()) { + lookup.put(d.getName(), d); + } } private final String name; @@ -84,9 +70,7 @@ public enum EntityTables { } public static ImmutableList getStatus(String name) { - if (lookup.get(name) != null) { - return lookup.get(name).getCodes(); - } + if (lookup.get(name) != null) { return lookup.get(name).getCodes(); } return ImmutableList.of(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/GenericResultsetData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/GenericResultsetData.java index d589aa969..a2bf949e8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/GenericResultsetData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/GenericResultsetData.java @@ -64,4 +64,4 @@ public final class GenericResultsetData { public boolean hasMoreThanOneEntry() { return this.data.size() > 1; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportData.java index e80ee677f..d89d26ea6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportData.java @@ -101,4 +101,4 @@ final public class ReportData { } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportParameterData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportParameterData.java index baf81f00b..03fb12e0e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportParameterData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportParameterData.java @@ -36,4 +36,4 @@ final public class ReportParameterData { this.parameterName = parameterName; this.reportParameterName = reportParameterName; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportParameterJoinData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportParameterJoinData.java index bafe0b0c0..08caaa84d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportParameterJoinData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ReportParameterJoinData.java @@ -105,4 +105,4 @@ final public class ReportParameterJoinData { public String getDescription() { return this.description; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ResultsetColumnHeaderData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ResultsetColumnHeaderData.java index a55f46f67..96629b646 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ResultsetColumnHeaderData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ResultsetColumnHeaderData.java @@ -88,8 +88,8 @@ public final class ResultsetColumnHeaderData implements Serializable { } else if (isBit()) { displayType = "BOOLEAN"; } else { - throw new PlatformDataIntegrityException("error.msg.invalid.lookup.type", "Invalid Lookup Type:" + this.columnType - + " - Column Name: " + this.columnName); + throw new PlatformDataIntegrityException("error.msg.invalid.lookup.type", + "Invalid Lookup Type:" + this.columnType + " - Column Name: " + this.columnName); } } else { @@ -98,8 +98,8 @@ public final class ResultsetColumnHeaderData implements Serializable { } else if (isVarchar()) { displayType = "CODEVALUE"; } else { - throw new PlatformDataIntegrityException("error.msg.invalid.lookup.type", "Invalid Lookup Type:" + this.columnType - + " - Column Name: " + this.columnName); + throw new PlatformDataIntegrityException("error.msg.invalid.lookup.type", + "Invalid Lookup Type:" + this.columnType + " - Column Name: " + this.columnName); } } @@ -302,4 +302,4 @@ public final class ResultsetColumnHeaderData implements Serializable { public String getColumnCode() { return this.columnCode; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ResultsetColumnValueData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ResultsetColumnValueData.java index ae9e7940a..7f561fc0f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ResultsetColumnValueData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/ResultsetColumnValueData.java @@ -50,4 +50,4 @@ public class ResultsetColumnValueData implements Serializable { public boolean codeMatches(final Integer match) { return match.intValue() == this.id; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/StatusEnum.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/StatusEnum.java index 82c922821..fc8627002 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/StatusEnum.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/data/StatusEnum.java @@ -31,7 +31,7 @@ public enum StatusEnum { private final Integer code; - public Integer getCode() { + public Integer getCode() { return code; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/EntityDatatableChecks.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/EntityDatatableChecks.java index d3a55e135..84ef4eaf6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/EntityDatatableChecks.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/EntityDatatableChecks.java @@ -44,11 +44,10 @@ public class EntityDatatableChecks extends AbstractPersistableCustom { @Column(name = "product_id", nullable = true) private Long productId; - public EntityDatatableChecks() { - } + public EntityDatatableChecks() {} - public EntityDatatableChecks(final String entity, final String datatableName, final Long status, - final boolean systemDefined, final Long productId) { + public EntityDatatableChecks(final String entity, final String datatableName, final Long status, final boolean systemDefined, + final Long productId) { this.entity = entity; this.status = status; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/EntityDatatableChecksRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/EntityDatatableChecksRepository.java index 358f2a796..0bacdacb6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/EntityDatatableChecksRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/EntityDatatableChecksRepository.java @@ -25,25 +25,21 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface EntityDatatableChecksRepository - extends - JpaRepository, - JpaSpecificationExecutor { + extends JpaRepository, JpaSpecificationExecutor { public List findByEntityAndStatus(String entityName, Long status); @Query("select t from EntityDatatableChecks t WHERE t.status =:status and t.entity=:entity and t.productId = :productId ") - public List findByEntityStatusAndProduct(@Param("entity") String entity, - @Param("status") Long status, @Param("productId") Long productId); + public List findByEntityStatusAndProduct(@Param("entity") String entity, @Param("status") Long status, + @Param("productId") Long productId); @Query("select t from EntityDatatableChecks t WHERE t.status =:status and t.entity=:entity and t.productId IS NULL ") - public List findByEntityStatusAndNoProduct(@Param("entity") String entity, - @Param("status") Long status); + public List findByEntityStatusAndNoProduct(@Param("entity") String entity, @Param("status") Long status); @Query("select t from EntityDatatableChecks t WHERE t.status =:status " + "and t.entity=:entity and t.datatableName = :datatableName AND t.productId = :productId") public List findByEntityStatusAndDatatableIdAndProductId(@Param("entity") String entityName, - @Param("status") Long status, @Param("datatableName") String datatableName, - @Param("productId") Long productId); + @Param("status") Long status, @Param("datatableName") String datatableName, @Param("productId") Long productId); @Query("select t from EntityDatatableChecks t WHERE t.status =:status and t.entity=:entity " + " and t.datatableName = :datatableName AND t.productId IS NULL") diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/Report.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/Report.java index eb8429ced..589944efc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/Report.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/Report.java @@ -70,7 +70,7 @@ public final class Report extends AbstractPersistableCustom { @Column(name = "report_sql") private String reportSql; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "report", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "report", orphanRemoval = true, fetch = FetchType.EAGER) private Set reportParameterUsages = new HashSet<>(); @Column(name = "self_service_user_report") @@ -188,9 +188,10 @@ public final class Report extends AbstractPersistableCustom { if (!actualChanges.isEmpty()) { if (isCoreReport()) { for (final String key : actualChanges.keySet()) { - if (!key.equals("useReport")) { throw new PlatformDataIntegrityException( - "error.msg.only.use.report.can.be.updated.for.core.report", - "Only the Use Report field can be updated for Core Reports", key); } + if (!key.equals("useReport")) { + throw new PlatformDataIntegrityException("error.msg.only.use.report.can.be.updated.for.core.report", + "Only the Use Report field can be updated for Core Reports", key); + } } } } @@ -239,11 +240,11 @@ public final class Report extends AbstractPersistableCustom { if (StringUtils.isNotBlank(this.reportType)) { if (this.reportType.equals("Table") || this.reportType.equals("Chart")) { - baseDataValidator.reset().parameter("reportSql").value(this.reportSql) - .cantBeBlankWhenParameterProvidedIs("reportType", this.reportType); + baseDataValidator.reset().parameter("reportSql").value(this.reportSql).cantBeBlankWhenParameterProvidedIs("reportType", + this.reportType); } else { - baseDataValidator.reset().parameter("reportSql").value(this.reportSql) - .mustBeBlankWhenParameterProvidedIs("reportType", this.reportType); + baseDataValidator.reset().parameter("reportSql").value(this.reportSql).mustBeBlankWhenParameterProvidedIs("reportType", + this.reportType); } } throwExceptionIfValidationWarningsExist(dataValidationErrors); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameter.java index 80d212b73..b8fdaf59e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameter.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameter.java @@ -33,4 +33,4 @@ public class ReportParameter extends AbstractPersistableCustom { public boolean hasIdOf(final Long id) { return getId().equals(id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterRepository.java index ecfc27b3f..6e937453f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterRepository.java @@ -23,4 +23,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ReportParameterRepository extends JpaRepository, JpaSpecificationExecutor { // no added behaviour -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterUsage.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterUsage.java index 2924b9497..6665154dc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterUsage.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterUsage.java @@ -50,29 +50,22 @@ public final class ReportParameterUsage extends AbstractPersistableCustom { this.reportParameterName = reportParameterName; } - /*@Override - public boolean equals(final Object obj) { - if (obj == null) { return false; } - if (obj == this) { return true; } - if (obj.getClass() != getClass()) { return false; } - final ReportParameterUsage rhs = (ReportParameterUsage) obj; - return new EqualsBuilder().appendSuper(super.equals(obj)) // - .append(getId(), rhs.getId()) // - .append(this.report.getId(), rhs.report.getId()) // - .append(this.parameter.getId(), rhs.parameter.getId()) // - .append(this.reportParameterName, rhs.reportParameterName) // - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(3, 5) // - .append(getId()) // - .append(this.report.getId()) // - .append(this.parameter.getId()) // - .append(this.reportParameterName) // - .toHashCode(); - }*/ + /* + * @Override public boolean equals(final Object obj) { if (obj == null) { + * return false; } if (obj == this) { return true; } if (obj.getClass() != + * getClass()) { return false; } final ReportParameterUsage rhs = + * (ReportParameterUsage) obj; return new + * EqualsBuilder().appendSuper(super.equals(obj)) // .append(getId(), + * rhs.getId()) // .append(this.report.getId(), rhs.report.getId()) // + * .append(this.parameter.getId(), rhs.parameter.getId()) // + * .append(this.reportParameterName, rhs.reportParameterName) // + * .isEquals(); } + * + * @Override public int hashCode() { return new HashCodeBuilder(3, 5) // + * .append(getId()) // .append(this.report.getId()) // + * .append(this.parameter.getId()) // .append(this.reportParameterName) // + * .toHashCode(); } + */ public boolean hasIdOf(final Long id) { return getId().equals(id); @@ -89,4 +82,4 @@ public final class ReportParameterUsage extends AbstractPersistableCustom { public String getReportParameterName() { return this.reportParameterName; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterUsageRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterUsageRepository.java index 36b54e902..b74923a93 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterUsageRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportParameterUsageRepository.java @@ -22,9 +22,9 @@ import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface ReportParameterUsageRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface ReportParameterUsageRepository + extends JpaRepository, JpaSpecificationExecutor { // no added behaviour List findByReport(Report report); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportRepository.java index 2a1f8434f..42454c86d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportRepository.java @@ -23,4 +23,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ReportRepository extends JpaRepository, JpaSpecificationExecutor { // no added behaviour -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportRepositoryWrapper.java index 60b13e3dd..3772c0487 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/domain/ReportRepositoryWrapper.java @@ -23,11 +23,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** - * A wrapper class for the ReportRepository that provides a method that returns a Report entity if it exists, - * else throws "ReportNotFoundException" exception if the Report does not exist + * A wrapper class for the ReportRepository that provides a method that returns + * a Report entity if it exists, else throws "ReportNotFoundException" exception + * if the Report does not exist **/ @Service public class ReportRepositoryWrapper { + private final ReportRepository reportRepository; @Autowired @@ -38,12 +40,13 @@ public class ReportRepositoryWrapper { /** * Retrieves an entity by its id * - * @param id must not be null - * @throws ReportNotFoundException if entity not found + * @param id + * must not be null + * @throws ReportNotFoundException + * if entity not found * @return {@link Report} object */ public Report findOneThrowExceptionIfNotFound(final Long id) { - return this.reportRepository.findById(id) - .orElseThrow(() -> new ReportNotFoundException(id)); + return this.reportRepository.findById(id).orElseThrow(() -> new ReportNotFoundException(id)); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableEntryRequiredException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableEntryRequiredException.java index c774fe789..90a540e7e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableEntryRequiredException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableEntryRequiredException.java @@ -21,13 +21,14 @@ package org.apache.fineract.infrastructure.dataqueries.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * A {@link AbstractPlatformDomainRuleException} thrown when datatable resources are not found. + * A {@link AbstractPlatformDomainRuleException} thrown when datatable resources + * are not found. */ public class DatatableEntryRequiredException extends AbstractPlatformDomainRuleException { public DatatableEntryRequiredException(String datatableName) { - super("error.msg.entry.required.in.datatable." + datatableName, "The datatable " + datatableName - + " needs to be filled in before the current action can be proceeded", datatableName); + super("error.msg.entry.required.in.datatable." + datatableName, + "The datatable " + datatableName + " needs to be filled in before the current action can be proceeded", datatableName); } public DatatableEntryRequiredException(String datatableName, Long appTableId) { @@ -35,4 +36,4 @@ public class DatatableEntryRequiredException extends AbstractPlatformDomainRuleE "The entry cannot be deleted, due to datatable " + datatableName + " is attached to an Entity-Datatable check", datatableName, appTableId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableNotFoundException.java index d70b26df9..072527a81 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableNotFoundException.java @@ -32,4 +32,4 @@ public class DatatableNotFoundException extends AbstractPlatformResourceNotFound public DatatableNotFoundException(final String datatable) { super("error.msg.datatable.not.found", "Datatable not found.", datatable); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableSystemErrorException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableSystemErrorException.java index c842aa02f..92968f739 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableSystemErrorException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/DatatableSystemErrorException.java @@ -25,4 +25,4 @@ public class DatatableSystemErrorException extends AbstractPlatformDomainRuleExc public DatatableSystemErrorException(final String msg) { super("error.msg.datatable.system.error", msg, msg); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckAlreadyExistsException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckAlreadyExistsException.java index 5a8decb92..2b2534dfc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckAlreadyExistsException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckAlreadyExistsException.java @@ -25,19 +25,16 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR */ public class EntityDatatableCheckAlreadyExistsException extends AbstractPlatformDomainRuleException { - public EntityDatatableCheckAlreadyExistsException(final String entityName, final Long status, - final String datatableName) { - super("error.msg.entityDatatableCheck.duplicate.entry", - "the entity datatable check for status: '" + status + "' and datatable name '" + datatableName - + "' on entity '" + entityName + "' already exist", - "status", "datatableName", "entity", status, datatableName, entityName); + public EntityDatatableCheckAlreadyExistsException(final String entityName, final Long status, final String datatableName) { + super("error.msg.entityDatatableCheck.duplicate.entry", "the entity datatable check for status: '" + status + + "' and datatable name '" + datatableName + "' on entity '" + entityName + "' already exist", "status", "datatableName", + "entity", status, datatableName, entityName); } - public EntityDatatableCheckAlreadyExistsException(final String entityName, long status, String datatableName, - long productId) { + public EntityDatatableCheckAlreadyExistsException(final String entityName, long status, String datatableName, long productId) { super("error.msg.entityDatatableCheck.duplicate.entry", - "the entity datatable check for status: '" + status + "' and datatable name '" + datatableName - + "' on entity '" + entityName + "' and product id '" + productId + "' already exist", + "the entity datatable check for status: '" + status + "' and datatable name '" + datatableName + "' on entity '" + + entityName + "' and product id '" + productId + "' already exist", "status", "datatableName", "entity", "productId", status, datatableName, entityName, productId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckNotAllowException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckNotAllowException.java index d92172557..134211b5b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckNotAllowException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckNotAllowException.java @@ -26,10 +26,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class EntityDatatableCheckNotAllowException extends AbstractPlatformResourceNotFoundException { public EntityDatatableCheckNotAllowException(final String entityName) { - super("error.msg.entity.datatable.check.is.not.allowed", - "Entity Datatable check is not allow without a loan product id to :entity," - + " because there is already a check attached to the same entity with a loan product id", - entityName); + super("error.msg.entity.datatable.check.is.not.allowed", "Entity Datatable check is not allow without a loan product id to :entity," + + " because there is already a check attached to the same entity with a loan product id", entityName); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckNotSupportedException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckNotSupportedException.java index daaa15265..b9d35fa95 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckNotSupportedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableCheckNotSupportedException.java @@ -27,13 +27,12 @@ public class EntityDatatableCheckNotSupportedException extends AbstractPlatformR public EntityDatatableCheckNotSupportedException(final String datatableName, final String entityName) { super("error.msg.entity.datatable.check.combination.not.supported", - "Entity Datatable check on table "+datatableName+" is not supported for entity "+entityName, datatableName, + "Entity Datatable check on table " + datatableName + " is not supported for entity " + entityName, datatableName, entityName); } public EntityDatatableCheckNotSupportedException(final String entityName, final Long productId) { super("error.msg.entity.datatable.check.combination.not.supported", - "Entity Datatable check on entity "+entityName+" is not supported with productId "+productId, entityName, - productId); + "Entity Datatable check on entity " + entityName + " is not supported with productId " + productId, entityName, productId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableChecksNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableChecksNotFoundException.java index 3a7432653..a75f54226 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableChecksNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/EntityDatatableChecksNotFoundException.java @@ -26,7 +26,6 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class EntityDatatableChecksNotFoundException extends AbstractPlatformResourceNotFoundException { public EntityDatatableChecksNotFoundException(final Long id) { - super("error.msg.entity.datatable.check.not.found", - "Entity datatable check with identifier " + id + " does not exist", id); + super("error.msg.entity.datatable.check.not.found", "Entity datatable check with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/ReportNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/ReportNotFoundException.java index 9e5f7d62c..76ca485f2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/ReportNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/ReportNotFoundException.java @@ -33,4 +33,4 @@ public class ReportNotFoundException extends AbstractPlatformResourceNotFoundExc public ReportNotFoundException(final Long id) { super("error.msg.report.parameter.id.invalid", "Report Parameter with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/ReportParameterNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/ReportParameterNotFoundException.java index 402b02879..302bdee47 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/ReportParameterNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/exception/ReportParameterNotFoundException.java @@ -28,4 +28,4 @@ public class ReportParameterNotFoundException extends AbstractPlatformResourceNo public ReportParameterNotFoundException(final Long id) { super("error.msg.report.parameter.id.invalid", "Report Parameter with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateDatatableCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateDatatableCommandHandler.java index 78f2643c1..e181fed81 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateDatatableCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateDatatableCommandHandler.java @@ -42,4 +42,4 @@ public class CreateDatatableCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createDatatable(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateDatatableEntryCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateDatatableEntryCommandHandler.java index 056f88d49..c6bfb3610 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateDatatableEntryCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateDatatableEntryCommandHandler.java @@ -54,4 +54,4 @@ public class CreateDatatableEntryCommandHandler implements NewCommandSourceHandl .withLoanId(commandProcessingResult.getLoanId()) // .build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateEntityDatatableChecksCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateEntityDatatableChecksCommandHandler.java index 847c71a93..bde202ad7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateEntityDatatableChecksCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateEntityDatatableChecksCommandHandler.java @@ -34,8 +34,7 @@ public class CreateEntityDatatableChecksCommandHandler implements NewCommandSour private final EntityDatatableChecksWritePlatformService writePlatformService; @Autowired - public CreateEntityDatatableChecksCommandHandler( - final EntityDatatableChecksWritePlatformService writePlatformService) { + public CreateEntityDatatableChecksCommandHandler(final EntityDatatableChecksWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } @@ -45,4 +44,4 @@ public class CreateEntityDatatableChecksCommandHandler implements NewCommandSour return this.writePlatformService.createCheck(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateReportCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateReportCommandHandler.java index 4d6dd52c9..b1a64d909 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateReportCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/CreateReportCommandHandler.java @@ -44,4 +44,4 @@ public class CreateReportCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createReport(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteDatatableCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteDatatableCommandHandler.java index 59214cf98..c23f24674 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteDatatableCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteDatatableCommandHandler.java @@ -47,4 +47,4 @@ public class DeleteDatatableCommandHandler implements NewCommandSourceHandler { return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withResourceIdAsString(datatableName).build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteEntityDatatableChecksCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteEntityDatatableChecksCommandHandler.java index 9009b476a..5d5c2f6a3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteEntityDatatableChecksCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteEntityDatatableChecksCommandHandler.java @@ -34,8 +34,7 @@ public class DeleteEntityDatatableChecksCommandHandler implements NewCommandSour private final EntityDatatableChecksWritePlatformService writePlatformService; @Autowired - public DeleteEntityDatatableChecksCommandHandler( - final EntityDatatableChecksWritePlatformService writePlatformService) { + public DeleteEntityDatatableChecksCommandHandler(final EntityDatatableChecksWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } @@ -45,4 +44,4 @@ public class DeleteEntityDatatableChecksCommandHandler implements NewCommandSour return this.writePlatformService.deleteCheck(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteOneToManyDatatableEntryCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteOneToManyDatatableEntryCommandHandler.java index b3d9f5f43..6c916fbc3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteOneToManyDatatableEntryCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteOneToManyDatatableEntryCommandHandler.java @@ -54,4 +54,4 @@ public class DeleteOneToManyDatatableEntryCommandHandler implements NewCommandSo .withLoanId(commandProcessingResult.getLoanId()) // .build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteOneToOneDatatableEntryCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteOneToOneDatatableEntryCommandHandler.java index db23e58f7..705dc4e16 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteOneToOneDatatableEntryCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteOneToOneDatatableEntryCommandHandler.java @@ -54,4 +54,4 @@ public class DeleteOneToOneDatatableEntryCommandHandler implements NewCommandSou .withLoanId(commandProcessingResult.getLoanId()) // .build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteReportCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteReportCommandHandler.java index eb08e442f..b3935288d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteReportCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/DeleteReportCommandHandler.java @@ -50,4 +50,4 @@ public class DeleteReportCommandHandler implements NewCommandSourceHandler { .withEntityId(command.entityId()) // .build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/RegisterDatatableCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/RegisterDatatableCommandHandler.java index 1088b5643..0d351de0c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/RegisterDatatableCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/RegisterDatatableCommandHandler.java @@ -43,6 +43,7 @@ public class RegisterDatatableCommandHandler implements NewCommandSourceHandler this.writePlatformService.registerDatatable(command); - return new CommandProcessingResultBuilder().withResourceIdAsString(this.writePlatformService.getDataTableName(command.getUrl())).build(); + return new CommandProcessingResultBuilder().withResourceIdAsString(this.writePlatformService.getDataTableName(command.getUrl())) + .build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateDatatableCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateDatatableCommandHandler.java index a10391130..8c4eddf09 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateDatatableCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateDatatableCommandHandler.java @@ -47,4 +47,4 @@ public class UpdateDatatableCommandHandler implements NewCommandSourceHandler { return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withResourceIdAsString(datatableName).build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateOneToManyDatatableEntryCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateOneToManyDatatableEntryCommandHandler.java index 96b58b109..d7da9877b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateOneToManyDatatableEntryCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateOneToManyDatatableEntryCommandHandler.java @@ -41,8 +41,8 @@ public class UpdateOneToManyDatatableEntryCommandHandler implements NewCommandSo @Override public CommandProcessingResult processCommand(final JsonCommand command) { - final CommandProcessingResult commandProcessingResult = this.writePlatformService.updateDatatableEntryOneToMany( - command.entityName(), command.entityId(), command.subentityId(), command); + final CommandProcessingResult commandProcessingResult = this.writePlatformService + .updateDatatableEntryOneToMany(command.entityName(), command.entityId(), command.subentityId(), command); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -55,4 +55,4 @@ public class UpdateOneToManyDatatableEntryCommandHandler implements NewCommandSo .with(commandProcessingResult.getChanges()) // .build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateOneToOneDatatableEntryCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateOneToOneDatatableEntryCommandHandler.java index 42b34547b..152c26e02 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateOneToOneDatatableEntryCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateOneToOneDatatableEntryCommandHandler.java @@ -41,8 +41,8 @@ public class UpdateOneToOneDatatableEntryCommandHandler implements NewCommandSou @Override public CommandProcessingResult processCommand(final JsonCommand command) { - final CommandProcessingResult commandProcessingResult = this.writePlatformService.updateDatatableEntryOneToOne( - command.entityName(), command.entityId(), command); + final CommandProcessingResult commandProcessingResult = this.writePlatformService.updateDatatableEntryOneToOne(command.entityName(), + command.entityId(), command); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -55,4 +55,4 @@ public class UpdateOneToOneDatatableEntryCommandHandler implements NewCommandSou .with(commandProcessingResult.getChanges()) // .build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateReportCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateReportCommandHandler.java index 5e3d2419f..6a873eff2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateReportCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/handler/UpdateReportCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateReportCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.updateReport(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/serialization/ReportCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/serialization/ReportCommandFromApiJsonDeserializer.java index 641e55507..09a88114c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/serialization/ReportCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/serialization/ReportCommandFromApiJsonDeserializer.java @@ -53,4 +53,4 @@ public final class ReportCommandFromApiJsonDeserializer { this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksDataValidator.java index 2f712ddf6..22e00df6b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksDataValidator.java @@ -54,23 +54,18 @@ public final class EntityDatatableChecksDataValidator { } public void validateForCreate(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource("entityDatatableChecks"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("entityDatatableChecks"); final JsonElement element = this.fromApiJsonHelper.parse(json); final String entity = this.fromApiJsonHelper.extractStringNamed("entity", element); - baseDataValidator.reset().parameter("entity").value(entity).notBlank() - .isOneOfTheseStringValues(EntityTables.getEntitiesList()); + baseDataValidator.reset().parameter("entity").value(entity).notBlank().isOneOfTheseStringValues(EntityTables.getEntitiesList()); final Integer status = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("status", element); final Object[] entityTablesStatuses = EntityTables.getStatus(entity).toArray(); @@ -94,8 +89,6 @@ public final class EntityDatatableChecksDataValidator { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksReadPlatformServiceImpl.java index 2809f2db5..a8c44ae43 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksReadPlatformServiceImpl.java @@ -108,7 +108,7 @@ public class EntityDatatableChecksReadPlatformServiceImpl implements EntityDatat } } final String sqlCountRows = "SELECT FOUND_ROWS()"; - return this.paginationHelper.fetchPage(jdbcTemplate, sqlCountRows, sqlBuilder.toString(),paramList.toArray(), + return this.paginationHelper.fetchPage(jdbcTemplate, sqlCountRows, sqlBuilder.toString(), paramList.toArray(), entityDataTableChecksMapper); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksReadService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksReadService.java index 704cab9f4..1a926e974 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksReadService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksReadService.java @@ -33,4 +33,4 @@ public interface EntityDatatableChecksReadService { Page retrieveAll(SearchParameters searchParameters, Long status, String entity, Long productLoanId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksWritePlatformService.java index 053bea36b..533a1eb36 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksWritePlatformService.java @@ -25,10 +25,14 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; public interface EntityDatatableChecksWritePlatformService { CommandProcessingResult createCheck(JsonCommand command); + CommandProcessingResult deleteCheck(final Long entityDatatableCheckId); + void runTheCheck(final Long entityId, final String entityName, final Long statusCode, String foreignKeyColumn); - void runTheCheckForProduct(final Long entityId, final String entityName, final Long statusCode, - String foreignKeyColumn, long productLoanId); + + void runTheCheckForProduct(final Long entityId, final String entityName, final Long statusCode, String foreignKeyColumn, + long productLoanId); + boolean saveDatatables(Long status, String entity, Long entityId, Long productId, JsonArray data); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksWritePlatformServiceImpl.java index b850e53b2..be3da00ed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/EntityDatatableChecksWritePlatformServiceImpl.java @@ -116,7 +116,9 @@ public class EntityDatatableChecksWritePlatformServiceImpl implements EntityData if (productId == null) { entityDatatableCheck = this.entityDatatableChecksRepository.findByEntityStatusAndDatatableIdAndNoProduct(entity, status, datatableName); - if (!entityDatatableCheck.isEmpty()) { throw new EntityDatatableCheckAlreadyExistsException(entity, status, datatableName); } + if (!entityDatatableCheck.isEmpty()) { + throw new EntityDatatableCheckAlreadyExistsException(entity, status, datatableName); + } } else { if (entity.equals("m_loan")) { // if invalid loan product id, throws exception @@ -129,8 +131,9 @@ public class EntityDatatableChecksWritePlatformServiceImpl implements EntityData } entityDatatableCheck = this.entityDatatableChecksRepository.findByEntityStatusAndDatatableIdAndProductId(entity, status, datatableName, productId); - if (!entityDatatableCheck.isEmpty()) { throw new EntityDatatableCheckAlreadyExistsException(entity, status, datatableName, - productId); } + if (!entityDatatableCheck.isEmpty()) { + throw new EntityDatatableCheckAlreadyExistsException(entity, status, datatableName, productId); + } } final EntityDatatableChecks check = EntityDatatableChecks.fromJson(command); @@ -153,8 +156,8 @@ public class EntityDatatableChecksWritePlatformServiceImpl implements EntityData @Override public void runTheCheck(final Long entityId, final String entityName, final Long statusCode, String foreignKeyColumn) { - final List tableRequiredBeforeClientActivation = entityDatatableChecksRepository.findByEntityAndStatus( - entityName, statusCode); + final List tableRequiredBeforeClientActivation = entityDatatableChecksRepository + .findByEntityAndStatus(entityName, statusCode); if (tableRequiredBeforeClientActivation != null) { List reqDatatables = new ArrayList<>(); @@ -277,8 +280,8 @@ public class EntityDatatableChecksWritePlatformServiceImpl implements EntityData if (realCause.getMessage().contains("FOREIGN KEY (`x_registered_table_name`)")) { final String datatableName = command.stringValueOfParameterNamed("datatableName"); - throw new PlatformDataIntegrityException("error.msg.entityDatatableCheck.foreign.key.constraint", "datatable with name '" - + datatableName + "' do not exist", "datatableName", datatableName); + throw new PlatformDataIntegrityException("error.msg.entityDatatableCheck.foreign.key.constraint", + "datatable with name '" + datatableName + "' do not exist", "datatableName", datatableName); } if (realCause.getMessage().contains("unique_entity_check")) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/GenericDataService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/GenericDataService.java index e351a7b0a..d83a06c34 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/GenericDataService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/GenericDataService.java @@ -33,4 +33,4 @@ public interface GenericDataService { String wrapSQL(String sql); List fillResultsetColumnHeaders(String datatable); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/GenericDataServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/GenericDataServiceImpl.java index e0b8497cd..a2efa6720 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/GenericDataServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/GenericDataServiceImpl.java @@ -55,34 +55,34 @@ public class GenericDataServiceImpl implements GenericDataService { @Override public GenericResultsetData fillGenericResultSet(final String sql) { - try{ - final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); + try { + final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); - final List columnHeaders = new ArrayList<>(); - final List resultsetDataRows = new ArrayList<>(); + final List columnHeaders = new ArrayList<>(); + final List resultsetDataRows = new ArrayList<>(); - final SqlRowSetMetaData rsmd = rs.getMetaData(); + final SqlRowSetMetaData rsmd = rs.getMetaData(); + for (int i = 0; i < rsmd.getColumnCount(); i++) { + + final String columnName = rsmd.getColumnName(i + 1); + final String columnType = rsmd.getColumnTypeName(i + 1); + + final ResultsetColumnHeaderData columnHeader = ResultsetColumnHeaderData.basic(columnName, columnType); + columnHeaders.add(columnHeader); + } + + while (rs.next()) { + final List columnValues = new ArrayList<>(); for (int i = 0; i < rsmd.getColumnCount(); i++) { - final String columnName = rsmd.getColumnName(i + 1); - final String columnType = rsmd.getColumnTypeName(i + 1); - - final ResultsetColumnHeaderData columnHeader = ResultsetColumnHeaderData.basic(columnName, columnType); - columnHeaders.add(columnHeader); + final String columnValue = rs.getString(columnName); + columnValues.add(columnValue); } - while (rs.next()) { - final List columnValues = new ArrayList<>(); - for (int i = 0; i < rsmd.getColumnCount(); i++) { - final String columnName = rsmd.getColumnName(i + 1); - final String columnValue = rs.getString(columnName); - columnValues.add(columnValue); - } - - final ResultsetRowData resultsetDataRow = ResultsetRowData.create(columnValues); - resultsetDataRows.add(resultsetDataRow); - } + final ResultsetRowData resultsetDataRow = ResultsetRowData.create(columnValues); + resultsetDataRows.add(resultsetDataRow); + } return new GenericResultsetData(columnHeaders, resultsetDataRows); } catch (DataAccessException e) { @@ -162,8 +162,8 @@ public class GenericDataServiceImpl implements GenericDataService { } else { if (currColType.equals("DATE")) { final LocalDate localDate = new LocalDate(currVal); - writer.append("[" + localDate.getYear() + ", " + localDate.getMonthOfYear() + ", " + localDate.getDayOfMonth() - + "]"); + writer.append( + "[" + localDate.getYear() + ", " + localDate.getMonthOfYear() + ", " + localDate.getDayOfMonth() + "]"); } else if (currColType.equals("DATETIME")) { final LocalDateTime localDateTime = new LocalDateTime(currVal); writer.append("[" + localDateTime.getYear() + ", " + localDateTime.getMonthOfYear() + ", " diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadReportingService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadReportingService.java index 8b9389cd1..f1d723fe0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadReportingService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadReportingService.java @@ -32,7 +32,8 @@ public interface ReadReportingService { StreamingOutput retrieveReportCSV(String name, String type, Map extractedQueryParams, boolean isSelfServiceUserReport); - GenericResultsetData retrieveGenericResultset(String name, String type, Map extractedQueryParams, boolean isSelfServiceUserReport); + GenericResultsetData retrieveGenericResultset(String name, String type, Map extractedQueryParams, + boolean isSelfServiceUserReport); String retrieveReportPDF(String name, String type, Map extractedQueryParams, boolean isSelfServiceUserReport); @@ -46,11 +47,12 @@ public interface ReadReportingService { Collection getAllowedReportTypes(); - //needed for smsCampaign and emailCampaign jobs where securityContext is null + // needed for smsCampaign and emailCampaign jobs where securityContext is + // null GenericResultsetData retrieveGenericResultSetForSmsEmailCampaign(String name, String type, Map extractedQueryParams); - String sqlToRunForSmsEmailCampaign(String name, String type, Map queryParams); + String sqlToRunForSmsEmailCampaign(String name, String type, Map queryParams); - ByteArrayOutputStream generatePentahoReportAsOutputStream(String reportName, String outputTypeParam, - Map queryParams, Locale locale, AppUser runReportAsUser, StringBuilder errorLog); -} \ No newline at end of file + ByteArrayOutputStream generatePentahoReportAsOutputStream(String reportName, String outputTypeParam, Map queryParams, + Locale locale, AppUser runReportAsUser, StringBuilder errorLog); +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadReportingServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadReportingServiceImpl.java index 0e3cb3dda..70dc6a13b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadReportingServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadReportingServiceImpl.java @@ -91,8 +91,8 @@ public class ReadReportingServiceImpl implements ReadReportingService { } @Override - public StreamingOutput retrieveReportCSV(final String name, final String type, - final Map queryParams, final boolean isSelfServiceUserReport) { + public StreamingOutput retrieveReportCSV(final String name, final String type, final Map queryParams, + final boolean isSelfServiceUserReport) { return new StreamingOutput() { @@ -173,8 +173,8 @@ public class ReadReportingServiceImpl implements ReadReportingService { } @Override - public GenericResultsetData retrieveGenericResultset(final String name, final String type, - final Map queryParams, final boolean isSelfServiceUserReport) { + public GenericResultsetData retrieveGenericResultset(final String name, final String type, final Map queryParams, + final boolean isSelfServiceUserReport) { final long startTime = System.currentTimeMillis(); LOG.info("STARTING REPORT: {} Type: {}", name, type); @@ -208,8 +208,7 @@ public class ReadReportingServiceImpl implements ReadReportingService { // permitted to be run by the user sql = this.genericDataService.replace(sql, "${currentUserId}", currentUser.getId().toString()); - sql = this.genericDataService.replace(sql, "${isSelfServiceUser}", - Integer.toString(isSelfServiceUserReport ? 1 : 0)); + sql = this.genericDataService.replace(sql, "${isSelfServiceUser}", Integer.toString(isSelfServiceUserReport ? 1 : 0)); sql = this.genericDataService.wrapSQL(sql); @@ -234,13 +233,14 @@ public class ReadReportingServiceImpl implements ReadReportingService { @Override public String getReportType(final String reportName, final boolean isSelfServiceUserReport) { - final String sql = "SELECT ifnull(report_type,'') as report_type FROM `stretchy_report` where report_name = '" + reportName + "' and self_service_user_report = ?"; + final String sql = "SELECT ifnull(report_type,'') as report_type FROM `stretchy_report` where report_name = '" + reportName + + "' and self_service_user_report = ?"; validateReportName(reportName); this.columnValidator.validateSqlInjection(sql, reportName); final String sqlWrapped = this.genericDataService.wrapSQL(sql); - final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sqlWrapped, new Object [] {isSelfServiceUserReport}); + final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sqlWrapped, new Object[] { isSelfServiceUserReport }); if (rs.next()) { return rs.getString("report_type"); } throw new ReportNotFoundException(reportName); @@ -360,8 +360,8 @@ public class ReadReportingServiceImpl implements ReadReportingService { if (reportParameters == null) { reportParameters = new ArrayList<>(); } - reportParameters.add(new ReportParameterData(rpJoin.getReportParameterId(), rpJoin.getParameterId(), rpJoin - .getReportParameterName(), rpJoin.getParameterName())); + reportParameters.add(new ReportParameterData(rpJoin.getReportParameterId(), rpJoin.getParameterId(), + rpJoin.getReportParameterName(), rpJoin.getParameterName())); } else { if (firstReport) { @@ -387,8 +387,8 @@ public class ReadReportingServiceImpl implements ReadReportingService { if (rpJoin.getReportParameterId() != null) { // report has at least one parameter reportParameters = new ArrayList<>(); - reportParameters.add(new ReportParameterData(rpJoin.getReportParameterId(), rpJoin.getParameterId(), rpJoin - .getReportParameterName(), rpJoin.getParameterName())); + reportParameters.add(new ReportParameterData(rpJoin.getReportParameterId(), rpJoin.getParameterId(), + rpJoin.getReportParameterName(), rpJoin.getParameterName())); } else { reportParameters = null; } @@ -536,89 +536,85 @@ public class ReadReportingServiceImpl implements ReadReportingService { } @Override - public ByteArrayOutputStream generatePentahoReportAsOutputStream(final String reportName, final String outputTypeParam, final Map queryParams, - final Locale locale, final AppUser runReportAsUser, final StringBuilder errorLog) { - //This complete implementation should be moved to Pentaho Report Service + public ByteArrayOutputStream generatePentahoReportAsOutputStream(final String reportName, final String outputTypeParam, + final Map queryParams, final Locale locale, final AppUser runReportAsUser, final StringBuilder errorLog) { + // This complete implementation should be moved to Pentaho Report + // Service /* - String outputType = "HTML"; - if (StringUtils.isNotBlank(outputTypeParam)) { - outputType = outputTypeParam; - } - - if (!(outputType.equalsIgnoreCase("HTML") || outputType.equalsIgnoreCase("PDF") || outputType.equalsIgnoreCase("XLS") || outputType - .equalsIgnoreCase("CSV"))) { throw new PlatformDataIntegrityException("error.msg.invalid.outputType", - "No matching Output Type: " + outputType); } - - if (this.noPentaho) { throw new PlatformDataIntegrityException("error.msg.no.pentaho", "Pentaho is not enabled", - "Pentaho is not enabled"); } - - final String reportPath = FileSystemContentRepository.FINERACT_BASE_DIR + File.separator + "pentahoReports" + File.separator - + reportName + ".prpt"; - LOG.info("Report path: {}", reportPath); - - // load report definition - final ResourceManager manager = new ResourceManager(); - manager.registerDefaults(); - Resource res; - - try { - res = manager.createDirectly(reportPath, MasterReport.class); - final MasterReport masterReport = (MasterReport) res.getResource(); - final DefaultReportEnvironment reportEnvironment = (DefaultReportEnvironment) masterReport.getReportEnvironment(); - - if (locale != null) { - reportEnvironment.setLocale(locale); - } - addParametersToReport(masterReport, queryParams, runReportAsUser, errorLog); - - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - if ("PDF".equalsIgnoreCase(outputType)) { - PdfReportUtil.createPDF(masterReport, baos); - return baos; - } - - if ("XLS".equalsIgnoreCase(outputType)) { - ExcelReportUtil.createXLS(masterReport, baos); - return baos; - } - - if ("CSV".equalsIgnoreCase(outputType)) { - CSVReportUtil.createCSV(masterReport, baos, "UTF-8"); - return baos; - } - - if ("HTML".equalsIgnoreCase(outputType)) { - HtmlReportUtil.createStreamHTML(masterReport, baos); - return baos; - } - - } catch (final ResourceException e) { - errorLog.append("ReadReportingServiceImpl.generatePentahoReportAsOutputStream method threw a Pentaho ResourceException " - + "exception: " + e.getMessage() + " ---------- "); - throw new PlatformDataIntegrityException("error.msg.reporting.error", e.getMessage()); - } catch (final ReportProcessingException e) { - errorLog.append("ReadReportingServiceImpl.generatePentahoReportAsOutputStream method threw a Pentaho ReportProcessingException " - + "exception: " + e.getMessage() + " ---------- "); - throw new PlatformDataIntegrityException("error.msg.reporting.error", e.getMessage()); - } catch (final IOException e) { - errorLog.append("ReadReportingServiceImpl.generatePentahoReportAsOutputStream method threw an IOException " - + "exception: " + e.getMessage() + " ---------- "); - throw new PlatformDataIntegrityException("error.msg.reporting.error", e.getMessage()); - } - - errorLog.append("ReadReportingServiceImpl.generatePentahoReportAsOutputStream method threw a PlatformDataIntegrityException " - + "exception: No matching Output Type: " + outputType + " ---------- "); - throw new PlatformDataIntegrityException("error.msg.invalid.outputType", "No matching Output Type: " + outputType); - - */ - return null ; + * String outputType = "HTML"; if + * (StringUtils.isNotBlank(outputTypeParam)) { outputType = + * outputTypeParam; } + * + * if (!(outputType.equalsIgnoreCase("HTML") || + * outputType.equalsIgnoreCase("PDF") || + * outputType.equalsIgnoreCase("XLS") || outputType + * .equalsIgnoreCase("CSV"))) { throw new + * PlatformDataIntegrityException("error.msg.invalid.outputType", + * "No matching Output Type: " + outputType); } + * + * if (this.noPentaho) { throw new + * PlatformDataIntegrityException("error.msg.no.pentaho", + * "Pentaho is not enabled", "Pentaho is not enabled"); } + * + * final String reportPath = + * FileSystemContentRepository.FINERACT_BASE_DIR + File.separator + + * "pentahoReports" + File.separator + reportName + ".prpt"; + * LOG.info("Report path: {}", reportPath); + * + * // load report definition final ResourceManager manager = new + * ResourceManager(); manager.registerDefaults(); Resource res; + * + * try { res = manager.createDirectly(reportPath, MasterReport.class); + * final MasterReport masterReport = (MasterReport) res.getResource(); + * final DefaultReportEnvironment reportEnvironment = + * (DefaultReportEnvironment) masterReport.getReportEnvironment(); + * + * if (locale != null) { reportEnvironment.setLocale(locale); } + * addParametersToReport(masterReport, queryParams, runReportAsUser, + * errorLog); + * + * final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + * + * if ("PDF".equalsIgnoreCase(outputType)) { + * PdfReportUtil.createPDF(masterReport, baos); return baos; } + * + * if ("XLS".equalsIgnoreCase(outputType)) { + * ExcelReportUtil.createXLS(masterReport, baos); return baos; } + * + * if ("CSV".equalsIgnoreCase(outputType)) { + * CSVReportUtil.createCSV(masterReport, baos, "UTF-8"); return baos; } + * + * if ("HTML".equalsIgnoreCase(outputType)) { + * HtmlReportUtil.createStreamHTML(masterReport, baos); return baos; } + * + * } catch (final ResourceException e) { errorLog. + * append("ReadReportingServiceImpl.generatePentahoReportAsOutputStream method threw a Pentaho ResourceException " + * + "exception: " + e.getMessage() + " ---------- "); throw new + * PlatformDataIntegrityException("error.msg.reporting.error", + * e.getMessage()); } catch (final ReportProcessingException e) { + * errorLog. + * append("ReadReportingServiceImpl.generatePentahoReportAsOutputStream method threw a Pentaho ReportProcessingException " + * + "exception: " + e.getMessage() + " ---------- "); throw new + * PlatformDataIntegrityException("error.msg.reporting.error", + * e.getMessage()); } catch (final IOException e) { errorLog. + * append("ReadReportingServiceImpl.generatePentahoReportAsOutputStream method threw an IOException " + * + "exception: " + e.getMessage() + " ---------- "); throw new + * PlatformDataIntegrityException("error.msg.reporting.error", + * e.getMessage()); } + * + * errorLog. + * append("ReadReportingServiceImpl.generatePentahoReportAsOutputStream method threw a PlatformDataIntegrityException " + * + "exception: No matching Output Type: " + outputType + + * " ---------- "); throw new + * PlatformDataIntegrityException("error.msg.invalid.outputType", + * "No matching Output Type: " + outputType); + * + */ + return null; } private void validateReportName(final String name) { - if (!StringUtils.isBlank(name) && !name.matches(REPORT_NAME_REGEX_PATTERN)) { - throw new SQLInjectionException(); - } + if (!StringUtils.isBlank(name) && !name.matches(REPORT_NAME_REGEX_PATTERN)) { throw new SQLInjectionException(); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java index 2e5579f58..f348b3803 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java @@ -69,5 +69,5 @@ public interface ReadWriteNonCoreDataService { String getDataTableName(String Url); - Long countDatatableEntries(String datatableName,Long appTableId,String foreignKeyColumn); + Long countDatatableEntries(String datatableName, Long appTableId, String foreignKeyColumn); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java index 25442375c..357c85428 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java @@ -90,16 +90,9 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ private final static String CODE_VALUES_TABLE = "m_code_value"; private final static Logger LOG = LoggerFactory.getLogger(ReadWriteNonCoreDataServiceImpl.class); - private final static ImmutableMap apiTypeToMySQL = ImmutableMap.builder() - .put("string", "VARCHAR") - .put("number", "INT") - .put("boolean", "BIT") - .put("decimal", "DECIMAL") - .put("date", "DATE") - .put("datetime", "DATETIME") - .put("text", "TEXT") - .put("dropdown", "INT") - .build(); + private final static ImmutableMap apiTypeToMySQL = ImmutableMap. builder().put("string", "VARCHAR") + .put("number", "INT").put("boolean", "BIT").put("decimal", "DECIMAL").put("date", "DATE").put("datetime", "DATETIME") + .put("text", "TEXT").put("dropdown", "INT").build(); private final static List stringDataTypes = Arrays.asList("char", "varchar", "blob", "text", "tinyblob", "tinytext", "mediumblob", "mediumtext", "longblob", "longtext"); @@ -267,31 +260,30 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ // add the registered table to the config if it is a ppi if (this.isSurveyCategory(category)) { - this.namedParameterJdbcTemplate.update("insert into c_configuration (name, value, enabled ) values( :dataTableName , '0','0')", paramMap); + this.namedParameterJdbcTemplate + .update("insert into c_configuration (name, value, enabled ) values( :dataTableName , '0','0')", paramMap); } - } - catch (final DataIntegrityViolationException dve) { - final Throwable cause = dve.getCause() ; + } catch (final DataIntegrityViolationException dve) { + final Throwable cause = dve.getCause(); final Throwable realCause = dve.getMostSpecificCause(); // even if duplicate is only due to permission duplicate, okay to // show duplicate datatable error msg - if (realCause.getMessage() - .contains("Duplicate entry") || cause.getMessage() - .contains("Duplicate entry")) { + if (realCause.getMessage().contains("Duplicate entry") || cause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException("error.msg.datatable.registered", - "Datatable `" + dataTableName + "` is already registered against an application table.", "dataTableName", - dataTableName); } + "Datatable `" + dataTableName + "` is already registered against an application table.", "dataTableName", + dataTableName); + } logAsErrorUnexpectedDataIntegrityException(dve); throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); - }catch (final PersistenceException dve) { - final Throwable cause = dve.getCause() ; - if (cause.getMessage() - .contains("Duplicate entry")) { + } catch (final PersistenceException dve) { + final Throwable cause = dve.getCause(); + if (cause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException("error.msg.datatable.registered", - "Datatable `" + dataTableName + "` is already registered against an application table.", "dataTableName", - dataTableName); } + "Datatable `" + dataTableName + "` is already registered against an application table.", "dataTableName", + dataTableName); + } logAsErrorUnexpectedDataIntegrityException(dve); throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); @@ -395,16 +387,20 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ return commandProcessingResult; // } catch (final DataAccessException dve) { - final Throwable cause = dve.getCause() ; + final Throwable cause = dve.getCause(); final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("Duplicate entry") || cause.getMessage().contains("Duplicate entry")) { - throw new PlatformDataIntegrityException("error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" - + dataTableName + "` and application table with identifier `" + appTableId + "`.", "dataTableName", dataTableName, - appTableId); + throw new PlatformDataIntegrityException( + "error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" + dataTableName + + "` and application table with identifier `" + appTableId + "`.", + "dataTableName", dataTableName, appTableId); } else if (realCause.getMessage().contains("doesn't have a default value") - || cause.getMessage().contains("doesn't have a default value")) { throw new PlatformDataIntegrityException( - "error.msg.datatable.no.value.provided.for.required.fields", "No values provided for the datatable `" + dataTableName - + "` and application table with identifier `" + appTableId + "`.", "dataTableName", dataTableName, appTableId); } + || cause.getMessage().contains("doesn't have a default value")) { + throw new PlatformDataIntegrityException( + "error.msg.datatable.no.value.provided.for.required.fields", "No values provided for the datatable `" + + dataTableName + "` and application table with identifier `" + appTableId + "`.", + "dataTableName", dataTableName, appTableId); + } logAsErrorUnexpectedDataIntegrityException(dve); throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", @@ -412,12 +408,16 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } catch (final PersistenceException e) { final Throwable cause = e.getCause(); if (cause.getMessage().contains("Duplicate entry")) { - throw new PlatformDataIntegrityException("error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" - + dataTableName + "` and application table with identifier `" + appTableId + "`.", "dataTableName", dataTableName, - appTableId); - } else if (cause.getMessage().contains("doesn't have a default value")) { throw new PlatformDataIntegrityException( - "error.msg.datatable.no.value.provided.for.required.fields", "No values provided for the datatable `" + dataTableName - + "` and application table with identifier `" + appTableId + "`.", "dataTableName", dataTableName, appTableId); } + throw new PlatformDataIntegrityException( + "error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" + dataTableName + + "` and application table with identifier `" + appTableId + "`.", + "dataTableName", dataTableName, appTableId); + } else if (cause.getMessage().contains("doesn't have a default value")) { + throw new PlatformDataIntegrityException( + "error.msg.datatable.no.value.provided.for.required.fields", "No values provided for the datatable `" + + dataTableName + "` and application table with identifier `" + appTableId + "`.", + "dataTableName", dataTableName, appTableId); + } logAsErrorUnexpectedDataIntegrityException(e); throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", @@ -445,25 +445,26 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ return commandProcessingResult; // } catch (final DataAccessException dve) { - final Throwable cause = dve.getCause() ; + final Throwable cause = dve.getCause(); final Throwable realCause = dve.getMostSpecificCause(); - if (realCause.getMessage() - .contains("Duplicate entry") || cause.getMessage() - .contains("Duplicate entry")) { throw new PlatformDataIntegrityException( - "error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" + dataTableName - + "` and application table with identifier `" + appTableId + "`.", - "dataTableName", dataTableName, appTableId); } + if (realCause.getMessage().contains("Duplicate entry") || cause.getMessage().contains("Duplicate entry")) { + throw new PlatformDataIntegrityException( + "error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" + dataTableName + + "` and application table with identifier `" + appTableId + "`.", + "dataTableName", dataTableName, appTableId); + } logAsErrorUnexpectedDataIntegrityException(dve); throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); - }catch (final PersistenceException dve) { - final Throwable cause = dve.getCause() ; - if (cause.getMessage() - .contains("Duplicate entry")) { throw new PlatformDataIntegrityException( - "error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" + dataTableName - + "` and application table with identifier `" + appTableId + "`.", - "dataTableName", dataTableName, appTableId); } + } catch (final PersistenceException dve) { + final Throwable cause = dve.getCause(); + if (cause.getMessage().contains("Duplicate entry")) { + throw new PlatformDataIntegrityException( + "error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" + dataTableName + + "` and application table with identifier `" + appTableId + "`.", + "dataTableName", dataTableName, appTableId); + } logAsErrorUnexpectedDataIntegrityException(dve); throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", @@ -482,16 +483,19 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ final String sql = "select if((exists (select 1 from information_schema.tables where table_schema = schema() and table_name = ?)) = 1, 'true', 'false')"; final String dataTableExistsString = this.jdbcTemplate.queryForObject(sql, String.class, new Object[] { datatableName }); final boolean dataTableExists = Boolean.valueOf(dataTableExistsString); - if (!dataTableExists) { throw new PlatformDataIntegrityException("error.msg.invalid.datatable", - "Invalid Data Table: " + datatableName, "name", datatableName); } + if (!dataTableExists) { + throw new PlatformDataIntegrityException("error.msg.invalid.datatable", "Invalid Data Table: " + datatableName, "name", + datatableName); + } } private void validateDatatableName(final String name) { if (name == null || name.isEmpty()) { throw new PlatformDataIntegrityException("error.msg.datatables.datatable.null.name", "Data table name must not be blank."); - } else if (!name.matches(DATATABLE_NAME_REGEX_PATTERN)) { throw new PlatformDataIntegrityException( - "error.msg.datatables.datatable.invalid.name.regex", "Invalid data table name.", name); } + } else if (!name.matches(DATATABLE_NAME_REGEX_PATTERN)) { + throw new PlatformDataIntegrityException("error.msg.datatables.datatable.invalid.name.regex", "Invalid data table name.", name); + } SQLInjectionValidator.validateSQLInput(name); } @@ -501,8 +505,10 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } private void parseDatatableColumnObjectForCreate(final JsonObject column, StringBuilder sqlBuilder, @@ -588,8 +594,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ sqlBuilder = sqlBuilder.append("CREATE TABLE `" + datatableName + "` ("); if (multiRow) { - sqlBuilder = sqlBuilder.append("`id` BIGINT NOT NULL AUTO_INCREMENT, ") - .append("`" + fkColumnName + "` BIGINT NOT NULL, "); + sqlBuilder = sqlBuilder.append("`id` BIGINT NOT NULL AUTO_INCREMENT, ").append("`" + fkColumnName + "` BIGINT NOT NULL, "); } else { sqlBuilder = sqlBuilder.append("`" + fkColumnName + "` BIGINT NOT NULL, "); } @@ -635,21 +640,21 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } throwExceptionIfValidationWarningsExist(dataValidationErrors); - }catch (final PersistenceException | BadSqlGrammarException ee) { - Throwable realCause = ExceptionUtils.getRootCause(ee.getCause()) ; - final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable"); - if (realCause.getMessage().toLowerCase().contains("duplicate column name")) { - baseDataValidator.reset().parameter("name").failWithCode("duplicate.column.name"); - } else if (realCause.getMessage().contains("Table") && realCause.getMessage().contains("already exists")) { - baseDataValidator.reset().parameter("datatableName").value(datatableName).failWithCode("datatable.already.exists"); - } else if (realCause.getMessage().contains("Column") && realCause.getMessage().contains("big")) { - baseDataValidator.reset().parameter("column").failWithCode("length.too.big"); - } else if (realCause.getMessage().contains("Row") && realCause.getMessage().contains("large")) { - baseDataValidator.reset().parameter("row").failWithCode("size.too.large"); - } + } catch (final PersistenceException | BadSqlGrammarException ee) { + Throwable realCause = ExceptionUtils.getRootCause(ee.getCause()); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable"); + if (realCause.getMessage().toLowerCase().contains("duplicate column name")) { + baseDataValidator.reset().parameter("name").failWithCode("duplicate.column.name"); + } else if (realCause.getMessage().contains("Table") && realCause.getMessage().contains("already exists")) { + baseDataValidator.reset().parameter("datatableName").value(datatableName).failWithCode("datatable.already.exists"); + } else if (realCause.getMessage().contains("Column") && realCause.getMessage().contains("big")) { + baseDataValidator.reset().parameter("column").failWithCode("length.too.big"); + } else if (realCause.getMessage().contains("Row") && realCause.getMessage().contains("large")) { + baseDataValidator.reset().parameter("row").failWithCode("size.too.large"); + } - throwExceptionIfValidationWarningsExist(dataValidationErrors); + throwExceptionIfValidationWarningsExist(dataValidationErrors); } return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withResourceIdAsString(datatableName).build(); @@ -713,8 +718,10 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } } } - if (!mapColumnNameDefinition.containsKey(name)) { throw new PlatformDataIntegrityException( - "error.msg.datatable.column.missing.update.parse", "Column " + name + " does not exist.", name); } + if (!mapColumnNameDefinition.containsKey(name)) { + throw new PlatformDataIntegrityException("error.msg.datatable.column.missing.update.parse", + "Column " + name + " does not exist.", name); + } final String type = mapColumnNameDefinition.get(name).getColumnType(); if (length == null && type.toLowerCase().equals("varchar")) { length = mapColumnNameDefinition.get(name).getColumnLength().intValue(); @@ -802,7 +809,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ final StringBuilder constrainBuilder, final List codeMappings) { final String datatableAlias = datatableName.toLowerCase().replaceAll("\\s", "_"); final String name = column.has("name") ? column.get("name").getAsString() : null; - //sqlBuilder = sqlBuilder.append(", DROP COLUMN `" + name + "`"); + // sqlBuilder = sqlBuilder.append(", DROP COLUMN `" + name + "`"); final StringBuilder findFKSql = new StringBuilder(); findFKSql.append("SELECT count(*)").append("FROM information_schema.TABLE_CONSTRAINTS i") .append(" WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY'").append(" AND i.TABLE_SCHEMA = DATABASE()") @@ -928,7 +935,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (changeColumns == null && addColumns == null && dropColumns == null) { return; } if (dropColumns != null) { - if(rowCount>0){ + if (rowCount > 0) { throw new GeneralPlatformDomainRuleException("error.msg.non.empty.datatable.column.cannot.be.deleted", "Non-empty datatable columns can not be deleted."); } @@ -955,7 +962,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ final Map codeMappings = new HashMap<>(); for (final JsonElement column : addColumns) { JsonObject columnAsJson = column.getAsJsonObject(); - if(rowCount>0 && columnAsJson.has("mandatory") && columnAsJson.get("mandatory").getAsBoolean()){ + if (rowCount > 0 && columnAsJson.has("mandatory") && columnAsJson.get("mandatory").getAsBoolean()) { throw new GeneralPlatformDomainRuleException("error.msg.non.empty.datatable.mandatory.column.cannot.be.added", "Non empty datatable mandatory columns can not be added."); } @@ -997,18 +1004,20 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ deleteColumnCodeMapping(removeMappings); registerColumnCodeMapping(codeMappings); } catch (final Exception e) { - if (e.getMessage().contains("Error on rename")) { throw new PlatformServiceUnavailableException( - "error.msg.datatable.column.update.not.allowed", "One of the column name modification not allowed"); } + if (e.getMessage().contains("Error on rename")) { + throw new PlatformServiceUnavailableException("error.msg.datatable.column.update.not.allowed", + "One of the column name modification not allowed"); + } // handle all other exceptions in here // check if exception message contains the // "invalid use of null value" SQL exception message // throw a 503 HTTP error - // PlatformServiceUnavailableException - if (e.getMessage().toLowerCase() - .contains("invalid use of null value")) { throw new PlatformServiceUnavailableException( - "error.msg.datatable.column.update.not.allowed", - "One of the data table columns contains null values"); } + if (e.getMessage().toLowerCase().contains("invalid use of null value")) { + throw new PlatformServiceUnavailableException("error.msg.datatable.column.update.not.allowed", + "One of the data table columns contains null values"); + } } } } catch (final DataIntegrityViolationException e) { @@ -1025,9 +1034,9 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } throwExceptionIfValidationWarningsExist(dataValidationErrors); - }catch (final PersistenceException ee) { - Throwable realCause = ExceptionUtils.getRootCause(ee.getCause()) ; - final List dataValidationErrors = new ArrayList<>(); + } catch (final PersistenceException ee) { + Throwable realCause = ExceptionUtils.getRootCause(ee.getCause()); + final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable"); if (realCause.getMessage().toLowerCase().contains("duplicate column name")) { baseDataValidator.reset().parameter("name").failWithCode("duplicate.column.name"); @@ -1040,7 +1049,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } throwExceptionIfValidationWarningsExist(dataValidationErrors); - } + } } @Transactional @@ -1079,11 +1088,13 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ private void assertDataTableEmpty(final String datatableName) { final int rowCount = getRowCount(datatableName); - if (rowCount != 0) { throw new GeneralPlatformDomainRuleException("error.msg.non.empty.datatable.cannot.be.deleted", - "Non-empty datatable cannot be deleted."); } + if (rowCount != 0) { + throw new GeneralPlatformDomainRuleException("error.msg.non.empty.datatable.cannot.be.deleted", + "Non-empty datatable cannot be deleted."); + } } - private int getRowCount(final String datatableName){ + private int getRowCount(final String datatableName) { final String sql = "select count(*) from `" + datatableName + "`"; return this.jdbcTemplate.queryForObject(sql, Integer.class); } @@ -1114,8 +1125,10 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (grs.hasNoEntries()) { throw new DatatableNotFoundException(dataTableName, appTableId); } - if (grs.hasMoreThanOneEntry()) { throw new PlatformDataIntegrityException("error.msg.attempting.multiple.update", - "Application table: " + dataTableName + " Foreign key id: " + appTableId); } + if (grs.hasMoreThanOneEntry()) { + throw new PlatformDataIntegrityException("error.msg.attempting.multiple.update", + "Application table: " + dataTableName + " Foreign key id: " + appTableId); + } final Type typeOfMap = new TypeToken>() {}.getType(); final Map dataParams = this.fromJsonHelper.extractDataMap(typeOfMap, command.json()); @@ -1158,7 +1171,9 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ public CommandProcessingResult deleteDatatableEntries(final String dataTableName, final Long appTableId) { validateDatatableName(dataTableName); - if (isDatatableAttachedToEntityDatatableCheck(dataTableName)) { throw new DatatableEntryRequiredException(dataTableName, appTableId); } + if (isDatatableAttachedToEntityDatatableCheck(dataTableName)) { + throw new DatatableEntryRequiredException(dataTableName, appTableId); + } final String appTable = queryForApplicationTableName(dataTableName); final CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); final String deleteOneToOneEntrySql = getDeleteEntriesSql(dataTableName, getFKField(appTable), appTableId); @@ -1173,7 +1188,9 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ @Override public CommandProcessingResult deleteDatatableEntry(final String dataTableName, final Long appTableId, final Long datatableId) { validateDatatableName(dataTableName); - if (isDatatableAttachedToEntityDatatableCheck(dataTableName)) { throw new DatatableEntryRequiredException(dataTableName, appTableId); } + if (isDatatableAttachedToEntityDatatableCheck(dataTableName)) { + throw new DatatableEntryRequiredException(dataTableName, appTableId); + } final String appTable = queryForApplicationTableName(dataTableName); final CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); @@ -1324,8 +1341,10 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ + appTable + " as p WHERE p.id = " + appTableId; } - if (scopedSQL == null) { throw new PlatformDataIntegrityException("error.msg.invalid.dataScopeCriteria", - "Application Table: " + appTable + " not catered for in data Scoping"); } + if (scopedSQL == null) { + throw new PlatformDataIntegrityException("error.msg.invalid.dataScopeCriteria", + "Application Table: " + appTable + " not catered for in data Scoping"); + } return scopedSQL; @@ -1593,8 +1612,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ // ignores id and foreign key fields // also ignores locale and dateformat fields that are used for // validating numeric and date data - if (!(key.equalsIgnoreCase("id") || key.equalsIgnoreCase(keyFieldName) || key.equals("locale") - || key.equals("dateFormat"))) { + if (!(key.equalsIgnoreCase("id") || key.equalsIgnoreCase(keyFieldName) || key.equals("locale") || key.equals("dateFormat"))) { notFound = true; // matches incoming fields with and without underscores (spaces // and underscores considered the same) diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReportWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReportWritePlatformService.java index f6c0d3fe3..d1485c495 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReportWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReportWritePlatformService.java @@ -28,4 +28,4 @@ public interface ReportWritePlatformService { CommandProcessingResult updateReport(Long reportId, JsonCommand command); CommandProcessingResult deleteReport(Long reportId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReportWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReportWritePlatformServiceImpl.java index 850d8d669..de8c602fa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReportWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReportWritePlatformServiceImpl.java @@ -102,8 +102,8 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic } catch (final DataIntegrityViolationException dve) { handleReportDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleReportDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -118,8 +118,7 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic this.fromApiJsonDeserializer.validate(command.json()); - final Report report = this.reportRepository.findById(reportId) - .orElseThrow(() -> new ReportNotFoundException(reportId)); + final Report report = this.reportRepository.findById(reportId).orElseThrow(() -> new ReportNotFoundException(reportId)); final Map changes = report.update(command, this.readReportingService.getAllowedReportTypes()); @@ -143,8 +142,8 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic } catch (final DataIntegrityViolationException dve) { handleReportDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleReportDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -154,8 +153,7 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic @Override public CommandProcessingResult deleteReport(final Long reportId) { - final Report report = this.reportRepository.findById(reportId) - .orElseThrow(() -> new ReportNotFoundException(reportId)); + final Report report = this.reportRepository.findById(reportId).orElseThrow(() -> new ReportNotFoundException(reportId)); if (report.isCoreReport()) { // diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/DocumentManagementApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/DocumentManagementApiResource.java index 312cd8156..d5b8a8b03 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/DocumentManagementApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/DocumentManagementApiResource.java @@ -64,14 +64,16 @@ import org.springframework.stereotype.Component; @Path("{entityType}/{entityId}/documents") @Component @Scope("singleton") -@Api(tags = {"Documents"}) +@Api(tags = { "Documents" }) @SwaggerDefinition(tags = { - @Tag(name = "Documents", description = "Multiple Documents (a combination of a name, description and a file) may be attached to different Entities like Clients, Groups, Staff, Loans, Savings and Client Identifiers in the system\n" + "\n" + "Note: The currently allowed Entities are\n" + "\n" + "Clients: URL Pattern as clients\n" + "Staff: URL Pattern as staff\n" + "Loans: URL Pattern as loans\n" + "Savings: URL Pattern as savings\n" + "Client Identifiers: URL Pattern as client_identifiers\n" + "Groups: URL Pattern as groups") -}) + @Tag(name = "Documents", description = "Multiple Documents (a combination of a name, description and a file) may be attached to different Entities like Clients, Groups, Staff, Loans, Savings and Client Identifiers in the system\n" + + "\n" + "Note: The currently allowed Entities are\n" + "\n" + "Clients: URL Pattern as clients\n" + + "Staff: URL Pattern as staff\n" + "Loans: URL Pattern as loans\n" + "Savings: URL Pattern as savings\n" + + "Client Identifiers: URL Pattern as client_identifiers\n" + "Groups: URL Pattern as groups") }) public class DocumentManagementApiResource { - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "parentEntityType", "parentEntityId", - "name", "fileName", "size", "type", "description")); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "parentEntityType", "parentEntityId", "name", "fileName", "size", "type", "description")); private final String SystemEntityType = "DOCUMENT"; @@ -95,9 +97,12 @@ public class DocumentManagementApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List documents", notes = "Example Requests:\n" + "\n" + "clients/1/documents\n" + "\n" + "client_identifiers/1/documents\n" + "\n" + "loans/1/documents?fields=name,description") - @ApiResponses({@ApiResponse(code = 200, message = "", response = DocumentManagementApiResourceSwagger.GetEntityTypeEntityIdDocumentsResponse.class, responseContainer = "list")}) - public String retreiveAllDocuments(@Context final UriInfo uriInfo, @PathParam("entityType") @ApiParam(value = "entityType") final String entityType, + @ApiOperation(value = "List documents", notes = "Example Requests:\n" + "\n" + "clients/1/documents\n" + "\n" + + "client_identifiers/1/documents\n" + "\n" + "loans/1/documents?fields=name,description") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = DocumentManagementApiResourceSwagger.GetEntityTypeEntityIdDocumentsResponse.class, responseContainer = "list") }) + public String retreiveAllDocuments(@Context final UriInfo uriInfo, + @PathParam("entityType") @ApiParam(value = "entityType") final String entityType, @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId) { this.context.authenticatedUser().validateHasReadPermission(this.SystemEntityType); @@ -111,12 +116,20 @@ public class DocumentManagementApiResource { @POST @Consumes({ MediaType.MULTIPART_FORM_DATA }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Document", notes = "Note: A document is created using a Multi-part form upload \n" + "\n" + "Body Parts\n" + "\n" + "name : \n" + "Name or summary of the document\n" + "\n" + "description : \n" + "Description of the document\n" + "\n" + "file : \n" + "The file to be uploaded\n" + "\n" + "Mandatory Fields : \n" + "file and description") - @ApiResponses({@ApiResponse(code = 200, message = "Not Shown (multi-part form data)", response = DocumentManagementApiResourceSwagger.PostEntityTypeEntityIdDocumentsResponse.class)}) - public String createDocument(@PathParam("entityType") @ApiParam(value = "entityType") final String entityType, @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, - @HeaderParam("Content-Length") @ApiParam(value = "Content-Length") final Long fileSize, @FormDataParam("file") @ApiParam(value = "file") final InputStream inputStream, - @FormDataParam("file") final @ApiParam(value = "file") FormDataContentDisposition fileDetails, @FormDataParam("file") @ApiParam(value = "file") final FormDataBodyPart bodyPart, - @FormDataParam("name") @ApiParam(value = "name") final String name, @FormDataParam("description") @ApiParam(value = "description") final String description) { + @ApiOperation(value = "Create a Document", notes = "Note: A document is created using a Multi-part form upload \n" + "\n" + + "Body Parts\n" + "\n" + "name : \n" + "Name or summary of the document\n" + "\n" + "description : \n" + + "Description of the document\n" + "\n" + "file : \n" + "The file to be uploaded\n" + "\n" + "Mandatory Fields : \n" + + "file and description") + @ApiResponses({ + @ApiResponse(code = 200, message = "Not Shown (multi-part form data)", response = DocumentManagementApiResourceSwagger.PostEntityTypeEntityIdDocumentsResponse.class) }) + public String createDocument(@PathParam("entityType") @ApiParam(value = "entityType") final String entityType, + @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, + @HeaderParam("Content-Length") @ApiParam(value = "Content-Length") final Long fileSize, + @FormDataParam("file") @ApiParam(value = "file") final InputStream inputStream, + @FormDataParam("file") final @ApiParam(value = "file") FormDataContentDisposition fileDetails, + @FormDataParam("file") @ApiParam(value = "file") final FormDataBodyPart bodyPart, + @FormDataParam("name") @ApiParam(value = "name") final String name, + @FormDataParam("description") @ApiParam(value = "description") final String description) { /** * TODO: also need to have a backup and stop reading from stream after @@ -139,12 +152,19 @@ public class DocumentManagementApiResource { @Path("{documentId}") @Consumes({ MediaType.MULTIPART_FORM_DATA }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Update a Document", notes = "Note: A document is updated using a Multi-part form upload \n" + "Body Parts\n" + "name\n" + "Name or summary of the document\n" + "description\n" + "Description of the document\n" + "file\n" + "The file to be uploaded") - @ApiResponses({@ApiResponse(code = 200, message = "Not Shown (multi-part form data)", response = DocumentManagementApiResourceSwagger.PutEntityTypeEntityIdDocumentsResponse.class)}) - public String updateDocument(@PathParam("entityType") @ApiParam(value = "entityType") final String entityType, @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, - @PathParam("documentId") @ApiParam(value = "documentId") final Long documentId, @HeaderParam("Content-Length") @ApiParam(value = "Content-Length") final Long fileSize, - @FormDataParam("file") @ApiParam(value = "file") final InputStream inputStream, @FormDataParam("file") @ApiParam(value = "file") final FormDataContentDisposition fileDetails, - @FormDataParam("file") @ApiParam(value = "file") final FormDataBodyPart bodyPart, @FormDataParam("name") @ApiParam(value = "name") final String name, + @ApiOperation(value = "Update a Document", notes = "Note: A document is updated using a Multi-part form upload \n" + "Body Parts\n" + + "name\n" + "Name or summary of the document\n" + "description\n" + "Description of the document\n" + "file\n" + + "The file to be uploaded") + @ApiResponses({ + @ApiResponse(code = 200, message = "Not Shown (multi-part form data)", response = DocumentManagementApiResourceSwagger.PutEntityTypeEntityIdDocumentsResponse.class) }) + public String updateDocument(@PathParam("entityType") @ApiParam(value = "entityType") final String entityType, + @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, + @PathParam("documentId") @ApiParam(value = "documentId") final Long documentId, + @HeaderParam("Content-Length") @ApiParam(value = "Content-Length") final Long fileSize, + @FormDataParam("file") @ApiParam(value = "file") final InputStream inputStream, + @FormDataParam("file") @ApiParam(value = "file") final FormDataContentDisposition fileDetails, + @FormDataParam("file") @ApiParam(value = "file") final FormDataBodyPart bodyPart, + @FormDataParam("name") @ApiParam(value = "name") final String name, @FormDataParam("description") @ApiParam(value = "description") final String description) { final Set modifiedParams = new HashSet<>(); @@ -180,9 +200,12 @@ public class DocumentManagementApiResource { @Path("{documentId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Document", notes = "Example Requests:\n" + "\n" + "clients/1/documents/1\n" + "\n" + "\n" + "loans/1/documents/1\n" + "\n" + "\n" + "client_identifiers/1/documents/1?fields=name,description") - @ApiResponses({@ApiResponse(code = 200, message = "", response = DocumentManagementApiResourceSwagger.GetEntityTypeEntityIdDocumentsResponse.class)}) - public String getDocument(@PathParam("entityType") @ApiParam(value = "entityType") final String entityType, @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, + @ApiOperation(value = "Retrieve a Document", notes = "Example Requests:\n" + "\n" + "clients/1/documents/1\n" + "\n" + "\n" + + "loans/1/documents/1\n" + "\n" + "\n" + "client_identifiers/1/documents/1?fields=name,description") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = DocumentManagementApiResourceSwagger.GetEntityTypeEntityIdDocumentsResponse.class) }) + public String getDocument(@PathParam("entityType") @ApiParam(value = "entityType") final String entityType, + @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, @PathParam("documentId") @ApiParam(value = "documentId") final Long documentId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.SystemEntityType); @@ -197,9 +220,11 @@ public class DocumentManagementApiResource { @Path("{documentId}/attachment") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_OCTET_STREAM }) - @ApiOperation(value = "Retrieve Binary File associated with Document", notes = "Request used to download the file associated with the document\n" + "\n" + "Example Requests:\n" + "\n" + "clients/1/documents/1/attachment\n" + "\n" + "\n" + "loans/1/documents/1/attachment") - @ApiResponses({@ApiResponse(code = 200, message = "Not Shown: The corresponding Binary file")}) - public Response downloadFile(@PathParam("entityType") @ApiParam(value = "entityType") final String entityType, @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, + @ApiOperation(value = "Retrieve Binary File associated with Document", notes = "Request used to download the file associated with the document\n" + + "\n" + "Example Requests:\n" + "\n" + "clients/1/documents/1/attachment\n" + "\n" + "\n" + "loans/1/documents/1/attachment") + @ApiResponses({ @ApiResponse(code = 200, message = "Not Shown: The corresponding Binary file") }) + public Response downloadFile(@PathParam("entityType") @ApiParam(value = "entityType") final String entityType, + @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, @PathParam("documentId") @ApiParam(value = "documentId") final Long documentId) { this.context.authenticatedUser().validateHasReadPermission(this.SystemEntityType); @@ -217,8 +242,10 @@ public class DocumentManagementApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Remove a Document", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = DocumentManagementApiResourceSwagger.DeleteEntityTypeEntityIdDocumentsResponse.class)}) - public String deleteDocument(@PathParam("entityType") @ApiParam(value = "entityType") final String entityType, @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = DocumentManagementApiResourceSwagger.DeleteEntityTypeEntityIdDocumentsResponse.class) }) + public String deleteDocument(@PathParam("entityType") @ApiParam(value = "entityType") final String entityType, + @PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, @PathParam("documentId") @ApiParam(value = "documentId") final Long documentId) { final DocumentCommand documentCommand = new DocumentCommand(null, documentId, entityType, entityId, null, null, null, null, null, @@ -228,4 +255,4 @@ public class DocumentManagementApiResource { return this.toApiJsonSerializer.serialize(documentIdentifier); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/DocumentManagementApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/DocumentManagementApiResourceSwagger.java index 39fe48215..d4d84b0f6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/DocumentManagementApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/DocumentManagementApiResourceSwagger.java @@ -26,12 +26,14 @@ import io.swagger.annotations.ApiModelProperty; */ final class DocumentManagementApiResourceSwagger { + private DocumentManagementApiResourceSwagger() { } @ApiModel(value = "GetEntityTypeEntityIdDocumentsResponse") public static final class GetEntityTypeEntityIdDocumentsResponse { + private GetEntityTypeEntityIdDocumentsResponse() { } @@ -60,9 +62,11 @@ final class DocumentManagementApiResourceSwagger { @ApiModel(value = "PostEntityTypeEntityIdDocumentsResponse") public static final class PostEntityTypeEntityIdDocumentsResponse { + private PostEntityTypeEntityIdDocumentsResponse() { } + @ApiModelProperty(example = "3") public Long resourceId; @ApiModelProperty(example = "3") @@ -71,16 +75,19 @@ final class DocumentManagementApiResourceSwagger { @ApiModel(value = "PutEntityTypeEntityIdDocumentsResponse") public static final class PutEntityTypeEntityIdDocumentsResponse { + private PutEntityTypeEntityIdDocumentsResponse() { } - public final class PutEntityTypeEntityIdDocumentsResponseChangesSwagger{ + public final class PutEntityTypeEntityIdDocumentsResponseChangesSwagger { + private PutEntityTypeEntityIdDocumentsResponseChangesSwagger() { } } + @ApiModelProperty(example = "3") public Long resourceId; public PutEntityTypeEntityIdDocumentsResponseChangesSwagger changes; @@ -90,16 +97,19 @@ final class DocumentManagementApiResourceSwagger { @ApiModel(value = "DeleteEntityTypeEntityIdDocumentsResponse") public static final class DeleteEntityTypeEntityIdDocumentsResponse { + private DeleteEntityTypeEntityIdDocumentsResponse() { } - public final class PutEntityTypeEntityIdDocumentsResponseChangesSwagger{ + public final class PutEntityTypeEntityIdDocumentsResponseChangesSwagger { + private PutEntityTypeEntityIdDocumentsResponseChangesSwagger() { } } + @ApiModelProperty(example = "3") public Long resourceId; public PutEntityTypeEntityIdDocumentsResponseChangesSwagger changes; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/ImagesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/ImagesApiResource.java index 6bd8f8e81..27039ba08 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/ImagesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/ImagesApiResource.java @@ -127,8 +127,9 @@ public class ImagesApiResource { this.context.authenticatedUser().validateHasReadPermission("STAFFIMAGE"); } - if (output != null && (output.equals("octet") || output.equals("inline_octet"))) { return downloadClientImage(entityName, entityId, - maxWidth, maxHeight, output); } + if (output != null && (output.equals("octet") || output.equals("inline_octet"))) { + return downloadClientImage(entityName, entityId, maxWidth, maxHeight, output); + } final ImageData imageData = this.imageReadPlatformService.retrieveImage(entityName, entityId); @@ -162,8 +163,8 @@ public class ImagesApiResource { final ResponseBuilder response = Response.ok(imageData.getContentOfSize(maxWidth, maxHeight)); String dispositionType = "inline_octet".equals(output) ? "inline" : "attachment"; - response.header("Content-Disposition", dispositionType + "; filename=\"" + imageData.getEntityDisplayName() - + ImageFileExtension.JPEG + "\""); + response.header("Content-Disposition", + dispositionType + "; filename=\"" + imageData.getEntityDisplayName() + ImageFileExtension.JPEG + "\""); // TODO: Need a better way of determining image type @@ -209,6 +210,7 @@ public class ImagesApiResource { /*** Entities for document Management **/ public enum EntityTypeForImages { + STAFF, CLIENTS; @Override @@ -228,4 +230,4 @@ public class ImagesApiResource { return false; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/ImagesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/ImagesApiResourceSwagger.java index 7455260d1..1535c0b54 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/ImagesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/api/ImagesApiResourceSwagger.java @@ -23,6 +23,7 @@ package org.apache.fineract.infrastructure.documentmanagement.api; */ final class ImagesApiResourceSwagger { + private ImagesApiResourceSwagger() { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/command/DocumentCommand.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/command/DocumentCommand.java index 0e9272839..0c430c8fd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/command/DocumentCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/command/DocumentCommand.java @@ -141,4 +141,4 @@ public class DocumentCommand { return this.modifiedParameters.contains("location"); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/command/DocumentCommandValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/command/DocumentCommandValidator.java index e0ca4235e..4cb094397 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/command/DocumentCommandValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/command/DocumentCommandValidator.java @@ -47,8 +47,10 @@ public class DocumentCommandValidator { baseDataValidator.reset().anyOfNotNull(this.command.getName(), this.command.getFileName(), this.command.getDescription(), this.command.getLocation(), this.command.getSize()); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForCreate() { @@ -63,7 +65,9 @@ public class DocumentCommandValidator { baseDataValidator.reset().parameter("fileName").value(this.command.getFileName()).notBlank().notExceedingLengthOf(250); baseDataValidator.reset().parameter("description").value(this.command.getName()).notExceedingLengthOf(250); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/ContentRepositoryUtils.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/ContentRepositoryUtils.java index cdd26d3f3..af9ba5daa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/ContentRepositoryUtils.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/ContentRepositoryUtils.java @@ -34,6 +34,7 @@ public class ContentRepositoryUtils { private static final Random random = new Random(); public static enum ImageMIMEtype { + GIF("image/gif"), JPEG("image/jpeg"), PNG("image/png"); private final String value; @@ -62,6 +63,7 @@ public class ContentRepositoryUtils { } public static enum ImageFileExtension { + GIF(".gif"), JPEG(".jpeg"), JPG(".jpg"), PNG(".png"); private final String value; @@ -93,6 +95,7 @@ public class ContentRepositoryUtils { } public static enum ImageDataURIsuffix { + GIF("data:" + ImageMIMEtype.GIF.getValue() + ";base64,"), JPEG("data:" + ImageMIMEtype.JPEG.getValue() + ";base64,"), PNG( "data:" + ImageMIMEtype.PNG.getValue() + ";base64,"); @@ -113,14 +116,17 @@ public class ContentRepositoryUtils { * @param mimeType */ public static void validateImageMimeType(final String mimeType) { - if (!(mimeType.equalsIgnoreCase(ImageMIMEtype.GIF.getValue()) || mimeType.equalsIgnoreCase(ImageMIMEtype.JPEG.getValue()) || mimeType - .equalsIgnoreCase(ImageMIMEtype.PNG.getValue()))) { throw new ImageUploadException(); } + if (!(mimeType.equalsIgnoreCase(ImageMIMEtype.GIF.getValue()) || mimeType.equalsIgnoreCase(ImageMIMEtype.JPEG.getValue()) + || mimeType.equalsIgnoreCase(ImageMIMEtype.PNG.getValue()))) { + throw new ImageUploadException(); + } } /** * Extracts Image from a Data URL * - * @param dataURL mimeType + * @param dataURL + * mimeType */ public static Base64EncodedImage extractImageFromDataURL(final String dataURL) { String fileExtension = ""; @@ -148,8 +154,9 @@ public class ContentRepositoryUtils { * content i.e name and description while compared to the uploaded file * size is negligible **/ - if (fileSize != null && ((fileSize / (1024 * 1024)) > ContentRepository.MAX_FILE_UPLOAD_SIZE_IN_MB)) { throw new ContentManagementException( - name, fileSize, ContentRepository.MAX_FILE_UPLOAD_SIZE_IN_MB); } + if (fileSize != null && ((fileSize / (1024 * 1024)) > ContentRepository.MAX_FILE_UPLOAD_SIZE_IN_MB)) { + throw new ContentManagementException(name, fileSize, ContentRepository.MAX_FILE_UPLOAD_SIZE_IN_MB); + } } public static void validateClientImageNotEmpty(final String imageFileName) { @@ -189,4 +196,4 @@ public class ContentRepositoryUtils { final Random randomGenerator = new Random(); return randomGenerator.nextInt(11) + 5; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/FileSystemContentRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/FileSystemContentRepository.java index fea1ced31..45a509e8c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/FileSystemContentRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/FileSystemContentRepository.java @@ -169,8 +169,9 @@ public class FileSystemContentRepository implements ContentRepository { out.flush(); out.close(); } catch (final IOException ioException) { - LOG.warn("writeFileToFileSystem() IOException (logged because cause is not propagated in ContentManagementException)", ioException); + LOG.warn("writeFileToFileSystem() IOException (logged because cause is not propagated in ContentManagementException)", + ioException); throw new ContentManagementException(fileName, ioException.getMessage()); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/S3ContentRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/S3ContentRepository.java index ed75213f5..257416ce6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/S3ContentRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/contentrepository/S3ContentRepository.java @@ -94,7 +94,8 @@ public class S3ContentRepository implements ContentRepository { public String saveImage(final Base64EncodedImage base64EncodedImage, final Long resourceId, final String imageName) { final String uploadImageLocation = generateClientImageParentDirectory(resourceId); final String fileLocation = uploadImageLocation + File.separator + imageName + base64EncodedImage.getFileExtension(); - final InputStream toUploadInputStream = new ByteArrayInputStream(Base64.getMimeDecoder().decode(base64EncodedImage.getBase64EncodedString())); + final InputStream toUploadInputStream = new ByteArrayInputStream( + Base64.getMimeDecoder().decode(base64EncodedImage.getBase64EncodedString())); uploadDocument(imageName, toUploadInputStream, fileLocation); return fileLocation; @@ -138,7 +139,7 @@ public class S3ContentRepository implements ContentRepository { try { final S3Object s3object = this.s3Client.getObject(new GetObjectRequest(this.s3BucketName, imageData.location())); imageData.updateContent(s3object.getObjectContent()); - }catch(AmazonS3Exception e) { + } catch (AmazonS3Exception e) { LOG.error("Error occured.", e); } return imageData; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/data/DocumentData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/data/DocumentData.java index 7e36bfc99..cf815cf8d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/data/DocumentData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/data/DocumentData.java @@ -81,4 +81,4 @@ public class DocumentData { return this.id; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/data/ImageData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/data/ImageData.java index f0096282f..7ac460e5e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/data/ImageData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/data/ImageData.java @@ -198,7 +198,7 @@ public class ImageData { try { fileInputStream.close(); } catch (IOException e) { - LOG.error("Problem occurred in available function",e); + LOG.error("Problem occurred in available function", e); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/Document.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/Document.java index a0ec39723..5247c6fe6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/Document.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/Document.java @@ -164,4 +164,4 @@ public class Document extends AbstractPersistableCustom { public StorageType storageType() { return StorageType.fromInt(this.storageType); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/DocumentRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/DocumentRepository.java index 0597fbce8..2f4a2b16c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/DocumentRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/DocumentRepository.java @@ -23,4 +23,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface DocumentRepository extends JpaRepository, JpaSpecificationExecutor { // no added behaviour -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/Image.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/Image.java index a7231e03c..b82b49b71 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/Image.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/Image.java @@ -58,4 +58,4 @@ public final class Image extends AbstractPersistableCustom { this.storageType = storageType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/ImageRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/ImageRepository.java index f336a787a..fd1e051b1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/ImageRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/ImageRepository.java @@ -22,4 +22,4 @@ import org.apache.fineract.portfolio.client.domain.Client; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface ImageRepository extends JpaRepository, JpaSpecificationExecutor {} \ No newline at end of file +public interface ImageRepository extends JpaRepository, JpaSpecificationExecutor {} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/StorageType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/StorageType.java index 56efab343..fb771bd77 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/StorageType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/domain/StorageType.java @@ -22,6 +22,7 @@ import java.util.HashMap; import java.util.Map; public enum StorageType { + FILE_SYSTEM(1), S3(2); private final Integer value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/ContentManagementException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/ContentManagementException.java index 788917e0d..9677d9bc2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/ContentManagementException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/ContentManagementException.java @@ -23,13 +23,13 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class ContentManagementException extends AbstractPlatformDomainRuleException { public ContentManagementException(final String filename, final String message) { - super("error.msg.document.save", - "Error while manipulating file " + filename + " due to a File system / Amazon S3 issue " + message, filename, message); + super("error.msg.document.save", "Error while manipulating file " + filename + " due to a File system / Amazon S3 issue " + message, + filename, message); } public ContentManagementException(final String name, final Long fileSize, final int maxFileSize) { - super("error.msg.document.file.too.big", "Unable to save the document with name" + name + " since its file Size of " + fileSize - / (1024 * 1024) + " MB exceeds the max permissable file size of " + maxFileSize + " MB", name, fileSize); + super("error.msg.document.file.too.big", "Unable to save the document with name" + name + " since its file Size of " + + fileSize / (1024 * 1024) + " MB exceeds the max permissable file size of " + maxFileSize + " MB", name, fileSize); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/DocumentNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/DocumentNotFoundException.java index 577379505..f1243e713 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/DocumentNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/DocumentNotFoundException.java @@ -23,7 +23,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class DocumentNotFoundException extends AbstractPlatformResourceNotFoundException { public DocumentNotFoundException(final String entityType, final Long entityId, final Long id) { - super("error.msg.document.id.invalid", "Document with identifier " + id + " does not exist for the " + entityType - + " with Identifier " + entityId, id); + super("error.msg.document.id.invalid", + "Document with identifier " + id + " does not exist for the " + entityType + " with Identifier " + entityId, id); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/InvalidEntityTypeForDocumentManagementException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/InvalidEntityTypeForDocumentManagementException.java index 5cfafa6ad..ae9b4263c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/InvalidEntityTypeForDocumentManagementException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/exception/InvalidEntityTypeForDocumentManagementException.java @@ -30,4 +30,4 @@ public class InvalidEntityTypeForDocumentManagementException extends AbstractPla super("error.documentmanagement.entitytype.invalid", "Document Management is not support for the Entity Type: " + entityType, entityType); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentReadPlatformService.java index 4893853c8..b76e050fb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentReadPlatformService.java @@ -30,4 +30,4 @@ public interface DocumentReadPlatformService { DocumentData retrieveDocument(String entityType, Long entityId, Long documentId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentReadPlatformServiceImpl.java index 47f5fba63..b8facf8a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentReadPlatformServiceImpl.java @@ -139,4 +139,4 @@ public class DocumentReadPlatformServiceImpl implements DocumentReadPlatformServ } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentWritePlatformService.java index 71e730964..807a8d977 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentWritePlatformService.java @@ -35,8 +35,7 @@ public interface DocumentWritePlatformService { CommandProcessingResult deleteDocument(DocumentCommand documentCommand); @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'CREATE_DOCUMENT')") - Long createInternalDocument(String entityType, Long entityId, - Long fileSize, InputStream inputStream, String mimeType, - String name, String description, String fileName); + Long createInternalDocument(String entityType, Long entityId, Long fileSize, InputStream inputStream, String mimeType, String name, + String description, String fileName); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentWritePlatformServiceJpaRepositoryImpl.java index 57f5e08b6..d7d80077e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/DocumentWritePlatformServiceJpaRepositoryImpl.java @@ -49,8 +49,8 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr private final ContentRepositoryFactory contentRepositoryFactory; @Autowired - public DocumentWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, - final DocumentRepository documentRepository, final ContentRepositoryFactory documentStoreFactory) { + public DocumentWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final DocumentRepository documentRepository, + final ContentRepositoryFactory documentStoreFactory) { this.context = context; this.documentRepository = documentRepository; this.contentRepositoryFactory = documentStoreFactory; @@ -88,13 +88,11 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr @Transactional @Override - public Long createInternalDocument(final String entityType, final Long entityId, - final Long fileSize, final InputStream inputStream, final String mimeType, - final String name, final String description, final String fileName) { + public Long createInternalDocument(final String entityType, final Long entityId, final Long fileSize, final InputStream inputStream, + final String mimeType, final String name, final String description, final String fileName) { - - final DocumentCommand documentCommand = new DocumentCommand(null, null, entityType, entityId, name, fileName, - fileSize, mimeType, description, null); + final DocumentCommand documentCommand = new DocumentCommand(null, null, entityType, entityId, name, fileName, fileSize, mimeType, + description, null); final Long documentId = createDocument(documentCommand, inputStream); @@ -153,8 +151,8 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr validateParentEntityType(documentCommand); // TODO: Check document is present under this entity Id final Document document = this.documentRepository.findById(documentCommand.getId()) - .orElseThrow(() -> new DocumentNotFoundException(documentCommand.getParentEntityType(), - documentCommand.getParentEntityId(), documentCommand.getId())); + .orElseThrow(() -> new DocumentNotFoundException(documentCommand.getParentEntityType(), documentCommand.getParentEntityId(), + documentCommand.getId())); this.documentRepository.delete(document); final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(document.storageType()); @@ -163,8 +161,9 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr } private void validateParentEntityType(final DocumentCommand documentCommand) { - if (!checkValidEntityType(documentCommand.getParentEntityType())) { throw new InvalidEntityTypeForDocumentManagementException( - documentCommand.getParentEntityType()); } + if (!checkValidEntityType(documentCommand.getParentEntityType())) { + throw new InvalidEntityTypeForDocumentManagementException(documentCommand.getParentEntityType()); + } } private static boolean checkValidEntityType(final String entityType) { @@ -176,7 +175,8 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr /*** Entities for document Management **/ public static enum DocumentManagementEntity { - CLIENTS, CLIENT_IDENTIFIERS, STAFF, LOANS, SAVINGS, GROUPS,IMPORT; + + CLIENTS, CLIENT_IDENTIFIERS, STAFF, LOANS, SAVINGS, GROUPS, IMPORT; @Override public String toString() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageReadPlatformService.java old mode 100755 new mode 100644 index c28366403..436ebc3fd --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageReadPlatformService.java @@ -24,4 +24,4 @@ public interface ImageReadPlatformService { ImageData retrieveImage(String entityType, Long entityId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 557120bce..137dc9801 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageReadPlatformServiceImpl.java @@ -63,7 +63,8 @@ public class ImageReadPlatformServiceImpl implements ImageReadPlatformService { } public String schema(String entityType) { - StringBuilder builder = new StringBuilder("image.id as id, image.location as location, image.storage_type_enum as storageType "); + StringBuilder builder = new StringBuilder( + "image.id as id, image.location as location, image.storage_type_enum as storageType "); if (EntityTypeForImages.CLIENTS.toString().equalsIgnoreCase(entityType)) { builder.append(" from m_image image , m_client client " + " where client.image_id = image.id and client.id=?"); } else if (EntityTypeForImages.STAFF.toString().equalsIgnoreCase(entityType)) { @@ -102,8 +103,10 @@ public class ImageReadPlatformServiceImpl implements ImageReadPlatformService { final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(imageData.storageType()); final ImageData result = contentRepository.fetchImage(imageData); - //Once we read content EofSensorInputStream, the wrappedStream object is becoming null. So further image source is becoming null - //For Amazon S3. If file is not present, already S3ContentRepository would have thrown this exception. + // Once we read content EofSensorInputStream, the wrappedStream + // object is becoming null. So further image source is becoming null + // For Amazon S3. If file is not present, already + // S3ContentRepository would have thrown this exception. if (!result.available()) { throw new ImageNotFoundException(entityType, entityId); } return result; @@ -111,4 +114,4 @@ public class ImageReadPlatformServiceImpl implements ImageReadPlatformService { throw new ImageNotFoundException("clients", entityId); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index 5b8350705..534fde1bd --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/documentmanagement/service/ImageWritePlatformServiceJpaRepositoryImpl.java @@ -97,8 +97,8 @@ public class ImageWritePlatformServiceJpaRepositoryImpl implements ImageWritePla } // delete image from the file system if (image != null) { - final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(StorageType.fromInt(image - .getStorageType())); + final ContentRepository contentRepository = this.contentRepositoryFactory + .getRepository(StorageType.fromInt(image.getStorageType())); contentRepository.deleteImage(clientId, image.getLocation()); this.imageRepository.delete(image); } @@ -124,8 +124,8 @@ public class ImageWritePlatformServiceJpaRepositoryImpl implements ImageWritePla owner = staff; } if (image != null) { - final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(StorageType.fromInt(image - .getStorageType())); + final ContentRepository contentRepository = this.contentRepositoryFactory + .getRepository(StorageType.fromInt(image.getStorageType())); contentRepository.deleteImage(entityId, image.getLocation()); } return owner; @@ -164,4 +164,4 @@ public class ImageWritePlatformServiceJpaRepositoryImpl implements ImageWritePla return image; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/FineractEntityAccessConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/FineractEntityAccessConstants.java index fcb23a8b1..003a01316 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/FineractEntityAccessConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/FineractEntityAccessConstants.java @@ -28,12 +28,9 @@ public class FineractEntityAccessConstants { * Enum of all parameters passed in while creating/updating an entity access ***/ public static enum EntityAccessJSONinputParams { - ENTITY_TYPE("entityType"), - ENTITY_ID("entityId"), - ENTITY_ACCESS_TYPE_ID("entityAccessTypeId"), - SECOND_ENTITY_TYPE("secondEntityType"), - SECOND_ENTITY_ID("secondEntityId") - ; + + ENTITY_TYPE("entityType"), ENTITY_ID("entityId"), ENTITY_ACCESS_TYPE_ID("entityAccessTypeId"), SECOND_ENTITY_TYPE( + "secondEntityType"), SECOND_ENTITY_ID("secondEntityId"); private final String value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/api/FineractEntityApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/api/FineractEntityApiResource.java index 6b58d4289..74d3715eb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/api/FineractEntityApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/api/FineractEntityApiResource.java @@ -110,8 +110,8 @@ public class FineractEntityApiResource { this.context.authenticatedUser().validateHasReadPermission(FineractEntityApiResourceConstants.FINERACT_ENTITY_RESOURCE_NAME); - final Collection entityToEntityMappings = this.readPlatformService.retrieveEntityToEntityMappings( - mapId, fromId, toId); + final Collection entityToEntityMappings = this.readPlatformService + .retrieveEntityToEntityMappings(mapId, fromId, toId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializerOfficeToLoanProducts.serialize(settings, entityToEntityMappings, FineractEntityApiResourceConstants.FETCH_ENTITY_TO_ENTITY_MAPPINGS); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/api/FineractEntityApiResourceConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/api/FineractEntityApiResourceConstants.java index 53a54b716..ca4bbea9f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/api/FineractEntityApiResourceConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/api/FineractEntityApiResourceConstants.java @@ -43,7 +43,7 @@ public class FineractEntityApiResourceConstants { protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(mappingTypes)); - protected static final Set FETCH_ENTITY_TO_ENTITY_MAPPINGS = new HashSet<>(Arrays.asList(mapId,relId, - fromEnityType, toEntityType)); + protected static final Set FETCH_ENTITY_TO_ENTITY_MAPPINGS = new HashSet<>( + Arrays.asList(mapId, relId, fromEnityType, toEntityType)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityAccessData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityAccessData.java index bb095e1cf..3ab22b43d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityAccessData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityAccessData.java @@ -22,15 +22,12 @@ import org.apache.fineract.infrastructure.entityaccess.domain.FineractEntity; import org.apache.fineract.infrastructure.entityaccess.domain.FineractEntityAccessType; public class FineractEntityAccessData { + private FineractEntity firstEntity; private FineractEntityAccessType accessType; private FineractEntity secondEntity; - public FineractEntityAccessData ( - FineractEntity firstEntity, - FineractEntityAccessType accessType, - FineractEntity secondEntity - ) { + public FineractEntityAccessData(FineractEntity firstEntity, FineractEntityAccessType accessType, FineractEntity secondEntity) { this.firstEntity = firstEntity; this.accessType = accessType; this.secondEntity = secondEntity; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityDataValidator.java index b9b70af85..e86e55f48 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityDataValidator.java @@ -46,8 +46,6 @@ import org.joda.time.LocalDate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; - - @Component public class FineractEntityDataValidator { @@ -57,10 +55,10 @@ public class FineractEntityDataValidator { private final SavingsProductRepository savingsProductRepository; private final ChargeRepositoryWrapper chargeRepositoryWrapper; private final RoleRepository roleRepository; - private static final Set CREATE_ENTITY_MAPPING_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - FineractEntityApiResourceConstants.fromEnityType, FineractEntityApiResourceConstants.toEntityType, - FineractEntityApiResourceConstants.startDate, FineractEntityApiResourceConstants.LOCALE, - FineractEntityApiResourceConstants.DATE_FORMAT, FineractEntityApiResourceConstants.endDate)); + private static final Set CREATE_ENTITY_MAPPING_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(FineractEntityApiResourceConstants.fromEnityType, FineractEntityApiResourceConstants.toEntityType, + FineractEntityApiResourceConstants.startDate, FineractEntityApiResourceConstants.LOCALE, + FineractEntityApiResourceConstants.DATE_FORMAT, FineractEntityApiResourceConstants.endDate)); private static final Set UPDATE_ENTITY_MAPPING_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(FineractEntityApiResourceConstants.relId, FineractEntityApiResourceConstants.fromEnityType, @@ -85,8 +83,7 @@ public class FineractEntityDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - CREATE_ENTITY_MAPPING_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, CREATE_ENTITY_MAPPING_REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); final List dataValidationErrors = new ArrayList<>(); @@ -159,13 +156,11 @@ public class FineractEntityDataValidator { } public void checkForLoanProducts(final Long id) { - this.loanProductRepository.findById(id) - .orElseThrow(() -> new LoanProductNotFoundException(id)); + this.loanProductRepository.findById(id).orElseThrow(() -> new LoanProductNotFoundException(id)); } public void checkForSavingsProducts(final Long id) { - this.savingsProductRepository.findById(id) - .orElseThrow(() -> new SavingsProductNotFoundException(id)); + this.savingsProductRepository.findById(id).orElseThrow(() -> new SavingsProductNotFoundException(id)); } public void checkForCharges(final Long id) { @@ -173,8 +168,7 @@ public class FineractEntityDataValidator { } public void checkForRoles(final Long id) { - this.roleRepository.findById(id) - .orElseThrow(() -> new RoleNotFoundException(id)); + this.roleRepository.findById(id).orElseThrow(() -> new RoleNotFoundException(id)); } public void validateForUpdate(final String json) { @@ -182,8 +176,7 @@ public class FineractEntityDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - UPDATE_ENTITY_MAPPING_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, UPDATE_ENTITY_MAPPING_REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); final List dataValidationErrors = new ArrayList<>(); @@ -194,7 +187,8 @@ public class FineractEntityDataValidator { boolean atLeastOneParameterPassedForUpdate = false; if (this.fromApiJsonHelper.parameterExists(FineractEntityApiResourceConstants.fromEnityType, element)) { atLeastOneParameterPassedForUpdate = true; - final String fromEnityType = this.fromApiJsonHelper.extractStringNamed(FineractEntityApiResourceConstants.fromEnityType, element); + final String fromEnityType = this.fromApiJsonHelper.extractStringNamed(FineractEntityApiResourceConstants.fromEnityType, + element); baseDataValidator.reset().parameter(FineractEntityApiResourceConstants.fromEnityType).value(fromEnityType); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityRelationData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityRelationData.java index 860f1305b..7e3f80e78 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityRelationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityRelationData.java @@ -38,7 +38,7 @@ public class FineractEntityRelationData implements Serializable { this.mappingTypes = mappingTypes; } - public static FineractEntityRelationData getMappingTypes(final Long id,final String mappingTypes) { + public static FineractEntityRelationData getMappingTypes(final Long id, final String mappingTypes) { Integer fromEntityType = null; final Integer toEntityType = null; return new FineractEntityRelationData(id, fromEntityType, toEntityType, mappingTypes); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityToEntityMappingData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityToEntityMappingData.java index 48f226222..85d271289 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityToEntityMappingData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/data/FineractEntityToEntityMappingData.java @@ -60,8 +60,7 @@ public class FineractEntityToEntityMappingData implements Serializable { } public static FineractEntityToEntityMappingData getRelatedEntities(final Long mapId, final Long relationId, final Long fromId, - final Long toId, final Date startDate, final Date endDate ,final String fromEntity, final String toEntity) { - + final Long toId, final Date startDate, final Date endDate, final String fromEntity, final String toEntity) { return new FineractEntityToEntityMappingData(mapId, relationId, fromId, toId, startDate, endDate, fromEntity, toEntity); @@ -89,5 +88,4 @@ public class FineractEntityToEntityMappingData implements Serializable { return fromEntity; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntity.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntity.java index 26a3c3845..704577763 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntity.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntity.java @@ -19,23 +19,23 @@ package org.apache.fineract.infrastructure.entityaccess.domain; public class FineractEntity { + private Long entityId; private FineractEntityType type; @SuppressWarnings("unused") - private FineractEntity() { - } + private FineractEntity() {} public FineractEntity(Long entityId, FineractEntityType type) { this.entityId = entityId; this.type = type; } - public Long getId () { + public Long getId() { return this.entityId; } - public FineractEntityType getType () { + public FineractEntityType getType() { return this.type; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccess.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccess.java index fe5b2936d..36f687c47 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccess.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccess.java @@ -50,20 +50,17 @@ public class FineractEntityAccess extends AbstractPersistableCustom { @Column(name = "second_entity_id") private Long secondEntityId; - protected FineractEntityAccess () { + protected FineractEntityAccess() { } - public static FineractEntityAccess createNew(final String entityType, final Long entityId, - final CodeValue accessType, + public static FineractEntityAccess createNew(final String entityType, final Long entityId, final CodeValue accessType, final String secondEntityType, final Long secondEntityId) { - return new FineractEntityAccess(entityType, entityId, accessType, - secondEntityType, secondEntityId); + return new FineractEntityAccess(entityType, entityId, accessType, secondEntityType, secondEntityId); } - public FineractEntityAccess(final String entityType, final Long entityId, - final CodeValue accessType, - final String secondEntityType, final Long secondEntityId) { + public FineractEntityAccess(final String entityType, final Long entityId, final CodeValue accessType, final String secondEntityType, + final Long secondEntityId) { this.entityType = entityType; this.entityId = entityId; this.accessType = accessType; @@ -72,17 +69,16 @@ public class FineractEntityAccess extends AbstractPersistableCustom { } public static FineractEntityAccess fromJson(final CodeValue accessType, final JsonCommand command) { - final String entityType = command.stringValueOfParameterNamed( - FineractEntityAccessConstants.EntityAccessJSONinputParams.ENTITY_TYPE.getValue()); - final Long entityId = command.longValueOfParameterNamed( - FineractEntityAccessConstants.EntityAccessJSONinputParams.ENTITY_ID.getValue()); - final String secondEntityType = command.stringValueOfParameterNamed( - FineractEntityAccessConstants.EntityAccessJSONinputParams.SECOND_ENTITY_ID.getValue()); - final Long secondEntityId = command.longValueOfParameterNamed( - FineractEntityAccessConstants.EntityAccessJSONinputParams.SECOND_ENTITY_ID.getValue()); + final String entityType = command + .stringValueOfParameterNamed(FineractEntityAccessConstants.EntityAccessJSONinputParams.ENTITY_TYPE.getValue()); + final Long entityId = command + .longValueOfParameterNamed(FineractEntityAccessConstants.EntityAccessJSONinputParams.ENTITY_ID.getValue()); + final String secondEntityType = command + .stringValueOfParameterNamed(FineractEntityAccessConstants.EntityAccessJSONinputParams.SECOND_ENTITY_ID.getValue()); + final Long secondEntityId = command + .longValueOfParameterNamed(FineractEntityAccessConstants.EntityAccessJSONinputParams.SECOND_ENTITY_ID.getValue()); - return new FineractEntityAccess (entityType, entityId, accessType, - secondEntityType, secondEntityId); + return new FineractEntityAccess(entityType, entityId, accessType, secondEntityType, secondEntityId); } @@ -156,4 +152,4 @@ public class FineractEntityAccess extends AbstractPersistableCustom { return this.secondEntityId; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessRepository.java index 6c3c5f561..77701d46f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessRepository.java @@ -21,6 +21,7 @@ package org.apache.fineract.infrastructure.entityaccess.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface FineractEntityAccessRepository extends JpaRepository, JpaSpecificationExecutor { +public interface FineractEntityAccessRepository + extends JpaRepository, JpaSpecificationExecutor { // no added behaviour } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessRepositoryWrapper.java index 50c391fe4..540f685e7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessRepositoryWrapper.java @@ -24,8 +24,8 @@ import org.springframework.stereotype.Service; /** *

- * Wrapper for {@link FineractEntityAccessRepository} that adds NULL checking and Error - * handling capabilities + * Wrapper for {@link FineractEntityAccessRepository} that adds NULL checking + * and Error handling capabilities *

*/ @Service @@ -39,8 +39,7 @@ public class FineractEntityAccessRepositoryWrapper { } public FineractEntityAccess findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new FineractEntityAccessNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new FineractEntityAccessNotFoundException(id)); } public void save(final FineractEntityAccess fineractEntityAccess) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessType.java index dd070aeae..90c531de6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityAccessType.java @@ -22,28 +22,30 @@ public class FineractEntityAccessType { private String str; - public static final FineractEntityAccessType OFFICE_ACCESS_TO_LOAN_PRODUCTS = new FineractEntityAccessType("office_access_to_loan_products"); - public static final FineractEntityAccessType OFFICE_ACCESS_TO_SAVINGS_PRODUCTS = new FineractEntityAccessType("office_access_to_savings_products"); + public static final FineractEntityAccessType OFFICE_ACCESS_TO_LOAN_PRODUCTS = new FineractEntityAccessType( + "office_access_to_loan_products"); + public static final FineractEntityAccessType OFFICE_ACCESS_TO_SAVINGS_PRODUCTS = new FineractEntityAccessType( + "office_access_to_savings_products"); public static final FineractEntityAccessType OFFICE_ACCESS_TO_CHARGES = new FineractEntityAccessType("office_access_to_fees/charges"); - private FineractEntityAccessType (String str) { + private FineractEntityAccessType(String str) { this.str = str; } - public String toStr () { + public String toStr() { return this.str; } - public static FineractEntityAccessType get (String type) { + public static FineractEntityAccessType get(String type) { FineractEntityAccessType retType = null; if (type.equals(OFFICE_ACCESS_TO_LOAN_PRODUCTS.str)) { - retType = OFFICE_ACCESS_TO_LOAN_PRODUCTS; + retType = OFFICE_ACCESS_TO_LOAN_PRODUCTS; } else if (type.equals(OFFICE_ACCESS_TO_SAVINGS_PRODUCTS.str)) { retType = OFFICE_ACCESS_TO_SAVINGS_PRODUCTS; } else if (type.equals(OFFICE_ACCESS_TO_CHARGES.str)) { - retType = OFFICE_ACCESS_TO_CHARGES; + retType = OFFICE_ACCESS_TO_CHARGES; } return retType; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelation.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelation.java index 5a53ff8cb..faa96d234 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelation.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelation.java @@ -43,68 +43,47 @@ public class FineractEntityRelation extends AbstractPersistableCustom { @Column(name = "code_name", nullable = false, length = 50) private String codeName; - /* private FineractEntityRelation(final String fromEntityType, final String toEntityType, final String codeName) { - this.fromEntityType = fromEntityType; - this.toEntityType = toEntityType; - this.codeName = codeName; - }*/ - + /* + * private FineractEntityRelation(final String fromEntityType, final String + * toEntityType, final String codeName) { this.fromEntityType = + * fromEntityType; this.toEntityType = toEntityType; this.codeName = + * codeName; } + */ public FineractEntityRelation() { // TODO Auto-generated constructor stub } - - public Set getFineractEntityToEntityMapping() { return this.fineractEntityToEntityMapping; } - - public void setFineractEntityToEntityMapping(Set fineractEntityToEntityMapping) { this.fineractEntityToEntityMapping = fineractEntityToEntityMapping; } - - public String getFromEntityType() { return this.fromEntityType; } - - public void setFromEntityType(String fromEntityType) { this.fromEntityType = fromEntityType; } - - public String getToEntityType() { return this.toEntityType; } - - public void setToEntityType(String toEntityType) { this.toEntityType = toEntityType; } - - public String getCodeName() { return this.codeName; } - - public void setCodeName(String codeName) { this.codeName = codeName; } - - - - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelationRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelationRepository.java index f148f4549..14693f227 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelationRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelationRepository.java @@ -22,7 +22,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface FineractEntityRelationRepository extends JpaRepository{ +public interface FineractEntityRelationRepository extends JpaRepository { @Query("select fea from FineractEntityRelation fea where fea.codeName= :codeName") FineractEntityRelation findOneByCodeName(@Param("codeName") String codeName); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelationRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelationRepositoryWrapper.java index f57e5b24b..8cae3849a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelationRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityRelationRepositoryWrapper.java @@ -34,14 +34,13 @@ public class FineractEntityRelationRepositoryWrapper { } public FineractEntityRelation findOneWithNotFoundDetection(final Long id) { - return this.fineractEntityRelationRepository.findById(id) - .orElseThrow(() -> new FineractEntityAccessNotFoundException(id)); + return this.fineractEntityRelationRepository.findById(id).orElseThrow(() -> new FineractEntityAccessNotFoundException(id)); } public FineractEntityRelation findOneByCodeName(final String codeName) { - final FineractEntityRelation fineractEntityRelation = this.fineractEntityRelationRepository.findOneByCodeName(codeName) ; - if (fineractEntityRelation == null) { throw new FineractEntityAccessNotFoundException(codeName); } - return fineractEntityRelation; - } + final FineractEntityRelation fineractEntityRelation = this.fineractEntityRelationRepository.findOneByCodeName(codeName); + if (fineractEntityRelation == null) { throw new FineractEntityAccessNotFoundException(codeName); } + return fineractEntityRelation; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMapping.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMapping.java index 3eb69e434..40f869e6e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMapping.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMapping.java @@ -70,7 +70,8 @@ public class FineractEntityToEntityMapping extends AbstractPersistableCustom { // } - public static FineractEntityToEntityMapping newMap(FineractEntityRelation relationId, Long fromId, Long toId, Date startDate, Date endDate) { + public static FineractEntityToEntityMapping newMap(FineractEntityRelation relationId, Long fromId, Long toId, Date startDate, + Date endDate) { return new FineractEntityToEntityMapping(relationId, fromId, toId, startDate, endDate); @@ -106,7 +107,9 @@ public class FineractEntityToEntityMapping extends AbstractPersistableCustom { this.endDate = endDate; } if (startDate != null && endDate != null) { - if (endDate.before(startDate)) { throw new FineractEntityToEntityMappingDateException(startDate.toString(), endDate.toString()); } + if (endDate.before(startDate)) { + throw new FineractEntityToEntityMappingDateException(startDate.toString(), endDate.toString()); + } } return actualChanges; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMappingRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMappingRepository.java index fb60f3bdd..0af10c962 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMappingRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMappingRepository.java @@ -22,11 +22,9 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; - -public interface FineractEntityToEntityMappingRepository extends JpaRepository{ - - +public interface FineractEntityToEntityMappingRepository extends JpaRepository { @Query("select feem from FineractEntityToEntityMapping feem where feem.fromId= :fromId and feem.toId= :toId and feem.relationId= :relId") - FineractEntityToEntityMapping findListByProductId(@Param("relId")FineractEntityRelation relId, @Param("toId")Long toId, @Param("fromId")Long fromId ); + FineractEntityToEntityMapping findListByProductId(@Param("relId") FineractEntityRelation relId, @Param("toId") Long toId, + @Param("fromId") Long fromId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMappingRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMappingRepositoryWrapper.java index 911a1b5c0..49dd932a4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMappingRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityToEntityMappingRepositoryWrapper.java @@ -28,13 +28,13 @@ public class FineractEntityToEntityMappingRepositoryWrapper { private final FineractEntityToEntityMappingRepository fineractEntityToEntityMappingRepository; @Autowired - public FineractEntityToEntityMappingRepositoryWrapper(final FineractEntityToEntityMappingRepository fineractEntityToEntityMappingRepository) { + public FineractEntityToEntityMappingRepositoryWrapper( + final FineractEntityToEntityMappingRepository fineractEntityToEntityMappingRepository) { this.fineractEntityToEntityMappingRepository = fineractEntityToEntityMappingRepository; } public FineractEntityToEntityMapping findOneWithNotFoundDetection(final Long id) { - return this.fineractEntityToEntityMappingRepository.findById(id) - .orElseThrow(() -> new FineractEntityAccessNotFoundException(id)); + return this.fineractEntityToEntityMappingRepository.findById(id).orElseThrow(() -> new FineractEntityAccessNotFoundException(id)); } public void delete(final FineractEntityToEntityMapping mapId) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityType.java index 6176673e7..5797ee046 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/domain/FineractEntityType.java @@ -19,51 +19,50 @@ package org.apache.fineract.infrastructure.entityaccess.domain; public class FineractEntityType { + private String type; private String description; private String table_name; - public static final FineractEntityType OFFICE = new FineractEntityType ("office", "Offices", "m_office"); - public static final FineractEntityType LOAN_PRODUCT = new FineractEntityType ("loan_product", "Loan Products", - "m_product_loan"); - public static final FineractEntityType SAVINGS_PRODUCT = new FineractEntityType ("savings_product", "Savings Products" - , "m_savings_product"); - public static final FineractEntityType CHARGE = new FineractEntityType ("charge", "Fees/Charges", "m_charge"); - public static final FineractEntityType SHARE_PRODUCT = new FineractEntityType("shares_product", "Shares Products", - "m_share_product") ; + public static final FineractEntityType OFFICE = new FineractEntityType("office", "Offices", "m_office"); + public static final FineractEntityType LOAN_PRODUCT = new FineractEntityType("loan_product", "Loan Products", "m_product_loan"); + public static final FineractEntityType SAVINGS_PRODUCT = new FineractEntityType("savings_product", "Savings Products", + "m_savings_product"); + public static final FineractEntityType CHARGE = new FineractEntityType("charge", "Fees/Charges", "m_charge"); + public static final FineractEntityType SHARE_PRODUCT = new FineractEntityType("shares_product", "Shares Products", "m_share_product"); - private FineractEntityType (String type, String description, String table_name) { + private FineractEntityType(String type, String description, String table_name) { this.type = type; this.description = description; this.table_name = table_name; } - public String getType () { + public String getType() { return this.type; } - public String getDescription () { + public String getDescription() { return this.description; } - public String getTable () { + public String getTable() { return this.table_name; } - public static FineractEntityType get (String type) { + public static FineractEntityType get(String type) { FineractEntityType retType = null; if (type.equals(OFFICE.type)) { - retType = OFFICE; + retType = OFFICE; } else if (type.equals(LOAN_PRODUCT.type)) { - retType = LOAN_PRODUCT; + retType = LOAN_PRODUCT; } else if (type.equals(SAVINGS_PRODUCT.type)) { - retType = SAVINGS_PRODUCT; + retType = SAVINGS_PRODUCT; } else if (type.equals(CHARGE.type)) { retType = CHARGE; - }else if(type.equals(SHARE_PRODUCT.type)) { - retType = SHARE_PRODUCT ; + } else if (type.equals(SHARE_PRODUCT.type)) { + retType = SHARE_PRODUCT; } return retType; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityAccessConfigurationException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityAccessConfigurationException.java index 3ee3e55bb..e15b883ce 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityAccessConfigurationException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityAccessConfigurationException.java @@ -24,13 +24,10 @@ import org.apache.fineract.infrastructure.entityaccess.domain.FineractEntityType public class FineractEntityAccessConfigurationException extends AbstractPlatformDomainRuleException { - public FineractEntityAccessConfigurationException(final Long firstEntityId, - final FineractEntityType entityType1, - final FineractEntityAccessType accessType, - final FineractEntityType entityType2) { - super("error.msg.entityaccess.config", - "Error while getting entity access configuration for " + entityType1.getType() + ":" + firstEntityId + - " with type " + accessType.toStr() + " against " + entityType2.getType()); + public FineractEntityAccessConfigurationException(final Long firstEntityId, final FineractEntityType entityType1, + final FineractEntityAccessType accessType, final FineractEntityType entityType2) { + super("error.msg.entityaccess.config", "Error while getting entity access configuration for " + entityType1.getType() + ":" + + firstEntityId + " with type " + accessType.toStr() + " against " + entityType2.getType()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityAccessNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityAccessNotFoundException.java index 60dad533e..fae40cf4e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityAccessNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityAccessNotFoundException.java @@ -30,6 +30,6 @@ public class FineractEntityAccessNotFoundException extends AbstractPlatformResou } public FineractEntityAccessNotFoundException(final String codeName) { - super("error.msg.entityaccess.id.invalid", "FineractEntityAccess with identifier " + codeName + " does not exist"); - } -} \ No newline at end of file + super("error.msg.entityaccess.id.invalid", "FineractEntityAccess with identifier " + codeName + " does not exist"); + } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityMappingConfigurationException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityMappingConfigurationException.java index acdedd778..cf57e47a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityMappingConfigurationException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityMappingConfigurationException.java @@ -23,7 +23,6 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class FineractEntityMappingConfigurationException extends AbstractPlatformDomainRuleException { public FineractEntityMappingConfigurationException() { - super("error.msg.entityaccess.config", - "Error while getting entity maping configuration "); -} + super("error.msg.entityaccess.config", "Error while getting entity maping configuration "); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityToEntityMappingDateException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityToEntityMappingDateException.java index 661fddacd..c4c84d683 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityToEntityMappingDateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/FineractEntityToEntityMappingDateException.java @@ -20,10 +20,9 @@ package org.apache.fineract.infrastructure.entityaccess.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - public class FineractEntityToEntityMappingDateException extends AbstractPlatformResourceNotFoundException { - public FineractEntityToEntityMappingDateException(final String startDate,final String endDate) { - super("error.msg.invalid.endDate", "EndDate " + endDate + " cannot be before StartDate "+startDate); + public FineractEntityToEntityMappingDateException(final String startDate, final String endDate) { + super("error.msg.invalid.endDate", "EndDate " + endDate + " cannot be before StartDate " + startDate); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/NotOfficeSpecificProductException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/NotOfficeSpecificProductException.java index 47ac00f3d..d5a636d50 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/NotOfficeSpecificProductException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/exception/NotOfficeSpecificProductException.java @@ -24,10 +24,10 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR * A {@link RuntimeException} thrown when valid api request end up violating * some domain rule. */ -public class NotOfficeSpecificProductException extends AbstractPlatformDomainRuleException { +public class NotOfficeSpecificProductException extends AbstractPlatformDomainRuleException { public NotOfficeSpecificProductException(final Long productId, final Long officeId) { - super("error.msg.office.product.not.found", "Product with productId " + productId + - " not office Specific Product in offfice with officeId", officeId); - } + super("error.msg.office.product.not.found", + "Product with productId " + productId + " not office Specific Product in offfice with officeId", officeId); } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/handler/CreateEntityToEntityMappingCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/handler/CreateEntityToEntityMappingCommandHandler.java index 7e7b75f6d..91e06eef7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/handler/CreateEntityToEntityMappingCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/handler/CreateEntityToEntityMappingCommandHandler.java @@ -41,7 +41,7 @@ public class CreateEntityToEntityMappingCommandHandler implements NewCommandSour @Override @Transactional public CommandProcessingResult processCommand(JsonCommand command) { - return this.fineractEntityAccessWriteService.createEntityToEntityMapping(command.entityId(),command); + return this.fineractEntityAccessWriteService.createEntityToEntityMapping(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/handler/UpdateEntityToEntityMappingCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/handler/UpdateEntityToEntityMappingCommandHandler.java index 26764444b..8fd82d479 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/handler/UpdateEntityToEntityMappingCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/handler/UpdateEntityToEntityMappingCommandHandler.java @@ -41,7 +41,7 @@ public class UpdateEntityToEntityMappingCommandHandler implements NewCommandSour @Override @Transactional public CommandProcessingResult processCommand(JsonCommand command) { - return this.fineractEntityAccessWriteService.updateEntityToEntityMapping(command.entityId(),command); + return this.fineractEntityAccessWriteService.updateEntityToEntityMapping(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessReadService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessReadService.java index 033814a36..7dbcd0240 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessReadService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessReadService.java @@ -25,11 +25,11 @@ import org.apache.fineract.infrastructure.entityaccess.domain.FineractEntityType public interface FineractEntityAccessReadService { - Collection retrieveEntityAccessFor(FineractEntityType firstEntityType, - final Long relId, final Long fromEntityId,boolean includeAllSubOffices); + Collection retrieveEntityAccessFor(FineractEntityType firstEntityType, final Long relId, + final Long fromEntityId, boolean includeAllSubOffices); - String getSQLQueryInClause_WithListOfIDsForEntityAccess( FineractEntityType firstEntityType, - final Long relId,final Long fromEntityId ,boolean includeAllOffices); + String getSQLQueryInClause_WithListOfIDsForEntityAccess(FineractEntityType firstEntityType, final Long relId, final Long fromEntityId, + boolean includeAllOffices); String getSQLQueryInClauseIDList_ForLoanProductsForOffice(Long loanProductId, boolean includeAllOffices); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessReadServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessReadServiceImpl.java index 474b3afd4..5b211ca56 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessReadServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessReadServiceImpl.java @@ -62,40 +62,38 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess * * @see org.apache.fineract.infrastructure.entityaccess.service. * FineractEntityAccessReadService#getSQLQueryWithListOfIDsForEntityAccess - * (Long, - * org.apache.fineract.infrastructure.entityaccess.domain.FineractEntityType, + * (Long, org.apache.fineract.infrastructure.entityaccess.domain. + * FineractEntityType, * org.apache.fineract.infrastructure.entityaccess.domain. * FineractEntityAccessType, - * org.apache.fineract.infrastructure.entityaccess.domain.FineractEntityType, - * boolean) + * org.apache.fineract.infrastructure.entityaccess.domain. + * FineractEntityType, boolean) * * This method returns the list of entity IDs as a comma separated list Or * null if there is no entity restrictions or if there */ @Override - public String getSQLQueryInClause_WithListOfIDsForEntityAccess( FineractEntityType firstEntityType, - final Long relId, final Long fromEntityId, boolean includeAllOffices) { - Collection accesslist = retrieveEntityAccessFor(firstEntityType, relId, fromEntityId, - includeAllOffices); + public String getSQLQueryInClause_WithListOfIDsForEntityAccess(FineractEntityType firstEntityType, final Long relId, + final Long fromEntityId, boolean includeAllOffices) { + Collection accesslist = retrieveEntityAccessFor(firstEntityType, relId, fromEntityId, + includeAllOffices); String returnIdListStr = null; StringBuilder accessListCSVStrBuf = null; if ((accesslist != null) && (accesslist.size() > 0)) { - for(FineractEntityToEntityMappingData accessData: accesslist){ - if (accessData == null) { - throw new FineractEntityMappingConfigurationException(); - } + for (FineractEntityToEntityMappingData accessData : accesslist) { + if (accessData == null) { throw new FineractEntityMappingConfigurationException(); } - if(accessListCSVStrBuf == null){ - accessListCSVStrBuf = new StringBuilder() ; - }else{ - accessListCSVStrBuf.append(","); - } - accessListCSVStrBuf.append(accessData.getToId()); - if(accessData.getToId() == 0){ - accessListCSVStrBuf =null; - break; - } + if (accessListCSVStrBuf == null) { + accessListCSVStrBuf = new StringBuilder(); + } else { + accessListCSVStrBuf.append(","); } + accessListCSVStrBuf.append(accessData.getToId()); + if (accessData.getToId() == 0) { + accessListCSVStrBuf = null; + break; + } + } } else { @@ -111,8 +109,8 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess } @Override - public Collection retrieveEntityAccessFor(FineractEntityType firstEntityType, - final Long relId, final Long fromEntityId,boolean includeAllSubOffices) { + public Collection retrieveEntityAccessFor(FineractEntityType firstEntityType, final Long relId, + final Long fromEntityId, boolean includeAllSubOffices) { final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); @@ -131,7 +129,7 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess sql += " where firstentity.hierarchy like ? order by firstEntity.hierarchy"; entityAccessData = this.jdbcTemplate.query(sql, mapper, new Object[] { fromEntityId, fromEntityId, hierarchySearchString }); } else { - entityAccessData = this.jdbcTemplate.query(sql, mapper, new Object[] { relId, fromEntityId}); + entityAccessData = this.jdbcTemplate.query(sql, mapper, new Object[] { relId, fromEntityId }); } return entityAccessData; @@ -139,10 +137,10 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess private String getSQLForRetriveEntityAccessFor() { StringBuilder str = new StringBuilder("select eem.rel_id as relId,eem.from_id as fromId, "); - str.append("eem.to_id as toId, eem.start_date as startDate, eem.end_date as endDate "); - str.append("from m_entity_to_entity_mapping eem "); - str.append("where eem.rel_id = ? "); - str.append("and eem.from_id = ? "); + str.append("eem.to_id as toId, eem.start_date as startDate, eem.end_date as endDate "); + str.append("from m_entity_to_entity_mapping eem "); + str.append("where eem.rel_id = ? "); + str.append("and eem.from_id = ? "); LOG.debug("{}", str); return str.toString(); } @@ -192,7 +190,7 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess FineractEntityType firstEntityType = FineractEntityType.OFFICE; FineractEntityRelation fineractEntityRelation = fineractEntityRelationRepository - .findOneByCodeName(FineractEntityAccessType.OFFICE_ACCESS_TO_LOAN_PRODUCTS.toStr()); + .findOneByCodeName(FineractEntityAccessType.OFFICE_ACCESS_TO_LOAN_PRODUCTS.toStr()); Long relId = fineractEntityRelation.getId(); return getSQLQueryInClause_WithListOfIDsForEntityAccess(firstEntityType, relId, officeId, includeAllOffices); } @@ -202,7 +200,7 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess FineractEntityType firstEntityType = FineractEntityType.OFFICE; FineractEntityRelation fineractEntityRelation = fineractEntityRelationRepository - .findOneByCodeName(FineractEntityAccessType.OFFICE_ACCESS_TO_SAVINGS_PRODUCTS.toStr()); + .findOneByCodeName(FineractEntityAccessType.OFFICE_ACCESS_TO_SAVINGS_PRODUCTS.toStr()); Long relId = fineractEntityRelation.getId(); return getSQLQueryInClause_WithListOfIDsForEntityAccess(firstEntityType, relId, officeId, includeAllOffices); @@ -213,7 +211,7 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess FineractEntityType firstEntityType = FineractEntityType.OFFICE; FineractEntityRelation fineractEntityRelation = fineractEntityRelationRepository - .findOneByCodeName(FineractEntityAccessType.OFFICE_ACCESS_TO_CHARGES.toStr()); + .findOneByCodeName(FineractEntityAccessType.OFFICE_ACCESS_TO_CHARGES.toStr()); Long relId = fineractEntityRelation.getId(); return getSQLQueryInClause_WithListOfIDsForEntityAccess(firstEntityType, relId, officeId, includeAllOffices); @@ -280,7 +278,8 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess } @Override - public FineractEntityToEntityMappingData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { + public FineractEntityToEntityMappingData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) + throws SQLException { final Long relId = rs.getLong("relId"); final Long fromId = rs.getLong("fromId"); @@ -349,7 +348,8 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess } @Override - public FineractEntityToEntityMappingData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { + public FineractEntityToEntityMappingData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) + throws SQLException { final Long mapId = rs.getLong("mapId"); final Long relId = rs.getLong("relId"); final Long fromId = rs.getLong("from_id"); @@ -358,7 +358,8 @@ public class FineractEntityAccessReadServiceImpl implements FineractEntityAccess final String toEntity = rs.getString("to_name"); final Date startDate = rs.getDate("startDate"); final Date endDate = rs.getDate("endDate"); - return FineractEntityToEntityMappingData.getRelatedEntities(mapId, relId, fromId, toId, startDate, endDate, fromEntity, toEntity); + return FineractEntityToEntityMappingData.getRelatedEntities(mapId, relId, fromId, toId, startDate, endDate, fromEntity, + toEntity); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessUtil.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessUtil.java index 2ab02963d..42201a42a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessUtil.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessUtil.java @@ -49,12 +49,10 @@ public class FineractEntityAccessUtil { private final FineractEntityToEntityMappingRepository fineractEntityToEntityMappingRepository; @Autowired - public FineractEntityAccessUtil ( - final PlatformSecurityContext context, + public FineractEntityAccessUtil(final PlatformSecurityContext context, final GlobalConfigurationRepositoryWrapper globalConfigurationRepository, final FineractEntityAccessWriteService fineractEntityAccessWriteService, - final CodeValueReadPlatformService codeValueReadPlatformService, - final CodeValueRepositoryWrapper codeValueRepository, + final CodeValueReadPlatformService codeValueReadPlatformService, final CodeValueRepositoryWrapper codeValueRepository, final FineractEntityAccessReadService fineractEntityAccessReadService, final FineractEntityRelationRepositoryWrapper fineractEntityRelationRepositoryWrapper, final FineractEntityToEntityMappingRepository fineractEntityToEntityMappingRepository) { @@ -68,68 +66,62 @@ public class FineractEntityAccessUtil { this.fineractEntityToEntityMappingRepository = fineractEntityToEntityMappingRepository; } - @Transactional - public void checkConfigurationAndAddProductResrictionsForUserOffice ( - final FineractEntityAccessType fineractEntityAccessType, + public void checkConfigurationAndAddProductResrictionsForUserOffice(final FineractEntityAccessType fineractEntityAccessType, final Long productOrChargeId) { AppUser thisUser = this.context.authenticatedUser(); - // check if the office specific products are enabled. If yes, then save this product or charge against a specific office + // check if the office specific products are enabled. If yes, then save + // this product or charge against a specific office // i.e. this product or charge is specific for this office. final GlobalConfigurationProperty property = this.globalConfigurationRepository - .findOneByNameWithNotFoundDetection( - FineractEntityAccessConstants.GLOBAL_CONFIG_FOR_OFFICE_SPECIFIC_PRODUCTS); - if (property.isEnabled() ) { - // If this property is enabled, then Fineract need to restrict access to this loan product to only the office of the current user + .findOneByNameWithNotFoundDetection(FineractEntityAccessConstants.GLOBAL_CONFIG_FOR_OFFICE_SPECIFIC_PRODUCTS); + if (property.isEnabled()) { + // If this property is enabled, then Fineract need to restrict + // access to this loan product to only the office of the current + // user final GlobalConfigurationProperty restrictToUserOfficeProperty = this.globalConfigurationRepository - .findOneByNameWithNotFoundDetection( - FineractEntityAccessConstants.GLOBAL_CONFIG_FOR_RESTRICT_PRODUCTS_TO_USER_OFFICE); + .findOneByNameWithNotFoundDetection(FineractEntityAccessConstants.GLOBAL_CONFIG_FOR_RESTRICT_PRODUCTS_TO_USER_OFFICE); - if (restrictToUserOfficeProperty.isEnabled() ) { + if (restrictToUserOfficeProperty.isEnabled()) { final Long officeId = thisUser.getOffice().getId(); - Date startDateFormapping = null; - Date endDateFormapping = null; - FineractEntityRelation fineractEntityRelation = fineractEntityRelationRepositoryWrapper - .findOneByCodeName(fineractEntityAccessType.toStr()); - Long relId = fineractEntityRelation.getId(); - final FineractEntityRelation mapId = this.fineractEntityRelationRepositoryWrapper - .findOneWithNotFoundDetection(relId); - final FineractEntityToEntityMapping newMap = FineractEntityToEntityMapping.newMap(mapId, officeId, - productOrChargeId, startDateFormapping, endDateFormapping); - this.fineractEntityToEntityMappingRepository.save(newMap); - } + Date startDateFormapping = null; + Date endDateFormapping = null; + FineractEntityRelation fineractEntityRelation = fineractEntityRelationRepositoryWrapper + .findOneByCodeName(fineractEntityAccessType.toStr()); + Long relId = fineractEntityRelation.getId(); + final FineractEntityRelation mapId = this.fineractEntityRelationRepositoryWrapper.findOneWithNotFoundDetection(relId); + final FineractEntityToEntityMapping newMap = FineractEntityToEntityMapping.newMap(mapId, officeId, productOrChargeId, + startDateFormapping, endDateFormapping); + this.fineractEntityToEntityMappingRepository.save(newMap); + } } } - public String getSQLWhereClauseForProductIDsForUserOffice_ifGlobalConfigEnabled ( - FineractEntityType fineractEntityType) { + public String getSQLWhereClauseForProductIDsForUserOffice_ifGlobalConfigEnabled(FineractEntityType fineractEntityType) { String inClause = ""; final GlobalConfigurationProperty property = this.globalConfigurationRepository - .findOneByNameWithNotFoundDetection( - FineractEntityAccessConstants.GLOBAL_CONFIG_FOR_OFFICE_SPECIFIC_PRODUCTS); + .findOneByNameWithNotFoundDetection(FineractEntityAccessConstants.GLOBAL_CONFIG_FOR_OFFICE_SPECIFIC_PRODUCTS); - if (property.isEnabled() ) { - // Get 'SQL In Clause' for fetching only products/charges that are relevant for current user's office + if (property.isEnabled()) { + // Get 'SQL In Clause' for fetching only products/charges that are + // relevant for current user's office if (fineractEntityType.equals(FineractEntityType.SAVINGS_PRODUCT)) { - inClause = fineractEntityAccessReadService. - getSQLQueryInClauseIDList_ForSavingsProductsForOffice ( - this.context.authenticatedUser().getOffice().getId(), false); + inClause = fineractEntityAccessReadService + .getSQLQueryInClauseIDList_ForSavingsProductsForOffice(this.context.authenticatedUser().getOffice().getId(), false); } else if (fineractEntityType.equals(FineractEntityType.LOAN_PRODUCT)) { - inClause = fineractEntityAccessReadService. - getSQLQueryInClauseIDList_ForLoanProductsForOffice ( - this.context.authenticatedUser().getOffice().getId(), false); + inClause = fineractEntityAccessReadService + .getSQLQueryInClauseIDList_ForLoanProductsForOffice(this.context.authenticatedUser().getOffice().getId(), false); } else if (fineractEntityType.equals(FineractEntityType.CHARGE)) { - inClause = fineractEntityAccessReadService. - getSQLQueryInClauseIDList_ForChargesForOffice( - this.context.authenticatedUser().getOffice().getId(), false); + inClause = fineractEntityAccessReadService + .getSQLQueryInClauseIDList_ForChargesForOffice(this.context.authenticatedUser().getOffice().getId(), false); } } return inClause; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessWriteService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessWriteService.java index 054c093b5..27cd7e5ad 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessWriteService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessWriteService.java @@ -26,7 +26,7 @@ public interface FineractEntityAccessWriteService { CommandProcessingResult createEntityAccess(final JsonCommand command); - CommandProcessingResult createEntityToEntityMapping(final Long relId,final JsonCommand command); + CommandProcessingResult createEntityToEntityMapping(final Long relId, final JsonCommand command); CommandProcessingResult updateEntityToEntityMapping(final Long mapId, final JsonCommand command); @@ -43,4 +43,4 @@ public interface FineractEntityAccessWriteService { * final Long entityId, final Long accessType, final String * secondEntityType, final Long secondEntityId); */ -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessWriteServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessWriteServiceImpl.java index 9ce1162e6..756cf46e9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessWriteServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/entityaccess/service/FineractEntityAccessWriteServiceImpl.java @@ -77,7 +77,8 @@ public class FineractEntityAccessWriteServiceImpl implements FineractEntityAcces @Transactional public void addNewEntityAccess(final String entityType, final Long entityId, final CodeValue accessType, final String secondEntityType, final Long secondEntityId) { - FineractEntityAccess entityAccess = FineractEntityAccess.createNew(entityType, entityId, accessType, secondEntityType, secondEntityId); + FineractEntityAccess entityAccess = FineractEntityAccess.createNew(entityType, entityId, accessType, secondEntityType, + secondEntityId); entityAccessRepository.save(entityAccess); } @@ -98,8 +99,9 @@ public class FineractEntityAccessWriteServiceImpl implements FineractEntityAcces fromApiJsonDeserializer.checkForEntity(relId.toString(), fromId, toId); if (startDate != null && endDate != null) { - if (endDate - .before(startDate)) { throw new FineractEntityToEntityMappingDateException(startDate.toString(), endDate.toString()); } + if (endDate.before(startDate)) { + throw new FineractEntityToEntityMappingDateException(startDate.toString(), endDate.toString()); + } } final FineractEntityToEntityMapping newMap = FineractEntityToEntityMapping.newMap(mapId, fromId, toId, startDate, endDate); @@ -110,8 +112,8 @@ public class FineractEntityAccessWriteServiceImpl implements FineractEntityAcces } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -143,8 +145,8 @@ public class FineractEntityAccessWriteServiceImpl implements FineractEntityAcces } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -155,7 +157,8 @@ public class FineractEntityAccessWriteServiceImpl implements FineractEntityAcces public CommandProcessingResult deleteEntityToEntityMapping(Long mapId) { // TODO Auto-generated method stub - final FineractEntityToEntityMapping deleteMap = this.fineractEntityToEntityMappingRepositoryWrapper.findOneWithNotFoundDetection(mapId); + final FineractEntityToEntityMapping deleteMap = this.fineractEntityToEntityMappingRepositoryWrapper + .findOneWithNotFoundDetection(mapId); this.fineractEntityToEntityMappingRepository.delete(deleteMap); return new CommandProcessingResultBuilder(). // @@ -164,7 +167,7 @@ public class FineractEntityAccessWriteServiceImpl implements FineractEntityAcces } private void handleDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { - LOG.error("Problem occurred in handleDataIntegrityIssues function",realCause); + LOG.error("Problem occurred in handleDataIntegrityIssues function", realCause); if (realCause.getMessage().contains("rel_id_from_id_to_id")) { final String fromId = command.stringValueOfParameterNamed(FineractEntityApiResourceConstants.fromEnityType); final String toId = command.stringValueOfParameterNamed(FineractEntityApiResourceConstants.toEntityType); @@ -190,4 +193,4 @@ public class FineractEntityAccessWriteServiceImpl implements FineractEntityAcces * secondEntityId) { // TODO Auto-generated method stub return null; } */ -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/GcmConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/GcmConstants.java index 554aafe21..c5c2470d4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/GcmConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/GcmConstants.java @@ -23,7 +23,6 @@ package org.apache.fineract.infrastructure.gcm; */ public final class GcmConstants { - /** * Title for notification */ @@ -34,7 +33,6 @@ public final class GcmConstants { */ public static final String defaultIcon = "default"; - /** * Parameter for to field. */ @@ -48,7 +46,7 @@ public final class GcmConstants { /** * HTTP parameter for registration id. */ - //public static final String PARAM_REGISTRATION_ID = "registration_id"; + // public static final String PARAM_REGISTRATION_ID = "registration_id"; /** * HTTP parameter for collapse key. diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/api/DeviceRegistrationApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/api/DeviceRegistrationApiConstants.java index e00286c9f..3bb9ebbce 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/api/DeviceRegistrationApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/api/DeviceRegistrationApiConstants.java @@ -19,6 +19,7 @@ package org.apache.fineract.infrastructure.gcm.api; public class DeviceRegistrationApiConstants { + public static final String clientIdParamName = "clientId"; public static final String registrationIdParamName = "registrationId"; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/api/DeviceRegistrationApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/api/DeviceRegistrationApiResource.java index f39ff92d8..ece5c9f73 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/api/DeviceRegistrationApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/api/DeviceRegistrationApiResource.java @@ -148,7 +148,7 @@ public class DeviceRegistrationApiResource { } - public String responseMap(Long id){ + public String responseMap(Long id) { HashMap responseMap = new HashMap<>(); responseMap.put("resource", id); return new Gson().toJson(responseMap); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistration.java index 8f2aeab20..1b6565930 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistration.java @@ -53,8 +53,7 @@ public class DeviceRegistration extends AbstractPersistableCustom { this.updatedOnDate = DateUtils.getLocalDateTimeOfTenant().toDate(); } - public static DeviceRegistration instance(final Client client, - final String registrationId) { + public static DeviceRegistration instance(final Client client, final String registrationId) { return new DeviceRegistration(client, registrationId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationData.java index 10ab0b4f8..a2334fefe 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationData.java @@ -28,19 +28,16 @@ public class DeviceRegistrationData { public String registrationId; public Date updatedOnDate; - private DeviceRegistrationData(final Long id, final ClientData clientData, - final String registrationId, final Date updatedOnDate) { + private DeviceRegistrationData(final Long id, final ClientData clientData, final String registrationId, final Date updatedOnDate) { this.id = id; this.clientData = clientData; this.registrationId = registrationId; this.updatedOnDate = updatedOnDate; } - public static DeviceRegistrationData instance(final Long id, - final ClientData clientData, final String registrationId, + public static DeviceRegistrationData instance(final Long id, final ClientData clientData, final String registrationId, final Date updatedOnDate) { - return new DeviceRegistrationData(id, clientData, registrationId, - updatedOnDate); + return new DeviceRegistrationData(id, clientData, registrationId, updatedOnDate); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationRepository.java index 3d7be8097..f2365a516 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationRepository.java @@ -23,14 +23,12 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface DeviceRegistrationRepository extends - JpaRepository, - JpaSpecificationExecutor { +public interface DeviceRegistrationRepository + extends JpaRepository, JpaSpecificationExecutor { public static final String FIND_DEVICE_REGISTRATION_BY_CLIENT = "select dr from DeviceRegistration dr where dr.client.id =:clientId "; @Query(FIND_DEVICE_REGISTRATION_BY_CLIENT) - DeviceRegistration findDeviceRegistrationByClientId( - @Param("clientId") Long clientId); + DeviceRegistration findDeviceRegistrationByClientId(@Param("clientId") Long clientId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationRepositoryWrapper.java index 524a11096..c99c5b523 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/DeviceRegistrationRepositoryWrapper.java @@ -28,13 +28,11 @@ public class DeviceRegistrationRepositoryWrapper { private final DeviceRegistrationRepository repository; @Autowired - public DeviceRegistrationRepositoryWrapper( - DeviceRegistrationRepository repository) { + public DeviceRegistrationRepositoryWrapper(DeviceRegistrationRepository repository) { this.repository = repository; } - public DeviceRegistration findOneWithNotFoundDetection( - final Long deviceRegistrationId) { + public DeviceRegistration findOneWithNotFoundDetection(final Long deviceRegistrationId) { return this.repository.findById(deviceRegistrationId) .orElseThrow(() -> new DeviceRegistrationNotFoundException(deviceRegistrationId)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Message.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Message.java index 4ee1c380a..7da0771f6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Message.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Message.java @@ -160,11 +160,11 @@ public final class Message implements Serializable { */ public Builder priority(Priority value) { switch (value) { - case NORMAL: - priority = GcmConstants.MESSAGE_PRIORITY_NORMAL; + case NORMAL: + priority = GcmConstants.MESSAGE_PRIORITY_NORMAL; break; - case HIGH: - priority = GcmConstants.MESSAGE_PRIORITY_HIGH; + case HIGH: + priority = GcmConstants.MESSAGE_PRIORITY_HIGH; break; } return this; @@ -274,8 +274,7 @@ public final class Message implements Serializable { builder.append("priority=").append(priority).append(", "); } if (contentAvailable != null) { - builder.append("contentAvailable=").append(contentAvailable) - .append(", "); + builder.append("contentAvailable=").append(contentAvailable).append(", "); } if (collapseKey != null) { builder.append("collapseKey=").append(collapseKey).append(", "); @@ -284,15 +283,13 @@ public final class Message implements Serializable { builder.append("timeToLive=").append(timeToLive).append(", "); } if (delayWhileIdle != null) { - builder.append("delayWhileIdle=").append(delayWhileIdle) - .append(", "); + builder.append("delayWhileIdle=").append(delayWhileIdle).append(", "); } if (dryRun != null) { builder.append("dryRun=").append(dryRun).append(", "); } if (restrictedPackageName != null) { - builder.append("restrictedPackageName=") - .append(restrictedPackageName).append(", "); + builder.append("restrictedPackageName=").append(restrictedPackageName).append(", "); } if (notification != null) { builder.append("notification: ").append(notification).append(", "); @@ -300,8 +297,7 @@ public final class Message implements Serializable { if (!data.isEmpty()) { builder.append("data: {"); for (Map.Entry entry : data.entrySet()) { - builder.append(entry.getKey()).append("=") - .append(entry.getValue()).append(","); + builder.append(entry.getKey()).append("=").append(entry.getValue()).append(","); } builder.delete(builder.length() - 1, builder.length()); builder.append("}"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/MulticastResult.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/MulticastResult.java index 4abb5a87e..4980bd17b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/MulticastResult.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/MulticastResult.java @@ -48,8 +48,7 @@ public final class MulticastResult implements Serializable { // optional parameters private List retryMulticastIds; - public Builder(int success, int failure, int canonicalIds, - long multicastId) { + public Builder(int success, int failure, int canonicalIds, long multicastId) { this.success = success; this.failure = failure; this.canonicalIds = canonicalIds; @@ -136,12 +135,9 @@ public final class MulticastResult implements Serializable { @Override public String toString() { - StringBuilder builder = new StringBuilder("MulticastResult(") - .append("multicast_id=").append(multicastId).append(",") - .append("total=").append(getTotal()).append(",") - .append("success=").append(success).append(",") - .append("failure=").append(failure).append(",") - .append("canonical_ids=").append(canonicalIds).append(","); + StringBuilder builder = new StringBuilder("MulticastResult(").append("multicast_id=").append(multicastId).append(",") + .append("total=").append(getTotal()).append(",").append("success=").append(success).append(",").append("failure=") + .append(failure).append(",").append("canonical_ids=").append(canonicalIds).append(","); if (!results.isEmpty()) { builder.append("results: " + results); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/NotificationConfigurationData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/NotificationConfigurationData.java index 9761d6552..a445f9cc0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/NotificationConfigurationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/NotificationConfigurationData.java @@ -24,15 +24,18 @@ public class NotificationConfigurationData { private final String serverKey; private final String gcmEndPoint; private final String fcmEndPoint; - public NotificationConfigurationData(Long id, String serverKey,final String gcmEndPoint,final String fcmEndPoint) { + + public NotificationConfigurationData(Long id, String serverKey, final String gcmEndPoint, final String fcmEndPoint) { this.id = id; this.serverKey = serverKey; this.gcmEndPoint = gcmEndPoint; this.fcmEndPoint = fcmEndPoint; } + public Long getId() { return id; } + public String getServerKey() { return serverKey; } @@ -40,10 +43,9 @@ public class NotificationConfigurationData { public String getGcmEndPoint() { return gcmEndPoint; } + public String getFcmEndPoint() { return fcmEndPoint; } - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Result.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Result.java index e618d8a37..782502745 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Result.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Result.java @@ -159,8 +159,7 @@ public final class Result implements Serializable { builder.append(" messageId=").append(messageId); } if (canonicalRegistrationId != null) { - builder.append(" canonicalRegistrationId=").append( - canonicalRegistrationId); + builder.append(" canonicalRegistrationId=").append(canonicalRegistrationId); } if (errorCode != null) { builder.append(" errorCode=").append(errorCode); @@ -172,8 +171,7 @@ public final class Result implements Serializable { builder.append(" groupFailure=").append(failure); } if (failedRegistrationIds != null) { - builder.append(" failedRegistrationIds=").append( - failedRegistrationIds); + builder.append(" failedRegistrationIds=").append(failedRegistrationIds); } return builder.append(" ]").toString(); } @@ -182,6 +180,4 @@ public final class Result implements Serializable { return this.status; } - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Sender.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Sender.java index 6989dd936..b35653009 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Sender.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/domain/Sender.java @@ -89,8 +89,7 @@ public class Sender { protected static final int MAX_BACKOFF_DELAY = 1024000; protected final Random random = new Random(); - protected static final Logger LOG = Logger.getLogger(Sender.class - .getName()); + protected static final Logger LOG = Logger.getLogger(Sender.class.getName()); private final String key; @@ -125,9 +124,7 @@ public class Sender { * @see java.net.URLConnection#setConnectTimeout(int) */ public final void setConnectTimeout(int connectTimeout) { - if (connectTimeout < 0) { - throw new IllegalArgumentException("timeout can not be negative"); - } + if (connectTimeout < 0) { throw new IllegalArgumentException("timeout can not be negative"); } this.connectTimeout = connectTimeout; } @@ -140,9 +137,7 @@ public class Sender { * @see java.net.URLConnection#setReadTimeout(int) */ public final void setReadTimeout(int readTimeout) { - if (readTimeout < 0) { - throw new IllegalArgumentException("timeout can not be negative"); - } + if (readTimeout < 0) { throw new IllegalArgumentException("timeout can not be negative"); } this.readTimeout = readTimeout; } @@ -171,8 +166,7 @@ public class Sender { * @throws IOException * if message could not be sent. */ - public Result send(Message message, String to, int retries) - throws IOException { + public Result send(Message message, String to, int retries) throws IOException { int attempt = 0; Result result; int backoff = BACKOFF_INITIAL_DELAY; @@ -180,8 +174,7 @@ public class Sender { do { attempt++; if (LOG.isLoggable(Level.FINE)) { - LOG.fine("Attempt #" + attempt + " to send message " - + message + " to regIds " + to); + LOG.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + to); } result = sendNoRetry(message, to); tryAgain = result == null && attempt <= retries; @@ -193,10 +186,7 @@ public class Sender { } } } while (tryAgain); - if (result == null) { - throw new IOException("Could not send message after " + attempt - + " attempts"); - } + if (result == null) { throw new IOException("Could not send message after " + attempt + " attempts"); } return result; } @@ -218,16 +208,14 @@ public class Sender { Map jsonRequest = new HashMap<>(); messageToMap(message, jsonRequest); jsonRequest.put(JSON_TO, to); - Map responseMap = makeGcmHttpRequest(jsonRequest); + Map responseMap = makeGcmHttpRequest(jsonRequest); String responseBody = null; if (responseMap.get("responseBody") != null) { responseBody = (String) responseMap.get("responseBody"); } int status = (int) responseMap.get("status"); - //responseBody - if (responseBody == null) { - return null; - } + // responseBody + if (responseBody == null) { return null; } JsonObject jsonResponse; try { jsonResponse = JsonParser.parseString(responseBody).getAsJsonObject(); @@ -240,34 +228,27 @@ public class Sender { String messageId = null; String canonicalRegId = null; String error = null; - if(jsonResult.has(JSON_MESSAGE_ID)){ + if (jsonResult.has(JSON_MESSAGE_ID)) { messageId = jsonResult.get(JSON_MESSAGE_ID).getAsString(); } - if(jsonResult.has(TOKEN_CANONICAL_REG_ID)){ - canonicalRegId = jsonResult - .get(TOKEN_CANONICAL_REG_ID).getAsString(); + if (jsonResult.has(TOKEN_CANONICAL_REG_ID)) { + canonicalRegId = jsonResult.get(TOKEN_CANONICAL_REG_ID).getAsString(); } - if(jsonResult.has(JSON_ERROR)){ + if (jsonResult.has(JSON_ERROR)) { error = jsonResult.get(JSON_ERROR).getAsString(); } int success = 0; int failure = 0; - if(jsonResponse.get("success") != null){ + if (jsonResponse.get("success") != null) { success = Integer.parseInt(jsonResponse.get("success").toString()); } - if(jsonResponse.get("failure") != null){ + if (jsonResponse.get("failure") != null) { failure = Integer.parseInt(jsonResponse.get("failure").toString()); } - resultBuilder.messageId(messageId) - .canonicalRegistrationId(canonicalRegId) - .success(success) - .failure(failure) - .status(status) - .errorCode(error); + resultBuilder.messageId(messageId).canonicalRegistrationId(canonicalRegId).success(success).failure(failure) + .status(status).errorCode(error); } else { - LOG.log(Level.WARNING, - "Found null or " + jsonResults.size() - + " results, expected one"); + LOG.log(Level.WARNING, "Found null or " + jsonResults.size() + " results, expected one"); return null; } } else if (to.startsWith(TOPIC_PREFIX)) { @@ -280,31 +261,26 @@ public class Sender { String error = jsonResponse.get(JSON_ERROR).getAsString(); resultBuilder.errorCode(error); } else { - LOG.log(Level.WARNING, "Expected " + JSON_MESSAGE_ID - + " or " + JSON_ERROR + " found: " + responseBody); + LOG.log(Level.WARNING, "Expected " + JSON_MESSAGE_ID + " or " + JSON_ERROR + " found: " + responseBody); return null; } - } else if (jsonResponse.has(JSON_SUCCESS) - && jsonResponse.has(JSON_FAILURE)) { + } else if (jsonResponse.has(JSON_SUCCESS) && jsonResponse.has(JSON_FAILURE)) { // success and failure are expected when response is from group // message. int success = getNumber(responseMap, JSON_SUCCESS).intValue(); int failure = getNumber(responseMap, JSON_FAILURE).intValue(); List failedIds = null; if (jsonResponse.has("failed_registration_ids")) { - JsonArray jFailedIds = jsonResponse - .get("failed_registration_ids").getAsJsonArray(); + JsonArray jFailedIds = jsonResponse.get("failed_registration_ids").getAsJsonArray(); failedIds = new ArrayList<>(); for (int i = 0; i < jFailedIds.size(); i++) { failedIds.add(jFailedIds.get(i).getAsString()); } } - resultBuilder.success(success).failure(failure) - .failedRegistrationIds(failedIds); + resultBuilder.success(success).failure(failure).failedRegistrationIds(failedIds); } else { LOG.warning("Unrecognized response: " + responseBody); - throw newIoException(responseBody, new Exception( - "Unrecognized response.")); + throw newIoException(responseBody, new Exception("Unrecognized response.")); } return resultBuilder.build(); } catch (CustomParserException e) { @@ -336,8 +312,7 @@ public class Sender { * @throws IOException * if message could not be sent. */ - public MulticastResult send(Message message, List regIds, - int retries) throws IOException { + public MulticastResult send(Message message, List regIds, int retries) throws IOException { int attempt = 0; MulticastResult multicastResult; int backoff = BACKOFF_INITIAL_DELAY; @@ -352,8 +327,7 @@ public class Sender { multicastResult = null; attempt++; if (LOG.isLoggable(Level.FINE)) { - LOG.fine("Attempt #" + attempt + " to send message " - + message + " to regIds " + unsentRegIds); + LOG.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + unsentRegIds); } try { multicastResult = sendNoRetry(message, unsentRegIds); @@ -363,11 +337,9 @@ public class Sender { } if (multicastResult != null) { long multicastId = multicastResult.getMulticastId(); - LOG.fine("multicast_id on attempt # " + attempt + ": " - + multicastId); + LOG.fine("multicast_id on attempt # " + attempt + ": " + multicastId); multicastIds.add(multicastId); - unsentRegIds = updateStatus(unsentRegIds, results, - multicastResult); + unsentRegIds = updateStatus(unsentRegIds, results, multicastResult); tryAgain = !unsentRegIds.isEmpty() && attempt <= retries; } else { tryAgain = attempt <= retries; @@ -382,8 +354,7 @@ public class Sender { } while (tryAgain); if (multicastIds.isEmpty()) { // all JSON posts failed due to GCM unavailability - throw new IOException("Could not post JSON requests to GCM after " - + attempt + " attempts"); + throw new IOException("Could not post JSON requests to GCM after " + attempt + " attempts"); } // calculate summary int success = 0; @@ -401,8 +372,7 @@ public class Sender { } // build a new object with the overall result long multicastId = multicastIds.remove(0); - MulticastResult.Builder builder = new MulticastResult.Builder(success, - failure, canonicalIds, multicastId) + MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId) .retryMulticastIds(multicastIds); // add results, in the same order as the input for (String regId : regIds) { @@ -425,14 +395,12 @@ public class Sender { * * @return updated version of devices that should be retried. */ - private List updateStatus(List unsentRegIds, - Map allResults, MulticastResult multicastResult) { + private List updateStatus(List unsentRegIds, Map allResults, MulticastResult multicastResult) { List results = multicastResult.getResults(); if (results.size() != unsentRegIds.size()) { // should never happen, unless there is a flaw in the algorithm - throw new RuntimeException("Internal error: sizes do not match. " - + "currentResults: " + results + "; unsentRegIds: " - + unsentRegIds); + throw new RuntimeException( + "Internal error: sizes do not match. " + "currentResults: " + results + "; unsentRegIds: " + unsentRegIds); } List newUnsentRegIds = new ArrayList<>(); for (int i = 0; i < unsentRegIds.size(); i++) { @@ -440,9 +408,7 @@ public class Sender { Result result = results.get(i); allResults.put(regId, result); String error = result.getErrorCodeName(); - if (error != null - && (error.equals(GcmConstants.ERROR_UNAVAILABLE) || error - .equals(GcmConstants.ERROR_INTERNAL_SERVER_ERROR))) { + if (error != null && (error.equals(GcmConstants.ERROR_UNAVAILABLE) || error.equals(GcmConstants.ERROR_INTERNAL_SERVER_ERROR))) { newUnsentRegIds.add(regId); } } @@ -463,47 +429,35 @@ public class Sender { * @throws IOException * if there was a JSON parsing error */ - public MulticastResult sendNoRetry(Message message, - List registrationIds) throws IOException { - if (nonNull(registrationIds).isEmpty()) { - throw new IllegalArgumentException( - "registrationIds cannot be empty"); - } + public MulticastResult sendNoRetry(Message message, List registrationIds) throws IOException { + if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map jsonRequest = new HashMap<>(); messageToMap(message, jsonRequest); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); - Map responseMap = makeGcmHttpRequest(jsonRequest); + Map responseMap = makeGcmHttpRequest(jsonRequest); String responseBody = null; if (responseMap.get("responseBody") != null) { responseBody = (String) responseMap.get("responseBody"); } - if (responseBody == null) { - return null; - } + if (responseBody == null) { return null; } JsonObject jsonResponse; try { jsonResponse = JsonParser.parseString(responseBody).getAsJsonObject(); int success = getNumber(responseMap, JSON_SUCCESS).intValue(); int failure = getNumber(responseMap, JSON_FAILURE).intValue(); - int canonicalIds = getNumber(responseMap, JSON_CANONICAL_IDS) - .intValue(); - long multicastId = getNumber(responseMap, JSON_MULTICAST_ID) - .longValue(); - MulticastResult.Builder builder = new MulticastResult.Builder( - success, failure, canonicalIds, multicastId); + int canonicalIds = getNumber(responseMap, JSON_CANONICAL_IDS).intValue(); + long multicastId = getNumber(responseMap, JSON_MULTICAST_ID).longValue(); + MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") - List> results = (List>) jsonResponse - .get(JSON_RESULTS); + List> results = (List>) jsonResponse.get(JSON_RESULTS); if (results != null) { for (Map jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); - String canonicalRegId = (String) jsonResult - .get(TOKEN_CANONICAL_REG_ID); + String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); - Result result = new Result.Builder().messageId(messageId) - .canonicalRegistrationId(canonicalRegId) - .errorCode(error).build(); + Result result = new Result.Builder().messageId(messageId).canonicalRegistrationId(canonicalRegId).errorCode(error) + .build(); builder.addResult(result); } } @@ -513,8 +467,7 @@ public class Sender { } } - private Map makeGcmHttpRequest(Map jsonRequest) - throws InvalidRequestException { + private Map makeGcmHttpRequest(Map jsonRequest) throws InvalidRequestException { String requestBody = new Gson().toJson(jsonRequest); LOG.finest("JSON request: " + requestBody); HttpURLConnection conn; @@ -547,7 +500,7 @@ public class Sender { return null; } LOG.finest("JSON response: " + responseBody); - Map map = new HashMap<>(); + Map map = new HashMap<>(); map.put("responseBody", responseBody); map.put("status", status); @@ -563,18 +516,13 @@ public class Sender { * Map populated by Message. */ private void messageToMap(Message message, Map mapRequest) { - if (message == null || mapRequest == null) { - return; - } + if (message == null || mapRequest == null) { return; } setJsonField(mapRequest, PARAM_PRIORITY, message.getPriority()); - setJsonField(mapRequest, PARAM_CONTENT_AVAILABLE, - message.getContentAvailable()); + setJsonField(mapRequest, PARAM_CONTENT_AVAILABLE, message.getContentAvailable()); setJsonField(mapRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(mapRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey()); - setJsonField(mapRequest, PARAM_RESTRICTED_PACKAGE_NAME, - message.getRestrictedPackageName()); - setJsonField(mapRequest, PARAM_DELAY_WHILE_IDLE, - message.isDelayWhileIdle()); + setJsonField(mapRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName()); + setJsonField(mapRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); setJsonField(mapRequest, PARAM_DRY_RUN, message.isDryRun()); Map payload = message.getData(); if (!payload.isEmpty()) { @@ -584,25 +532,19 @@ public class Sender { Notification notification = message.getNotification(); Map nMap = new HashMap<>(); if (notification.getBadge() != null) { - setJsonField(nMap, JSON_NOTIFICATION_BADGE, notification - .getBadge().toString()); + setJsonField(nMap, JSON_NOTIFICATION_BADGE, notification.getBadge().toString()); } setJsonField(nMap, JSON_NOTIFICATION_BODY, notification.getBody()); - setJsonField(nMap, JSON_NOTIFICATION_BODY_LOC_ARGS, - notification.getBodyLocArgs()); - setJsonField(nMap, JSON_NOTIFICATION_BODY_LOC_KEY, - notification.getBodyLocKey()); - setJsonField(nMap, JSON_NOTIFICATION_CLICK_ACTION, - notification.getClickAction()); + setJsonField(nMap, JSON_NOTIFICATION_BODY_LOC_ARGS, notification.getBodyLocArgs()); + setJsonField(nMap, JSON_NOTIFICATION_BODY_LOC_KEY, notification.getBodyLocKey()); + setJsonField(nMap, JSON_NOTIFICATION_CLICK_ACTION, notification.getClickAction()); setJsonField(nMap, JSON_NOTIFICATION_COLOR, notification.getColor()); setJsonField(nMap, JSON_NOTIFICATION_ICON, notification.getIcon()); setJsonField(nMap, JSON_NOTIFICATION_SOUND, notification.getSound()); setJsonField(nMap, JSON_NOTIFICATION_TAG, notification.getTag()); setJsonField(nMap, JSON_NOTIFICATION_TITLE, notification.getTitle()); - setJsonField(nMap, JSON_NOTIFICATION_TITLE_LOC_ARGS, - notification.getTitleLocArgs()); - setJsonField(nMap, JSON_NOTIFICATION_TITLE_LOC_KEY, - notification.getTitleLocKey()); + setJsonField(nMap, JSON_NOTIFICATION_TITLE_LOC_ARGS, notification.getTitleLocArgs()); + setJsonField(nMap, JSON_NOTIFICATION_TITLE_LOC_KEY, notification.getTitleLocKey()); mapRequest.put(JSON_NOTIFICATION, nMap); } } @@ -630,8 +572,7 @@ public class Sender { /** * Sets a JSON field, but only if the value is not {@literal null}. */ - private void setJsonField(Map json, String field, - Object value) { + private void setJsonField(Map json, String field, Object value) { if (value != null) { json.put(field, value); } @@ -639,17 +580,13 @@ public class Sender { private Number getNumber(Map json, String field) { Object value = json.get(field); - if (value == null) { - throw new CustomParserException("Missing field: " + field); - } - if (!(value instanceof Number)) { - throw new CustomParserException("Field " + field - + " does not contain a number: " + value); - } + if (value == null) { throw new CustomParserException("Missing field: " + field); } + if (!(value instanceof Number)) { throw new CustomParserException("Field " + field + " does not contain a number: " + value); } return (Number) value; } class CustomParserException extends RuntimeException { + CustomParserException(String message) { super(message); } @@ -660,10 +597,8 @@ public class Sender { * * @return HTTP response. */ - protected HttpURLConnection post(String url, String body) - throws IOException { - return post(url, "application/x-www-form-urlencoded;charset=UTF-8", - body); + protected HttpURLConnection post(String url, String body) throws IOException { + return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body); } /** @@ -686,11 +621,8 @@ public class Sender { * @throws IOException * propagated from underlying methods. */ - protected HttpURLConnection post(String url, String contentType, String body) - throws IOException { - if (url == null || contentType == null || body == null) { - throw new IllegalArgumentException("arguments cannot be null"); - } + protected HttpURLConnection post(String url, String contentType, String body) throws IOException { + if (url == null || contentType == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } if (!url.startsWith("https://")) { LOG.warning("URL does not use https: " + url); } @@ -716,8 +648,7 @@ public class Sender { /** * Creates a map with just one key-value pair. */ - protected static final Map newKeyValues(String key, - String value) { + protected static final Map newKeyValues(String key, String value) { Map keyValues = new HashMap<>(1); keyValues.put(nonNull(key), nonNull(value)); return keyValues; @@ -733,8 +664,7 @@ public class Sender { * @return StringBuilder to be used an HTTP POST body. */ protected static StringBuilder newBody(String name, String value) { - return new StringBuilder(nonNull(name)).append('=').append( - nonNull(value)); + return new StringBuilder(nonNull(name)).append('=').append(nonNull(value)); } /** @@ -747,18 +677,15 @@ public class Sender { * @param value * parameter's value. */ - protected static void addParameter(StringBuilder body, String name, - String value) { - nonNull(body).append('&').append(nonNull(name)).append('=') - .append(nonNull(value)); + protected static void addParameter(StringBuilder body, String name, String value) { + nonNull(body).append('&').append(nonNull(name)).append('=').append(nonNull(value)); } /** * Gets an {@link HttpURLConnection} given an URL. */ protected HttpURLConnection getConnection(String url) throws IOException { - HttpURLConnection conn = (HttpURLConnection) new URL(url) - .openConnection(); + HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); return conn; @@ -772,11 +699,8 @@ public class Sender { * If the stream is {@literal null}, returns an empty string. */ protected static String getString(InputStream stream) throws IOException { - if (stream == null) { - return ""; - } - BufferedReader reader = new BufferedReader( - new InputStreamReader(stream, StandardCharsets.UTF_8)); + if (stream == null) { return ""; } + BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); StringBuilder content = new StringBuilder(); String newLine; do { @@ -803,9 +727,7 @@ public class Sender { } static T nonNull(T argument) { - if (argument == null) { - throw new IllegalArgumentException("argument cannot be null"); - } + if (argument == null) { throw new IllegalArgumentException("argument cannot be null"); } return argument; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/exception/DeviceRegistrationNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/exception/DeviceRegistrationNotFoundException.java index 22bb1e6bd..f2a130bbd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/exception/DeviceRegistrationNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/exception/DeviceRegistrationNotFoundException.java @@ -20,19 +20,15 @@ package org.apache.fineract.infrastructure.gcm.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; -public class DeviceRegistrationNotFoundException extends - AbstractPlatformResourceNotFoundException { +public class DeviceRegistrationNotFoundException extends AbstractPlatformResourceNotFoundException { public DeviceRegistrationNotFoundException(final Long id) { - super("error.msg.device.registration.id.invalid", - "Device registration with identifier " + id + " does not exist", - id); + super("error.msg.device.registration.id.invalid", "Device registration with identifier " + id + " does not exist", id); } public DeviceRegistrationNotFoundException(final Long clientId, String value) { super("error.msg.device.registration." + value + ".invalid", - "Device registration with " + value + " identifier " + clientId - + " does not exist", clientId); + "Device registration with " + value + " identifier " + clientId + " does not exist", clientId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/exception/InvalidRequestException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/exception/InvalidRequestException.java index 03b5eb25b..99a175d47 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/exception/InvalidRequestException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/exception/InvalidRequestException.java @@ -41,8 +41,7 @@ public final class InvalidRequestException extends IOException { } private static String getMessage(int status, String description) { - StringBuilder base = new StringBuilder("HTTP Status Code: ") - .append(status); + StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status); if (description != null) { base.append("(").append(description).append(")"); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationReadPlatformServiceImpl.java index 52de9a112..d3a23109a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationReadPlatformServiceImpl.java @@ -35,31 +35,25 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class DeviceRegistrationReadPlatformServiceImpl implements - DeviceRegistrationReadPlatformService { +public class DeviceRegistrationReadPlatformServiceImpl implements DeviceRegistrationReadPlatformService { private final JdbcTemplate jdbcTemplate; private final PlatformSecurityContext context; @Autowired - public DeviceRegistrationReadPlatformServiceImpl( - final PlatformSecurityContext context, - final RoutingDataSource dataSource) { + public DeviceRegistrationReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); } - private static final class DeviceRegistrationDataMapper implements - RowMapper { + private static final class DeviceRegistrationDataMapper implements RowMapper { private final String schema; public DeviceRegistrationDataMapper() { final StringBuilder sqlBuilder = new StringBuilder(200); - sqlBuilder - .append(" cdr.id as id, cdr.registration_id as registrationId, cdr.updatedon_date as updatedOnDate, "); - sqlBuilder - .append(" c.id as clientId, c.display_name as clientName "); + sqlBuilder.append(" cdr.id as id, cdr.registration_id as registrationId, cdr.updatedon_date as updatedOnDate, "); + sqlBuilder.append(" c.id as clientId, c.display_name as clientName "); sqlBuilder.append(" from client_device_registration cdr "); sqlBuilder.append(" left join m_client c on c.id = cdr.client_id "); this.schema = sqlBuilder.toString(); @@ -70,19 +64,15 @@ public class DeviceRegistrationReadPlatformServiceImpl implements } @Override - public DeviceRegistrationData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public DeviceRegistrationData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = JdbcSupport.getLong(rs, "id"); - final LocalDate updatedOnDate = JdbcSupport.getLocalDate(rs, - "updatedOnDate"); + final LocalDate updatedOnDate = JdbcSupport.getLocalDate(rs, "updatedOnDate"); final String registrationId = rs.getString("registrationId"); final Long clientId = rs.getLong("clientId"); final String clientName = rs.getString("clientName"); ClientData clientData = ClientData.instance(clientId, clientName); - return DeviceRegistrationData.instance(id, clientData, - registrationId, updatedOnDate.toDate()); + return DeviceRegistrationData.instance(id, clientData, registrationId, updatedOnDate.toDate()); } } @@ -100,22 +90,19 @@ public class DeviceRegistrationReadPlatformServiceImpl implements this.context.authenticatedUser(); DeviceRegistrationDataMapper drm = new DeviceRegistrationDataMapper(); String sql = "select " + drm.schema() + " where cdr.id = ? "; - return this.jdbcTemplate.queryForObject(sql, drm, - new Object[] { id }); + return this.jdbcTemplate.queryForObject(sql, drm, new Object[] { id }); } catch (final EmptyResultDataAccessException e) { throw new DeviceRegistrationNotFoundException(id); } } @Override - public DeviceRegistrationData retrieveDeviceRegiistrationByClientId( - Long clientId) { + public DeviceRegistrationData retrieveDeviceRegiistrationByClientId(Long clientId) { try { this.context.authenticatedUser(); DeviceRegistrationDataMapper drm = new DeviceRegistrationDataMapper(); String sql = "select " + drm.schema() + " where c.id = ? "; - return this.jdbcTemplate.queryForObject(sql, drm, - new Object[] { clientId }); + return this.jdbcTemplate.queryForObject(sql, drm, new Object[] { clientId }); } catch (final EmptyResultDataAccessException e) { throw new DeviceRegistrationNotFoundException(clientId, "client"); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationWritePlatformServiceImpl.java index f937aedc7..569e42f81 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/DeviceRegistrationWritePlatformServiceImpl.java @@ -34,18 +34,15 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -public class DeviceRegistrationWritePlatformServiceImpl implements - DeviceRegistrationWritePlatformService { +public class DeviceRegistrationWritePlatformServiceImpl implements DeviceRegistrationWritePlatformService { private final DeviceRegistrationRepositoryWrapper deviceRegistrationRepository; private final ClientRepositoryWrapper clientRepositoryWrapper; private final PlatformSecurityContext context; @Autowired - public DeviceRegistrationWritePlatformServiceImpl( - final DeviceRegistrationRepositoryWrapper deviceRegistrationRepository, - final ClientRepositoryWrapper clientRepositoryWrapper, - final PlatformSecurityContext context) { + public DeviceRegistrationWritePlatformServiceImpl(final DeviceRegistrationRepositoryWrapper deviceRegistrationRepository, + final ClientRepositoryWrapper clientRepositoryWrapper, final PlatformSecurityContext context) { this.deviceRegistrationRepository = deviceRegistrationRepository; this.clientRepositoryWrapper = clientRepositoryWrapper; this.context = context; @@ -53,22 +50,18 @@ public class DeviceRegistrationWritePlatformServiceImpl implements @Transactional @Override - public DeviceRegistration registerDevice(Long clientId, - String registrationId) { + public DeviceRegistration registerDevice(Long clientId, String registrationId) { this.context.authenticatedUser(); - Client client = this.clientRepositoryWrapper - .findOneWithNotFoundDetection(clientId); + Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); try { - DeviceRegistration deviceRegistration = DeviceRegistration - .instance(client, registrationId); + DeviceRegistration deviceRegistration = DeviceRegistration.instance(client, registrationId); this.deviceRegistrationRepository.save(deviceRegistration); return deviceRegistration; } catch (final EntityExistsException dve) { handleDataIntegrityIssues(registrationId, dve, dve); return null; } catch (final DataIntegrityViolationException dve) { - handleDataIntegrityIssues(registrationId, - dve.getMostSpecificCause(), dve); + handleDataIntegrityIssues(registrationId, dve.getMostSpecificCause(), dve); return null; } catch (final PersistenceException dve) { Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); @@ -82,34 +75,25 @@ public class DeviceRegistrationWritePlatformServiceImpl implements } - private void handleDataIntegrityIssues(final String registrationId, - final Throwable realCause, + private void handleDataIntegrityIssues(final String registrationId, final Throwable realCause, @SuppressWarnings("unused") final Exception dve) { if (realCause.getMessage().contains("registration_key")) { - throw new PlatformDataIntegrityException( - "error.msg.duplicate.device.registration.id", - "Registration id : " + registrationId + " already exist.", - "name", registrationId); + throw new PlatformDataIntegrityException("error.msg.duplicate.device.registration.id", + "Registration id : " + registrationId + " already exist.", "name", registrationId); } - throw new PlatformDataIntegrityException( - "error.msg.charge.unknown.data.integrity.issue", - "Unknown data integrity issue with resource: " - + realCause.getMessage()); + throw new PlatformDataIntegrityException("error.msg.charge.unknown.data.integrity.issue", + "Unknown data integrity issue with resource: " + realCause.getMessage()); } @Override - public DeviceRegistration updateDeviceRegistration(Long id, Long clientId, - String registrationId) { - DeviceRegistration deviceRegistration = this.deviceRegistrationRepository - .findOneWithNotFoundDetection(id); - Client client = this.clientRepositoryWrapper - .findOneWithNotFoundDetection(clientId); + public DeviceRegistration updateDeviceRegistration(Long id, Long clientId, String registrationId) { + DeviceRegistration deviceRegistration = this.deviceRegistrationRepository.findOneWithNotFoundDetection(id); + Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); deviceRegistration.setClient(client); deviceRegistration.setRegistrationId(registrationId); - deviceRegistration.setUpdatedOnDate(DateUtils - .getLocalDateTimeOfTenant().toDate()); + deviceRegistration.setUpdatedOnDate(DateUtils.getLocalDateTimeOfTenant().toDate()); return deviceRegistration; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/NotificationSenderService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/NotificationSenderService.java index 70c308d67..cf8f2bbb1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/NotificationSenderService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/gcm/service/NotificationSenderService.java @@ -50,9 +50,9 @@ public class NotificationSenderService { private ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService; @Autowired - public NotificationSenderService( - final DeviceRegistrationRepositoryWrapper deviceRegistrationRepositoryWrapper, - final SmsMessageRepository smsMessageRepository, final ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService) { + public NotificationSenderService(final DeviceRegistrationRepositoryWrapper deviceRegistrationRepositoryWrapper, + final SmsMessageRepository smsMessageRepository, + final ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService) { this.deviceRegistrationRepositoryWrapper = deviceRegistrationRepositoryWrapper; this.smsMessageRepository = smsMessageRepository; this.propertiesReadPlatformService = propertiesReadPlatformService; @@ -60,14 +60,12 @@ public class NotificationSenderService { public void sendNotification(List smsMessages) { Map> notificationByEachClient = getNotificationListByClient(smsMessages); - for (Map.Entry> entry : notificationByEachClient - .entrySet()) { + for (Map.Entry> entry : notificationByEachClient.entrySet()) { this.sendNotifiaction(entry.getKey(), entry.getValue()); } } - public Map> getNotificationListByClient( - List smsMessages) { + public Map> getNotificationListByClient(List smsMessages) { Map> notificationByEachClient = new HashMap<>(); for (SmsMessage smsMessage : smsMessages) { if (smsMessage.getClient() != null) { @@ -75,8 +73,7 @@ public class NotificationSenderService { if (notificationByEachClient.containsKey(clientId)) { notificationByEachClient.get(clientId).add(smsMessage); } else { - List msgList = new ArrayList<>( - Arrays.asList(smsMessage)); + List msgList = new ArrayList<>(Arrays.asList(smsMessage)); notificationByEachClient.put(clientId, msgList); } @@ -87,8 +84,7 @@ public class NotificationSenderService { public void sendNotifiaction(Long clientId, List smsList) { - DeviceRegistration deviceRegistration = this.deviceRegistrationRepositoryWrapper - .findDeviceRegistrationByClientId(clientId); + DeviceRegistration deviceRegistration = this.deviceRegistrationRepositoryWrapper.findDeviceRegistrationByClientId(clientId); NotificationConfigurationData notificationConfigurationData = this.propertiesReadPlatformService.getNotificationConfiguration(); String registrationId = null; if (deviceRegistration != null) { @@ -96,8 +92,7 @@ public class NotificationSenderService { } for (SmsMessage smsMessage : smsList) { try { - Notification notification = new Notification.Builder( - GcmConstants.defaultIcon).title(GcmConstants.title) + Notification notification = new Notification.Builder(GcmConstants.defaultIcon).title(GcmConstants.title) .body(smsMessage.getMessage()).build(); Builder b = new Builder(); b.notification(notification); @@ -107,21 +102,18 @@ public class NotificationSenderService { b.priority(Priority.HIGH); b.delayWhileIdle(true); Message msg = b.build(); - Sender s = new Sender(notificationConfigurationData.getServerKey(),notificationConfigurationData.getFcmEndPoint()); + Sender s = new Sender(notificationConfigurationData.getServerKey(), notificationConfigurationData.getFcmEndPoint()); Result res; res = s.send(msg, registrationId, 3); - if (res.getSuccess() != null && res.getSuccess()>0) { - smsMessage.setStatusType(SmsMessageStatusType.SENT - .getValue()); + if (res.getSuccess() != null && res.getSuccess() > 0) { + smsMessage.setStatusType(SmsMessageStatusType.SENT.getValue()); smsMessage.setDeliveredOnDate(DateUtils.getLocalDateOfTenant().toDate()); - } else if (res.getFailure() != null && res.getFailure()>0) { - smsMessage.setStatusType(SmsMessageStatusType.FAILED - .getValue()); + } else if (res.getFailure() != null && res.getFailure() > 0) { + smsMessage.setStatusType(SmsMessageStatusType.FAILED.getValue()); } } catch (IOException e) { - smsMessage - .setStatusType(SmsMessageStatusType.FAILED.getValue()); + smsMessage.setStatusType(SmsMessageStatusType.FAILED.getValue()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiConstants.java index 3a96a7aa4..e1757fa70 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiConstants.java @@ -62,14 +62,10 @@ public class HookApiConstants { public static final String templateNameParamName = "templateName"; - protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(nameParamName, displayNameParamName, - templateIdParamName, isActiveParamName, configParamName, - eventsParamName, templateNameParamName)); + protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(nameParamName, displayNameParamName, + templateIdParamName, isActiveParamName, configParamName, eventsParamName, templateNameParamName)); - protected static final Set UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(nameParamName, displayNameParamName, - templateIdParamName, isActiveParamName, configParamName, - eventsParamName, templateNameParamName)); + protected static final Set UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(nameParamName, displayNameParamName, + templateIdParamName, isActiveParamName, configParamName, eventsParamName, templateNameParamName)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiResource.java index 0dbb7c6df..1d6f00180 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiResource.java @@ -61,10 +61,9 @@ import org.springframework.stereotype.Component; @Produces({ MediaType.APPLICATION_JSON }) @Component @Scope("singleton") -@Api(tags = {"Hooks"}) +@Api(tags = { "Hooks" }) @SwaggerDefinition(tags = { - @Tag(name = "Hooks", description = "Hooks are a mechanism to trigger custom code on the occurence of events. ") -}) + @Tag(name = "Hooks", description = "Hooks are a mechanism to trigger custom code on the occurence of events. ") }) public class HookApiResource { private final PlatformSecurityContext context; @@ -74,11 +73,8 @@ public class HookApiResource { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public HookApiResource( - final PlatformSecurityContext context, - final HookReadPlatformService readPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, + public HookApiResource(final PlatformSecurityContext context, final HookReadPlatformService readPlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.context = context; this.readPlatformService = readPlatformService; @@ -88,76 +84,69 @@ public class HookApiResource { } @GET - @ApiOperation(value = "Retrieve Hooks", notes = "Returns the list of hooks.\n" + "\n" + "Example Requests:\n" + "\n" + "hooks", responseContainer = "List", response = HookApiResourceSwagger.GetHookResponse.class) - @ApiResponses({@ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.GetHookResponse.class, responseContainer = "list")}) + @ApiOperation(value = "Retrieve Hooks", notes = "Returns the list of hooks.\n" + "\n" + "Example Requests:\n" + "\n" + + "hooks", responseContainer = "List", response = HookApiResourceSwagger.GetHookResponse.class) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.GetHookResponse.class, responseContainer = "list") }) public String retrieveHooks(@Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission( - HOOK_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(HOOK_RESOURCE_NAME); - final Collection hooks = this.readPlatformService - .retrieveAllHooks(); + final Collection hooks = this.readPlatformService.retrieveAllHooks(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, hooks, - RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, hooks, RESPONSE_DATA_PARAMETERS); } @GET @Path("{hookId}") @ApiOperation(value = "Retrieve a Hook", notes = "Returns the details of a Hook.\n" + "\n" + "Example Requests:\n" + "\n" + "hooks/1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.GetHookResponse.class)}) - public String retrieveHook(@PathParam("hookId") @ApiParam(value = "hookId") final Long hookId, - @Context final UriInfo uriInfo) { + @ApiResponses({ @ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.GetHookResponse.class) }) + public String retrieveHook(@PathParam("hookId") @ApiParam(value = "hookId") final Long hookId, @Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission( - HOOK_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(HOOK_RESOURCE_NAME); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); HookData hook = this.readPlatformService.retrieveHook(hookId); if (settings.isTemplate()) { - final HookData hookData = this.readPlatformService - .retrieveNewHookDetails(hook.getTemplateName()); - hook = HookData.templateExisting(hook, hookData.getTemplates(), - hookData.getGroupings()); + final HookData hookData = this.readPlatformService.retrieveNewHookDetails(hook.getTemplateName()); + hook = HookData.templateExisting(hook, hookData.getTemplates(), hookData.getGroupings()); } - return this.toApiJsonSerializer.serialize(settings, hook, - RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, hook, RESPONSE_DATA_PARAMETERS); } @GET @Path("template") - @ApiOperation(value = "Retrieve Hooks Template", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "hooks/template") - @ApiResponses({@ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.GetHookTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Hooks Template", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "hooks/template") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.GetHookTemplateResponse.class) }) public String template(@Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission( - HOOK_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(HOOK_RESOURCE_NAME); - final HookData hook = this.readPlatformService - .retrieveNewHookDetails(null); + final HookData hook = this.readPlatformService.retrieveNewHookDetails(null); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, hook, - RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, hook, RESPONSE_DATA_PARAMETERS); } @POST - @ApiOperation(value = "Create a Hook", notes = "The following parameters can be passed for the creation of a hook :-\n" + "\n" + "name - string - Required. The name of the template that is being called. (See /hooks/template for the list of valid hook names.)\n" + "\n" + "isActive - boolean - Determines whether the hook is actually triggered.\n" + "\n" + "events - array - Determines what events the hook is triggered for.\n" + "\n" + "config - hash - Required. Key/value pairs to provide settings for this hook. These settings vary between the templates.\n" + "\n" + "templateId - Optional. The UGD template ID associated with the same entity (client or loan).") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "body", required = true, type = "body", dataTypeClass = HookApiResourceSwagger.PostHookRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.PostHookResponse.class)}) + @ApiOperation(value = "Create a Hook", notes = "The following parameters can be passed for the creation of a hook :-\n" + "\n" + + "name - string - Required. The name of the template that is being called. (See /hooks/template for the list of valid hook names.)\n" + + "\n" + "isActive - boolean - Determines whether the hook is actually triggered.\n" + "\n" + + "events - array - Determines what events the hook is triggered for.\n" + "\n" + + "config - hash - Required. Key/value pairs to provide settings for this hook. These settings vary between the templates.\n" + + "\n" + "templateId - Optional. The UGD template ID associated with the same entity (client or loan).") + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", dataType = "body", required = true, type = "body", dataTypeClass = HookApiResourceSwagger.PostHookRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.PostHookResponse.class) }) public String createHook(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .createHook().withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().createHook().withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } @@ -165,16 +154,15 @@ public class HookApiResource { @PUT @Path("{hookId}") @ApiOperation(value = "Update a Hook", notes = "Updates the details of a hook.") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "body", required = true, type = "body", dataTypeClass = HookApiResourceSwagger.PutHookRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.PutHookResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", dataType = "body", required = true, type = "body", dataTypeClass = HookApiResourceSwagger.PutHookRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.PutHookResponse.class) }) public String updateHook(@PathParam("hookId") @ApiParam(value = "hookId") final Long hookId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .updateHook(hookId).withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateHook(hookId).withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } @@ -182,14 +170,12 @@ public class HookApiResource { @DELETE @Path("{hookId}") @ApiOperation(value = "Delete a Hook", notes = "Deletes a hook.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.DeleteHookResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = HookApiResourceSwagger.DeleteHookResponse.class) }) public String deleteHook(@PathParam("hookId") @ApiParam(value = "hookId") final Long hookId) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .deleteHook(hookId).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteHook(hookId).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiResourceSwagger.java index 78916acbe..4a8fd4c59 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/api/HookApiResourceSwagger.java @@ -32,13 +32,15 @@ import org.joda.time.LocalDate; */ final class HookApiResourceSwagger { + private HookApiResourceSwagger() { } @ApiModel(value = "PostHookRequest") public static final class PostHookRequest { - private PostHookRequest () { + + private PostHookRequest() { } @@ -56,15 +58,18 @@ final class HookApiResourceSwagger { @ApiModel(value = "PostHookResponse") public static final class PostHookResponse { + private PostHookResponse() { } + @ApiModelProperty(example = "4") public Long resourceId; } @ApiModel(value = "GetHookResponse") public static final class GetHookResponse { + private GetHookResponse() { } @@ -91,6 +96,7 @@ final class HookApiResourceSwagger { @ApiModel(value = "GetHookTemplateResponse") public static final class GetHookTemplateResponse { + private GetHookTemplateResponse() { } @@ -101,16 +107,19 @@ final class HookApiResourceSwagger { @ApiModel(value = "DeleteHookResponse") public static final class DeleteHookResponse { + private DeleteHookResponse() { } + @ApiModelProperty(example = "4") public Long resourceId; } @ApiModel(value = "PutHookRequest") public static final class PutHookRequest { - private PutHookRequest () { + + private PutHookRequest() { } @@ -128,17 +137,22 @@ final class HookApiResourceSwagger { @ApiModel(value = "PutHookResponse") public static final class PutHookResponse { - private PutHookResponse () { + + private PutHookResponse() { } + final class PutHookResponseChangesSwagger { + private PutHookResponseChangesSwagger() {} - @ApiModelProperty(example = "Kremlin") - public String displayName; - @ApiModelProperty(example = "1") - public List events; - public List config; + + @ApiModelProperty(example = "Kremlin") + public String displayName; + @ApiModelProperty(example = "1") + public List events; + public List config; } + @ApiModelProperty(example = "4") public Long resourceId; public PutHookResponseChangesSwagger changes; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Event.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Event.java index 97786e791..5e28c988b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Event.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Event.java @@ -25,8 +25,7 @@ public class Event implements Serializable { private final String actionName; private final String entityName; - public static Event instance(final String actionName, - final String entityName) { + public static Event instance(final String actionName, final String entityName) { return new Event(actionName, entityName); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/EventResultSetExtractor.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/EventResultSetExtractor.java index fb4d89949..365498373 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/EventResultSetExtractor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/EventResultSetExtractor.java @@ -30,12 +30,10 @@ import java.util.Map.Entry; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ResultSetExtractor; -public class EventResultSetExtractor implements - ResultSetExtractor> { +public class EventResultSetExtractor implements ResultSetExtractor> { @Override - public List extractData(final ResultSet rs) throws SQLException, - DataAccessException { + public List extractData(final ResultSet rs) throws SQLException, DataAccessException { final List groupings = new ArrayList<>(); final Map>> groupToEntityMapping = new HashMap<>(); @@ -45,8 +43,7 @@ public class EventResultSetExtractor implements final String groupingName = rs.getString("grouping"); final String entityName = rs.getString("entity_name"); final String actionName = rs.getString("action_name"); - Map> entities = groupToEntityMapping - .get(groupingName); + Map> entities = groupToEntityMapping.get(groupingName); List actions = entityToActionMapping.get(entityName); if (entities == null) { @@ -66,13 +63,11 @@ public class EventResultSetExtractor implements groupToEntityMapping.put(groupingName, entities); } - for (final Entry>> groupingEntry : groupToEntityMapping - .entrySet()) { + for (final Entry>> groupingEntry : groupToEntityMapping.entrySet()) { final List entities = new ArrayList<>(); final Grouping group = new Grouping(); group.setName(groupingEntry.getKey()); - for (final Entry> entityEntry : groupingEntry - .getValue().entrySet()) { + for (final Entry> entityEntry : groupingEntry.getValue().entrySet()) { final List actions = new ArrayList<>(); final Entity entity = new Entity(); entity.setName(entityEntry.getKey()); @@ -85,6 +80,7 @@ public class EventResultSetExtractor implements } Collections.sort(entities, new Comparator() { + @Override public int compare(final Entity entity1, final Entity entity2) { return entity1.getName().compareTo(entity2.getName()); @@ -95,9 +91,9 @@ public class EventResultSetExtractor implements } Collections.sort(groupings, new Comparator() { + @Override - public int compare(final Grouping grouping1, - final Grouping grouping2) { + public int compare(final Grouping grouping1, final Grouping grouping2) { return grouping1.getName().compareTo(grouping2.getName()); } }); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Field.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Field.java index 3fe03e64d..40ceb3612 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Field.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/Field.java @@ -29,19 +29,15 @@ public class Field implements Serializable { private final Boolean optional; private final String placeholder; - public static Field fromConfig(final String fieldName, - final String fieldValue) { + public static Field fromConfig(final String fieldName, final String fieldValue) { return new Field(null, fieldName, fieldValue, null, null); } - public static Field fromSchema(final String fieldType, - final String fieldName, final Boolean optional, - final String placeholder) { + public static Field fromSchema(final String fieldType, final String fieldName, final Boolean optional, final String placeholder) { return new Field(fieldType, fieldName, null, optional, placeholder); } - private Field(final String fieldType, final String fieldName, - final String fieldValue, final Boolean optional, + private Field(final String fieldType, final String fieldName, final String fieldValue, final Boolean optional, final String placeholder) { this.fieldType = fieldType; this.fieldName = fieldName; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/HookData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/HookData.java index 9754c5a03..ff0efff32 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/HookData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/HookData.java @@ -41,38 +41,26 @@ public class HookData implements Serializable { private final List templates; private final List groupings; - public static HookData instance(final Long id, final String name, - final String displayName, final boolean isActive, - final LocalDate createdAt, final LocalDate updatedAt, - final Long templateId, final List registeredEvents, + public static HookData instance(final Long id, final String name, final String displayName, final boolean isActive, + final LocalDate createdAt, final LocalDate updatedAt, final Long templateId, final List registeredEvents, final List config, final String templateName) { - return new HookData(id, name, displayName, isActive, createdAt, - updatedAt, templateId, registeredEvents, config, templateName, - null, null); + return new HookData(id, name, displayName, isActive, createdAt, updatedAt, templateId, registeredEvents, config, templateName, null, + null); } - public static HookData template(final List templates, - final List groupings) { - return new HookData(null, null, null, null, null, null, null, null, - null, null, templates, groupings); + public static HookData template(final List templates, final List groupings) { + return new HookData(null, null, null, null, null, null, null, null, null, null, templates, groupings); } - public static HookData templateExisting(final HookData hookData, - final List templates, + public static HookData templateExisting(final HookData hookData, final List templates, final List groupings) { - return new HookData(hookData.id, hookData.name, hookData.displayName, - hookData.isActive, hookData.createdAt, hookData.updatedAt, - hookData.templateId, hookData.events, hookData.config, - hookData.templateName, templates, groupings); + return new HookData(hookData.id, hookData.name, hookData.displayName, hookData.isActive, hookData.createdAt, hookData.updatedAt, + hookData.templateId, hookData.events, hookData.config, hookData.templateName, templates, groupings); } - private HookData(final Long id, final String name, - final String displayName, final Boolean isActive, - final LocalDate createdAt, final LocalDate updatedAt, - final Long templateId, final List events, - final List config, final String templateName, - final List templates, - final List groupings) { + private HookData(final Long id, final String name, final String displayName, final Boolean isActive, final LocalDate createdAt, + final LocalDate updatedAt, final Long templateId, final List events, final List config, final String templateName, + final List templates, final List groupings) { this.id = id; this.name = name; this.displayName = displayName; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/HookTemplateData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/HookTemplateData.java index f588426e2..ff44ceb87 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/HookTemplateData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/data/HookTemplateData.java @@ -30,13 +30,11 @@ public class HookTemplateData implements Serializable { // associations private final List schema; - public static HookTemplateData instance(final Long id, final String name, - final List schema) { + public static HookTemplateData instance(final Long id, final String name, final List schema) { return new HookTemplateData(id, name, schema); } - private HookTemplateData(final Long id, final String name, - final List schema) { + private HookTemplateData(final Long id, final String name, final List schema) { this.id = id; this.name = name; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/Hook.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/Hook.java index 860945c71..de8bbe53a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/Hook.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/Hook.java @@ -54,10 +54,10 @@ public class Hook extends AbstractAuditableCustom { @Column(name = "is_active", nullable = false) private Boolean isActive; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "hook", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "hook", orphanRemoval = true, fetch = FetchType.EAGER) private Set events = new HashSet<>(); - @OneToMany(cascade = CascadeType.ALL, mappedBy = "hook", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "hook", orphanRemoval = true, fetch = FetchType.EAGER) private Set config = new HashSet<>(); @ManyToOne(optional = true) diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookConfiguration.java index 88bd25d33..bb762053c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookConfiguration.java @@ -42,14 +42,11 @@ public class HookConfiguration extends AbstractPersistableCustom { @Column(name = "field_value", nullable = false, length = 100) private String fieldValue; - public static HookConfiguration createNewWithoutHook( - final String fieldType, final String fieldName, - final String fieldValue) { + public static HookConfiguration createNewWithoutHook(final String fieldType, final String fieldName, final String fieldValue) { return new HookConfiguration(null, fieldType, fieldName, fieldValue); } - public static HookConfiguration createNew(final Hook hook, final String fieldType, - final String fieldName, final String fieldValue) { + public static HookConfiguration createNew(final Hook hook, final String fieldType, final String fieldName, final String fieldValue) { return new HookConfiguration(hook, fieldType, fieldName, fieldValue); } @@ -57,8 +54,7 @@ public class HookConfiguration extends AbstractPersistableCustom { // } - private HookConfiguration(final Hook hook, final String fieldType, - final String fieldName, final String fieldValue) { + private HookConfiguration(final Hook hook, final String fieldType, final String fieldName, final String fieldValue) { this.hook = hook; this.fieldType = fieldType; this.fieldName = fieldName; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookConfigurationRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookConfigurationRepository.java index 814cbf2b9..c9a031d88 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookConfigurationRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookConfigurationRepository.java @@ -23,12 +23,9 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface HookConfigurationRepository extends - JpaRepository, - JpaSpecificationExecutor { +public interface HookConfigurationRepository extends JpaRepository, JpaSpecificationExecutor { @Query("select config.fieldValue from HookConfiguration config where config.hook.id = :hookId and config.fieldName = :fieldName") - String findOneByHookIdAndFieldName(@Param("hookId") Long hookId, - @Param("fieldName") String fieldName); + String findOneByHookIdAndFieldName(@Param("hookId") Long hookId, @Param("fieldName") String fieldName); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookRepository.java index e274fd416..c6ac200c7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookRepository.java @@ -24,13 +24,10 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface HookRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface HookRepository extends JpaRepository, JpaSpecificationExecutor { @Query("select hook from Hook hook inner join hook.events event where event.entityName = :entityName and event.actionName = :actionName and hook.isActive = true") - List findAllHooksListeningToEvent( - @Param("entityName") String entityName, - @Param("actionName") String actionName); + List findAllHooksListeningToEvent(@Param("entityName") String entityName, @Param("actionName") String actionName); @Query("select hook from Hook hook where hook.template.id = :templateId ") Hook findOneByTemplateId(@Param("templateId") Long templateId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookResource.java index 46f496fff..572362851 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookResource.java @@ -43,13 +43,11 @@ public class HookResource extends AbstractPersistableCustom { // } - public static HookResource createNewWithoutHook(final String entityName, - final String actionName) { + public static HookResource createNewWithoutHook(final String entityName, final String actionName) { return new HookResource(null, entityName, actionName); } - private HookResource(final Hook hook, final String entityName, - final String actionName) { + private HookResource(final Hook hook, final String entityName, final String actionName) { this.hook = hook; this.entityName = entityName; this.actionName = actionName; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookTemplate.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookTemplate.java index cd96f2412..9ca46e86a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookTemplate.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookTemplate.java @@ -39,7 +39,7 @@ public class HookTemplate extends AbstractPersistableCustom { @Column(name = "name", nullable = false, length = 100) private String name; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "template", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "template", orphanRemoval = true, fetch = FetchType.EAGER) private Set fields = new HashSet<>(); private HookTemplate(final String name) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookTemplateRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookTemplateRepository.java index f13c2784e..125d5bebc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookTemplateRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/domain/HookTemplateRepository.java @@ -23,9 +23,7 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface HookTemplateRepository extends - JpaRepository, - JpaSpecificationExecutor { +public interface HookTemplateRepository extends JpaRepository, JpaSpecificationExecutor { @Query("select template from HookTemplate template where template.name = :name") HookTemplate findOne(@Param("name") String name); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/event/HookEvent.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/event/HookEvent.java index 7e949f01b..81282b055 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/event/HookEvent.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/event/HookEvent.java @@ -31,8 +31,7 @@ public class HookEvent extends ApplicationEvent { private final String authToken; - public HookEvent(final HookEventSource source, final String payload, - final String tenantIdentifier, final AppUser appUser, + public HookEvent(final HookEventSource source, final String payload, final String tenantIdentifier, final AppUser appUser, final String authToken) { super(source); this.payload = payload; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/exception/HookNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/exception/HookNotFoundException.java index e9339026e..a6ead8425 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/exception/HookNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/exception/HookNotFoundException.java @@ -20,16 +20,13 @@ package org.apache.fineract.infrastructure.hooks.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; -public class HookNotFoundException extends - AbstractPlatformResourceNotFoundException { +public class HookNotFoundException extends AbstractPlatformResourceNotFoundException { public HookNotFoundException(final String name) { - super("error.msg.hook.not.found", "Hook with name `" + name - + "` does not exist", name); + super("error.msg.hook.not.found", "Hook with name `" + name + "` does not exist", name); } public HookNotFoundException(final Long hookId) { - super("error.msg.hook.identifier.not.found", "Hook with identifier `" - + hookId + "` does not exist", hookId); + super("error.msg.hook.identifier.not.found", "Hook with identifier `" + hookId + "` does not exist", hookId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/exception/HookTemplateNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/exception/HookTemplateNotFoundException.java index 85adb13fd..9d580c41e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/exception/HookTemplateNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/exception/HookTemplateNotFoundException.java @@ -20,18 +20,14 @@ package org.apache.fineract.infrastructure.hooks.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; -public class HookTemplateNotFoundException extends - AbstractPlatformResourceNotFoundException { +public class HookTemplateNotFoundException extends AbstractPlatformResourceNotFoundException { public HookTemplateNotFoundException(final String name) { - super("error.msg.template.not.found", "Template with name `" + name - + "` does not exist", name); + super("error.msg.template.not.found", "Template with name `" + name + "` does not exist", name); } public HookTemplateNotFoundException(final Long templateId) { - super("error.msg.template.identifier.not.found", - "Template with identifier `" + templateId + "` does not exist", - templateId); + super("error.msg.template.identifier.not.found", "Template with identifier `" + templateId + "` does not exist", templateId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/CreateHookCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/CreateHookCommandHandler.java index 3bd01535a..e97049224 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/CreateHookCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/CreateHookCommandHandler.java @@ -34,8 +34,7 @@ public class CreateHookCommandHandler implements NewCommandSourceHandler { private final HookWritePlatformService writePlatformService; @Autowired - public CreateHookCommandHandler( - final HookWritePlatformService writePlatformService) { + public CreateHookCommandHandler(final HookWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/DeleteHookCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/DeleteHookCommandHandler.java index 02057dfbd..ea041f4c7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/DeleteHookCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/DeleteHookCommandHandler.java @@ -34,8 +34,7 @@ public class DeleteHookCommandHandler implements NewCommandSourceHandler { private final HookWritePlatformService writePlatformService; @Autowired - public DeleteHookCommandHandler( - final HookWritePlatformService writePlatformService) { + public DeleteHookCommandHandler(final HookWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/UpdateHookCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/UpdateHookCommandHandler.java index 942bab051..a660e278e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/UpdateHookCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/handler/UpdateHookCommandHandler.java @@ -34,8 +34,7 @@ public class UpdateHookCommandHandler implements NewCommandSourceHandler { private final HookWritePlatformService writePlatformService; @Autowired - public UpdateHookCommandHandler( - final HookWritePlatformService writePlatformService) { + public UpdateHookCommandHandler(final HookWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } @@ -43,8 +42,7 @@ public class UpdateHookCommandHandler implements NewCommandSourceHandler { @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService - .updateHook(command.entityId(), command); + return this.writePlatformService.updateHook(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/listener/FineractHookListener.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/listener/FineractHookListener.java index e23cfd70e..0694678d7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/listener/FineractHookListener.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/listener/FineractHookListener.java @@ -40,8 +40,7 @@ public class FineractHookListener implements HookListener { private final TenantDetailsService tenantDetailsService; @Autowired - public FineractHookListener(final HookProcessorProvider hookProcessorProvider, - final HookReadPlatformService hookReadPlatformService, + public FineractHookListener(final HookProcessorProvider hookProcessorProvider, final HookReadPlatformService hookReadPlatformService, final TenantDetailsService tenantDetailsService) { this.hookReadPlatformService = hookReadPlatformService; this.hookProcessorProvider = hookProcessorProvider; @@ -52,8 +51,7 @@ public class FineractHookListener implements HookListener { public void onApplicationEvent(final HookEvent event) { final String tenantIdentifier = event.getTenantIdentifier(); - final FineractPlatformTenant tenant = this.tenantDetailsService - .loadTenantById(tenantIdentifier); + final FineractPlatformTenant tenant = this.tenantDetailsService.loadTenantById(tenantIdentifier); ThreadLocalContextUtil.setTenant(tenant); final AppUser appUser = event.getAppUser(); @@ -64,15 +62,12 @@ public class FineractHookListener implements HookListener { final String actionName = hookEventSource.getActionName(); final String payload = event.getPayload(); - final List hooks = this.hookReadPlatformService - .retrieveHooksByEvent(hookEventSource.getEntityName(), - hookEventSource.getActionName()); + final List hooks = this.hookReadPlatformService.retrieveHooksByEvent(hookEventSource.getEntityName(), + hookEventSource.getActionName()); for (final Hook hook : hooks) { - final HookProcessor processor = this.hookProcessorProvider - .getProcessor(hook); - processor.process(hook, appUser, payload, entityName, actionName, - tenantIdentifier, authToken); + final HookProcessor processor = this.hookProcessorProvider.getProcessor(hook); + processor.process(hook, appUser, payload, entityName, actionName, tenantIdentifier, authToken); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/HookProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/HookProcessor.java index da3a2f06e..976619f2b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/HookProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/HookProcessor.java @@ -23,7 +23,7 @@ import org.apache.fineract.useradministration.domain.AppUser; public interface HookProcessor { - void process(Hook hook, AppUser appUser, String payload, String entityName, - String actionName, String tenantIdentifier, String authToken); + void process(Hook hook, AppUser appUser, String payload, String entityName, String actionName, String tenantIdentifier, + String authToken); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/HookProcessorProvider.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/HookProcessorProvider.java index 5869ee72f..bd4e73f70 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/HookProcessorProvider.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/HookProcessorProvider.java @@ -33,8 +33,7 @@ public class HookProcessorProvider implements ApplicationContextAware { private ApplicationContext applicationContext; @Override - public void setApplicationContext( - final ApplicationContext applicationContext) throws BeansException { + public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -42,11 +41,9 @@ public class HookProcessorProvider implements ApplicationContextAware { HookProcessor processor; final String templateName = hook.getHookTemplate().getName(); if (templateName.equalsIgnoreCase(smsTemplateName)) { - processor = this.applicationContext.getBean("twilioHookProcessor", - TwilioHookProcessor.class); + processor = this.applicationContext.getBean("twilioHookProcessor", TwilioHookProcessor.class); } else if (templateName.equals(webTemplateName)) { - processor = this.applicationContext.getBean("webHookProcessor", - WebHookProcessor.class); + processor = this.applicationContext.getBean("webHookProcessor", WebHookProcessor.class); } else { processor = null; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/ProcessorHelper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/ProcessorHelper.java index c037d6c77..7bd774f80 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/ProcessorHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/ProcessorHelper.java @@ -40,8 +40,7 @@ import retrofit.client.Response; @SuppressWarnings("unused") public class ProcessorHelper { - private final static Logger LOG = LoggerFactory - .getLogger(ProcessorHelper.class); + private final static Logger LOG = LoggerFactory.getLogger(ProcessorHelper.class); @SuppressWarnings("null") public static OkHttpClient configureClient(final OkHttpClient client) { @@ -53,14 +52,10 @@ public class ProcessorHelper { } @Override - public void checkServerTrusted(final X509Certificate[] chain, - final String authType) throws CertificateException { - } + public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {} @Override - public void checkClientTrusted(final X509Certificate[] chain, - final String authType) throws CertificateException { - } + public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {} } }; SSLContext ctx = null; @@ -68,23 +63,23 @@ public class ProcessorHelper { ctx = SSLContext.getInstance("TLS"); ctx.init(null, certs, new SecureRandom()); } catch (KeyManagementException ex) { - LOG.error("Problem occurred in configureClient function",ex); + LOG.error("Problem occurred in configureClient function", ex); } catch (NoSuchAlgorithmException e) { LOG.error("No Provider supports a TrustManagerFactorySpi implementation for the specified protocol.", e); } try { final HostnameVerifier hostnameVerifier = new HostnameVerifier() { + @Override - public boolean verify(final String hostname, - final SSLSession session) { + public boolean verify(final String hostname, final SSLSession session) { return true; } }; client.setHostnameVerifier(hostnameVerifier); client.setSslSocketFactory(ctx.getSocketFactory()); } catch (final Exception e) { - LOG.error("Problem occurred in configureClient function",e); + LOG.error("Problem occurred in configureClient function", e); } return client; @@ -99,6 +94,7 @@ public class ProcessorHelper { public static Callback createCallback(final String url) { return new Callback() { + @Override public void success(final Object o, final Response response) { LOG.info("URL: {}\tStatus: {}", url, response.getStatus()); @@ -115,10 +111,9 @@ public class ProcessorHelper { final OkHttpClient client = ProcessorHelper.createClient(); - final RestAdapter restAdapter = new RestAdapter.Builder() - .setEndpoint(url).setClient(new OkClient(client)).build(); + final RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(url).setClient(new OkClient(client)).build(); return restAdapter.create(WebHookService.class); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/TwilioHookProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/TwilioHookProcessor.java index e7102daca..b371fee78 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/TwilioHookProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/TwilioHookProcessor.java @@ -43,58 +43,46 @@ import retrofit.Callback; @Service public class TwilioHookProcessor implements HookProcessor { + private final static Logger LOG = LoggerFactory.getLogger(TwilioHookProcessor.class); private final HookConfigurationRepository hookConfigurationRepository; private final TemplateMergeService templateMergeService; private final ClientRepositoryWrapper clientRepositoryWrapper; @Autowired - public TwilioHookProcessor( - final HookConfigurationRepository hookConfigurationRepository, - final TemplateMergeService templateMergeService, - final ClientRepositoryWrapper clientRepositoryWrapper) { + public TwilioHookProcessor(final HookConfigurationRepository hookConfigurationRepository, + final TemplateMergeService templateMergeService, final ClientRepositoryWrapper clientRepositoryWrapper) { this.hookConfigurationRepository = hookConfigurationRepository; this.templateMergeService = templateMergeService; this.clientRepositoryWrapper = clientRepositoryWrapper; } @Override - public void process(final Hook hook, - @SuppressWarnings("unused") final AppUser appUser, - final String payload, final String entityName, - final String actionName, final String tenantIdentifier, - final String authToken) { + public void process(final Hook hook, @SuppressWarnings("unused") final AppUser appUser, final String payload, final String entityName, + final String actionName, final String tenantIdentifier, final String authToken) { - final SmsProviderData smsProviderData = new SmsProviderData( - hook.getHookConfig()); + final SmsProviderData smsProviderData = new SmsProviderData(hook.getHookConfig()); - sendRequest(smsProviderData, payload, entityName, actionName, - tenantIdentifier, authToken, hook); + sendRequest(smsProviderData, payload, entityName, actionName, tenantIdentifier, authToken, hook); } @SuppressWarnings("unchecked") - private void sendRequest(final SmsProviderData smsProviderData, - final String payload, String entityName, String actionName, - final String tenantIdentifier, final String authToken, - final Hook hook) { + private void sendRequest(final SmsProviderData smsProviderData, final String payload, String entityName, String actionName, + final String tenantIdentifier, final String authToken, final Hook hook) { - final WebHookService service = ProcessorHelper - .createWebHookService(smsProviderData.getUrl()); + final WebHookService service = ProcessorHelper.createWebHookService(smsProviderData.getUrl()); @SuppressWarnings("rawtypes") - final Callback callback = ProcessorHelper - .createCallback(smsProviderData.getUrl()); + final Callback callback = ProcessorHelper.createCallback(smsProviderData.getUrl()); - String apiKey = this.hookConfigurationRepository - .findOneByHookIdAndFieldName(hook.getId(), apiKeyName); + String apiKey = this.hookConfigurationRepository.findOneByHookIdAndFieldName(hook.getId(), apiKeyName); if (apiKey == null) { smsProviderData.setUrl(null); smsProviderData.setEndpoint(System.getProperty("baseUrl")); smsProviderData.setTenantId(tenantIdentifier); smsProviderData.setMifosToken(authToken); apiKey = service.sendSmsBridgeConfigRequest(smsProviderData); - final HookConfiguration apiKeyEntry = HookConfiguration.createNew( - hook, "string", apiKeyName, apiKey); + final HookConfiguration apiKeyEntry = HookConfiguration.createNew(hook, "string", apiKeyName, apiKey); this.hookConfigurationRepository.save(apiKeyEntry); } @@ -104,36 +92,29 @@ public class TwilioHookProcessor implements HookProcessor { entityName = "sms"; actionName = "send"; json = processUgdTemplate(payload, hook, authToken); - if (json == null) { - return; - } + if (json == null) { return; } } else { json = JsonParser.parseString(payload).getAsJsonObject(); } - service.sendSmsBridgeRequest(entityName, actionName, - tenantIdentifier, apiKey, json, callback); + service.sendSmsBridgeRequest(entityName, actionName, tenantIdentifier, apiKey, json, callback); } } - private JsonObject processUgdTemplate(final String payload, - final Hook hook, final String authToken) { + private JsonObject processUgdTemplate(final String payload, final Hook hook, final String authToken) { JsonObject json = null; try { @SuppressWarnings("unchecked") - final HashMap map = new ObjectMapper().readValue( - payload, HashMap.class); + final HashMap map = new ObjectMapper().readValue(payload, HashMap.class); map.put("BASE_URI", System.getProperty("baseUrl")); if (map.containsKey("clientId")) { - final Long clientId = Long.valueOf(Integer.toString((int) map - .get("clientId"))); + final Long clientId = Long.valueOf(Integer.toString((int) map.get("clientId"))); final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); final String mobileNo = client.mobileNo(); if (mobileNo != null && !mobileNo.isEmpty()) { this.templateMergeService.setAuthToken(authToken); - final String compiledMessage = this.templateMergeService - .compile(hook.getUgdTemplate(), map) - .replace("

", "").replace("

", ""); + final String compiledMessage = this.templateMergeService.compile(hook.getUgdTemplate(), map).replace("

", "") + .replace("

", ""); final Map jsonMap = new HashMap<>(); jsonMap.put("mobileNo", mobileNo); jsonMap.put("message", compiledMessage); @@ -142,7 +123,7 @@ public class TwilioHookProcessor implements HookProcessor { } } } catch (IOException e) { - LOG.error("Problem occurred in processUgdTemplate function",e); + LOG.error("Problem occurred in processUgdTemplate function", e); } return json; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/WebHookProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/WebHookProcessor.java index 8d1c04f19..f9753b74a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/WebHookProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/WebHookProcessor.java @@ -37,11 +37,8 @@ import retrofit.Callback; public class WebHookProcessor implements HookProcessor { @Override - public void process(final Hook hook, - @SuppressWarnings("unused") final AppUser appUser, - final String payload, final String entityName, - final String actionName, final String tenantIdentifier, - final String authToken) { + public void process(final Hook hook, @SuppressWarnings("unused") final AppUser appUser, final String payload, final String entityName, + final String actionName, final String tenantIdentifier, final String authToken) { final Set config = hook.getHookConfig(); @@ -58,35 +55,27 @@ public class WebHookProcessor implements HookProcessor { } } - sendRequest(url, contentType, payload, entityName, actionName, - tenantIdentifier, authToken); + sendRequest(url, contentType, payload, entityName, actionName, tenantIdentifier, authToken); } @SuppressWarnings("unchecked") - private void sendRequest(final String url, final String contentType, - final String payload, final String entityName, - final String actionName, final String tenantIdentifier, - @SuppressWarnings("unused") final String authToken) { + private void sendRequest(final String url, final String contentType, final String payload, final String entityName, + final String actionName, final String tenantIdentifier, @SuppressWarnings("unused") final String authToken) { final String fineractEndpointUrl = System.getProperty("baseUrl"); - final WebHookService service = ProcessorHelper - .createWebHookService(url); + final WebHookService service = ProcessorHelper.createWebHookService(url); @SuppressWarnings("rawtypes") final Callback callback = ProcessorHelper.createCallback(url); - if (contentType.equalsIgnoreCase("json") - || contentType.contains("json")) { - final JsonObject json = JsonParser.parseString(payload) - .getAsJsonObject(); - service.sendJsonRequest(entityName, actionName, tenantIdentifier, - fineractEndpointUrl, json, callback); + if (contentType.equalsIgnoreCase("json") || contentType.contains("json")) { + final JsonObject json = JsonParser.parseString(payload).getAsJsonObject(); + service.sendJsonRequest(entityName, actionName, tenantIdentifier, fineractEndpointUrl, json, callback); } else { Map map = new HashMap<>(); map = new Gson().fromJson(payload, map.getClass()); - service.sendFormRequest(entityName, actionName, tenantIdentifier, - fineractEndpointUrl, map, callback); + service.sendFormRequest(entityName, actionName, tenantIdentifier, fineractEndpointUrl, map, callback); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/WebHookService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/WebHookService.java index 2cf87990f..f00024ade 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/WebHookService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/WebHookService.java @@ -44,27 +44,21 @@ public interface WebHookService { // Template - Web @POST("/") - void sendJsonRequest(@Header(ENTITY_HEADER) String entityHeader, - @Header(ACTION_HEADER) String actionHeader, - @Header(TENANT_HEADER) String tenantHeader, - @Header(ENDPOINT_HEADER) String endpointHeader, - @Body JsonObject result, Callback callBack); + void sendJsonRequest(@Header(ENTITY_HEADER) String entityHeader, @Header(ACTION_HEADER) String actionHeader, + @Header(TENANT_HEADER) String tenantHeader, @Header(ENDPOINT_HEADER) String endpointHeader, @Body JsonObject result, + Callback callBack); @FormUrlEncoded @POST("/") - void sendFormRequest(@Header(ENTITY_HEADER) String entityHeader, - @Header(ACTION_HEADER) String actionHeader, - @Header(TENANT_HEADER) String tenantHeader, - @Header(ENDPOINT_HEADER) String endpointHeader, + void sendFormRequest(@Header(ENTITY_HEADER) String entityHeader, @Header(ACTION_HEADER) String actionHeader, + @Header(TENANT_HEADER) String tenantHeader, @Header(ENDPOINT_HEADER) String endpointHeader, @FieldMap Map params, Callback callBack); // Template - SMS Bridge @POST("/") - void sendSmsBridgeRequest(@Header(ENTITY_HEADER) String entityHeader, - @Header(ACTION_HEADER) String actionHeader, - @Header(TENANT_HEADER) String tenantHeader, - @Header(API_KEY_HEADER) String apiKeyHeader, - @Body JsonObject result, Callback callBack); + void sendSmsBridgeRequest(@Header(ENTITY_HEADER) String entityHeader, @Header(ACTION_HEADER) String actionHeader, + @Header(TENANT_HEADER) String tenantHeader, @Header(API_KEY_HEADER) String apiKeyHeader, @Body JsonObject result, + Callback callBack); @POST("/configuration") String sendSmsBridgeConfigRequest(@Body SmsProviderData config); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/serialization/HookCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/serialization/HookCommandFromApiJsonDeserializer.java index 6eeffbb33..62f0a3ea5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/serialization/HookCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/serialization/HookCommandFromApiJsonDeserializer.java @@ -44,89 +44,63 @@ public class HookCommandFromApiJsonDeserializer { * The parameters supported for this command. */ private final Set supportedParameters = new HashSet<>( - Arrays.asList("name", "displayName", "isActive", "events", - "config", "templateId")); + Arrays.asList("name", "displayName", "isActive", "events", "config", "templateId")); private final FromJsonHelper fromApiJsonHelper; @Autowired - public HookCommandFromApiJsonDeserializer( - final FromJsonHelper fromApiJsonHelper) { + public HookCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { this.fromApiJsonHelper = fromApiJsonHelper; } public void validateForCreate(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - this.supportedParameters); + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( - dataValidationErrors).resource("hook"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("hook"); final JsonElement element = this.fromApiJsonHelper.parse(json); - final String name = this.fromApiJsonHelper.extractStringNamed("name", - element); - baseDataValidator.reset().parameter("name").value(name).notBlank() - .notExceedingLengthOf(100); + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); + baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); - if (this.fromApiJsonHelper.parameterExists( - HookApiConstants.templateIdParamName, element)) { - final Long templateId = this.fromApiJsonHelper.extractLongNamed( - HookApiConstants.templateIdParamName, element); - baseDataValidator.reset() - .parameter(HookApiConstants.templateIdParamName) - .value(templateId).notNull().integerGreaterThanZero(); + if (this.fromApiJsonHelper.parameterExists(HookApiConstants.templateIdParamName, element)) { + final Long templateId = this.fromApiJsonHelper.extractLongNamed(HookApiConstants.templateIdParamName, element); + baseDataValidator.reset().parameter(HookApiConstants.templateIdParamName).value(templateId).notNull().integerGreaterThanZero(); } throwExceptionIfValidationWarningsExist(dataValidationErrors); } public void validateForUpdate(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - this.supportedParameters); + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( - dataValidationErrors).resource("hook"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("hook"); final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists("name", element)) { - final String name = this.fromApiJsonHelper.extractStringNamed( - "name", element); - baseDataValidator.reset().parameter("name").value(name).notBlank() - .notExceedingLengthOf(100); + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); + baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); } - if (this.fromApiJsonHelper.parameterExists( - HookApiConstants.templateIdParamName, element)) { - final Long templateId = this.fromApiJsonHelper.extractLongNamed( - HookApiConstants.templateIdParamName, element); - baseDataValidator.reset() - .parameter(HookApiConstants.templateIdParamName) - .value(templateId).notNull().integerGreaterThanZero(); + if (this.fromApiJsonHelper.parameterExists(HookApiConstants.templateIdParamName, element)) { + final Long templateId = this.fromApiJsonHelper.extractLongNamed(HookApiConstants.templateIdParamName, element); + baseDataValidator.reset().parameter(HookApiConstants.templateIdParamName).value(templateId).notNull().integerGreaterThanZero(); } throwExceptionIfValidationWarningsExist(dataValidationErrors); } - private void throwExceptionIfValidationWarningsExist( - final List dataValidationErrors) { + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookReadPlatformService.java index 2c0205659..26d93081d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookReadPlatformService.java @@ -29,7 +29,7 @@ public interface HookReadPlatformService { HookData retrieveHook(Long hookId); - List retrieveHooksByEvent(final String entityName,final String actionName); + List retrieveHooksByEvent(final String entityName, final String actionName); HookData retrieveNewHookDetails(String templateName); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookReadPlatformServiceImpl.java index 3f3923675..9ecd93f3a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookReadPlatformServiceImpl.java @@ -50,8 +50,7 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { private final PlatformSecurityContext context; @Autowired - public HookReadPlatformServiceImpl(final PlatformSecurityContext context, - final HookRepository hookRepository, + public HookReadPlatformServiceImpl(final PlatformSecurityContext context, final HookRepository hookRepository, final RoutingDataSource dataSource) { this.context = context; this.hookRepository = hookRepository; @@ -64,7 +63,7 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { final HookMapper rm = new HookMapper(this.jdbcTemplate); final String sql = "select " + rm.schema() + " order by h.name"; - return this.jdbcTemplate.query(sql, rm, new Object[]{}); + return this.jdbcTemplate.query(sql, rm, new Object[] {}); } @Override @@ -74,8 +73,7 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { final HookMapper rm = new HookMapper(this.jdbcTemplate); final String sql = "select " + rm.schema() + " where h.id = ?"; - return this.jdbcTemplate.queryForObject(sql, rm, - new Object[]{hookId}); + return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { hookId }); } catch (final EmptyResultDataAccessException e) { throw new HookNotFoundException(hookId); } @@ -86,8 +84,7 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { @Cacheable(value = "hooks", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('HK')") public List retrieveHooksByEvent(final String entityName, final String actionName) { - return this.hookRepository.findAllHooksListeningToEvent(entityName, - actionName); + return this.hookRepository.findAllHooksListeningToEvent(entityName, actionName); } @Override @@ -100,11 +97,10 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { if (templateName == null) { sql = "select " + rm.schema() + " order by s.name"; - templateData = this.jdbcTemplate.query(sql, rm, new Object[]{}); + templateData = this.jdbcTemplate.query(sql, rm, new Object[] {}); } else { sql = "select " + rm.schema() + " where s.name = ? order by s.name"; - templateData = this.jdbcTemplate.query(sql, rm, - new Object[]{templateName}); + templateData = this.jdbcTemplate.query(sql, rm, new Object[] { templateName }); } final List events = getTemplateForEvents(); @@ -114,8 +110,7 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { private List getTemplateForEvents() { final String sql = "select p.grouping, p.entity_name, p.action_name from m_permission p " - + " where p.action_name NOT LIKE '%CHECKER%' AND p.action_name NOT LIKE '%READ%' " - + " order by p.grouping, p.entity_name "; + + " where p.action_name NOT LIKE '%CHECKER%' AND p.action_name NOT LIKE '%READ%' " + " order by p.grouping, p.entity_name "; final EventResultSetExtractor extractor = new EventResultSetExtractor(); return this.jdbcTemplate.query(sql, extractor); } @@ -136,25 +131,20 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { } @Override - public HookData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public HookData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); final String name = rs.getString("name"); final String displayname = rs.getString("display_name"); final boolean isActive = rs.getBoolean("is_active"); - final LocalDate createdAt = JdbcSupport.getLocalDate(rs, - "created_date"); - final LocalDate updatedAt = JdbcSupport.getLocalDate(rs, - "lastmodified_date"); + final LocalDate createdAt = JdbcSupport.getLocalDate(rs, "created_date"); + final LocalDate updatedAt = JdbcSupport.getLocalDate(rs, "lastmodified_date"); final Long templateId = rs.getLong("ugd_template_id"); final String templateName = rs.getString("ugd_template_name"); final List registeredEvents = retrieveEvents(id); final List config = retrieveConfig(id); - return HookData.instance(id, name, displayname, isActive, - createdAt, updatedAt, templateId, registeredEvents, config, + return HookData.instance(id, name, displayname, isActive, createdAt, updatedAt, templateId, registeredEvents, config, templateName); } @@ -163,17 +153,15 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { final HookEventMapper rm = new HookEventMapper(); final String sql = "select " + rm.schema() + " where h.id= ?"; - return this.jdbcTemplate.query(sql, rm, new Object[]{hookId}); + return this.jdbcTemplate.query(sql, rm, new Object[] { hookId }); } private List retrieveConfig(final Long hookId) { final HookConfigMapper rm = new HookConfigMapper(); - final String sql = "select " + rm.schema() - + " where h.id= ? order by hc.field_name"; + final String sql = "select " + rm.schema() + " where h.id= ? order by hc.field_name"; - final List fields = this.jdbcTemplate.query(sql, rm, - new Object[]{hookId}); + final List fields = this.jdbcTemplate.query(sql, rm, new Object[] { hookId }); return fields; } @@ -186,9 +174,7 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { } @Override - public Event mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public Event mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final String actionName = rs.getString("action_name"); final String entityName = rs.getString("entity_name"); return Event.instance(actionName, entityName); @@ -202,18 +188,14 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { } @Override - public Field mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public Field mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final String fieldName = rs.getString("field_name"); final String fieldValue = rs.getString("field_value"); return Field.fromConfig(fieldName, fieldValue); } } - private static final class TemplateMapper - implements - RowMapper { + private static final class TemplateMapper implements RowMapper { private final JdbcTemplate jdbcTemplate; @@ -226,9 +208,7 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { } @Override - public HookTemplateData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public HookTemplateData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); final String name = rs.getString("name"); @@ -240,11 +220,9 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { private List retrieveSchema(final Long templateId) { final TemplateSchemaMapper rm = new TemplateSchemaMapper(); - final String sql = "select " + rm.schema() - + " where s.id= ? order by hs.field_name "; + final String sql = "select " + rm.schema() + " where s.id= ? order by hs.field_name "; - final List fields = this.jdbcTemplate.query(sql, rm, - new Object[]{templateId}); + final List fields = this.jdbcTemplate.query(sql, rm, new Object[] { templateId }); return fields; } @@ -258,15 +236,12 @@ public class HookReadPlatformServiceImpl implements HookReadPlatformService { } @Override - public Field mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public Field mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final String fieldName = rs.getString("field_name"); final String fieldType = rs.getString("field_type"); final Boolean optional = rs.getBoolean("optional"); final String placeholder = rs.getString("placeholder"); - return Field - .fromSchema(fieldType, fieldName, optional, placeholder); + return Field.fromSchema(fieldType, fieldName, optional, placeholder); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookWritePlatformServiceJpaRepositoryImpl.java index ee2eab7d7..6da34f80f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/service/HookWritePlatformServiceJpaRepositoryImpl.java @@ -70,9 +70,7 @@ import org.springframework.transaction.annotation.Transactional; import retrofit.RetrofitError; @Service -public class HookWritePlatformServiceJpaRepositoryImpl - implements - HookWritePlatformService { +public class HookWritePlatformServiceJpaRepositoryImpl implements HookWritePlatformService { private final PlatformSecurityContext context; private final HookRepository hookRepository; @@ -82,13 +80,9 @@ public class HookWritePlatformServiceJpaRepositoryImpl private final FromJsonHelper fromApiJsonHelper; @Autowired - public HookWritePlatformServiceJpaRepositoryImpl( - final PlatformSecurityContext context, - final HookRepository hookRepository, - final HookTemplateRepository hookTemplateRepository, - final TemplateRepository ugdTemplateRepository, - final HookCommandFromApiJsonDeserializer fromApiJsonDeserializer, - final FromJsonHelper fromApiJsonHelper) { + public HookWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final HookRepository hookRepository, + final HookTemplateRepository hookTemplateRepository, final TemplateRepository ugdTemplateRepository, + final HookCommandFromApiJsonDeserializer fromApiJsonDeserializer, final FromJsonHelper fromApiJsonHelper) { this.context = context; this.hookRepository = hookRepository; this.hookTemplateRepository = hookTemplateRepository; @@ -107,36 +101,29 @@ public class HookWritePlatformServiceJpaRepositoryImpl this.fromApiJsonDeserializer.validateForCreate(command.json()); - final HookTemplate template = retrieveHookTemplateBy(command - .stringValueOfParameterNamed(nameParamName)); + final HookTemplate template = retrieveHookTemplateBy(command.stringValueOfParameterNamed(nameParamName)); final String configJson = command.jsonFragment(configParamName); - final Set config = assembleConfig( - command.mapValueOfParameterNamed(configJson), template); - final JsonArray events = command - .arrayOfParameterNamed(eventsParamName); + final Set config = assembleConfig(command.mapValueOfParameterNamed(configJson), template); + final JsonArray events = command.arrayOfParameterNamed(eventsParamName); final Set allEvents = assembleSetOfEvents(events); Template ugdTemplate = null; if (command.hasParameter(templateIdParamName)) { - final Long ugdTemplateId = command - .longValueOfParameterNamed(templateIdParamName); + final Long ugdTemplateId = command.longValueOfParameterNamed(templateIdParamName); ugdTemplate = this.ugdTemplateRepository.findById(ugdTemplateId) .orElseThrow(() -> new TemplateNotFoundException(ugdTemplateId)); } - final Hook hook = Hook.fromJson(command, template, config, - allEvents, ugdTemplate); + final Hook hook = Hook.fromJson(command, template, config, allEvents, ugdTemplate); validateHookRules(template, config, allEvents); this.hookRepository.save(hook); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withEntityId(hook.getId()).build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(hook.getId()).build(); } catch (final DataIntegrityViolationException dve) { handleHookDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleHookDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -145,8 +132,7 @@ public class HookWritePlatformServiceJpaRepositoryImpl @Transactional @Override @CacheEvict(value = "hooks", allEntries = true) - public CommandProcessingResult updateHook(final Long hookId, - final JsonCommand command) { + public CommandProcessingResult updateHook(final Long hookId, final JsonCommand command) { try { this.context.authenticatedUser(); @@ -160,8 +146,7 @@ public class HookWritePlatformServiceJpaRepositoryImpl if (!changes.isEmpty()) { if (changes.containsKey(templateIdParamName)) { - final Long ugdTemplateId = command - .longValueOfParameterNamed(templateIdParamName); + final Long ugdTemplateId = command.longValueOfParameterNamed(templateIdParamName); final Template ugdTemplate = this.ugdTemplateRepository.findById(ugdTemplateId).orElse(null); if (ugdTemplate == null) { changes.remove(templateIdParamName); @@ -171,8 +156,7 @@ public class HookWritePlatformServiceJpaRepositoryImpl } if (changes.containsKey(eventsParamName)) { - final Set events = assembleSetOfEvents(command - .arrayOfParameterNamed(eventsParamName)); + final Set events = assembleSetOfEvents(command.arrayOfParameterNamed(eventsParamName)); final boolean updated = hook.updateEvents(events); if (!updated) { changes.remove(eventsParamName); @@ -180,11 +164,8 @@ public class HookWritePlatformServiceJpaRepositoryImpl } if (changes.containsKey(configParamName)) { - final String configJson = command - .jsonFragment(configParamName); - final Set config = assembleConfig( - command.mapValueOfParameterNamed(configJson), - template); + final String configJson = command.jsonFragment(configParamName); + final Set config = assembleConfig(command.mapValueOfParameterNamed(configJson), template); final boolean updated = hook.updateConfig(config); if (!updated) { changes.remove(configParamName); @@ -202,8 +183,8 @@ public class HookWritePlatformServiceJpaRepositoryImpl } catch (final DataIntegrityViolationException dve) { handleHookDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleHookDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -219,31 +200,23 @@ public class HookWritePlatformServiceJpaRepositoryImpl try { this.hookRepository.delete(hook); } catch (final DataIntegrityViolationException e) { - throw new PlatformDataIntegrityException( - "error.msg.unknown.data.integrity.issue", - "Unknown data integrity issue with resource: " - + e.getMostSpecificCause()); + throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", + "Unknown data integrity issue with resource: " + e.getMostSpecificCause()); } - return new CommandProcessingResultBuilder().withEntityId(hookId) - .build(); + return new CommandProcessingResultBuilder().withEntityId(hookId).build(); } private Hook retrieveHookBy(final Long hookId) { - return this.hookRepository.findById(hookId) - .orElseThrow(() -> new HookNotFoundException(hookId)); + return this.hookRepository.findById(hookId).orElseThrow(() -> new HookNotFoundException(hookId)); } private HookTemplate retrieveHookTemplateBy(final String templateName) { - final HookTemplate template = this.hookTemplateRepository - .findOne(templateName); - if (template == null) { - throw new HookTemplateNotFoundException(templateName); - } + final HookTemplate template = this.hookTemplateRepository.findOne(templateName); + if (template == null) { throw new HookTemplateNotFoundException(templateName); } return template; } - private Set assembleConfig( - final Map hookConfig, final HookTemplate template) { + private Set assembleConfig(final Map hookConfig, final HookTemplate template) { final Set configuration = new HashSet<>(); final Set fields = template.getSchema(); @@ -253,10 +226,8 @@ public class HookWritePlatformServiceJpaRepositoryImpl final String fieldName = field.getFieldName(); if (fieldName.equalsIgnoreCase(configEntry.getKey())) { - final HookConfiguration config = HookConfiguration - .createNewWithoutHook(field.getFieldType(), - configEntry.getKey(), - configEntry.getValue()); + final HookConfiguration config = HookConfiguration.createNewWithoutHook(field.getFieldType(), configEntry.getKey(), + configEntry.getValue()); configuration.add(config); break; } @@ -273,51 +244,39 @@ public class HookWritePlatformServiceJpaRepositoryImpl for (int i = 0; i < eventsArray.size(); i++) { - final JsonObject eventElement = eventsArray.get(i) - .getAsJsonObject(); + final JsonObject eventElement = eventsArray.get(i).getAsJsonObject(); - final String entityName = this.fromApiJsonHelper - .extractStringNamed(entityNameParamName, eventElement); - final String actionName = this.fromApiJsonHelper - .extractStringNamed(actionNameParamName, eventElement); - final HookResource event = HookResource.createNewWithoutHook( - entityName, actionName); + final String entityName = this.fromApiJsonHelper.extractStringNamed(entityNameParamName, eventElement); + final String actionName = this.fromApiJsonHelper.extractStringNamed(actionNameParamName, eventElement); + final HookResource event = HookResource.createNewWithoutHook(entityName, actionName); allEvents.add(event); } return allEvents; } - private void validateHookRules(final HookTemplate template, - final Set config, Set events) { + private void validateHookRules(final HookTemplate template, final Set config, Set events) { final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( - dataValidationErrors).resource("hook"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("hook"); - if (!template.getName().equalsIgnoreCase(webTemplateName) - && this.hookRepository.findOneByTemplateId(template.getId()) != null) { + if (!template.getName().equalsIgnoreCase(webTemplateName) && this.hookRepository.findOneByTemplateId(template.getId()) != null) { final String errorMessage = "multiple.non.web.template.hooks.not.supported"; - baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( - errorMessage); + baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(errorMessage); } for (final HookConfiguration conf : config) { final String fieldValue = conf.getFieldValue(); if (conf.getFieldName().equals(contentTypeName)) { - if (!(fieldValue.equalsIgnoreCase("json") || fieldValue - .equalsIgnoreCase("form"))) { + if (!(fieldValue.equalsIgnoreCase("json") || fieldValue.equalsIgnoreCase("form"))) { final String errorMessage = "content.type.must.be.json.or.form"; - baseDataValidator.reset() - .failWithCodeNoParameterAddedToErrorCode( - errorMessage); + baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(errorMessage); } } if (conf.getFieldName().equals(payloadURLName)) { try { - final WebHookService service = ProcessorHelper - .createWebHookService(fieldValue); + final WebHookService service = ProcessorHelper.createWebHookService(fieldValue); service.sendEmptyRequest(); } catch (RetrofitError re) { // Swallow error if it's because of method not supported or @@ -325,9 +284,7 @@ public class HookWritePlatformServiceJpaRepositoryImpl // url generated on 1st POST request if (re.getResponse() == null) { String errorMessage = "url.invalid"; - baseDataValidator.reset() - .failWithCodeNoParameterAddedToErrorCode( - errorMessage); + baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(errorMessage); } } } @@ -335,8 +292,7 @@ public class HookWritePlatformServiceJpaRepositoryImpl if (events == null || events.isEmpty()) { final String errorMessage = "registered.events.cannot.be.empty"; - baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( - errorMessage); + baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(errorMessage); } final Set fields = template.getSchema(); @@ -349,34 +305,23 @@ public class HookWritePlatformServiceJpaRepositoryImpl } } if (!found) { - final String errorMessage = "required.config.field." - + "not.provided"; - baseDataValidator - .reset() - .value(field.getFieldName()) - .failWithCodeNoParameterAddedToErrorCode( - errorMessage); + final String errorMessage = "required.config.field." + "not.provided"; + baseDataValidator.reset().value(field.getFieldName()).failWithCodeNoParameterAddedToErrorCode(errorMessage); } } } - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - private void handleHookDataIntegrityIssues(final JsonCommand command, final Throwable realCause, - final Exception dve) { + private void handleHookDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { if (realCause.getMessage().contains("hook_name")) { final String name = command.stringValueOfParameterNamed("name"); - throw new PlatformDataIntegrityException( - "error.msg.hook.duplicate.name", "A hook with name '" - + name + "' already exists", "name", name); + throw new PlatformDataIntegrityException("error.msg.hook.duplicate.name", "A hook with name '" + name + "' already exists", + "name", name); } - throw new PlatformDataIntegrityException( - "error.msg.unknown.data.integrity.issue", - "Unknown data integrity issue with resource: " - + realCause.getMessage()); + throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", + "Unknown data integrity issue with resource: " + realCause.getMessage()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/annotation/CronMethodParser.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/annotation/CronMethodParser.java index ff3b3a82b..69e5900f9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/annotation/CronMethodParser.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/annotation/CronMethodParser.java @@ -70,16 +70,20 @@ public class CronMethodParser { */ private static void findAnnotationMethods(final Class annotationClass, final String attributeName) throws IOException { - final String basePackagePath = ClassUtils.convertClassNameToResourcePath(new StandardEnvironment() - .resolveRequiredPlaceholders(SEARCH_PACKAGE)); + final String basePackagePath = ClassUtils + .convertClassNameToResourcePath(new StandardEnvironment().resolveRequiredPlaceholders(SEARCH_PACKAGE)); String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + basePackagePath + "/" + RESOURCE_PATTERN; - packageSearchPath = packageSearchPath.replace("//", "/"); // else it doesn't work if *.class are in WAR!! + packageSearchPath = packageSearchPath.replace("//", "/"); // else it + // doesn't + // work if + // *.class are + // in WAR!! final Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); for (final Resource resource : resources) { if (resource.isReadable()) { final MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); - final Set metadataSet = metadataReader.getAnnotationMetadata().getAnnotatedMethods( - annotationClass.getName()); + final Set metadataSet = metadataReader.getAnnotationMetadata() + .getAnnotatedMethods(annotationClass.getName()); if (metadataSet != null && metadataSet.size() > 0) { for (final MethodMetadata metadata : metadataSet) { final Map attributes = metadata.getAnnotationAttributes(annotationClass.getName()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerApiResource.java old mode 100755 new mode 100644 index e04d3c86f..448c4fda5 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerApiResource.java @@ -49,10 +49,8 @@ import org.springframework.stereotype.Component; @Path("/scheduler") @Component -@Api(tags = {"Scheduler"}) -@SwaggerDefinition(tags = { - @Tag(name = "Scheduler", description = "") -}) +@Api(tags = { "Scheduler" }) +@SwaggerDefinition(tags = { @Tag(name = "Scheduler", description = "") }) public class SchedulerApiResource { private final PlatformSecurityContext context; @@ -72,8 +70,9 @@ public class SchedulerApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Scheduler Status", notes = "Returns the scheduler status.\n" + "\n" + "Example Requests:\n" + "\n" + "scheduler") - @ApiResponses({@ApiResponse(code = 200, message = "", response = SchedulerApiResourceSwagger.GetSchedulerResponse.class)}) + @ApiOperation(value = "Retrieve Scheduler Status", notes = "Returns the scheduler status.\n" + "\n" + "Example Requests:\n" + "\n" + + "scheduler") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = SchedulerApiResourceSwagger.GetSchedulerResponse.class) }) public String retrieveStatus(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SchedulerJobApiConstants.SCHEDULER_RESOURCE_NAME); final boolean isSchedulerRunning = this.jobRegisterService.isSchedulerRunning(); @@ -87,8 +86,9 @@ public class SchedulerApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Activate Scheduler Jobs | Suspend Scheduler Jobs", notes = "Activates the scheduler job service. | Suspends the scheduler job service.") - @ApiResponses({@ApiResponse(code = 200, message = "POST : scheduler?command=start\n\n"+"\n"+"POST : scheduler?command=stop")}) - public Response changeSchedulerStatus(@QueryParam(SchedulerJobApiConstants.COMMAND) @ApiParam(value = "command") final String commandParam) { + @ApiResponses({ @ApiResponse(code = 200, message = "POST : scheduler?command=start\n\n" + "\n" + "POST : scheduler?command=stop") }) + public Response changeSchedulerStatus( + @QueryParam(SchedulerJobApiConstants.COMMAND) @ApiParam(value = "command") final String commandParam) { // check the logged in user have permissions to update scheduler status final boolean hasNotPermission = this.context.authenticatedUser().hasNotPermissionForAnyOf("ALL_FUNCTIONS", "UPDATE_SCHEDULER"); if (hasNotPermission) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerApiResourceSwagger.java index e2f1b913d..3b462ed6d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerApiResourceSwagger.java @@ -25,18 +25,20 @@ import io.swagger.annotations.ApiModelProperty; * Created by sanyam on 12/8/17. */ final class SchedulerApiResourceSwagger { - private SchedulerApiResourceSwagger(){ + + private SchedulerApiResourceSwagger() { } @ApiModel(value = "GetSchedulerResponse") public static final class GetSchedulerResponse { + private GetSchedulerResponse() { } + @ApiModelProperty(example = "true") public boolean active; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiConstants.java old mode 100755 new mode 100644 index eeb9a3a7a..1746fc642 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiConstants.java @@ -53,16 +53,13 @@ public class SchedulerJobApiConstants { public static final String JOB_RUN_HISTORY = "runhistory"; public static final String SCHEDULER_STATUS_PATH = "scheduler"; - protected static final Set JOB_DETAIL_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList - (jobIdentifierParamName, - displayNameParamName, nextRunTimeParamName, initializingErrorParamName, cronExpressionParamName, jobActiveStatusParamName, - currentlyRunningParamName, lastRunHistoryObjParamName)); + protected static final Set JOB_DETAIL_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(jobIdentifierParamName, displayNameParamName, nextRunTimeParamName, initializingErrorParamName, + cronExpressionParamName, jobActiveStatusParamName, currentlyRunningParamName, lastRunHistoryObjParamName)); - protected static final Set JOB_HISTORY_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList - (versionParamName, - jobRunStartTimeParamName, jobRunEndTimeParamName, statusParamName, jobRunErrorMessageParamName, triggerTypeParamName, - jobRunErrorLogParamName)); + protected static final Set JOB_HISTORY_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(versionParamName, jobRunStartTimeParamName, jobRunEndTimeParamName, statusParamName, jobRunErrorMessageParamName, + triggerTypeParamName, jobRunErrorLogParamName)); - protected static final Set SCHEDULER_DETAIL_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList - (schedulerStatusParamName)); + protected static final Set SCHEDULER_DETAIL_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(schedulerStatusParamName)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiResource.java old mode 100755 new mode 100644 index a3aa217a5..e9635fb43 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiResource.java @@ -64,10 +64,9 @@ import org.springframework.stereotype.Component; @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Component -@Api(tags = {"MIFOSX-BATCH JOBS"}) +@Api(tags = { "MIFOSX-BATCH JOBS" }) @SwaggerDefinition(tags = { - @Tag(name = "MIFOSX-BATCH JOBS", description = "Batch jobs (also known as cron jobs on Unix-based systems) are a series of back-end jobs executed on a computer at a particular time defined in job's cron expression.\n\n At any point, you can view the list of batch jobs scheduled to run along with other details specific to each job. Manually you can execute the jobs at any point of time.\n\n The scheduler status can be either \"Active\" or \"Standby\". If the scheduler status is Active, it indicates that all batch jobs are running/ will run as per the specified schedule.If the scheduler status is Standby, it will ensure all scheduled batch runs are suspended.") -}) + @Tag(name = "MIFOSX-BATCH JOBS", description = "Batch jobs (also known as cron jobs on Unix-based systems) are a series of back-end jobs executed on a computer at a particular time defined in job's cron expression.\n\n At any point, you can view the list of batch jobs scheduled to run along with other details specific to each job. Manually you can execute the jobs at any point of time.\n\n The scheduler status can be either \"Active\" or \"Standby\". If the scheduler status is Active, it indicates that all batch jobs are running/ will run as per the specified schedule.If the scheduler status is Standby, it will ensure all scheduled batch runs are suspended.") }) public class SchedulerJobApiResource { private final SchedulerJobRunnerReadService schedulerJobRunnerReadService; @@ -83,8 +82,7 @@ public class SchedulerJobApiResource { final JobRegisterService jobRegisterService, final ToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final ToApiJsonSerializer jobHistoryToApiJsonSerializer, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final PlatformSecurityContext context) { + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final PlatformSecurityContext context) { this.schedulerJobRunnerReadService = schedulerJobRunnerReadService; this.jobRegisterService = jobRegisterService; this.toApiJsonSerializer = toApiJsonSerializer; @@ -96,7 +94,8 @@ public class SchedulerJobApiResource { @GET @ApiOperation(value = "Retrieve Scheduler Jobs", notes = "Returns the list of jobs.\n" + "\n" + "Example Requests:\n" + "\n" + "jobs") - @ApiResponses({@ApiResponse(code = 200, message = "", response = SchedulerJobApiResourceSwagger.GetJobsResponse.class, responseContainer = "list")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = SchedulerJobApiResourceSwagger.GetJobsResponse.class, responseContainer = "list") }) public String retrieveAll(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SchedulerJobApiConstants.SCHEDULER_RESOURCE_NAME); final List jobDetailDatas = this.schedulerJobRunnerReadService.findAllJobDeatils(); @@ -107,8 +106,9 @@ public class SchedulerJobApiResource { @GET @Path("{" + SchedulerJobApiConstants.JOB_ID + "}") @ApiOperation(value = "Retrieve a Job", notes = "Returns the details of a Job.\n" + "\n" + "Example Requests:\n" + "\n" + "jobs/5") - @ApiResponses({@ApiResponse(code = 200, message = "", response = SchedulerJobApiResourceSwagger.GetJobsResponse.class)}) - public String retrieveOne(@PathParam(SchedulerJobApiConstants.JOB_ID) @ApiParam(value = "jobId") final Long jobId, @Context final UriInfo uriInfo) { + @ApiResponses({ @ApiResponse(code = 200, message = "", response = SchedulerJobApiResourceSwagger.GetJobsResponse.class) }) + public String retrieveOne(@PathParam(SchedulerJobApiConstants.JOB_ID) @ApiParam(value = "jobId") final Long jobId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SchedulerJobApiConstants.SCHEDULER_RESOURCE_NAME); final JobDetailData jobDetailData = this.schedulerJobRunnerReadService.retrieveOne(jobId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -118,10 +118,14 @@ public class SchedulerJobApiResource { @GET @Path("{" + SchedulerJobApiConstants.JOB_ID + "}/" + SchedulerJobApiConstants.JOB_RUN_HISTORY) @ApiOperation(value = "Retrieve Job Run History", notes = "Example Requests:\n" + "\n" + "jobs/5/runhistory?offset=0&limit=200") - @ApiResponses({@ApiResponse(code = 200, message = "", response = SchedulerJobApiResourceSwagger.GetJobsJobIDJobRunHistoryResponse.class)}) - public String retrieveHistory(@Context final UriInfo uriInfo, @PathParam(SchedulerJobApiConstants.JOB_ID) @ApiParam(value = "jobId") final Long jobId, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = SchedulerJobApiResourceSwagger.GetJobsJobIDJobRunHistoryResponse.class) }) + public String retrieveHistory(@Context final UriInfo uriInfo, + @PathParam(SchedulerJobApiConstants.JOB_ID) @ApiParam(value = "jobId") final Long jobId, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { this.context.authenticatedUser().validateHasReadPermission(SchedulerJobApiConstants.SCHEDULER_RESOURCE_NAME); final SearchParameters searchParameters = SearchParameters.forPagination(offset, limit, orderBy, sortOrder); final Page jobhistoryDetailData = this.schedulerJobRunnerReadService.retrieveJobHistory(jobId, @@ -134,7 +138,7 @@ public class SchedulerJobApiResource { @POST @Path("{" + SchedulerJobApiConstants.JOB_ID + "}") @ApiOperation(value = "Run a Job", notes = "Manually Execute Specific Job.") - @ApiResponses({@ApiResponse(code = 200, message = "POST: jobs/1?command=executeJob")}) + @ApiResponses({ @ApiResponse(code = 200, message = "POST: jobs/1?command=executeJob") }) public Response executeJob(@PathParam(SchedulerJobApiConstants.JOB_ID) @ApiParam(value = "jobId") final Long jobId, @QueryParam(SchedulerJobApiConstants.COMMAND) @ApiParam(value = "command") final String commandParam) { // check the logged in user have permissions to execute scheduler jobs @@ -156,18 +160,19 @@ public class SchedulerJobApiResource { @PUT @Path("{" + SchedulerJobApiConstants.JOB_ID + "}") @ApiOperation(value = "Update a Job", notes = "Updates the details of a job.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SchedulerJobApiResourceSwagger.PutJobsJobIDRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "")}) - public String updateJobDetail(@PathParam(SchedulerJobApiConstants.JOB_ID) @ApiParam(value = "jobId") final Long jobId, @ApiParam(hidden = true) final String jsonRequestBody) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SchedulerJobApiResourceSwagger.PutJobsJobIDRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "") }) + public String updateJobDetail(@PathParam(SchedulerJobApiConstants.JOB_ID) @ApiParam(value = "jobId") final Long jobId, + @ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .updateJobDetail(jobId) // .withJson(jsonRequestBody) // .build(); // final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - if (result.getChanges() != null - && (result.getChanges().containsKey(SchedulerJobApiConstants.jobActiveStatusParamName) || result.getChanges().containsKey( - SchedulerJobApiConstants.cronExpressionParamName))) { + if (result.getChanges() != null && (result.getChanges().containsKey(SchedulerJobApiConstants.jobActiveStatusParamName) + || result.getChanges().containsKey(SchedulerJobApiConstants.cronExpressionParamName))) { this.jobRegisterService.rescheduleJob(jobId); } return this.toApiJsonSerializer.serialize(result); @@ -176,4 +181,4 @@ public class SchedulerJobApiResource { private boolean is(final String commandParam, final String commandValue) { return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiResourceSwagger.java index 1bd568ecf..205749d5f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/api/SchedulerJobApiResourceSwagger.java @@ -28,15 +28,18 @@ import org.apache.fineract.infrastructure.jobs.data.JobDetailHistoryData; * Created by sanyam on 12/8/17. */ final class SchedulerJobApiResourceSwagger { + private SchedulerJobApiResourceSwagger() { } @ApiModel(value = "GetJobsResponse") public static final class GetJobsResponse { + private GetJobsResponse() { } + @ApiModelProperty(example = "1") public Long jobId; @ApiModelProperty(example = "Update loan Summary") @@ -56,9 +59,11 @@ final class SchedulerJobApiResourceSwagger { @ApiModel(value = "PutJobsJobsIDRequest") public static final class PutJobsJobIDRequest { + private PutJobsJobIDRequest() { } + @ApiModelProperty(example = "Update loan Summary") public String displayName; @ApiModelProperty(example = "0 0 22 1/1 * ? *") @@ -70,12 +75,15 @@ final class SchedulerJobApiResourceSwagger { @ApiModel(value = "GetJobsJobIDJobRunHistoryResponse") public static final class GetJobsJobIDJobRunHistoryResponse { + private GetJobsJobIDJobRunHistoryResponse() { } final class JobDetailHistoryDataSwagger { - private JobDetailHistoryDataSwagger(){} + + private JobDetailHistoryDataSwagger() {} + @ApiModelProperty(example = "1") public Long version; @ApiModelProperty(example = "Jul 16, 2013 12:00:00 PM") @@ -87,6 +95,7 @@ final class SchedulerJobApiResourceSwagger { @ApiModelProperty(example = "cron") public String triggerType; } + @ApiModelProperty(example = "8") public int totalFilteredRecords; public List pageItems; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/data/JobDetailDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/data/JobDetailDataValidator.java old mode 100755 new mode 100644 index af1441021..c0583cd89 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/data/JobDetailDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/data/JobDetailDataValidator.java @@ -41,9 +41,9 @@ import org.springframework.stereotype.Component; public class JobDetailDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set JOB_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - SchedulerJobApiConstants.displayNameParamName, SchedulerJobApiConstants.jobActiveStatusParamName, - SchedulerJobApiConstants.cronExpressionParamName)); + private static final Set JOB_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(SchedulerJobApiConstants.displayNameParamName, SchedulerJobApiConstants.jobActiveStatusParamName, + SchedulerJobApiConstants.cronExpressionParamName)); @Autowired public JobDetailDataValidator(final FromJsonHelper fromApiJsonHelper) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/data/JobDetailHistoryData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/data/JobDetailHistoryData.java old mode 100755 new mode 100644 index 99a1fe265..9e508f62d --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/data/JobDetailHistoryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/data/JobDetailHistoryData.java @@ -53,4 +53,4 @@ public class JobDetailHistoryData { this.triggerType = triggerType; this.jobRunErrorLog = jobRunErrorLog; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/JobParameter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/JobParameter.java index a40f0607d..9788718e5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/JobParameter.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/JobParameter.java @@ -31,10 +31,10 @@ public class JobParameter extends AbstractPersistableCustom { @Column(name = "job_id", nullable = false) private Long jobId; - @Column(name = "parameter_name",nullable = true) + @Column(name = "parameter_name", nullable = true) private String parameterName; - @Column(name = "parameter_value",nullable = true) + @Column(name = "parameter_value", nullable = true) private String parameterValue; public JobParameter() {} @@ -45,8 +45,8 @@ public class JobParameter extends AbstractPersistableCustom { this.parameterValue = parameterValue; } - public static JobParameter getInstance(final Long jobId, final String parameterName, final String parameterValue){ - return new JobParameter(jobId,parameterName,parameterValue); + public static JobParameter getInstance(final Long jobId, final String parameterName, final String parameterValue) { + return new JobParameter(jobId, parameterName, parameterValue); } public Long getJobId() { @@ -73,12 +73,9 @@ public class JobParameter extends AbstractPersistableCustom { this.parameterValue = parameterValue; } - @Override public boolean equals(Object obj) { - if (!(obj instanceof JobParameter)) { - return false; - } + if (!(obj instanceof JobParameter)) { return false; } JobParameter jobParameter = (JobParameter) obj; return Objects.equals(jobParameter.getJobId(), this.getJobId()) && Objects.equals(jobParameter.getParameterName(), this.getParameterName()) @@ -87,6 +84,6 @@ public class JobParameter extends AbstractPersistableCustom { @Override public int hashCode() { - return Objects.hash(jobId,parameterName,parameterValue); + return Objects.hash(jobId, parameterName, parameterValue); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/JobParameterRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/JobParameterRepository.java index 933b154fc..dc61e2c2a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/JobParameterRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/JobParameterRepository.java @@ -28,4 +28,4 @@ public interface JobParameterRepository extends JpaRepository findJobParametersByJobId(@Param("jobId") Long jobId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobDetailRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobDetailRepository.java index 102c1e9e8..216a36280 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobDetailRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobDetailRepository.java @@ -25,7 +25,8 @@ import org.springframework.data.jpa.repository.Lock; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface ScheduledJobDetailRepository extends JpaRepository, JpaSpecificationExecutor { +public interface ScheduledJobDetailRepository + extends JpaRepository, JpaSpecificationExecutor { @Query("select jobDetail from ScheduledJobDetail jobDetail where jobDetail.jobKey = :jobKey") ScheduledJobDetail findByJobKey(@Param("jobKey") String jobKey); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobRunHistory.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobRunHistory.java index 202e24d8c..c04ab9261 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobRunHistory.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobRunHistory.java @@ -63,8 +63,8 @@ public class ScheduledJobRunHistory extends AbstractPersistableCustom { } - public ScheduledJobRunHistory(final ScheduledJobDetail scheduledJobDetail, final Long version, final Date startTime, - final Date endTime, final String status, final String errorMessage, final String triggerType, final String errorLog) { + public ScheduledJobRunHistory(final ScheduledJobDetail scheduledJobDetail, final Long version, final Date startTime, final Date endTime, + final String status, final String errorMessage, final String triggerType, final String errorLog) { this.scheduledJobDetail = scheduledJobDetail; this.version = version; this.startTime = startTime; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobRunHistoryRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobRunHistoryRepository.java index 12c23c3a1..8fbeee043 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobRunHistoryRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/domain/ScheduledJobRunHistoryRepository.java @@ -23,8 +23,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface ScheduledJobRunHistoryRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface ScheduledJobRunHistoryRepository + extends JpaRepository, JpaSpecificationExecutor { @Query("select max(sjrh.version) from ScheduledJobRunHistory sjrh where sjrh.scheduledJobDetail.jobKey = :jobKey") Long findMaxVersionByJobKey(@Param("jobKey") String jobKey); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/exception/JobNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/exception/JobNotFoundException.java old mode 100755 new mode 100644 index a50a7a8ff..c9a58c46a --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/exception/JobNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/exception/JobNotFoundException.java @@ -28,4 +28,4 @@ public class JobNotFoundException extends AbstractPlatformResourceNotFoundExcept public JobNotFoundException(final String identifier) { super("error.msg.sheduler.job.id.invalid", "Job with identifier " + identifier + " does not exist", identifier); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/exception/OperationNotAllowedException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/exception/OperationNotAllowedException.java old mode 100755 new mode 100644 index e6504feda..1e35a08ec --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/exception/OperationNotAllowedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/exception/OperationNotAllowedException.java @@ -26,7 +26,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformService public class OperationNotAllowedException extends AbstractPlatformServiceUnavailableException { public OperationNotAllowedException(final String jobNames) { - super("error.msg.sheduler.job.currently.running", "Execution is in-process for jobs " + jobNames - + "...., so update operations are not allowed at this moment", jobNames); + super("error.msg.sheduler.job.currently.running", + "Execution is in-process for jobs " + jobNames + "...., so update operations are not allowed at this moment", jobNames); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/JobName.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/JobName.java old mode 100755 new mode 100644 index 97d9b1494..fd0892006 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/JobName.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/JobName.java @@ -20,36 +20,33 @@ package org.apache.fineract.infrastructure.jobs.service; public enum JobName { - UPDATE_LOAN_SUMMARY("Update loan Summary"), - UPDATE_LOAN_ARREARS_AGEING("Update Loan Arrears Ageing"), - UPDATE_LOAN_PAID_IN_ADVANCE("Update Loan Paid In Advance"), - APPLY_ANNUAL_FEE_FOR_SAVINGS("Apply Annual Fee For Savings"), - APPLY_HOLIDAYS_TO_LOANS("Apply Holidays To Loans"), - POST_INTEREST_FOR_SAVINGS("Post Interest For Savings"), - TRANSFER_FEE_CHARGE_FOR_LOANS("Transfer Fee For Loans From Savings"), - ACCOUNTING_RUNNING_BALANCE_UPDATE("Update Accounting Running Balances"), - PAY_DUE_SAVINGS_CHARGES("Pay Due Savings Charges"), - APPLY_CHARGE_TO_OVERDUE_LOAN_INSTALLMENT("Apply penalty to overdue loans"), - EXECUTE_STANDING_INSTRUCTIONS("Execute Standing Instruction"), - ADD_ACCRUAL_ENTRIES("Add Accrual Transactions"), - UPDATE_NPA("Update Non Performing Assets"), - UPDATE_DEPOSITS_ACCOUNT_MATURITY_DETAILS("Update Deposit Accounts Maturity details"), - TRANSFER_INTEREST_TO_SAVINGS("Transfer Interest To Savings"), - ADD_PERIODIC_ACCRUAL_ENTRIES("Add Periodic Accrual Transactions"), - RECALCULATE_INTEREST_FOR_LOAN("Recalculate Interest For Loans"), - GENERATE_RD_SCEHDULE("Generate Mandatory Savings Schedule"), - GENERATE_LOANLOSS_PROVISIONING("Generate Loan Loss Provisioning"), - POST_DIVIDENTS_FOR_SHARES("Post Dividends For Shares"), - UPDATE_SAVINGS_DORMANT_ACCOUNTS("Update Savings Dormant Accounts"), - ADD_PERIODIC_ACCRUAL_ENTRIES_FOR_LOANS_WITH_INCOME_POSTED_AS_TRANSACTIONS("Add Accrual Transactions For Loans With Income Posted As Transactions"), - EXECUTE_REPORT_MAILING_JOBS("Execute Report Mailing Jobs"), - UPDATE_SMS_OUTBOUND_WITH_CAMPAIGN_MESSAGE("Update SMS Outbound with Campaign Message"), - SEND_MESSAGES_TO_SMS_GATEWAY("Send Messages to SMS Gateway"), - GET_DELIVERY_REPORTS_FROM_SMS_GATEWAY("Get Delivery Reports from SMS Gateway"), - GENERATE_ADHOCCLIENT_SCEHDULE("Generate AdhocClient Schedule"), - UPDATE_EMAIL_OUTBOUND_WITH_CAMPAIGN_MESSAGE("Update Email Outbound with campaign message"), - EXECUTE_EMAIL("Execute Email"), - UPDATE_TRAIL_BALANCE_DETAILS("Update Trial Balance Details"); + UPDATE_LOAN_SUMMARY("Update loan Summary"), UPDATE_LOAN_ARREARS_AGEING("Update Loan Arrears Ageing"), UPDATE_LOAN_PAID_IN_ADVANCE( + "Update Loan Paid In Advance"), APPLY_ANNUAL_FEE_FOR_SAVINGS("Apply Annual Fee For Savings"), APPLY_HOLIDAYS_TO_LOANS( + "Apply Holidays To Loans"), POST_INTEREST_FOR_SAVINGS("Post Interest For Savings"), TRANSFER_FEE_CHARGE_FOR_LOANS( + "Transfer Fee For Loans From Savings"), ACCOUNTING_RUNNING_BALANCE_UPDATE( + "Update Accounting Running Balances"), PAY_DUE_SAVINGS_CHARGES( + "Pay Due Savings Charges"), APPLY_CHARGE_TO_OVERDUE_LOAN_INSTALLMENT( + "Apply penalty to overdue loans"), EXECUTE_STANDING_INSTRUCTIONS( + "Execute Standing Instruction"), ADD_ACCRUAL_ENTRIES( + "Add Accrual Transactions"), UPDATE_NPA( + "Update Non Performing Assets"), UPDATE_DEPOSITS_ACCOUNT_MATURITY_DETAILS( + "Update Deposit Accounts Maturity details"), TRANSFER_INTEREST_TO_SAVINGS( + "Transfer Interest To Savings"), ADD_PERIODIC_ACCRUAL_ENTRIES( + "Add Periodic Accrual Transactions"), RECALCULATE_INTEREST_FOR_LOAN( + "Recalculate Interest For Loans"), GENERATE_RD_SCEHDULE( + "Generate Mandatory Savings Schedule"), GENERATE_LOANLOSS_PROVISIONING( + "Generate Loan Loss Provisioning"), POST_DIVIDENTS_FOR_SHARES( + "Post Dividends For Shares"), UPDATE_SAVINGS_DORMANT_ACCOUNTS( + "Update Savings Dormant Accounts"), ADD_PERIODIC_ACCRUAL_ENTRIES_FOR_LOANS_WITH_INCOME_POSTED_AS_TRANSACTIONS( + "Add Accrual Transactions For Loans With Income Posted As Transactions"), EXECUTE_REPORT_MAILING_JOBS( + "Execute Report Mailing Jobs"), UPDATE_SMS_OUTBOUND_WITH_CAMPAIGN_MESSAGE( + "Update SMS Outbound with Campaign Message"), SEND_MESSAGES_TO_SMS_GATEWAY( + "Send Messages to SMS Gateway"), GET_DELIVERY_REPORTS_FROM_SMS_GATEWAY( + "Get Delivery Reports from SMS Gateway"), GENERATE_ADHOCCLIENT_SCEHDULE( + "Generate AdhocClient Schedule"), UPDATE_EMAIL_OUTBOUND_WITH_CAMPAIGN_MESSAGE( + "Update Email Outbound with campaign message"), EXECUTE_EMAIL( + "Execute Email"), UPDATE_TRAIL_BALANCE_DETAILS( + "Update Trial Balance Details"); private final String name; @@ -61,4 +58,4 @@ public enum JobName { public String toString() { return this.name; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/JobRegisterServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/JobRegisterServiceImpl.java index f4002ad2c..8325253e3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/JobRegisterServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/JobRegisterServiceImpl.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.infrastructure.jobs.service; - import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; @@ -115,8 +114,8 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi } @Autowired - public void setJobParameterRepository(JobParameterRepository jobParameterRepository){ - this.jobParameterRepository=jobParameterRepository; + public void setJobParameterRepository(JobParameterRepository jobParameterRepository) { + this.jobParameterRepository = jobParameterRepository; } @PostConstruct @@ -348,9 +347,11 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi private JobDetail createJobDetail(final ScheduledJobDetail scheduledJobDetail) throws Exception { final FineractPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); final ClassMethodNamesPair jobDetails = CronMethodParser.findTargetMethodDetails(scheduledJobDetail.getJobName()); - if (jobDetails == null) { throw new IllegalArgumentException( - "Code has no @CronTarget with this job name (@see JobName); seems like DB/code are not in line: " - + scheduledJobDetail.getJobName()); } + if (jobDetails == null) { + throw new IllegalArgumentException( + "Code has no @CronTarget with this job name (@see JobName); seems like DB/code are not in line: " + + scheduledJobDetail.getJobName()); + } final Object targetObject = getBeanObject(Class.forName(jobDetails.className)); final MethodInvokingJobDetailFactoryBean jobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean(); jobDetailFactoryBean.setName(scheduledJobDetail.getJobName() + "JobDetail" + tenant.getId()); @@ -362,14 +363,15 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi return jobDetailFactoryBean.getObject(); } - public Map getJobParameter(ScheduledJobDetail scheduledJobDetail){ - List jobParameterList= jobParameterRepository.findJobParametersByJobId(scheduledJobDetail.getId()); - Map jobParameterMap=new HashMap<>(); - for (JobParameter jobparameter:jobParameterList) { - jobParameterMap.put(jobparameter.getParameterName(),jobparameter.getParameterValue()); + public Map getJobParameter(ScheduledJobDetail scheduledJobDetail) { + List jobParameterList = jobParameterRepository.findJobParametersByJobId(scheduledJobDetail.getId()); + Map jobParameterMap = new HashMap<>(); + for (JobParameter jobparameter : jobParameterList) { + jobParameterMap.put(jobparameter.getParameterName(), jobparameter.getParameterValue()); } - return jobParameterMap; + return jobParameterMap; } + private Object getBeanObject(final Class classType) throws ClassNotFoundException { final List> typesList = new ArrayList<>(); final Class[] interfaceType = classType.getInterfaces(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedularWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedularWritePlatformServiceJpaRepositoryImpl.java index 4a9ee4cfa..37574dfcf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedularWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedularWritePlatformServiceJpaRepositoryImpl.java @@ -134,8 +134,8 @@ public class SchedularWritePlatformServiceJpaRepositoryImpl implements Schedular public boolean processJobDetailForExecution(final String jobKey, final String triggerType) { boolean isStopExecution = false; final ScheduledJobDetail scheduledJobDetail = this.scheduledJobDetailsRepository.findByJobKeyWithLock(jobKey); - if (scheduledJobDetail.isCurrentlyRunning() - || (triggerType.equals(SchedulerServiceConstants.TRIGGER_TYPE_CRON) && scheduledJobDetail.getNextRunTime().after(new Date()))) { + if (scheduledJobDetail.isCurrentlyRunning() || (triggerType.equals(SchedulerServiceConstants.TRIGGER_TYPE_CRON) + && scheduledJobDetail.getNextRunTime().after(new Date()))) { isStopExecution = true; } final SchedulerDetail schedulerDetail = retriveSchedulerDetail(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerJobListener.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerJobListener.java index 80b04bcef..5b13c55d7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerJobListener.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerJobListener.java @@ -51,15 +51,14 @@ public class SchedulerJobListener implements JobListener { private final SchedularWritePlatformService schedularService; - private final AppUserRepositoryWrapper userRepository ; + private final AppUserRepositoryWrapper userRepository; private final GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper(); @Autowired - public SchedulerJobListener(final SchedularWritePlatformService schedularService, - final AppUserRepositoryWrapper userRepository) { + public SchedulerJobListener(final SchedularWritePlatformService schedularService, final AppUserRepositoryWrapper userRepository) { this.schedularService = schedularService; - this.userRepository = userRepository ; + this.userRepository = userRepository; } @Override @@ -127,11 +126,10 @@ public class SchedulerJobListener implements JobListener { } private Throwable getCauseFromException(final Throwable exception) { - if (this.stackTraceLevel <= SchedulerServiceConstants.STACK_TRACE_LEVEL - && exception.getCause() != null + if (this.stackTraceLevel <= SchedulerServiceConstants.STACK_TRACE_LEVEL && exception.getCause() != null && (exception.getCause().toString().contains(SchedulerServiceConstants.SCHEDULER_EXCEPTION) - || exception.getCause().toString().contains(SchedulerServiceConstants.JOB_EXECUTION_EXCEPTION) || exception - .getCause().toString().contains(SchedulerServiceConstants.JOB_METHOD_INVOCATION_FAILED_EXCEPTION))) { + || exception.getCause().toString().contains(SchedulerServiceConstants.JOB_EXECUTION_EXCEPTION) + || exception.getCause().toString().contains(SchedulerServiceConstants.JOB_METHOD_INVOCATION_FAILED_EXCEPTION))) { this.stackTraceLevel++; return getCauseFromException(exception.getCause()); } else if (exception.getCause() != null) { return exception.getCause(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerJobRunnerReadServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerJobRunnerReadServiceImpl.java old mode 100755 new mode 100644 index 7825b681a..d8b549c0f --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerJobRunnerReadServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerJobRunnerReadServiceImpl.java @@ -46,8 +46,7 @@ public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerRead private final PaginationHelper paginationHelper = new PaginationHelper<>(); @Autowired - public SchedulerJobRunnerReadServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + public SchedulerJobRunnerReadServiceImpl(final RoutingDataSource dataSource, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.columnValidator = columnValidator; } @@ -115,14 +114,14 @@ public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerRead private boolean isJobExist(final Long jobId) { boolean isJobPresent = false; - try{ + try { final String sql = "select count(*) from job job where job.id= ?"; final int count = this.jdbcTemplate.queryForObject(sql, Integer.class, new Object[] { jobId }); if (count == 1) { isJobPresent = true; } return isJobPresent; - }catch(EmptyResultDataAccessException e){ + } catch (EmptyResultDataAccessException e) { return isJobPresent; } @@ -130,8 +129,8 @@ public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerRead private static final class JobDetailMapper implements RowMapper { - private final StringBuilder sqlBuilder = new StringBuilder("select") - .append(" job.id,job.display_name as displayName,job.next_run_time as nextRunTime,job.initializing_errorlog as initializingError,job.cron_expression as cronExpression,job.is_active as active,job.currently_running as currentlyRunning,") + private final StringBuilder sqlBuilder = new StringBuilder("select").append( + " job.id,job.display_name as displayName,job.next_run_time as nextRunTime,job.initializing_errorlog as initializingError,job.cron_expression as cronExpression,job.is_active as active,job.currently_running as currentlyRunning,") .append(" runHistory.version,runHistory.start_time as lastRunStartTime,runHistory.end_time as lastRunEndTime,runHistory.`status`,runHistory.error_message as jobRunErrorMessage,runHistory.trigger_type as triggerType,runHistory.error_log as jobRunErrorLog ") .append(" from job job left join job_run_history runHistory ON job.id=runHistory.job_id and job.previous_run_start_time=runHistory.start_time "); @@ -171,8 +170,8 @@ public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerRead private static final class JobHistoryMapper implements RowMapper { - private final StringBuilder sqlBuilder = new StringBuilder(200) - .append(" runHistory.version,runHistory.start_time as runStartTime,runHistory.end_time as runEndTime,runHistory.`status`,runHistory.error_message as jobRunErrorMessage,runHistory.trigger_type as triggerType,runHistory.error_log as jobRunErrorLog ") + private final StringBuilder sqlBuilder = new StringBuilder(200).append( + " runHistory.version,runHistory.start_time as runStartTime,runHistory.end_time as runEndTime,runHistory.`status`,runHistory.error_message as jobRunErrorMessage,runHistory.trigger_type as triggerType,runHistory.error_log as jobRunErrorLog ") .append(" from job job join job_run_history runHistory ON job.id=runHistory.job_id"); public String schema() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerServiceConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerServiceConstants.java index ddc0b0fa0..4bd5b80f7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerServiceConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerServiceConstants.java @@ -38,4 +38,4 @@ public interface SchedulerServiceConstants { public static final int GROUP_THREAD_COUNT = 1; public static final String SCHEDULER_NAME = "schedulerName"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerTriggerListener.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerTriggerListener.java old mode 100755 new mode 100644 index 5d9177d45..bf8f3860b --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerTriggerListener.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/jobs/service/SchedulerTriggerListener.java @@ -76,7 +76,8 @@ public class SchedulerTriggerListener implements TriggerListener { try { vetoJob = this.schedularService.processJobDetailForExecution(jobKey, triggerType); numberOfRetries = maxNumberOfRetries + 1; - } catch (Exception exception) { // Adding generic exception as it depends on JPA provider + } catch (Exception exception) { // Adding generic exception as it + // depends on JPA provider LOG.warn("vetoJobExecution() not able to acquire the lock to update job running status at retry {} (of {}) for JobKey: {}", numberOfRetries, maxNumberOfRetries, jobKey, exception); try { @@ -90,8 +91,9 @@ public class SchedulerTriggerListener implements TriggerListener { } } if (vetoJob) { - LOG.warn("vetoJobExecution() WILL veto the execution (returning vetoJob == true; the job's execute method will NOT be called); " - + "maxNumberOfRetries={}, tenant={}, jobKey={}, triggerType={}, trigger={}, context={}", + LOG.warn( + "vetoJobExecution() WILL veto the execution (returning vetoJob == true; the job's execute method will NOT be called); " + + "maxNumberOfRetries={}, tenant={}, jobKey={}, triggerType={}, trigger={}, context={}", maxNumberOfRetries, tenantIdentifier, jobKey, triggerType, trigger, context); } return vetoJob; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/openjpa/OpenJpaDialect.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/openjpa/OpenJpaDialect.java index 9a0d92907..db5a4328d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/openjpa/OpenJpaDialect.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/openjpa/OpenJpaDialect.java @@ -37,8 +37,8 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; /** - * {@link org.springframework.orm.jpa.JpaDialect} implementation for Apache OpenJPA. - * Developed and tested against OpenJPA 2.2. + * {@link org.springframework.orm.jpa.JpaDialect} implementation for Apache + * OpenJPA. Developed and tested against OpenJPA 2.2. * * @author Costin Leau * @author Juergen Hoeller @@ -53,7 +53,8 @@ public class OpenJpaDialect extends DefaultJpaDialect { OpenJPAEntityManager openJpaEntityManager = getOpenJPAEntityManager(entityManager); if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { - // Pass custom isolation level on to OpenJPA's JDBCFetchPlan configuration + // Pass custom isolation level on to OpenJPA's JDBCFetchPlan + // configuration FetchPlan fetchPlan = openJpaEntityManager.getFetchPlan(); if (fetchPlan instanceof JDBCFetchPlan) { IsolationLevel isolation = IsolationLevel.fromConnectionConstant(definition.getIsolationLevel()); @@ -64,8 +65,10 @@ public class OpenJpaDialect extends DefaultJpaDialect { entityManager.getTransaction().begin(); if (!definition.isReadOnly()) { - // Like with EclipseLink, make sure to start the logic transaction early so that other - // participants using the connection (such as JdbcTemplate) run in a transaction. + // Like with EclipseLink, make sure to start the logic transaction + // early so that other + // participants using the connection (such as JdbcTemplate) run in a + // transaction. openJpaEntityManager.beginStore(); } @@ -74,22 +77,22 @@ public class OpenJpaDialect extends DefaultJpaDialect { } @Override - public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly) - throws PersistenceException, SQLException { + public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly) throws PersistenceException, SQLException { return new OpenJpaConnectionHandle(getOpenJPAEntityManager(entityManager)); } /** * Return the OpenJPA-specific variant of {@code EntityManager}. - * @param em the generic {@code EntityManager} instance + * + * @param em + * the generic {@code EntityManager} instance * @return the OpenJPA-specific variant of {@code EntityManager} */ protected OpenJPAEntityManager getOpenJPAEntityManager(EntityManager em) { return OpenJPAPersistence.cast(em); } - /** * Transaction data Object exposed from {@code beginTransaction}, * implementing the {@link SavepointManager} interface. @@ -121,20 +124,19 @@ public class OpenJpaDialect extends DefaultJpaDialect { public void releaseSavepoint(Object savepoint) throws TransactionException { try { this.entityManager.releaseSavepoint((String) savepoint); - } - catch (Throwable ex) { - LogFactory.getLog(OpenJpaTransactionData.class).debug( - "Could not explicitly release OpenJPA savepoint", ex); + } catch (Throwable ex) { + LogFactory.getLog(OpenJpaTransactionData.class).debug("Could not explicitly release OpenJPA savepoint", ex); } } } - /** - * {@link ConnectionHandle} implementation that fetches a new OpenJPA-provided - * Connection for every {@code getConnection} call and closes the Connection on - * {@code releaseConnection}. This is necessary because OpenJPA requires the - * fetched Connection to be closed before continuing EntityManager work. + * {@link ConnectionHandle} implementation that fetches a new + * OpenJPA-provided Connection for every {@code getConnection} call and + * closes the Connection on {@code releaseConnection}. This is necessary + * because OpenJPA requires the fetched Connection to be closed before + * continuing EntityManager work. + * * @see org.apache.openjpa.persistence.OpenJPAEntityManager#getConnection() */ private static class OpenJpaConnectionHandle implements ConnectionHandle { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/openjpa/OpenJpaVendorAdapter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/openjpa/OpenJpaVendorAdapter.java index 015fc28df..02d4f9b7d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/openjpa/OpenJpaVendorAdapter.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/openjpa/OpenJpaVendorAdapter.java @@ -30,11 +30,13 @@ import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter; import org.springframework.orm.jpa.vendor.Database; /** - * {@link org.springframework.orm.jpa.JpaVendorAdapter} implementation for Apache OpenJPA. - * Developed and tested against OpenJPA 2.2. + * {@link org.springframework.orm.jpa.JpaVendorAdapter} implementation for + * Apache OpenJPA. Developed and tested against OpenJPA 2.2. * - *

Exposes OpenJPA's persistence provider and EntityManager extension interface, - * and supports {@link AbstractJpaVendorAdapter}'s common configuration settings. + *

+ * Exposes OpenJPA's persistence provider and EntityManager extension interface, + * and supports {@link AbstractJpaVendorAdapter}'s common configuration + * settings. * * @author Costin Leau * @author Juergen Hoeller @@ -48,7 +50,6 @@ public class OpenJpaVendorAdapter extends AbstractJpaVendorAdapter { private final OpenJpaDialect jpaDialect = new OpenJpaDialect(); - @Override public PersistenceProvider getPersistenceProvider() { return this.persistenceProvider; @@ -65,8 +66,7 @@ public class OpenJpaVendorAdapter extends AbstractJpaVendorAdapter { if (getDatabasePlatform() != null) { jpaProperties.put("openjpa.jdbc.DBDictionary", getDatabasePlatform()); - } - else if (getDatabase() != null) { + } else if (getDatabase() != null) { String databaseDictonary = determineDatabaseDictionary(getDatabase()); if (databaseDictonary != null) { jpaProperties.put("openjpa.jdbc.DBDictionary", databaseDictonary); @@ -77,7 +77,8 @@ public class OpenJpaVendorAdapter extends AbstractJpaVendorAdapter { jpaProperties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)"); } if (isShowSql()) { - // Taken from the OpenJPA 0.9.6 docs ("Standard OpenJPA Log Configuration + All SQL Statements") + // Taken from the OpenJPA 0.9.6 docs ("Standard OpenJPA Log + // Configuration + All SQL Statements") jpaProperties.put("openjpa.Log", "DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"); } @@ -86,21 +87,34 @@ public class OpenJpaVendorAdapter extends AbstractJpaVendorAdapter { /** * Determine the OpenJPA database dictionary name for the given database. - * @param database the specified database - * @return the OpenJPA database dictionary name, or {@code null} if none found + * + * @param database + * the specified database + * @return the OpenJPA database dictionary name, or {@code null} if none + * found */ protected String determineDatabaseDictionary(Database database) { switch (database) { - case DB2: return "db2"; - case DERBY: return "derby"; - case HSQL: return "hsql(SimulateLocking=true)"; - case INFORMIX: return "informix"; - case MYSQL: return "mysql"; - case ORACLE: return "oracle"; - case POSTGRESQL: return "postgres"; - case SQL_SERVER: return "sqlserver"; - case SYBASE: return "sybase"; - default: return null; + case DB2: + return "db2"; + case DERBY: + return "derby"; + case HSQL: + return "hsql(SimulateLocking=true)"; + case INFORMIX: + return "informix"; + case MYSQL: + return "mysql"; + case ORACLE: + return "oracle"; + case POSTGRESQL: + return "postgres"; + case SQL_SERVER: + return "sqlserver"; + case SYBASE: + return "sybase"; + default: + return null; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/annotation/ReportService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/annotation/ReportService.java index e6c2d5420..8c72b1bc4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/annotation/ReportService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/annotation/ReportService.java @@ -33,4 +33,4 @@ public @interface ReportService { * @return the type of the report */ String type(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/provider/ReportingProcessServiceProvider.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/provider/ReportingProcessServiceProvider.java index f151db9b4..ab48706bb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/provider/ReportingProcessServiceProvider.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/provider/ReportingProcessServiceProvider.java @@ -47,8 +47,9 @@ public class ReportingProcessServiceProvider implements ApplicationContextAware } public ReportingProcessService findReportingProcessService(final String reportType) { - if (this.reportingProcessServices.containsKey(reportType)) { return (ReportingProcessService) this.applicationContext - .getBean(this.reportingProcessServices.get(reportType)); } + if (this.reportingProcessServices.containsKey(reportType)) { + return (ReportingProcessService) this.applicationContext.getBean(this.reportingProcessServices.get(reportType)); + } return null; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/service/ReportingProcessService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/service/ReportingProcessService.java index 87c11b4e9..990bd0d91 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/service/ReportingProcessService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/report/service/ReportingProcessService.java @@ -25,4 +25,4 @@ public interface ReportingProcessService { Response processRequest(String reportName, MultivaluedMap queryParams); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/ReportMailingJobConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/ReportMailingJobConstants.java index 738e7eaee..94b9a7bf4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/ReportMailingJobConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/ReportMailingJobConstants.java @@ -64,26 +64,24 @@ public class ReportMailingJobConstants implements Serializable { public static final String STRETCHY_REPORT_PARAM_NAME = "stretchyReport"; // list of permitted parameters for the create report mailing job request - public static final Set CREATE_REQUEST_PARAMETERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(LOCALE_PARAM_NAME, DATE_FORMAT_PARAM_NAME, - NAME_PARAM_NAME, DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, EMAIL_RECIPIENTS_PARAM_NAME, EMAIL_SUBJECT_PARAM_NAME, - EMAIL_MESSAGE_PARAM_NAME, EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, STRETCHY_REPORT_ID_PARAM_NAME, + public static final Set CREATE_REQUEST_PARAMETERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(LOCALE_PARAM_NAME, + DATE_FORMAT_PARAM_NAME, NAME_PARAM_NAME, DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, EMAIL_RECIPIENTS_PARAM_NAME, + EMAIL_SUBJECT_PARAM_NAME, EMAIL_MESSAGE_PARAM_NAME, EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, STRETCHY_REPORT_ID_PARAM_NAME, STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, IS_ACTIVE_PARAM_NAME, START_DATE_TIME_PARAM_NAME))); // list of permitted parameters for the update report mailing job request - public static final Set UPDATE_REQUEST_PARAMETERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(LOCALE_PARAM_NAME, DATE_FORMAT_PARAM_NAME, - NAME_PARAM_NAME, DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, EMAIL_RECIPIENTS_PARAM_NAME, EMAIL_SUBJECT_PARAM_NAME, - EMAIL_MESSAGE_PARAM_NAME, EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, STRETCHY_REPORT_ID_PARAM_NAME, + public static final Set UPDATE_REQUEST_PARAMETERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(LOCALE_PARAM_NAME, + DATE_FORMAT_PARAM_NAME, NAME_PARAM_NAME, DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, EMAIL_RECIPIENTS_PARAM_NAME, + EMAIL_SUBJECT_PARAM_NAME, EMAIL_MESSAGE_PARAM_NAME, EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, STRETCHY_REPORT_ID_PARAM_NAME, STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, IS_ACTIVE_PARAM_NAME, START_DATE_TIME_PARAM_NAME))); // list of parameters that represent the properties of a report mailing job - public static final Set REPORT_MAILING_JOB_DATA_PARAMETERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(ID_PARAM_NAME, NAME_PARAM_NAME, - DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, EMAIL_RECIPIENTS_PARAM_NAME, EMAIL_SUBJECT_PARAM_NAME, EMAIL_MESSAGE_PARAM_NAME, - EMAIL_ATTACHMENT_FILE_FORMAT_PARAM_NAME, STRETCHY_REPORT_PARAM_NAME, STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, IS_ACTIVE_PARAM_NAME, - START_DATE_TIME_PARAM_NAME, PREVIOUS_RUN_DATE_TIME_PARAM_NAME, NEXT_RUN_DATE_TIME_PARAM_NAME, PREVIOUS_RUN_STATUS, - PREVIOUS_RUN_ERROR_LOG, PREVIOUS_RUN_ERROR_MESSAGE, NUMBER_OF_RUNS))); + public static final Set REPORT_MAILING_JOB_DATA_PARAMETERS = Collections + .unmodifiableSet(new HashSet<>(Arrays.asList(ID_PARAM_NAME, NAME_PARAM_NAME, DESCRIPTION_PARAM_NAME, RECURRENCE_PARAM_NAME, + EMAIL_RECIPIENTS_PARAM_NAME, EMAIL_SUBJECT_PARAM_NAME, EMAIL_MESSAGE_PARAM_NAME, + EMAIL_ATTACHMENT_FILE_FORMAT_PARAM_NAME, STRETCHY_REPORT_PARAM_NAME, STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, + IS_ACTIVE_PARAM_NAME, START_DATE_TIME_PARAM_NAME, PREVIOUS_RUN_DATE_TIME_PARAM_NAME, NEXT_RUN_DATE_TIME_PARAM_NAME, + PREVIOUS_RUN_STATUS, PREVIOUS_RUN_ERROR_LOG, PREVIOUS_RUN_ERROR_MESSAGE, NUMBER_OF_RUNS))); // report mailing job configuration names public static final String GMAIL_SMTP_SERVER = "GMAIL_SMTP_SERVER"; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobApiResource.java index 99582d9a6..076fc65e8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobApiResource.java @@ -59,10 +59,9 @@ import org.springframework.stereotype.Component; @Path("/" + ReportMailingJobConstants.REPORT_MAILING_JOB_RESOURCE_NAME) @Component @Scope("singleton") -@Api(tags = {"Report Mailing Jobs"}) +@Api(tags = { "Report Mailing Jobs" }) @SwaggerDefinition(tags = { - @Tag(name = "Report Mailing Jobs", description = "This resource allows you to create a scheduled job that runs a report and sents it by email to specified email addresses.\n\nThe scheduled job can be configured to run once or on a regular basis (once a day, twice a week, etc)") -}) + @Tag(name = "Report Mailing Jobs", description = "This resource allows you to create a scheduled job that runs a report and sents it by email to specified email addresses.\n\nThe scheduled job can be configured to run once or on a regular basis (once a day, twice a week, etc)") }) public class ReportMailingJobApiResource { private final PlatformSecurityContext platformSecurityContext; @@ -87,13 +86,16 @@ public class ReportMailingJobApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Report Mailing Job", notes = "Mandatory Fields: " + "name, startDateTime, stretchyReportId, emailRecipients, emailSubject, emailMessage, emailAttachmentFileFormatId, recurrence, isActive\n" + "\n" + "Optional Fields: " + "description, stretchyReportParamMap") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ReportMailingJobApiResourceSwagger.PostReportMailingJobsRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.PostReportMailingJobsResponse.class)}) + @ApiOperation(value = "Create a Report Mailing Job", notes = "Mandatory Fields: " + + "name, startDateTime, stretchyReportId, emailRecipients, emailSubject, emailMessage, emailAttachmentFileFormatId, recurrence, isActive\n" + + "\n" + "Optional Fields: " + "description, stretchyReportParamMap") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ReportMailingJobApiResourceSwagger.PostReportMailingJobsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.PostReportMailingJobsResponse.class) }) public String createReportMailingJob(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandWrapper = new CommandWrapperBuilder(). - createReportMailingJob(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME). - withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandWrapper = new CommandWrapperBuilder() + .createReportMailingJob(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME).withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandWrapper); @@ -105,12 +107,15 @@ public class ReportMailingJobApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Report Mailing Job\n", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ReportMailingJobApiResourceSwagger.PutReportMailingJobsRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.PutReportMailingJobsResponse.class)}) - public String updateReportMailingJob(@PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandWrapper = new CommandWrapperBuilder(). - updateReportMailingJob(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME, entityId). - withJson(apiRequestBodyAsJson).build(); + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ReportMailingJobApiResourceSwagger.PutReportMailingJobsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.PutReportMailingJobsResponse.class) }) + public String updateReportMailingJob(@PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + final CommandWrapper commandWrapper = new CommandWrapperBuilder() + .updateReportMailingJob(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME, entityId).withJson(apiRequestBodyAsJson) + .build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandWrapper); @@ -122,12 +127,15 @@ public class ReportMailingJobApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Report Mailing Job", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ReportMailingJobApiResourceSwagger.DeleteReportMailingJobsRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.DeleteReportMailingJobsResponse.class)}) - public String deleteReportMailingJob(@PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandWrapper = new CommandWrapperBuilder(). - deleteReportMailingJob(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME, entityId). - withJson(apiRequestBodyAsJson).build(); + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ReportMailingJobApiResourceSwagger.DeleteReportMailingJobsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.DeleteReportMailingJobsResponse.class) }) + public String deleteReportMailingJob(@PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + final CommandWrapper commandWrapper = new CommandWrapperBuilder() + .deleteReportMailingJob(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME, entityId).withJson(apiRequestBodyAsJson) + .build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandWrapper); @@ -138,52 +146,68 @@ public class ReportMailingJobApiResource { @Path("{entityId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Report Mailing Job", notes = "Example Requests:\n" + "\n" + "reportmailingjobs/1\n" + "\n" + "\n" + "reportmailingjobs/1?template=true") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.GetReportMailingJobsResponse.class)}) - public String retrieveReportMailingJob(@PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, @Context final UriInfo uriInfo) { - this.platformSecurityContext.authenticatedUser().validateHasReadPermission(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME); + @ApiOperation(value = "Retrieve a Report Mailing Job", notes = "Example Requests:\n" + "\n" + "reportmailingjobs/1\n" + "\n" + "\n" + + "reportmailingjobs/1?template=true") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.GetReportMailingJobsResponse.class) }) + public String retrieveReportMailingJob(@PathParam("entityId") @ApiParam(value = "entityId") final Long entityId, + @Context final UriInfo uriInfo) { + this.platformSecurityContext.authenticatedUser() + .validateHasReadPermission(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); ReportMailingJobData reportMailingJobData = this.reportMailingJobReadPlatformService.retrieveReportMailingJob(entityId); if (settings.isTemplate()) { - final ReportMailingJobData ReportMailingJobDataOptions = this.reportMailingJobReadPlatformService.retrieveReportMailingJobEnumOptions(); + final ReportMailingJobData ReportMailingJobDataOptions = this.reportMailingJobReadPlatformService + .retrieveReportMailingJobEnumOptions(); reportMailingJobData = ReportMailingJobData.newInstance(reportMailingJobData, ReportMailingJobDataOptions); } - return this.reportMailingToApiJsonSerializer.serialize(settings, reportMailingJobData, ReportMailingJobConstants.REPORT_MAILING_JOB_DATA_PARAMETERS); + return this.reportMailingToApiJsonSerializer.serialize(settings, reportMailingJobData, + ReportMailingJobConstants.REPORT_MAILING_JOB_DATA_PARAMETERS); } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Report Mailing Job Details Template", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for report mailing job applications. The template data returned consists of any or all of:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "reportmailingjobs/template") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.GetReportMailingJobsTemplate.class)}) + @ApiOperation(value = "Retrieve Report Mailing Job Details Template", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for report mailing job applications. The template data returned consists of any or all of:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "reportmailingjobs/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.GetReportMailingJobsTemplate.class) }) public String retrieveReportMailingJobTemplate(@Context final UriInfo uriInfo) { - this.platformSecurityContext.authenticatedUser().validateHasReadPermission(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME); + this.platformSecurityContext.authenticatedUser() + .validateHasReadPermission(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - final ReportMailingJobData ReportMailingJobDataOptions = this.reportMailingJobReadPlatformService.retrieveReportMailingJobEnumOptions(); + final ReportMailingJobData ReportMailingJobDataOptions = this.reportMailingJobReadPlatformService + .retrieveReportMailingJobEnumOptions(); - return this.reportMailingToApiJsonSerializer.serialize(settings, ReportMailingJobDataOptions, ReportMailingJobConstants.REPORT_MAILING_JOB_DATA_PARAMETERS); + return this.reportMailingToApiJsonSerializer.serialize(settings, ReportMailingJobDataOptions, + ReportMailingJobConstants.REPORT_MAILING_JOB_DATA_PARAMETERS); } @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "List Report Mailing Jobs", notes = "Example Requests:\n" + "\n" + "reportmailingjobs") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.GetReportMailingJobsResponse.class, responseContainer = "list")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ReportMailingJobApiResourceSwagger.GetReportMailingJobsResponse.class, responseContainer = "list") }) public String retrieveAllReportMailingJobs(@Context final UriInfo uriInfo, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, - @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { - this.platformSecurityContext.authenticatedUser().validateHasReadPermission(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME); + this.platformSecurityContext.authenticatedUser() + .validateHasReadPermission(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final SearchParameters searchParameters = SearchParameters.fromReportMailingJob(offset, limit, orderBy, sortOrder); - final Page reportMailingJobData = this.reportMailingJobReadPlatformService.retrieveAllReportMailingJobs(searchParameters); + final Page reportMailingJobData = this.reportMailingJobReadPlatformService + .retrieveAllReportMailingJobs(searchParameters); - return this.reportMailingToApiJsonSerializer.serialize(settings, reportMailingJobData, ReportMailingJobConstants.REPORT_MAILING_JOB_DATA_PARAMETERS); + return this.reportMailingToApiJsonSerializer.serialize(settings, reportMailingJobData, + ReportMailingJobConstants.REPORT_MAILING_JOB_DATA_PARAMETERS); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobApiResourceSwagger.java index 9d8e5229b..65791f0ec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobApiResourceSwagger.java @@ -30,15 +30,18 @@ import org.joda.time.DateTime; * Created by sanyam on 13/8/17. */ final class ReportMailingJobApiResourceSwagger { - private ReportMailingJobApiResourceSwagger(){ + + private ReportMailingJobApiResourceSwagger() { } @ApiModel(value = "GetReportMailingJobsTemplate") public static final class GetReportMailingJobsTemplate { - private GetReportMailingJobsTemplate(){ + + private GetReportMailingJobsTemplate() { } + @ApiModelProperty(example = "true") public boolean isActive; public List emailAttachmentFileFormatOptions; @@ -47,9 +50,11 @@ final class ReportMailingJobApiResourceSwagger { @ApiModel(value = "GetReportMailingJobsResponse") public static final class GetReportMailingJobsResponse { - private GetReportMailingJobsResponse(){ + + private GetReportMailingJobsResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Client Numbers Report") @@ -85,9 +90,11 @@ final class ReportMailingJobApiResourceSwagger { @ApiModel(value = "PostReportMailingJobsRequest") public static final class PostReportMailingJobsRequest { - private PostReportMailingJobsRequest(){ + + private PostReportMailingJobsRequest() { } + @ApiModelProperty(example = "en_GB") public String locale; @ApiModelProperty(example = "dd-MM-yyyy HH:mm:ss") @@ -117,18 +124,22 @@ final class ReportMailingJobApiResourceSwagger { @ApiModel(value = "PostReportMailingJobsResponse") public static final class PostReportMailingJobsResponse { - private PostReportMailingJobsResponse(){ + + private PostReportMailingJobsResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "PutReportMailingJobsRequest") public static final class PutReportMailingJobsRequest { - private PutReportMailingJobsRequest(){ + + private PutReportMailingJobsRequest() { } + @ApiModelProperty(example = "en_GB") public String locale; @ApiModelProperty(example = "dd-MM-yyyy HH:mm:ss") @@ -139,14 +150,19 @@ final class ReportMailingJobApiResourceSwagger { @ApiModel(value = "PutReportMailingJobsResponse") public static final class PutReportMailingJobsResponse { - private PutReportMailingJobsResponse(){ + + private PutReportMailingJobsResponse() { } - final class PutReportMailingJobsResponseChanges{ - private PutReportMailingJobsResponseChanges(){} + + final class PutReportMailingJobsResponseChanges { + + private PutReportMailingJobsResponseChanges() {} + @ApiModelProperty(example = "10-08-2016 23:30:00") public DateTime startDateTime; } + @ApiModelProperty(example = "1") public Long resourceId; public PutReportMailingJobsResponseChanges changes; @@ -154,16 +170,19 @@ final class ReportMailingJobApiResourceSwagger { @ApiModel(value = "DeleteReportMailingJobsRequest ") public static final class DeleteReportMailingJobsRequest { - private DeleteReportMailingJobsRequest(){ + + private DeleteReportMailingJobsRequest() { } } @ApiModel(value = "DeleteReportMailingJobsResponse") public static final class DeleteReportMailingJobsResponse { - private DeleteReportMailingJobsResponse(){ + + private DeleteReportMailingJobsResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobRunHistoryApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobRunHistoryApiResource.java index f216275d4..7bd2e5a41 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobRunHistoryApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobRunHistoryApiResource.java @@ -47,10 +47,8 @@ import org.springframework.stereotype.Component; @Path("/" + ReportMailingJobConstants.REPORT_MAILING_JOB_RUN_HISTORY_RESOURCE_NAME) @Component -@Api(tags = {"List Report Mailing Job History"}) -@SwaggerDefinition(tags = { - @Tag(name = "List Report Mailing Job History", description = "") -}) +@Api(tags = { "List Report Mailing Job History" }) +@SwaggerDefinition(tags = { @Tag(name = "List Report Mailing Job History", description = "") }) public class ReportMailingJobRunHistoryApiResource { private final PlatformSecurityContext platformSecurityContext; @@ -72,19 +70,21 @@ public class ReportMailingJobRunHistoryApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Report Mailing Job History", notes = "The list capability of report mailing job history can support pagination and sorting.\n" + "\n" + "Example Requests:\n" + "\n" + "reportmailingjobrunhistory/1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ReportMailingJobRunHistoryData.class)}) + @ApiOperation(value = "List Report Mailing Job History", notes = "The list capability of report mailing job history can support pagination and sorting.\n" + + "\n" + "Example Requests:\n" + "\n" + "reportmailingjobrunhistory/1") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = ReportMailingJobRunHistoryData.class) }) public String retrieveAllByReportMailingJobId(@Context final UriInfo uriInfo, - @QueryParam("reportMailingJobId") @ApiParam(value = "reportMailingJobId") final Long reportMailingJobId, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, - @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, - @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { - this.platformSecurityContext.authenticatedUser().validateHasReadPermission(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME); + @QueryParam("reportMailingJobId") @ApiParam(value = "reportMailingJobId") final Long reportMailingJobId, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { + this.platformSecurityContext.authenticatedUser() + .validateHasReadPermission(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME); final SearchParameters searchParameters = SearchParameters.fromReportMailingJobRunHistory(offset, limit, orderBy, sortOrder); - final Page reportMailingJobRunHistoryData = this.reportMailingJobRunHistoryReadPlatformService. - retrieveRunHistoryByJobId(reportMailingJobId, searchParameters); + final Page reportMailingJobRunHistoryData = this.reportMailingJobRunHistoryReadPlatformService + .retrieveRunHistoryByJobId(reportMailingJobId, searchParameters); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.reportMailingToApiJsonSerializer.serialize(settings, reportMailingJobRunHistoryData); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobRunHistoryApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobRunHistoryApiResourceSwagger.java index c9c7f9792..3e0ce9845 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobRunHistoryApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/api/ReportMailingJobRunHistoryApiResourceSwagger.java @@ -26,15 +26,18 @@ import org.joda.time.DateTime; * Created by sanyam on 13/8/17. */ final class ReportMailingJobRunHistoryApiResourceSwagger { - private ReportMailingJobRunHistoryApiResourceSwagger(){ + + private ReportMailingJobRunHistoryApiResourceSwagger() { } @ApiModel(value = "GetReportMailingJobRunHistoryResponse") public static final class GetReportMailingJobRunHistoryResponse { - private GetReportMailingJobRunHistoryResponse(){ + + private GetReportMailingJobRunHistoryResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "1") diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobConfigurationData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobConfigurationData.java index 8a6eaa9f4..ecb3d268a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobConfigurationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobConfigurationData.java @@ -22,6 +22,7 @@ package org.apache.fineract.infrastructure.reportmailingjob.data; * Immutable data object representing report mailing job configuration data. **/ public class ReportMailingJobConfigurationData { + private final int id; private final String name; private final String value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobData.java index 794fa5f3e..2b0a7df95 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobData.java @@ -27,6 +27,7 @@ import org.joda.time.DateTime; * Immutable data object representing report mailing job data. **/ public class ReportMailingJobData { + private final Long id; private final String name; private final String description; @@ -52,9 +53,10 @@ public class ReportMailingJobData { private ReportMailingJobData(final Long id, final String name, final String description, final DateTime startDateTime, final String recurrence, final ReportMailingJobTimelineData timeline, final String emailRecipients, final String emailSubject, - final String emailMessage, final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport, final String stretchyReportParamMap, - final DateTime previousRunDateTime, final DateTime nextRunDateTime, final String previousRunStatus, final String previousRunErrorLog, - final String previousRunErrorMessage, final Integer numberOfRuns, final boolean isActive, final List emailAttachmentFileFormatOptions, + final String emailMessage, final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport, + final String stretchyReportParamMap, final DateTime previousRunDateTime, final DateTime nextRunDateTime, + final String previousRunStatus, final String previousRunErrorLog, final String previousRunErrorMessage, + final Integer numberOfRuns, final boolean isActive, final List emailAttachmentFileFormatOptions, final List stretchyReportParamDateOptions, final Long runAsUserId) { this.id = id; this.name = name; @@ -85,9 +87,10 @@ public class ReportMailingJobData { **/ public static ReportMailingJobData newInstance(final Long id, final String name, final String description, final DateTime startDateTime, final String recurrence, final ReportMailingJobTimelineData timeline, final String emailRecipients, final String emailSubject, - final String emailMessage, final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport, final String stretchyReportParamMap, - final DateTime previousRunDateTime, final DateTime nextRunDateTime, final String previousRunStatus, final String previousRunErrorLog, - final String previousRunErrorMessage, final Integer numberOfRuns, final boolean isActive, final Long runAsUserId) { + final String emailMessage, final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport, + final String stretchyReportParamMap, final DateTime previousRunDateTime, final DateTime nextRunDateTime, + final String previousRunStatus, final String previousRunErrorLog, final String previousRunErrorMessage, + final Integer numberOfRuns, final boolean isActive, final Long runAsUserId) { return new ReportMailingJobData(id, name, description, startDateTime, recurrence, timeline, emailRecipients, emailSubject, emailMessage, emailAttachmentFileFormat, stretchyReport, stretchyReportParamMap, previousRunDateTime, nextRunDateTime, previousRunStatus, previousRunErrorLog, previousRunErrorMessage, numberOfRuns, isActive, null, null, runAsUserId); @@ -98,19 +101,22 @@ public class ReportMailingJobData { **/ public static ReportMailingJobData newInstance(final List emailAttachmentFileFormatOptions, final List stretchyReportParamDateOptions) { - return new ReportMailingJobData(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, - null, false, emailAttachmentFileFormatOptions, stretchyReportParamDateOptions, null); + return new ReportMailingJobData(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, + null, null, false, emailAttachmentFileFormatOptions, stretchyReportParamDateOptions, null); } /** * @return an instance of the ReportMailingJobData class **/ - public static ReportMailingJobData newInstance(final ReportMailingJobData dataWithoutEnumOptions, final ReportMailingJobData dataWithEnumOptions) { - return new ReportMailingJobData(dataWithoutEnumOptions.id, dataWithoutEnumOptions.name, dataWithoutEnumOptions.description, dataWithoutEnumOptions.startDateTime, - dataWithoutEnumOptions.recurrence, dataWithoutEnumOptions.timeline, dataWithoutEnumOptions.emailRecipients, dataWithoutEnumOptions.emailSubject, - dataWithoutEnumOptions.emailMessage, dataWithoutEnumOptions.emailAttachmentFileFormat, dataWithoutEnumOptions.stretchyReport, - dataWithoutEnumOptions.stretchyReportParamMap, dataWithoutEnumOptions.previousRunDateTime, dataWithoutEnumOptions.nextRunDateTime, - dataWithoutEnumOptions.previousRunStatus, dataWithoutEnumOptions.previousRunErrorLog, dataWithoutEnumOptions.previousRunErrorMessage, + public static ReportMailingJobData newInstance(final ReportMailingJobData dataWithoutEnumOptions, + final ReportMailingJobData dataWithEnumOptions) { + return new ReportMailingJobData(dataWithoutEnumOptions.id, dataWithoutEnumOptions.name, dataWithoutEnumOptions.description, + dataWithoutEnumOptions.startDateTime, dataWithoutEnumOptions.recurrence, dataWithoutEnumOptions.timeline, + dataWithoutEnumOptions.emailRecipients, dataWithoutEnumOptions.emailSubject, dataWithoutEnumOptions.emailMessage, + dataWithoutEnumOptions.emailAttachmentFileFormat, dataWithoutEnumOptions.stretchyReport, + dataWithoutEnumOptions.stretchyReportParamMap, dataWithoutEnumOptions.previousRunDateTime, + dataWithoutEnumOptions.nextRunDateTime, dataWithoutEnumOptions.previousRunStatus, + dataWithoutEnumOptions.previousRunErrorLog, dataWithoutEnumOptions.previousRunErrorMessage, dataWithoutEnumOptions.numberOfRuns, dataWithoutEnumOptions.isActive, dataWithEnumOptions.emailAttachmentFileFormatOptions, dataWithEnumOptions.stretchyReportParamDateOptions, dataWithoutEnumOptions.runAsUserId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobEmailAttachmentFileFormat.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobEmailAttachmentFileFormat.java index bf28d6a45..2360b8748 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobEmailAttachmentFileFormat.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobEmailAttachmentFileFormat.java @@ -24,10 +24,10 @@ import org.apache.commons.lang3.StringUtils; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public enum ReportMailingJobEmailAttachmentFileFormat { - INVALID(0, "ReportMailingJobEmailAttachmentFileFormat.INVALID", "Invalid"), - XLS(1, "ReportMailingJobEmailAttachmentFileFormat.XLS", "XLS"), - PDF(2, "ReportMailingJobEmailAttachmentFileFormat.PDF", "PDF"), - CSV(3, "ReportMailingJobEmailAttachmentFileFormat.CSV", "CSV"); + + INVALID(0, "ReportMailingJobEmailAttachmentFileFormat.INVALID", "Invalid"), XLS(1, "ReportMailingJobEmailAttachmentFileFormat.XLS", + "XLS"), PDF(2, "ReportMailingJobEmailAttachmentFileFormat.PDF", + "PDF"), CSV(3, "ReportMailingJobEmailAttachmentFileFormat.CSV", "CSV"); private final String code; private final String value; @@ -42,7 +42,8 @@ public enum ReportMailingJobEmailAttachmentFileFormat { /** * Creates a new {@link ReportMailingJobEmailAttachmentFileFormat} object * - * @param value the value of the enum constant + * @param value + * the value of the enum constant * @return {@link ReportMailingJobEmailAttachmentFileFormat} object */ public static ReportMailingJobEmailAttachmentFileFormat newInstance(final String value) { @@ -62,7 +63,8 @@ public enum ReportMailingJobEmailAttachmentFileFormat { /** * Creates a new {@link ReportMailingJobEmailAttachmentFileFormat} object * - * @param id the id of the enum constant + * @param id + * the id of the enum constant * @return {@link ReportMailingJobEmailAttachmentFileFormat} object */ public static ReportMailingJobEmailAttachmentFileFormat newInstance(final Integer id) { @@ -145,7 +147,8 @@ public enum ReportMailingJobEmailAttachmentFileFormat { } /** - * get a {@link EnumOptionData} representation of the {@link ReportMailingJobEmailAttachmentFileFormat} object + * get a {@link EnumOptionData} representation of the + * {@link ReportMailingJobEmailAttachmentFileFormat} object * * @return {@link EnumOptionData} object */ @@ -157,7 +160,8 @@ public enum ReportMailingJobEmailAttachmentFileFormat { } /** - * get the {@link EnumOptionData} representation of all valid {@link ReportMailingJobEmailAttachmentFileFormat} objects + * get the {@link EnumOptionData} representation of all valid + * {@link ReportMailingJobEmailAttachmentFileFormat} objects * * @return List of {@link EnumOptionData} objects */ diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobEmailData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobEmailData.java index f85c5bd37..b4b0cf607 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobEmailData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobEmailData.java @@ -24,6 +24,7 @@ import java.io.File; * Immutable data object representing report mailing job email data. **/ public class ReportMailingJobEmailData { + private final String to; private final String text; private final String subject; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobPreviousRunStatus.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobPreviousRunStatus.java index 4d9e0a5ba..d23f646c5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobPreviousRunStatus.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobPreviousRunStatus.java @@ -21,9 +21,9 @@ package org.apache.fineract.infrastructure.reportmailingjob.data; import org.apache.commons.lang3.StringUtils; public enum ReportMailingJobPreviousRunStatus { - INVALID(-1, "ReportMailingJobPreviousRunStatus.INVALID", "Invalid"), - SUCCESS(1, "ReportMailingJobPreviousRunStatus.SUCCESS", "Success"), - ERROR(0, "ReportMailingJobPreviousRunStatus.ERROR", "Error"); + + INVALID(-1, "ReportMailingJobPreviousRunStatus.INVALID", "Invalid"), SUCCESS(1, "ReportMailingJobPreviousRunStatus.SUCCESS", + "Success"), ERROR(0, "ReportMailingJobPreviousRunStatus.ERROR", "Error"); private final String code; private final String value; @@ -38,7 +38,8 @@ public enum ReportMailingJobPreviousRunStatus { /** * Creates a {@link ReportMailingJobPreviousRunStatus} object * - * @param value the value of the enum constant + * @param value + * the value of the enum constant * @return {@link ReportMailingJobPreviousRunStatus} object */ public static ReportMailingJobPreviousRunStatus newInstance(final String value) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobRunHistoryData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobRunHistoryData.java index 91d8a1fc3..b78e10784 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobRunHistoryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobRunHistoryData.java @@ -24,6 +24,7 @@ import org.joda.time.DateTime; * Immutable data object representing report mailing job run history data. **/ public class ReportMailingJobRunHistoryData { + private final Long id; private final Long reportMailingJobId; private final DateTime startDateTime; @@ -35,8 +36,8 @@ public class ReportMailingJobRunHistoryData { /** * ReportMailingJobRunHistoryData private constructor **/ - private ReportMailingJobRunHistoryData(Long id, Long reportMailingJobId, DateTime startDateTime, - DateTime endDateTime, String status, String errorMessage, String errorLog) { + private ReportMailingJobRunHistoryData(Long id, Long reportMailingJobId, DateTime startDateTime, DateTime endDateTime, String status, + String errorMessage, String errorLog) { this.id = id; this.reportMailingJobId = reportMailingJobId; this.startDateTime = startDateTime; @@ -51,8 +52,8 @@ public class ReportMailingJobRunHistoryData { * * @return ReportMailingJobRunHistoryData object **/ - public static ReportMailingJobRunHistoryData newInstance(Long id, Long reportMailingJobId, DateTime startDateTime, - DateTime endDateTime, String status, String errorMessage, String errorLog) { + public static ReportMailingJobRunHistoryData newInstance(Long id, Long reportMailingJobId, DateTime startDateTime, DateTime endDateTime, + String status, String errorMessage, String errorLog) { return new ReportMailingJobRunHistoryData(id, reportMailingJobId, startDateTime, endDateTime, status, errorMessage, errorLog); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobStretchyReportParamDateOption.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobStretchyReportParamDateOption.java index 7de02b407..6cf84a8de 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobStretchyReportParamDateOption.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobStretchyReportParamDateOption.java @@ -24,10 +24,11 @@ import org.apache.commons.lang3.StringUtils; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public enum ReportMailingJobStretchyReportParamDateOption { - INVALID(0, "ReportMailingJobStretchyReportParamDateOption.INVALID", "Invalid"), - TODAY(1, "ReportMailingJobStretchyReportParamDateOption.TODAY", "Today"), - YESTERDAY(2, "ReportMailingJobStretchyReportParamDateOption.YESTERDAY", "Yesterday"), - TOMORROW(3, "ReportMailingJobStretchyReportParamDateOption.TOMORROW", "Tomorrow"); + + INVALID(0, "ReportMailingJobStretchyReportParamDateOption.INVALID", "Invalid"), TODAY(1, + "ReportMailingJobStretchyReportParamDateOption.TODAY", "Today"), YESTERDAY(2, + "ReportMailingJobStretchyReportParamDateOption.YESTERDAY", + "Yesterday"), TOMORROW(3, "ReportMailingJobStretchyReportParamDateOption.TOMORROW", "Tomorrow"); private final String code; private final String value; @@ -45,9 +46,11 @@ public enum ReportMailingJobStretchyReportParamDateOption { } /** - * Creates a new {@link ReportMailingJobStretchyReportParamDateOption} object + * Creates a new {@link ReportMailingJobStretchyReportParamDateOption} + * object * - * @param value value of the enum constant + * @param value + * value of the enum constant * @return {@link ReportMailingJobStretchyReportParamDateOption} object */ public static ReportMailingJobStretchyReportParamDateOption newInstance(final String value) { @@ -65,9 +68,11 @@ public enum ReportMailingJobStretchyReportParamDateOption { } /** - * Creates a new {@link ReportMailingJobStretchyReportParamDateOption} object + * Creates a new {@link ReportMailingJobStretchyReportParamDateOption} + * object * - * @param id id of the enum constant + * @param id + * id of the enum constant * @return {@link ReportMailingJobStretchyReportParamDateOption} object */ public static ReportMailingJobStretchyReportParamDateOption newInstance(final Integer id) { @@ -120,12 +125,13 @@ public enum ReportMailingJobStretchyReportParamDateOption { } /** - * @return list of valid ReportMailingJobStretchyReportParamDateOption values + * @return list of valid ReportMailingJobStretchyReportParamDateOption + * values **/ public static Object[] validValues() { List validValues = new ArrayList<>(); - for (ReportMailingJobStretchyReportParamDateOption constant : ReportMailingJobStretchyReportParamDateOption.values()) { + for (ReportMailingJobStretchyReportParamDateOption constant : ReportMailingJobStretchyReportParamDateOption.values()) { if (constant.isValid()) { validValues.add(constant.value); } @@ -135,7 +141,8 @@ public enum ReportMailingJobStretchyReportParamDateOption { } /** - * get a {@link EnumOptionData} representation of the {@link ReportMailingJobStretchyReportParamDateOption} object + * get a {@link EnumOptionData} representation of the + * {@link ReportMailingJobStretchyReportParamDateOption} object * * @return {@link EnumOptionData} object */ @@ -147,7 +154,8 @@ public enum ReportMailingJobStretchyReportParamDateOption { } /** - * get the {@link EnumOptionData} representation of all valid {@link ReportMailingJobStretchyReportParamDateOption} objects + * get the {@link EnumOptionData} representation of all valid + * {@link ReportMailingJobStretchyReportParamDateOption} objects * * @return List of {@link EnumOptionData} objects */ diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobTimelineData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobTimelineData.java index 9a22262a3..e2ca6473e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobTimelineData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/data/ReportMailingJobTimelineData.java @@ -21,10 +21,12 @@ package org.apache.fineract.infrastructure.reportmailingjob.data; import org.joda.time.LocalDate; /** - * Immutable data object represent the timeline events of a report mailing job (creation) + * Immutable data object represent the timeline events of a report mailing job + * (creation) **/ @SuppressWarnings("unused") public class ReportMailingJobTimelineData { + private final LocalDate createdOnDate; private final String createdByUsername; private final String createdByFirstname; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJob.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJob.java index 43217d7aa..70f535d98 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJob.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJob.java @@ -45,6 +45,7 @@ import org.joda.time.format.DateTimeFormatter; @Entity @Table(name = "m_report_mailing_job", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "unique_name") }) public class ReportMailingJob extends AbstractAuditableCustom { + private static final long serialVersionUID = -2197602941230009227L; @Column(name = "name", nullable = false) @@ -112,17 +113,17 @@ public class ReportMailingJob extends AbstractAuditableCustom { /** * ReportMailingJob protected constructor **/ - protected ReportMailingJob() { } + protected ReportMailingJob() {} /** * ReportMailingJob private constructor **/ - private ReportMailingJob(final String name, final String description, final LocalDateTime startDateTime, - final String recurrence, final String emailRecipients, final String emailSubject, - final String emailMessage, final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat, - final Report stretchyReport, final String stretchyReportParamMap, final LocalDateTime previousRunDateTime, final LocalDateTime nextRunDateTime, - final ReportMailingJobPreviousRunStatus previousRunStatus, final String previousRunErrorLog, final String previousRunErrorMessage, - final boolean isActive, final boolean isDeleted, final AppUser runAsUser) { + private ReportMailingJob(final String name, final String description, final LocalDateTime startDateTime, final String recurrence, + final String emailRecipients, final String emailSubject, final String emailMessage, + final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat, final Report stretchyReport, + final String stretchyReportParamMap, final LocalDateTime previousRunDateTime, final LocalDateTime nextRunDateTime, + final ReportMailingJobPreviousRunStatus previousRunStatus, final String previousRunErrorLog, + final String previousRunErrorMessage, final boolean isActive, final boolean isDeleted, final AppUser runAsUser) { this.name = name; this.description = description; this.startDateTime = null; @@ -172,12 +173,13 @@ public class ReportMailingJob extends AbstractAuditableCustom { * * @return ReportMailingJob object **/ - public static ReportMailingJob newInstance(final String name, final String description, final LocalDateTime startDateTime, final String recurrence, - final String emailRecipients, final String emailSubject, final String emailMessage, - final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat, final Report stretchyReport, final String stretchyReportParamMap, - final boolean isActive, final AppUser runAsUser) { - return new ReportMailingJob(name, description, startDateTime, recurrence, emailRecipients, emailSubject, - emailMessage, emailAttachmentFileFormat, stretchyReport, stretchyReportParamMap, null, null, null, null, null, isActive, false, runAsUser); + public static ReportMailingJob newInstance(final String name, final String description, final LocalDateTime startDateTime, + final String recurrence, final String emailRecipients, final String emailSubject, final String emailMessage, + final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat, final Report stretchyReport, + final String stretchyReportParamMap, final boolean isActive, final AppUser runAsUser) { + return new ReportMailingJob(name, description, startDateTime, recurrence, emailRecipients, emailSubject, emailMessage, + emailAttachmentFileFormat, stretchyReport, stretchyReportParamMap, null, null, null, null, null, isActive, false, + runAsUser); } /** @@ -185,8 +187,7 @@ public class ReportMailingJob extends AbstractAuditableCustom { * * @return ReportMailingJob object **/ - public static ReportMailingJob newInstance(JsonCommand jsonCommand, final Report stretchyReport, - final AppUser runAsUser) { + public static ReportMailingJob newInstance(JsonCommand jsonCommand, final Report stretchyReport, final AppUser runAsUser) { final String name = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.NAME_PARAM_NAME); final String description = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.DESCRIPTION_PARAM_NAME); final String recurrence = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.RECURRENCE_PARAM_NAME); @@ -194,28 +195,35 @@ public class ReportMailingJob extends AbstractAuditableCustom { final String emailRecipients = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME); final String emailSubject = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME); final String emailMessage = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME); - final String stretchyReportParamMap = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME); - final Integer emailAttachmentFileFormatId = jsonCommand.integerValueOfParameterNamed(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME); - final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat.newInstance(emailAttachmentFileFormatId); + final String stretchyReportParamMap = jsonCommand + .stringValueOfParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME); + final Integer emailAttachmentFileFormatId = jsonCommand + .integerValueOfParameterNamed(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME); + final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat + .newInstance(emailAttachmentFileFormatId); LocalDateTime startDateTime = new LocalDateTime(); if (jsonCommand.hasParameter(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME)) { - final String startDateTimeString = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME); + final String startDateTimeString = jsonCommand + .stringValueOfParameterNamed(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME); if (startDateTimeString != null) { - final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat()).withLocale(jsonCommand.extractLocale()); + final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat()) + .withLocale(jsonCommand.extractLocale()); startDateTime = LocalDateTime.parse(startDateTimeString, dateTimeFormatter); } } - return new ReportMailingJob(name, description, startDateTime, recurrence, emailRecipients, emailSubject, - emailMessage, emailAttachmentFileFormat, stretchyReport, stretchyReportParamMap, null, startDateTime, null, null, null, isActive, false, runAsUser); + return new ReportMailingJob(name, description, startDateTime, recurrence, emailRecipients, emailSubject, emailMessage, + emailAttachmentFileFormat, stretchyReport, stretchyReportParamMap, null, startDateTime, null, null, null, isActive, false, + runAsUser); } /** * Update the ReportMailingJob entity * - * @param jsonCommand JsonCommand object + * @param jsonCommand + * JsonCommand object * @return map of string to object **/ public Map update(final JsonCommand jsonCommand) { @@ -270,27 +278,34 @@ public class ReportMailingJob extends AbstractAuditableCustom { this.emailMessage = emailMessage; } - if (jsonCommand.isChangeInStringParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, this.stretchyReportParamMap)) { - final String stretchyReportParamMap = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME); + if (jsonCommand.isChangeInStringParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, + this.stretchyReportParamMap)) { + final String stretchyReportParamMap = jsonCommand + .stringValueOfParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME); actualChanges.put(ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, stretchyReportParamMap); this.stretchyReportParamMap = stretchyReportParamMap; } - final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat.newInstance(this.emailAttachmentFileFormat); + final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat + .newInstance(this.emailAttachmentFileFormat); - if (jsonCommand.isChangeInIntegerParameterNamed(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, emailAttachmentFileFormat.getId())) { - final Integer emailAttachmentFileFormatId = jsonCommand.integerValueOfParameterNamed(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME); + if (jsonCommand.isChangeInIntegerParameterNamed(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, + emailAttachmentFileFormat.getId())) { + final Integer emailAttachmentFileFormatId = jsonCommand + .integerValueOfParameterNamed(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME); actualChanges.put(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, emailAttachmentFileFormatId); - final ReportMailingJobEmailAttachmentFileFormat newEmailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat.newInstance(emailAttachmentFileFormatId); + final ReportMailingJobEmailAttachmentFileFormat newEmailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat + .newInstance(emailAttachmentFileFormatId); this.emailAttachmentFileFormat = newEmailAttachmentFileFormat.getValue(); } final String newStartDateTimeString = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME); if (!StringUtils.isEmpty(newStartDateTimeString)) { - final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat()).withLocale(jsonCommand.extractLocale()); + final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat()) + .withLocale(jsonCommand.extractLocale()); final LocalDateTime newStartDateTime = LocalDateTime.parse(newStartDateTimeString, dateTimeFormatter); final LocalDateTime oldStartDateTime = (this.startDateTime != null) ? new LocalDateTime(this.startDateTime) : null; @@ -308,8 +323,8 @@ public class ReportMailingJob extends AbstractAuditableCustom { } if (jsonCommand.isChangeInLongParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, currentStretchyReportId)) { - final Long updatedStretchyReportId = jsonCommand.longValueOfParameterNamed( - ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME); + final Long updatedStretchyReportId = jsonCommand + .longValueOfParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME); actualChanges.put(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, updatedStretchyReportId); } @@ -319,7 +334,8 @@ public class ReportMailingJob extends AbstractAuditableCustom { /** * update the stretchy report entity associated with the credit check * - * @param stretchyReport -- Report entity + * @param stretchyReport + * -- Report entity * **/ public void update(final Report stretchyReport) { @@ -329,7 +345,8 @@ public class ReportMailingJob extends AbstractAuditableCustom { } /** - * delete the report mailing job, set the isDeleted property to 1 and alter the name + * delete the report mailing job, set the isDeleted property to 1 and alter + * the name * * **/ @@ -498,7 +515,8 @@ public class ReportMailingJob extends AbstractAuditableCustom { /** * update the previousRunStatus * - * @param previousRunStatus -- the status of the previous job execution + * @param previousRunStatus + * -- the status of the previous job execution * **/ public void updatePreviousRunStatus(final String previousRunStatus) { @@ -510,7 +528,8 @@ public class ReportMailingJob extends AbstractAuditableCustom { /** * update the previousRunDateTime * - * @param previousRunDateTime -- previous run date + * @param previousRunDateTime + * -- previous run date * **/ public void updatePreviousRunDateTime(final DateTime previousRunDateTime) { @@ -522,7 +541,8 @@ public class ReportMailingJob extends AbstractAuditableCustom { /** * update the nextRunDateTime * - * @param nextRunDateTime -- the next run DateTime + * @param nextRunDateTime + * -- the next run DateTime * **/ public void updateNextRunDateTime(final DateTime nextRunDateTime) { @@ -547,7 +567,8 @@ public class ReportMailingJob extends AbstractAuditableCustom { /** * update the previousRunErrorLog property * - * @param previousRunErrorLog -- the previous job run error log + * @param previousRunErrorLog + * -- the previous job run error log * **/ public void updatePreviousRunErrorLog(final String previousRunErrorLog) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobConfiguration.java index 3170de26c..bb24cabe4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobConfiguration.java @@ -25,8 +25,10 @@ import javax.persistence.UniqueConstraint; import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity -@Table(name = "m_report_mailing_job_configuration", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "unique_name") }) +@Table(name = "m_report_mailing_job_configuration", uniqueConstraints = { + @UniqueConstraint(columnNames = { "name" }, name = "unique_name") }) public class ReportMailingJobConfiguration extends AbstractPersistableCustom { + private static final long serialVersionUID = 3099279770861263184L; @Column(name = "name", nullable = false) @@ -38,7 +40,7 @@ public class ReportMailingJobConfiguration extends AbstractPersistableCustom { /** * ReportMailingJobConfiguration protected constructor **/ - protected ReportMailingJobConfiguration() { } + protected ReportMailingJobConfiguration() {} /** * ReportMailingJobConfiguration private constructor diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobConfigurationRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobConfigurationRepository.java index 2611be1bd..7dc621989 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobConfigurationRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobConfigurationRepository.java @@ -21,8 +21,8 @@ package org.apache.fineract.infrastructure.reportmailingjob.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface ReportMailingJobConfigurationRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface ReportMailingJobConfigurationRepository + extends JpaRepository, JpaSpecificationExecutor { /** * find ReportMailingJobConfiguration by name diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobEmailAttachmentFileFormat.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobEmailAttachmentFileFormat.java index 6d1806dfe..ae727ed54 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobEmailAttachmentFileFormat.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobEmailAttachmentFileFormat.java @@ -19,10 +19,10 @@ package org.apache.fineract.infrastructure.reportmailingjob.domain; public enum ReportMailingJobEmailAttachmentFileFormat { - INVALID(0, "ReportMailingJobEmailAttachmentFileFormat.invalid", "invalid"), - XLS(1, "ReportMailingJobEmailAttachmentFileFormat.xls", "xls"), - PDF(2, "ReportMailingJobEmailAttachmentFileFormat.pdf", "pdf"), - CSV(3, "ReportMailingJobEmailAttachmentFileFormat.csv", "csv"); + + INVALID(0, "ReportMailingJobEmailAttachmentFileFormat.invalid", "invalid"), XLS(1, "ReportMailingJobEmailAttachmentFileFormat.xls", + "xls"), PDF(2, "ReportMailingJobEmailAttachmentFileFormat.pdf", + "pdf"), CSV(3, "ReportMailingJobEmailAttachmentFileFormat.csv", "csv"); private final String code; private final String value; @@ -40,18 +40,18 @@ public enum ReportMailingJobEmailAttachmentFileFormat { switch (value) { case "xls": emailAttachmentFileFormat = XLS; - break; + break; case "pdf": emailAttachmentFileFormat = PDF; - break; + break; case "csv": emailAttachmentFileFormat = CSV; - break; + break; default: - break; + break; } return emailAttachmentFileFormat; @@ -63,18 +63,18 @@ public enum ReportMailingJobEmailAttachmentFileFormat { switch (id) { case 1: emailAttachmentFileFormat = XLS; - break; + break; case 2: emailAttachmentFileFormat = PDF; - break; + break; case 3: emailAttachmentFileFormat = CSV; - break; + break; default: - break; + break; } return emailAttachmentFileFormat; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRepository.java index 2874e3158..39f1de8b2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRepository.java @@ -23,8 +23,10 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ReportMailingJobRepository extends JpaRepository, JpaSpecificationExecutor { + /** - * Returns all instances of {@link ReportMailingJob} where isActive is true and isDeleted is false + * Returns all instances of {@link ReportMailingJob} where isActive is true + * and isDeleted is false * * @return instances of {@link ReportMailingJob} */ diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRepositoryWrapper.java index 5e91124de..db275f256 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRepositoryWrapper.java @@ -24,6 +24,7 @@ import org.springframework.stereotype.Service; @Service public class ReportMailingJobRepositoryWrapper { + private final ReportMailingJobRepository reportMailingJobRepository; @Autowired @@ -32,18 +33,18 @@ public class ReportMailingJobRepositoryWrapper { } /** - * find report mailing job by ID, throw a "entity not found" exception if the job does not exist + * find report mailing job by ID, throw a "entity not found" exception if + * the job does not exist * - * @param id -- the identifier of the report mailing job to be found + * @param id + * -- the identifier of the report mailing job to be found * @return ReportMailingJob object **/ public ReportMailingJob findOneThrowExceptionIfNotFound(final Long id) { final ReportMailingJob reportMailingJob = this.reportMailingJobRepository.findById(id) .orElseThrow(() -> new ReportMailingJobNotFoundException(id)); - if (reportMailingJob.isDeleted()) { - throw new ReportMailingJobNotFoundException(id); - } + if (reportMailingJob.isDeleted()) { throw new ReportMailingJobNotFoundException(id); } return reportMailingJob; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRunHistory.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRunHistory.java index d801b6747..2fd5efbc7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRunHistory.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRunHistory.java @@ -32,6 +32,7 @@ import org.joda.time.DateTime; @Entity @Table(name = "m_report_mailing_job_run_history") public class ReportMailingJobRunHistory extends AbstractPersistableCustom { + private static final long serialVersionUID = -3757370929988421076L; @ManyToOne @@ -58,13 +59,13 @@ public class ReportMailingJobRunHistory extends AbstractPersistableCustom { /** * ReportMailingJobRunHistory protected constructor **/ - protected ReportMailingJobRunHistory() { } + protected ReportMailingJobRunHistory() {} /** * ReportMailingJobRunHistory private constructor **/ - private ReportMailingJobRunHistory(final ReportMailingJob reportMailingJob, final DateTime startDateTime, final DateTime endDateTime, final String status, - final String errorMessage, final String errorLog) { + private ReportMailingJobRunHistory(final ReportMailingJob reportMailingJob, final DateTime startDateTime, final DateTime endDateTime, + final String status, final String errorMessage, final String errorLog) { this.reportMailingJob = reportMailingJob; this.startDateTime = null; @@ -88,8 +89,8 @@ public class ReportMailingJobRunHistory extends AbstractPersistableCustom { * * @return ReportMailingJobRunHistory object **/ - public static ReportMailingJobRunHistory newInstance(final ReportMailingJob reportMailingJob, final DateTime startDateTime, final DateTime endDateTime, - final String status, final String errorMessage, final String errorLog) { + public static ReportMailingJobRunHistory newInstance(final ReportMailingJob reportMailingJob, final DateTime startDateTime, + final DateTime endDateTime, final String status, final String errorMessage, final String errorLog) { return new ReportMailingJobRunHistory(reportMailingJob, startDateTime, endDateTime, status, errorMessage, errorLog); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRunHistoryRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRunHistoryRepository.java index be6cdfaa8..0906de6a6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRunHistoryRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/domain/ReportMailingJobRunHistoryRepository.java @@ -21,6 +21,7 @@ package org.apache.fineract.infrastructure.reportmailingjob.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface ReportMailingJobRunHistoryRepository extends JpaRepository, JpaSpecificationExecutor { +public interface ReportMailingJobRunHistoryRepository + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobConfigurationNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobConfigurationNotFoundException.java index 701d0a42d..a0588f004 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobConfigurationNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobConfigurationNotFoundException.java @@ -21,13 +21,14 @@ package org.apache.fineract.infrastructure.reportmailingjob.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when report mailing job configuration resources are not found. + * A {@link RuntimeException} thrown when report mailing job configuration + * resources are not found. **/ @SuppressWarnings("serial") public class ReportMailingJobConfigurationNotFoundException extends AbstractPlatformResourceNotFoundException { public ReportMailingJobConfigurationNotFoundException(final String name) { - super("error.msg.report.mailing.job.configuration.name.invalid", "Report mailing job configuration with name " + name + - " does not exist", name); + super("error.msg.report.mailing.job.configuration.name.invalid", + "Report mailing job configuration with name " + name + " does not exist", name); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobNotFoundException.java index 1ac264833..0fe74ddb0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobNotFoundException.java @@ -21,13 +21,14 @@ package org.apache.fineract.infrastructure.reportmailingjob.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when report mailing job resources are not found. + * A {@link RuntimeException} thrown when report mailing job resources are not + * found. **/ @SuppressWarnings("serial") public class ReportMailingJobNotFoundException extends AbstractPlatformResourceNotFoundException { public ReportMailingJobNotFoundException(final Long reportMailingJobId) { - super("error.msg.report.mailing.job.id.invalid", "Report mailing job with identifier " + reportMailingJobId + - " does not exist", reportMailingJobId); + super("error.msg.report.mailing.job.id.invalid", "Report mailing job with identifier " + reportMailingJobId + " does not exist", + reportMailingJobId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobRunHistoryNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobRunHistoryNotFoundException.java index a69999bb5..9f7d57514 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobRunHistoryNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/exception/ReportMailingJobRunHistoryNotFoundException.java @@ -21,12 +21,14 @@ package org.apache.fineract.infrastructure.reportmailingjob.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when report mailing job run history resources are not found. + * A {@link RuntimeException} thrown when report mailing job run history + * resources are not found. **/ @SuppressWarnings("serial") public class ReportMailingJobRunHistoryNotFoundException extends AbstractPlatformResourceNotFoundException { + public ReportMailingJobRunHistoryNotFoundException(final Long reportMailingJobId) { - super("error.msg.report.mailing.job.run.history.invalid", "Report mailing job run history with job identifier " - + reportMailingJobId + " does not exist", reportMailingJobId); + super("error.msg.report.mailing.job.run.history.invalid", + "Report mailing job run history with job identifier " + reportMailingJobId + " does not exist", reportMailingJobId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/CreateReportMailingJobCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/CreateReportMailingJobCommandHandler.java index f6b1c334d..d77af5004 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/CreateReportMailingJobCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/CreateReportMailingJobCommandHandler.java @@ -31,6 +31,7 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME, action = "CREATE") public class CreateReportMailingJobCommandHandler implements NewCommandSourceHandler { + private final ReportMailingJobWritePlatformService reportMailingJobWritePlatformService; @Autowired diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/DeleteReportMailingJobCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/DeleteReportMailingJobCommandHandler.java index 081565dc0..1ed850046 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/DeleteReportMailingJobCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/DeleteReportMailingJobCommandHandler.java @@ -31,6 +31,7 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME, action = "DELETE") public class DeleteReportMailingJobCommandHandler implements NewCommandSourceHandler { + private final ReportMailingJobWritePlatformService reportMailingJobWritePlatformService; @Autowired diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/UpdateReportMailingJobCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/UpdateReportMailingJobCommandHandler.java index 30a9682cb..72e035356 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/UpdateReportMailingJobCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/handler/UpdateReportMailingJobCommandHandler.java @@ -31,6 +31,7 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME, action = "UPDATE") public class UpdateReportMailingJobCommandHandler implements NewCommandSourceHandler { + private final ReportMailingJobWritePlatformService reportMailingJobWritePlatformService; @Autowired diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/helper/IPv4Helper.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/helper/IPv4Helper.java index 1022053d0..6712788da 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/helper/IPv4Helper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/helper/IPv4Helper.java @@ -22,39 +22,39 @@ import java.net.InetAddress; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + /** - * This utility provides methods to either convert an IPv4 address to its long format or a 32bit dotted format. + * This utility provides methods to either convert an IPv4 address to its long + * format or a 32bit dotted format. * * @see http://hawkee.com/snippet/9731/ */ public class IPv4Helper { + /** * Returns the long format of the provided IP address. * - * @param ipAddress the IP address + * @param ipAddress + * the IP address * @return the long format of ipAddress - * @throws IllegalArgumentException if ipAddress is invalid + * @throws IllegalArgumentException + * if ipAddress is invalid */ - private final static Logger LOG = LoggerFactory.getLogger(IPv4Helper.class); - public static long ipAddressToLong(String ipAddress) { - if (ipAddress == null || ipAddress.isEmpty()) { - throw new IllegalArgumentException("ip address cannot be null or empty"); - } + private final static Logger LOG = LoggerFactory.getLogger(IPv4Helper.class); + + public static long ipAddressToLong(String ipAddress) { + if (ipAddress == null || ipAddress.isEmpty()) { throw new IllegalArgumentException("ip address cannot be null or empty"); } String[] octets = ipAddress.split(java.util.regex.Pattern.quote(".")); - if (octets.length != 4) { - throw new IllegalArgumentException("invalid ip address"); - } + if (octets.length != 4) { throw new IllegalArgumentException("invalid ip address"); } long ip = 0; for (int i = 3; i >= 0; i--) { long octet = Long.parseLong(octets[3 - i]); - if (octet > 255 || octet < 0) { - throw new IllegalArgumentException("invalid ip address"); - } + if (octet > 255 || octet < 0) { throw new IllegalArgumentException("invalid ip address"); } ip |= octet << (i * 8); } @@ -65,15 +65,15 @@ public class IPv4Helper { /** * Returns the 32bit dotted format of the provided long ip. * - * @param ip the long ip + * @param ip + * the long ip * @return the 32bit dotted format of ip - * @throws IllegalArgumentException if ip is invalid + * @throws IllegalArgumentException + * if ip is invalid */ public static String longToIpAddress(long ip) { // if ip is bigger than 255.255.255.255 or smaller than 0.0.0.0 - if (ip > 4294967295L || ip < 0) { - throw new IllegalArgumentException("invalid ip"); - } + if (ip > 4294967295L || ip < 0) { throw new IllegalArgumentException("invalid ip"); } StringBuilder ipAddress = new StringBuilder(); @@ -91,9 +91,12 @@ public class IPv4Helper { /** * check if an IP Address is within a given range of IP Addresses * - * @param ipAddress -- the IP Address to be checked - * @param startOfRange -- the first IP address in the range - * @param endOfRange -- the last IP address in the range + * @param ipAddress + * -- the IP Address to be checked + * @param startOfRange + * -- the first IP address in the range + * @param endOfRange + * -- the last IP address in the range * @return boolean true if IP address is in the range of IP addresses **/ public static boolean ipAddressIsInRange(final String ipAddress, final String startOfRange, final String endOfRange) { @@ -129,8 +132,8 @@ public class IPv4Helper { } catch (Exception exception) { - LOG.error("Problem occurred in applicationIsRunningOnLocalMachine function",exception); - } + LOG.error("Problem occurred in applicationIsRunningOnLocalMachine function", exception); + } return isRunningOnLocalMachine; } @@ -138,7 +141,8 @@ public class IPv4Helper { /** * check if the java application is not running on a local machine * - * @return true if the application is not running on a local machine else false + * @return true if the application is not running on a local machine else + * false **/ public static boolean applicationIsNotRunningOnLocalMachine() { return !applicationIsRunningOnLocalMachine(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobConfigurationReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobConfigurationReadPlatformService.java index ea88ad95c..2bbe94c83 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobConfigurationReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobConfigurationReadPlatformService.java @@ -22,6 +22,7 @@ import java.util.Collection; import org.apache.fineract.infrastructure.reportmailingjob.data.ReportMailingJobConfigurationData; public interface ReportMailingJobConfigurationReadPlatformService { + /** * Retrieve all report mailing job configurations * diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobConfigurationReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobConfigurationReadPlatformServiceImpl.java index 061f08f9b..f916d8194 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobConfigurationReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobConfigurationReadPlatformServiceImpl.java @@ -33,6 +33,7 @@ import org.springframework.stereotype.Service; @Service public class ReportMailingJobConfigurationReadPlatformServiceImpl implements ReportMailingJobConfigurationReadPlatformService { + private final JdbcTemplate jdbcTemplate; /** @@ -66,9 +67,9 @@ public class ReportMailingJobConfigurationReadPlatformServiceImpl implements Rep } private static final class ReportMailingJobConfigurationMapper implements RowMapper { + public String reportMailingJobConfigurationSchema() { - return "rmjc.id, rmjc.name, rmjc.value " - + "from m_report_mailing_job_configuration rmjc"; + return "rmjc.id, rmjc.name, rmjc.value " + "from m_report_mailing_job_configuration rmjc"; } @Override diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobEmailService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobEmailService.java index 42e70c41f..749baa46b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobEmailService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobEmailService.java @@ -21,10 +21,12 @@ package org.apache.fineract.infrastructure.reportmailingjob.service; import org.apache.fineract.infrastructure.reportmailingjob.data.ReportMailingJobEmailData; public interface ReportMailingJobEmailService { + /** * Handles request to send an email with attachment * - * @param reportMailingJobEmailData {@link ReportMailingJobEmailData} object + * @param reportMailingJobEmailData + * {@link ReportMailingJobEmailData} object */ void sendEmailWithAttachment(final ReportMailingJobEmailData reportMailingJobEmailData); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobEmailServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobEmailServiceImpl.java index bc28b65dd..4c0efcaee 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobEmailServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobEmailServiceImpl.java @@ -35,6 +35,7 @@ import org.springframework.stereotype.Service; @Service public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailService { + private final static Logger LOG = LoggerFactory.getLogger(ReportMailingJobEmailServiceImpl.class); private final ReportMailingJobConfigurationReadPlatformService reportMailingJobConfigurationReadPlatformService; private Collection reportMailingJobConfigurationDataCollection; @@ -43,7 +44,8 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe * ReportMailingJobEmailServiceImpl constructor **/ @Autowired - public ReportMailingJobEmailServiceImpl(final ReportMailingJobConfigurationReadPlatformService reportMailingJobConfigurationReadPlatformService) { + public ReportMailingJobEmailServiceImpl( + final ReportMailingJobConfigurationReadPlatformService reportMailingJobConfigurationReadPlatformService) { this.reportMailingJobConfigurationReadPlatformService = reportMailingJobConfigurationReadPlatformService; } @@ -52,8 +54,8 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) { try { // get all ReportMailingJobConfiguration objects from the database - this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService. - retrieveAllReportMailingJobConfigurations(); + this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService + .retrieveAllReportMailingJobConfigurations(); JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl(); javaMailSenderImpl.setHost(this.getGmailSmtpServer()); @@ -72,7 +74,8 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe mimeMessageHelper.setSubject(reportMailingJobEmailData.getSubject()); if (reportMailingJobEmailData.getAttachment() != null) { - mimeMessageHelper.addAttachment(reportMailingJobEmailData.getAttachment().getName(), reportMailingJobEmailData.getAttachment()); + mimeMessageHelper.addAttachment(reportMailingJobEmailData.getAttachment().getName(), + reportMailingJobEmailData.getAttachment()); } javaMailSenderImpl.send(mimeMessage); @@ -80,7 +83,7 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe catch (MessagingException e) { // handle the exception - LOG.error("Problem occurred in sendEmailWithAttachment function",e); + LOG.error("Problem occurred in sendEmailWithAttachment function", e); } } @@ -98,9 +101,11 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe } /** - * get a report mailing job configuration object by name from collection of objects + * get a report mailing job configuration object by name from collection of + * objects * - * @param name -- the value of the name property + * @param name + * -- the value of the name property * @return ReportMailingJobConfigurationData object **/ private ReportMailingJobConfigurationData getReportMailingJobConfigurationData(final String name) { @@ -124,8 +129,8 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe * @return Gmail smtp server name **/ private String getGmailSmtpServer() { - final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData - (ReportMailingJobConstants.GMAIL_SMTP_SERVER); + final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this + .getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_SERVER); return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null; } @@ -134,8 +139,8 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe * @return Gmail smtp server port number **/ private Integer getGmailSmtpPort() { - final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData - (ReportMailingJobConstants.GMAIL_SMTP_PORT); + final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this + .getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_PORT); final String portNumber = (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null; return (portNumber != null) ? Integer.parseInt(portNumber) : null; @@ -145,8 +150,8 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe * @return Gmail smtp username **/ private String getGmailSmtpUsername() { - final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData - (ReportMailingJobConstants.GMAIL_SMTP_USERNAME); + final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this + .getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_USERNAME); return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null; } @@ -155,8 +160,8 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe * @return Gmail smtp password **/ private String getGmailSmtpPassword() { - final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData - (ReportMailingJobConstants.GMAIL_SMTP_PASSWORD); + final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this + .getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_PASSWORD); return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobReadPlatformService.java index 5df486125..1553fa59d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobReadPlatformService.java @@ -24,8 +24,10 @@ import org.apache.fineract.infrastructure.core.service.SearchParameters; import org.apache.fineract.infrastructure.reportmailingjob.data.ReportMailingJobData; public interface ReportMailingJobReadPlatformService { + /** - * Retrieve all report mailing jobs that have the isDeleted property set to 0 + * Retrieve all report mailing jobs that have the isDeleted property set to + * 0 **/ Page retrieveAllReportMailingJobs(SearchParameters searchParameters); @@ -40,7 +42,8 @@ public interface ReportMailingJobReadPlatformService { ReportMailingJobData retrieveReportMailingJobEnumOptions(); /** - * Retrieve all active report mailing jobs that have their isDeleted property set to 0 + * Retrieve all active report mailing jobs that have their isDeleted + * property set to 0 **/ Collection retrieveAllActiveReportMailingJobs(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobReadPlatformServiceImpl.java index eaed35d8f..efcc1b923 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobReadPlatformServiceImpl.java @@ -46,12 +46,12 @@ import org.springframework.stereotype.Service; @Service public class ReportMailingJobReadPlatformServiceImpl implements ReportMailingJobReadPlatformService { + private final JdbcTemplate jdbcTemplate; private final ColumnValidator columnValidator; @Autowired - public ReportMailingJobReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + public ReportMailingJobReadPlatformServiceImpl(final RoutingDataSource dataSource, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.columnValidator = columnValidator; } @@ -86,8 +86,8 @@ public class ReportMailingJobReadPlatformServiceImpl implements ReportMailingJob } } - return paginationHelper.fetchPage(this.jdbcTemplate, "SELECT FOUND_ROWS()", sqlStringBuilder.toString(), - queryParameters.toArray(), mapper); + return paginationHelper.fetchPage(this.jdbcTemplate, "SELECT FOUND_ROWS()", sqlStringBuilder.toString(), queryParameters.toArray(), + mapper); } @Override @@ -122,13 +122,13 @@ public class ReportMailingJobReadPlatformServiceImpl implements ReportMailingJob } private static final class ReportMailingJobMapper implements RowMapper { + public String reportMailingJobSchema() { return "rmj.id, rmj.name, rmj.description, rmj.start_datetime as startDateTime, rmj.recurrence, rmj.created_date as createdOnDate, " + "cbu.username as createdByUsername, cbu.firstname as createdByFirstname, cbu.lastname as createdByLastname, " + "rmj.lastmodified_date as updatedOnDate, " + "mbu.username as updatedByUsername, mbu.firstname as updatedByFirstname, mbu.lastname as updatedByLastname, " - + "rmj.email_recipients as emailRecipients, " - + "rmj.email_subject as emailSubject, rmj.email_message as emailMessage, " + + "rmj.email_recipients as emailRecipients, " + "rmj.email_subject as emailSubject, rmj.email_message as emailMessage, " + "rmj.email_attachment_file_format as emailAttachmentFileFormat, " + "rmj.stretchy_report_param_map as stretchyReportParamMap, rmj.previous_run_datetime as previousRunDateTime, " + "rmj.next_run_datetime as nextRunDateTime, rmj.previous_run_status as previousRunStatus, " @@ -136,14 +136,9 @@ public class ReportMailingJobReadPlatformServiceImpl implements ReportMailingJob + "rmj.number_of_runs as numberOfRuns, rmj.is_active as isActive, rmj.run_as_userid as runAsUserId, " + "sr.id as reportId, sr.report_name as reportName, sr.report_type as reportType, sr.report_subtype as reportSubType, " + "sr.report_category as reportCategory, sr.report_sql as reportSql, sr.description as reportDescription, " - + "sr.core_report as coreReport, sr.use_report as useReport " - + "from m_report_mailing_job rmj " - + "inner join m_appuser cbu " - + "on cbu.id = rmj.createdby_id " - + "left join m_appuser mbu " - + "on mbu.id = rmj.lastmodifiedby_id " - + "left join stretchy_report sr " - + "on rmj.stretchy_report_id = sr.id"; + + "sr.core_report as coreReport, sr.use_report as useReport " + "from m_report_mailing_job rmj " + + "inner join m_appuser cbu " + "on cbu.id = rmj.createdby_id " + "left join m_appuser mbu " + + "on mbu.id = rmj.lastmodifiedby_id " + "left join stretchy_report sr " + "on rmj.stretchy_report_id = sr.id"; } @Override @@ -162,7 +157,8 @@ public class ReportMailingJobReadPlatformServiceImpl implements ReportMailingJob EnumOptionData emailAttachmentFileFormat = null; if (emailAttachmentFileFormatString != null) { - ReportMailingJobEmailAttachmentFileFormat format = ReportMailingJobEmailAttachmentFileFormat.newInstance(emailAttachmentFileFormatString); + ReportMailingJobEmailAttachmentFileFormat format = ReportMailingJobEmailAttachmentFileFormat + .newInstance(emailAttachmentFileFormatString); emailAttachmentFileFormat = format.toEnumOptionData(); } @@ -200,8 +196,7 @@ public class ReportMailingJobReadPlatformServiceImpl implements ReportMailingJob return ReportMailingJobData.newInstance(id, name, description, startDateTime, recurrence, timeline, emailRecipients, emailSubject, emailMessage, emailAttachmentFileFormat, stretchyReport, stretchyReportParamMap, previousRunDateTime, - nextRunDateTime, previousRunStatus, previousRunErrorLog, previousRunErrorMessage, numberOfRuns, isActive, - runAsUserId); + nextRunDateTime, previousRunStatus, previousRunErrorLog, previousRunErrorMessage, numberOfRuns, isActive, runAsUserId); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobRunHistoryReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobRunHistoryReadPlatformService.java index ecd8a083f..d4bcd83e9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobRunHistoryReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobRunHistoryReadPlatformService.java @@ -23,11 +23,15 @@ import org.apache.fineract.infrastructure.core.service.SearchParameters; import org.apache.fineract.infrastructure.reportmailingjob.data.ReportMailingJobRunHistoryData; public interface ReportMailingJobRunHistoryReadPlatformService { + /** - * Retrieve all report mailing run history with similar job id to the one passed + * Retrieve all report mailing run history with similar job id to the one + * passed * - * @param reportMailingJobId ReportMailingJob identifier - * @param searchParameters {@link SearchParameters} object + * @param reportMailingJobId + * ReportMailingJob identifier + * @param searchParameters + * {@link SearchParameters} object * @return collection of {@link ReportMailingJobRunHistoryData} objects **/ Page retrieveRunHistoryByJobId(Long reportMailingJobId, SearchParameters searchParameters); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobRunHistoryReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobRunHistoryReadPlatformServiceImpl.java index 2abfa34fa..02b25bf6d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobRunHistoryReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobRunHistoryReadPlatformServiceImpl.java @@ -37,14 +37,14 @@ import org.springframework.stereotype.Service; @Service public class ReportMailingJobRunHistoryReadPlatformServiceImpl implements ReportMailingJobRunHistoryReadPlatformService { + private final JdbcTemplate jdbcTemplate; private final ReportMailingJobRunHistoryMapper reportMailingJobRunHistoryMapper; private final ColumnValidator columnValidator; private final PaginationHelper paginationHelper = new PaginationHelper<>(); @Autowired - public ReportMailingJobRunHistoryReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + public ReportMailingJobRunHistoryReadPlatformServiceImpl(final RoutingDataSource dataSource, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.reportMailingJobRunHistoryMapper = new ReportMailingJobRunHistoryMapper(); this.columnValidator = columnValidator; @@ -86,11 +86,11 @@ public class ReportMailingJobRunHistoryReadPlatformServiceImpl implements Report } private static final class ReportMailingJobRunHistoryMapper implements RowMapper { + public String reportMailingJobRunHistorySchema() { return "rmjrh.id, rmjrh.job_id as reportMailingJobId, rmjrh.start_datetime as startDateTime, " + "rmjrh.end_datetime as endDateTime, rmjrh.status, rmjrh.error_message as errorMessage, " - + "rmjrh.error_log as errorLog " - + "from m_report_mailing_job_run_history rmjrh"; + + "rmjrh.error_log as errorLog " + "from m_report_mailing_job_run_history rmjrh"; } @Override @@ -103,8 +103,8 @@ public class ReportMailingJobRunHistoryReadPlatformServiceImpl implements Report final String errorMessage = rs.getString("errorMessage"); final String errorLog = rs.getString("errorLog"); - return ReportMailingJobRunHistoryData.newInstance(id, reportMailingJobId, startDateTime, endDateTime, status, - errorMessage, errorLog); + return ReportMailingJobRunHistoryData.newInstance(id, reportMailingJobId, startDateTime, endDateTime, status, errorMessage, + errorLog); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobWritePlatformService.java index ce549191c..349a5a345 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobWritePlatformService.java @@ -23,8 +23,12 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; import org.apache.fineract.infrastructure.jobs.exception.JobExecutionException; public interface ReportMailingJobWritePlatformService { + CommandProcessingResult createReportMailingJob(JsonCommand jsonCommand); + CommandProcessingResult updateReportMailingJob(Long reportMailingJobId, JsonCommand jsonCommand); + CommandProcessingResult deleteReportMailingJob(Long reportMailingJobId); + void executeReportMailingJobs() throws JobExecutionException; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobWritePlatformServiceImpl.java index 3924a083e..094896abe 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/service/ReportMailingJobWritePlatformServiceImpl.java @@ -90,10 +90,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo public ReportMailingJobWritePlatformServiceImpl(final ReportRepositoryWrapper reportRepositoryWrapper, final ReportMailingJobValidator reportMailingJobValidator, final ReportMailingJobRepositoryWrapper reportMailingJobRepositoryWrapper, - final ReportMailingJobRepository reportMailingJobRepository, - final PlatformSecurityContext platformSecurityContext, - final ReportMailingJobEmailService reportMailingJobEmailService, - final ReadReportingService readReportingService, + final ReportMailingJobRepository reportMailingJobRepository, final PlatformSecurityContext platformSecurityContext, + final ReportMailingJobEmailService reportMailingJobEmailService, final ReadReportingService readReportingService, final ReportMailingJobRunHistoryRepository reportMailingJobRunHistoryRepository, final ReportingProcessServiceProvider reportingProcessServiceProvider) { this.reportRepositoryWrapper = reportRepositoryWrapper; @@ -117,17 +115,18 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo final AppUser appUser = this.platformSecurityContext.authenticatedUser(); // get the stretchy Report object - final Report stretchyReport = this.reportRepositoryWrapper.findOneThrowExceptionIfNotFound(jsonCommand.longValueOfParameterNamed( - ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME)); + final Report stretchyReport = this.reportRepositoryWrapper.findOneThrowExceptionIfNotFound( + jsonCommand.longValueOfParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME)); - // create an instance of ReportMailingJob class from the JsonCommand object + // create an instance of ReportMailingJob class from the JsonCommand + // object final ReportMailingJob reportMailingJob = ReportMailingJob.newInstance(jsonCommand, stretchyReport, appUser); // save entity this.reportMailingJobRepository.save(reportMailingJob); - return new CommandProcessingResultBuilder().withCommandId(jsonCommand.commandId()). - withEntityId(reportMailingJob.getId()).build(); + return new CommandProcessingResultBuilder().withCommandId(jsonCommand.commandId()).withEntityId(reportMailingJob.getId()) + .build(); } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(jsonCommand, dve); @@ -143,7 +142,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo this.reportMailingJobValidator.validateUpdateRequest(jsonCommand); // retrieve the ReportMailingJob object from the database - final ReportMailingJob reportMailingJob = this.reportMailingJobRepositoryWrapper.findOneThrowExceptionIfNotFound(reportMailingJobId); + final ReportMailingJob reportMailingJob = this.reportMailingJobRepositoryWrapper + .findOneThrowExceptionIfNotFound(reportMailingJobId); final Map changes = reportMailingJob.update(jsonCommand); @@ -184,7 +184,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo // update the next run time property reportMailingJob.updateNextRunDateTime(nextRecurringDateTime); - // check if the next run DateTime is not empty and the recurrence is empty + // check if the next run DateTime is not empty and the + // recurrence is empty } else if (StringUtils.isBlank(recurrence) && (nextRunDateTime != null)) { // the next run DateTime should be set to null reportMailingJob.updateNextRunDateTime(null); @@ -194,7 +195,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo if (changes.containsKey(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME)) { final DateTime startDateTime = reportMailingJob.getStartDateTime(); - // initially set the next recurring date time to the new start date time + // initially set the next recurring date time to the new start + // date time DateTime nextRecurringDateTime = startDateTime; // ensure that the recurrence pattern string is not empty @@ -208,15 +210,13 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo } if (!changes.isEmpty()) { - // save and flush immediately so any data integrity exception can be handled in the "catch" block + // save and flush immediately so any data integrity exception + // can be handled in the "catch" block this.reportMailingJobRepository.saveAndFlush(reportMailingJob); } - return new CommandProcessingResultBuilder(). - withCommandId(jsonCommand.commandId()). - withEntityId(reportMailingJob.getId()). - with(changes). - build(); + return new CommandProcessingResultBuilder().withCommandId(jsonCommand.commandId()).withEntityId(reportMailingJob.getId()) + .with(changes).build(); } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(jsonCommand, dve); @@ -228,9 +228,11 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo @Transactional public CommandProcessingResult deleteReportMailingJob(Long reportMailingJobId) { // retrieve the ReportMailingJob object from the database - final ReportMailingJob reportMailingJob = this.reportMailingJobRepositoryWrapper.findOneThrowExceptionIfNotFound(reportMailingJobId); + final ReportMailingJob reportMailingJob = this.reportMailingJobRepositoryWrapper + .findOneThrowExceptionIfNotFound(reportMailingJobId); - // delete the report mailing job by setting the isDeleted property to 1 and altering the name + // delete the report mailing job by setting the isDeleted property to 1 + // and altering the name reportMailingJob.delete(); // save the report mailing job entity @@ -242,7 +244,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo @Override @CronTarget(jobName = JobName.EXECUTE_REPORT_MAILING_JOBS) public void executeReportMailingJobs() throws JobExecutionException { - final Collection reportMailingJobCollection = this.reportMailingJobRepository.findByIsActiveTrueAndIsDeletedFalse(); + final Collection reportMailingJobCollection = this.reportMailingJobRepository + .findByIsActiveTrueAndIsDeletedFalse(); for (ReportMailingJob reportMailingJob : reportMailingJobCollection) { // get the tenant's date as a DateTime object @@ -251,19 +254,20 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo if (nextRunDateTime != null && nextRunDateTime.isBefore(localDateTimeOftenant)) { // get the emailAttachmentFileFormat enum object - final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat. - newInstance(reportMailingJob.getEmailAttachmentFileFormat()); + final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat + .newInstance(reportMailingJob.getEmailAttachmentFileFormat()); if (emailAttachmentFileFormat != null && emailAttachmentFileFormat.isValid()) { final Report stretchyReport = reportMailingJob.getStretchyReport(); final String reportName = (stretchyReport != null) ? stretchyReport.getReportName() : null; final StringBuilder errorLog = new StringBuilder(); - final Map validateStretchyReportParamMap = this.reportMailingJobValidator. - validateStretchyReportParamMap(reportMailingJob.getStretchyReportParamMap()); + final Map validateStretchyReportParamMap = this.reportMailingJobValidator + .validateStretchyReportParamMap(reportMailingJob.getStretchyReportParamMap()); MultivaluedMap reportParams = new MultivaluedMapImpl(); if (validateStretchyReportParamMap != null) { - Iterator> validateStretchyReportParamMapEntries = validateStretchyReportParamMap.entrySet().iterator(); + Iterator> validateStretchyReportParamMapEntries = validateStretchyReportParamMap + .entrySet().iterator(); while (validateStretchyReportParamMapEntries.hasNext()) { Map.Entry validateStretchyReportParamMapEntry = validateStretchyReportParamMapEntries.next(); @@ -271,8 +275,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo String value = validateStretchyReportParamMapEntry.getValue(); if (StringUtils.containsIgnoreCase(key, "date")) { - ReportMailingJobStretchyReportParamDateOption reportMailingJobStretchyReportParamDateOption = - ReportMailingJobStretchyReportParamDateOption.newInstance(value); + ReportMailingJobStretchyReportParamDateOption reportMailingJobStretchyReportParamDateOption = ReportMailingJobStretchyReportParamDateOption + .newInstance(value); if (reportMailingJobStretchyReportParamDateOption.isValid()) { value = ReportMailingJobDateUtil.getDateAsString(reportMailingJobStretchyReportParamDateOption); @@ -283,10 +287,12 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo } } - // generate the report output stream, method in turn call another that sends the file to the email recipients + // generate the report output stream, method in turn call + // another that sends the file to the email recipients this.generateReportOutputStream(reportMailingJob, emailAttachmentFileFormat, reportParams, reportName, errorLog); - // update the previous run time, next run time, status, error log properties + // update the previous run time, next run time, status, + // error log properties this.updateReportMailingJobAfterJobExecution(reportMailingJob, errorLog, localDateTimeOftenant); } } @@ -296,9 +302,12 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo /** * update the report mailing job entity after job execution * - * @param reportMailingJob -- the report mailing job entity - * @param errorLog -- StringBuilder object containing the error log if any - * @param jobStartDateTime -- the start DateTime of the job + * @param reportMailingJob + * -- the report mailing job entity + * @param errorLog + * -- StringBuilder object containing the error log if any + * @param jobStartDateTime + * -- the start DateTime of the job * **/ private void updateReportMailingJobAfterJobExecution(final ReportMailingJob reportMailingJob, final StringBuilder errorLog, @@ -318,7 +327,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo reportMailingJob.updatePreviousRunStatus(reportMailingJobPreviousRunStatus.getValue()); reportMailingJob.updatePreviousRunDateTime(reportMailingJob.getNextRunDateTime()); - // check if the job has a recurrence pattern, if not deactivate the job. The job will only run once + // check if the job has a recurrence pattern, if not deactivate the job. + // The job will only run once if (StringUtils.isEmpty(recurrence)) { // deactivate job reportMailingJob.deactivate(); @@ -341,7 +351,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo } /** - * create the next recurring DateTime from recurrence pattern, start DateTime and current DateTime + * create the next recurring DateTime from recurrence pattern, start + * DateTime and current DateTime * * @param recurrencePattern * @param startDateTime @@ -355,8 +366,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo final LocalDate nextDayLocalDate = startDateTime.plus(Duration.standardDays(1)).toLocalDate(); final LocalDate nextRecurringLocalDate = CalendarUtils.getNextRecurringDate(recurrencePattern, startDateTime.toLocalDate(), nextDayLocalDate); - final String nextDateTimeString = nextRecurringLocalDate + " " + startDateTime.getHourOfDay() + ":" + startDateTime.getMinuteOfHour() - + ":" + startDateTime.getSecondOfMinute(); + final String nextDateTimeString = nextRecurringLocalDate + " " + startDateTime.getHourOfDay() + ":" + + startDateTime.getMinuteOfHour() + ":" + startDateTime.getSecondOfMinute(); final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(DATETIME_FORMAT); nextRecurringDateTime = DateTime.parse(nextDateTimeString, dateTimeFormatter); @@ -368,18 +379,22 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo /** * create a new report mailing job run history entity after job execution * - * @param reportMailingJob -- the report mailing job entity - * @param errorLog -- StringBuilder object containing the error log if any - * @param jobStartDateTime -- the start DateTime of the job - * @param jobRunStatus -- the status of the job (success/error) + * @param reportMailingJob + * -- the report mailing job entity + * @param errorLog + * -- StringBuilder object containing the error log if any + * @param jobStartDateTime + * -- the start DateTime of the job + * @param jobRunStatus + * -- the status of the job (success/error) * **/ private void createReportMailingJobRunHistroryAfterJobExecution(final ReportMailingJob reportMailingJob, final StringBuilder errorLog, final DateTime jobStartDateTime, final String jobRunStatus) { final DateTime jobEndDateTime = DateUtils.getLocalDateTimeOfTenant().toDateTime(); final String errorLogToString = (errorLog != null) ? errorLog.toString() : null; - final ReportMailingJobRunHistory reportMailingJobRunHistory = ReportMailingJobRunHistory.newInstance(reportMailingJob, jobStartDateTime, - jobEndDateTime, jobRunStatus, null, errorLogToString); + final ReportMailingJobRunHistory reportMailingJobRunHistory = ReportMailingJobRunHistory.newInstance(reportMailingJob, + jobStartDateTime, jobEndDateTime, jobRunStatus, null, errorLogToString); this.reportMailingJobRunHistoryRepository.save(reportMailingJobRunHistory); } @@ -387,8 +402,10 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo /** * Handle any SQL data integrity issue * - * @param jsonCommand -- JsonCommand object - * @param dve -- data integrity exception object + * @param jsonCommand + * -- JsonCommand object + * @param dve + * -- data integrity exception object * **/ private void handleDataIntegrityIssues(final JsonCommand jsonCommand, final DataIntegrityViolationException dve) { @@ -396,8 +413,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo if (realCause.getMessage().contains(ReportMailingJobConstants.NAME_PARAM_NAME)) { final String name = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.NAME_PARAM_NAME); - throw new PlatformDataIntegrityException("error.msg.report.mailing.job.duplicate.name", "Report mailing job with name `" + name + "` already exists", - ReportMailingJobConstants.NAME_PARAM_NAME, name); + throw new PlatformDataIntegrityException("error.msg.report.mailing.job.duplicate.name", + "Report mailing job with name `" + name + "` already exists", ReportMailingJobConstants.NAME_PARAM_NAME, name); } LOG.error("Error occured.", dve); @@ -416,13 +433,15 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo * @param errorLog * @return the error log StringBuilder object */ - private StringBuilder generateReportOutputStream(final ReportMailingJob reportMailingJob, final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat, - final MultivaluedMap reportParams, final String reportName, final StringBuilder errorLog) { + private StringBuilder generateReportOutputStream(final ReportMailingJob reportMailingJob, + final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat, final MultivaluedMap reportParams, + final String reportName, final StringBuilder errorLog) { try { final boolean isSelfServiceUserReport = false; final String reportType = this.readReportingService.getReportType(reportName, isSelfServiceUserReport); - final ReportingProcessService reportingProcessService = this.reportingProcessServiceProvider.findReportingProcessService(reportType); + final ReportingProcessService reportingProcessService = this.reportingProcessServiceProvider + .findReportingProcessService(reportType); if (reportingProcessService != null) { final Response processReport = reportingProcessService.processRequest(reportName, reportParams); @@ -453,8 +472,8 @@ public class ReportMailingJobWritePlatformServiceImpl implements ReportMailingJo errorLog.append("ReportingProcessService object is null ---------- "); } } catch (Exception e) { - errorLog.append("The ReportMailingJobWritePlatformServiceImpl.generateReportOutputStream method threw an Exception: " - + e + " ---------- "); + errorLog.append("The ReportMailingJobWritePlatformServiceImpl.generateReportOutputStream method threw an Exception: " + e + + " ---------- "); } return errorLog; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/util/ReportMailingJobDateUtil.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/util/ReportMailingJobDateUtil.java index 0a8a92a77..18e6c539a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/util/ReportMailingJobDateUtil.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/util/ReportMailingJobDateUtil.java @@ -24,6 +24,7 @@ import java.util.Date; import org.apache.fineract.infrastructure.reportmailingjob.data.ReportMailingJobStretchyReportParamDateOption; public class ReportMailingJobDateUtil { + public static final String MYSQL_DATE_FORMAT = "yyyy-MM-dd"; /** @@ -36,7 +37,8 @@ public class ReportMailingJobDateUtil { // get a date to represent "today" Date today = calendar.getTime(); - // get a SimpleDateFormat instance, passing the mysql date format as parameter + // get a SimpleDateFormat instance, passing the mysql date format as + // parameter SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MYSQL_DATE_FORMAT); // return date as string @@ -56,7 +58,8 @@ public class ReportMailingJobDateUtil { // now get "yesterday" Date yesterday = calendar.getTime(); - // get a SimpleDateFormat instance, passing the mysql date format as parameter + // get a SimpleDateFormat instance, passing the mysql date format as + // parameter SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MYSQL_DATE_FORMAT); // return date as string @@ -76,7 +79,8 @@ public class ReportMailingJobDateUtil { // now get "tomorrow" Date tomorrow = calendar.getTime(); - // get a SimpleDateFormat instance, passing the mysql date format as parameter + // get a SimpleDateFormat instance, passing the mysql date format as + // parameter SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MYSQL_DATE_FORMAT); // return date as string @@ -84,28 +88,31 @@ public class ReportMailingJobDateUtil { } /** - * get date as string based on the value of the {@link ReportMailingJobStretchyReportParamDateOption} object + * get date as string based on the value of the + * {@link ReportMailingJobStretchyReportParamDateOption} object * - * @param reportMailingJobStretchyReportParamDateOption {@link ReportMailingJobStretchyReportParamDateOption} Enum + * @param reportMailingJobStretchyReportParamDateOption + * {@link ReportMailingJobStretchyReportParamDateOption} Enum **/ - public static String getDateAsString(final ReportMailingJobStretchyReportParamDateOption reportMailingJobStretchyReportParamDateOption) { + public static String getDateAsString( + final ReportMailingJobStretchyReportParamDateOption reportMailingJobStretchyReportParamDateOption) { String dateAsString = null; switch (reportMailingJobStretchyReportParamDateOption) { case TODAY: dateAsString = getTodayDateAsString(); - break; + break; case YESTERDAY: dateAsString = getYesterdayDateAsString(); - break; + break; case TOMORROW: dateAsString = getTomorrowDateAsString(); - break; + break; default: - break; + break; } return dateAsString; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/validation/ReportMailingJobValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/validation/ReportMailingJobValidator.java index 648bbfabb..eff75d9cc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/validation/ReportMailingJobValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/reportmailingjob/validation/ReportMailingJobValidator.java @@ -48,6 +48,7 @@ import org.springframework.stereotype.Component; @Component public class ReportMailingJobValidator { + private final FromJsonHelper fromJsonHelper; private static final String EMAIL_REGEX = "^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"; private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX); @@ -60,24 +61,22 @@ public class ReportMailingJobValidator { /** * validate the request to create a new report mailing job * - * @param jsonCommand -- the JSON command object (instance of the JsonCommand class) + * @param jsonCommand + * -- the JSON command object (instance of the JsonCommand class) * **/ public void validateCreateRequest(final JsonCommand jsonCommand) { final String jsonString = jsonCommand.json(); final JsonElement jsonElement = jsonCommand.parsedJson(); - if (StringUtils.isBlank(jsonString)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(jsonString)) { throw new InvalidJsonException(); } final Type typeToken = new TypeToken>() {}.getType(); - this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, - ReportMailingJobConstants.CREATE_REQUEST_PARAMETERS); + this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, ReportMailingJobConstants.CREATE_REQUEST_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors). - resource(StringUtils.lowerCase(ReportMailingJobConstants.REPORT_MAILING_JOB_RESOURCE_NAME)); + final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors) + .resource(StringUtils.lowerCase(ReportMailingJobConstants.REPORT_MAILING_JOB_RESOURCE_NAME)); final String name = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.NAME_PARAM_NAME, jsonElement); dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.NAME_PARAM_NAME).value(name).notBlank().notExceedingLengthOf(100); @@ -86,34 +85,35 @@ public class ReportMailingJobValidator { jsonElement); dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME).value(startDateTime).notBlank(); - final Integer stretchyReportId = this.fromJsonHelper.extractIntegerWithLocaleNamed(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, - jsonElement); - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME).value(stretchyReportId).notNull(). - integerGreaterThanZero(); + final Integer stretchyReportId = this.fromJsonHelper + .extractIntegerWithLocaleNamed(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement); + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME).value(stretchyReportId).notNull() + .integerGreaterThanZero(); - final String emailRecipients = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement); + final String emailRecipients = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME, + jsonElement); dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME).value(emailRecipients).notBlank(); final String emailSubject = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement); - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME).value(emailSubject).notBlank().notExceedingLengthOf(100); + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME).value(emailSubject).notBlank() + .notExceedingLengthOf(100); final String emailMessage = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement); dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME).value(emailMessage).notBlank(); if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement)) { - final Boolean isActive = this.fromJsonHelper.extractBooleanNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, - jsonElement); + final Boolean isActive = this.fromJsonHelper.extractBooleanNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement); dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME).value(isActive).notNull(); } - final Integer emailAttachmentFileFormatId = this.fromJsonHelper.extractIntegerSansLocaleNamed( - ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement); - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME). - value(emailAttachmentFileFormatId).notNull(); + final Integer emailAttachmentFileFormatId = this.fromJsonHelper + .extractIntegerSansLocaleNamed(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement); + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME) + .value(emailAttachmentFileFormatId).notNull(); if (emailAttachmentFileFormatId != null) { - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME).value(emailAttachmentFileFormatId). - isOneOfTheseValues(ReportMailingJobEmailAttachmentFileFormat.validIds()); + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME) + .value(emailAttachmentFileFormatId).isOneOfTheseValues(ReportMailingJobEmailAttachmentFileFormat.validIds()); } final String dateFormat = jsonCommand.dateFormat(); @@ -128,8 +128,9 @@ public class ReportMailingJobValidator { LocalDateTime.parse(startDateTime, dateTimeFormatter); } - catch(IllegalArgumentException ex) { - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat).failWithCode("invalid.date.format"); + catch (IllegalArgumentException ex) { + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat) + .failWithCode("invalid.date.format"); } } @@ -139,67 +140,69 @@ public class ReportMailingJobValidator { /** * validate the request to update a report mailing job * - * @param jsonCommand -- the JSON command object (instance of the JsonCommand class) + * @param jsonCommand + * -- the JSON command object (instance of the JsonCommand class) * **/ public void validateUpdateRequest(final JsonCommand jsonCommand) { final String jsonString = jsonCommand.json(); final JsonElement jsonElement = jsonCommand.parsedJson(); - if (StringUtils.isBlank(jsonString)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(jsonString)) { throw new InvalidJsonException(); } final Type typeToken = new TypeToken>() {}.getType(); - this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, - ReportMailingJobConstants.UPDATE_REQUEST_PARAMETERS); + this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, ReportMailingJobConstants.UPDATE_REQUEST_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors). - resource(StringUtils.lowerCase(ReportMailingJobConstants.REPORT_MAILING_JOB_RESOURCE_NAME)); + final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors) + .resource(StringUtils.lowerCase(ReportMailingJobConstants.REPORT_MAILING_JOB_RESOURCE_NAME)); if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.NAME_PARAM_NAME, jsonElement)) { final String name = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.NAME_PARAM_NAME, jsonElement); - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.NAME_PARAM_NAME).value(name).notBlank().notExceedingLengthOf(100); + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.NAME_PARAM_NAME).value(name).notBlank() + .notExceedingLengthOf(100); } if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement)) { - final Integer stretchyReportId = this.fromJsonHelper.extractIntegerWithLocaleNamed(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, - jsonElement); - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME).value(stretchyReportId).notNull(). - integerGreaterThanZero(); + final Integer stretchyReportId = this.fromJsonHelper + .extractIntegerWithLocaleNamed(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement); + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME).value(stretchyReportId) + .notNull().integerGreaterThanZero(); } if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement)) { - final String emailRecipients = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement); + final String emailRecipients = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME, + jsonElement); dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME).value(emailRecipients).notBlank(); } if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement)) { - final String emailSubject = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement); - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME).value(emailSubject).notBlank().notExceedingLengthOf(100); + final String emailSubject = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, + jsonElement); + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME).value(emailSubject).notBlank() + .notExceedingLengthOf(100); } if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement)) { - final String emailMessage = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement); + final String emailMessage = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, + jsonElement); dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME).value(emailMessage).notBlank(); } if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement)) { - final Boolean isActive = this.fromJsonHelper.extractBooleanNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, - jsonElement); + final Boolean isActive = this.fromJsonHelper.extractBooleanNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement); dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME).value(isActive).notNull(); } if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement)) { - final Integer emailAttachmentFileFormatId = this.fromJsonHelper.extractIntegerSansLocaleNamed( - ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement); - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME). - value(emailAttachmentFileFormatId).notNull(); + final Integer emailAttachmentFileFormatId = this.fromJsonHelper + .extractIntegerSansLocaleNamed(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement); + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME) + .value(emailAttachmentFileFormatId).notNull(); if (emailAttachmentFileFormatId != null) { - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME).value(emailAttachmentFileFormatId). - isOneOfTheseValues(ReportMailingJobEmailAttachmentFileFormat.validIds()); + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME) + .value(emailAttachmentFileFormatId).isOneOfTheseValues(ReportMailingJobEmailAttachmentFileFormat.validIds()); } } @@ -208,20 +211,22 @@ public class ReportMailingJobValidator { dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat).notBlank(); final String startDateTime = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME, - jsonElement); + jsonElement); dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME).value(startDateTime).notBlank(); if (StringUtils.isNotEmpty(dateFormat)) { try { - final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateFormat).withLocale(jsonCommand.extractLocale()); + final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateFormat) + .withLocale(jsonCommand.extractLocale()); // try to parse the date time string LocalDateTime.parse(startDateTime, dateTimeFormatter); } - catch(IllegalArgumentException ex) { - dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat).failWithCode("invalid.date.format"); + catch (IllegalArgumentException ex) { + dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat) + .failWithCode("invalid.date.format"); } } } @@ -232,27 +237,22 @@ public class ReportMailingJobValidator { /** * check if string is a valid email address * - * @param email -- string to be validated + * @param email + * -- string to be validated * @return true if string is a valid email address **/ public boolean isValidEmail(String email) { // this is the easiest check - if (email == null) { - return false; - } + if (email == null) { return false; } // this is another easy check - if (email.endsWith(".")) { - return false; - } + if (email.endsWith(".")) { return false; } // Check the whole email address structure Matcher emailMatcher = EMAIL_PATTERN.matcher(email); // check if the Matcher matches the email pattern - if (!emailMatcher.matches()) { - return false; - } + if (!emailMatcher.matches()) { return false; } return true; } @@ -260,7 +260,8 @@ public class ReportMailingJobValidator { /** * Validate the email recipients string * - * @param emailRecipients -- the email recipients string to be validated + * @param emailRecipients + * -- the email recipients string to be validated * @return a hashset containing valid email addresses **/ public Set validateEmailRecipients(String emailRecipients) { @@ -284,18 +285,20 @@ public class ReportMailingJobValidator { /** * validate the stretchy report param json string * - * @param stretchyReportParamMap -- json string to be validated + * @param stretchyReportParamMap + * -- json string to be validated * @return if string is valid or empty, a HashMap object, else null **/ - public HashMap validateStretchyReportParamMap(String stretchyReportParamMap) { - HashMap stretchyReportParamHashMap = new HashMap<>(); + public HashMap validateStretchyReportParamMap(String stretchyReportParamMap) { + HashMap stretchyReportParamHashMap = new HashMap<>(); if (!StringUtils.isEmpty(stretchyReportParamMap)) { try { - stretchyReportParamHashMap = new ObjectMapper().readValue(stretchyReportParamMap, new TypeReference>(){}); + stretchyReportParamHashMap = new ObjectMapper().readValue(stretchyReportParamMap, + new TypeReference>() {}); } - catch(Exception e) { + catch (Exception e) { stretchyReportParamHashMap = null; } } @@ -304,14 +307,14 @@ public class ReportMailingJobValidator { } /** - * throw a PlatformApiDataValidationException exception if there are validation errors + * throw a PlatformApiDataValidationException exception if there are + * validation errors * - * @param dataValidationErrors -- list of ApiParameterError objects + * @param dataValidationErrors + * -- list of ApiParameterError objects * **/ private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/AuthenticationApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/AuthenticationApiResource.java index 4b017c9ba..d3ed86423 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/AuthenticationApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/AuthenticationApiResource.java @@ -58,13 +58,13 @@ import org.springframework.stereotype.Component; @Scope("singleton") @Profile("basicauth") @Path("/authentication") -@Api(tags = {"Authentication HTTP Basic"}) +@Api(tags = { "Authentication HTTP Basic" }) @SwaggerDefinition(tags = { - @Tag(name = "Authentication HTTP Basic", description = "An API capability that allows client applications to verify authentication details using HTTP Basic Authentication.") -}) + @Tag(name = "Authentication HTTP Basic", description = "An API capability that allows client applications to verify authentication details using HTTP Basic Authentication.") }) public class AuthenticationApiResource { public static class AuthenticateRequest { + public String username; public String password; } @@ -89,15 +89,19 @@ public class AuthenticationApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Verify authentication", notes = "Authenticates the credentials provided and returns the set roles and permissions allowed.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = AuthenticationApiResourceSwagger.PostAuthenticationResponse.class), @ApiResponse(code = 400, message = "Unauthenticated. Please login")}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = AuthenticationApiResourceSwagger.PostAuthenticationResponse.class), + @ApiResponse(code = 400, message = "Unauthenticated. Please login") }) public String authenticate(final String apiRequestBodyAsJson) { - // TODO FINERACT-819: sort out Jersey so JSON conversion does not have to be done explicitly via GSON here, but implicit by arg + // TODO FINERACT-819: sort out Jersey so JSON conversion does not have + // to be done explicitly via GSON here, but implicit by arg AuthenticateRequest request = new Gson().fromJson(apiRequestBodyAsJson, AuthenticateRequest.class); if (request == null) { - throw new IllegalArgumentException("Invalid JSON in BODY (no longer URL param; see FINERACT-726) of POST to /authentication: " + apiRequestBodyAsJson); + throw new IllegalArgumentException( + "Invalid JSON in BODY (no longer URL param; see FINERACT-726) of POST to /authentication: " + apiRequestBodyAsJson); } if (request.username == null || request.password == null) { - throw new IllegalArgumentException("Username or Password is null in JSON (see FINERACT-726) of POST to /authentication: " + apiRequestBodyAsJson + "; username=" + request.username + ", password=" + request.password); + throw new IllegalArgumentException("Username or Password is null in JSON (see FINERACT-726) of POST to /authentication: " + + apiRequestBodyAsJson + "; username=" + request.username + ", password=" + request.password); } final Authentication authentication = new UsernamePasswordAuthenticationToken(request.username, request.password); @@ -129,8 +133,8 @@ public class AuthenticationApiResource { final EnumOptionData organisationalRole = principal.organisationalRoleData(); - boolean isTwoFactorRequired = twoFactorUtils.isTwoFactorAuthEnabled() && ! - principal.hasSpecificPermissionTo(TwoFactorConstants.BYPASS_TWO_FACTOR_PERMISSION); + boolean isTwoFactorRequired = twoFactorUtils.isTwoFactorAuthEnabled() + && !principal.hasSpecificPermissionTo(TwoFactorConstants.BYPASS_TWO_FACTOR_PERMISSION); if (this.springSecurityPlatformSecurityContext.doesPasswordHasToBeRenewed(principal)) { authenticatedUserData = new AuthenticatedUserData(request.username, principal.getId(), new String(base64EncodedAuthenticationKey, StandardCharsets.UTF_8), isTwoFactorRequired); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/AuthenticationApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/AuthenticationApiResourceSwagger.java index 1150ed778..7b511fef1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/AuthenticationApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/AuthenticationApiResourceSwagger.java @@ -28,15 +28,18 @@ import org.apache.fineract.useradministration.data.RoleData; * Created by sanyam on 13/8/17. */ final class AuthenticationApiResourceSwagger { - private AuthenticationApiResourceSwagger(){ + + private AuthenticationApiResourceSwagger() { } @ApiModel(value = "PostAuthenticationResponse") public static final class PostAuthenticationResponse { + private PostAuthenticationResponse() { } + @ApiModelProperty(example = "mifos") public String username; @ApiModelProperty(example = "1") diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/TwoFactorApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/TwoFactorApiResource.java index a5e5c7bf0..f00ff2bca 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/TwoFactorApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/TwoFactorApiResource.java @@ -54,7 +54,6 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class TwoFactorApiResource { - private final ToApiJsonSerializer otpRequestSerializer; private final ToApiJsonSerializer otpDeliveryMethodSerializer; private final ToApiJsonSerializer accessTokenSerializer; @@ -64,17 +63,11 @@ public class TwoFactorApiResource { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final TwoFactorService twoFactorService; - - @Autowired public TwoFactorApiResource(ToApiJsonSerializer otpRequestSerializer, - ToApiJsonSerializer otpDeliveryMethodSerializer, - ToApiJsonSerializer accessTokenSerializer, - DefaultToApiJsonSerializer> toApiJsonSerializer, - PlatformSecurityContext context, - PortfolioCommandSourceWritePlatformService - commandsSourceWritePlatformService, - TwoFactorService twoFactorService) { + ToApiJsonSerializer otpDeliveryMethodSerializer, ToApiJsonSerializer accessTokenSerializer, + DefaultToApiJsonSerializer> toApiJsonSerializer, PlatformSecurityContext context, + PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, TwoFactorService twoFactorService) { this.otpRequestSerializer = otpRequestSerializer; this.otpDeliveryMethodSerializer = otpDeliveryMethodSerializer; this.accessTokenSerializer = accessTokenSerializer; @@ -84,7 +77,6 @@ public class TwoFactorApiResource { this.twoFactorService = twoFactorService; } - @GET @Produces({ MediaType.APPLICATION_JSON }) public String getOTPDeliveryMethods(@Context final UriInfo uriInfo) { @@ -97,8 +89,7 @@ public class TwoFactorApiResource { @POST @Produces({ MediaType.APPLICATION_JSON }) public String requestToken(@QueryParam("deliveryMethod") final String deliveryMethod, - @QueryParam("extendedToken") @DefaultValue("false") boolean extendedAccessToken, - @Context final UriInfo uriInfo) { + @QueryParam("extendedToken") @DefaultValue("false") boolean extendedAccessToken, @Context final UriInfo uriInfo) { final AppUser user = context.authenticatedUser(); final OTPRequest request = twoFactorService.createNewOTPToken(user, deliveryMethod, extendedAccessToken); @@ -120,10 +111,9 @@ public class TwoFactorApiResource { @POST @Produces({ MediaType.APPLICATION_JSON }) public String updateConfiguration(final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .invalidateTwoFactorAccessToken().withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService. - logCommandSource(commandRequest); + final CommandWrapper commandRequest = new CommandWrapperBuilder().invalidateTwoFactorAccessToken().withJson(apiRequestBodyAsJson) + .build(); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/TwoFactorConfigurationApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/TwoFactorConfigurationApiResource.java index 53a361603..c6980ebdc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/TwoFactorConfigurationApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/TwoFactorConfigurationApiResource.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.infrastructure.security.api; - import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.GET; @@ -54,17 +53,15 @@ public class TwoFactorConfigurationApiResource { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public TwoFactorConfigurationApiResource(PlatformSecurityContext context, - TwoFactorConfigurationService configurationService, - DefaultToApiJsonSerializer> toApiJsonSerializer, - PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + public TwoFactorConfigurationApiResource(PlatformSecurityContext context, TwoFactorConfigurationService configurationService, + DefaultToApiJsonSerializer> toApiJsonSerializer, + PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.context = context; this.configurationService = configurationService; this.toApiJsonSerializer = toApiJsonSerializer; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } - @GET public String retrieveAll() { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -74,10 +71,9 @@ public class TwoFactorConfigurationApiResource { @PUT public String updateConfiguration(final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .updateTwoFactorConfiguration().withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService. - logCommandSource(commandRequest); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateTwoFactorConfiguration().withJson(apiRequestBodyAsJson) + .build(); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/UserDetailsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/UserDetailsApiResource.java index 163858a93..3dd768b00 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/UserDetailsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/UserDetailsApiResource.java @@ -58,10 +58,8 @@ import org.springframework.stereotype.Component; @Component @Profile("oauth") @Scope("singleton") -@Api(tags = {"Fetch authenticated user details"}) -@SwaggerDefinition(tags = { - @Tag(name = "Fetch authenticated user details", description = "") -}) +@Api(tags = { "Fetch authenticated user details" }) +@SwaggerDefinition(tags = { @Tag(name = "Fetch authenticated user details", description = "") }) @SuppressWarnings("deprecation") // TODO FINERACT-1012 public class UserDetailsApiResource { @@ -73,8 +71,7 @@ public class UserDetailsApiResource { @Autowired public UserDetailsApiResource(@Qualifier("tokenServices") final ResourceServerTokenServices tokenServices, final ToApiJsonSerializer apiJsonSerializerService, - final SpringSecurityPlatformSecurityContext springSecurityPlatformSecurityContext, - final TwoFactorUtils twoFactorUtils) { + final SpringSecurityPlatformSecurityContext springSecurityPlatformSecurityContext, final TwoFactorUtils twoFactorUtils) { this.tokenServices = tokenServices; this.apiJsonSerializerService = apiJsonSerializerService; this.springSecurityPlatformSecurityContext = springSecurityPlatformSecurityContext; @@ -84,7 +81,7 @@ public class UserDetailsApiResource { @GET @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Fetch authenticated user details\n", notes = "checks the Authentication and returns the set roles and permissions allowed.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = UserDetailsApiResourceSwagger.GetUserDetailsResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = UserDetailsApiResourceSwagger.GetUserDetailsResponse.class) }) public String fetchAuthenticatedUserData(@QueryParam("access_token") @ApiParam(value = "access_token") final String accessToken) { final Authentication authentication = this.tokenServices.loadAuthentication(accessToken); @@ -116,17 +113,16 @@ public class UserDetailsApiResource { final boolean requireTwoFactorAuth = twoFactorUtils.isTwoFactorAuthEnabled() && !principal.hasSpecificPermissionTo(TwoFactorConstants.BYPASS_TWO_FACTOR_PERMISSION); if (this.springSecurityPlatformSecurityContext.doesPasswordHasToBeRenewed(principal)) { - authenticatedUserData = new AuthenticatedOauthUserData(principal.getUsername(), - principal.getId(), accessToken, requireTwoFactorAuth); + authenticatedUserData = new AuthenticatedOauthUserData(principal.getUsername(), principal.getId(), accessToken, + requireTwoFactorAuth); } else { - authenticatedUserData = new AuthenticatedOauthUserData(principal.getUsername(), - officeId, officeName, staffId, staffDisplayName, organisationalRole, roles, - permissions, principal.getId(), accessToken, requireTwoFactorAuth); + authenticatedUserData = new AuthenticatedOauthUserData(principal.getUsername(), officeId, officeName, staffId, + staffDisplayName, organisationalRole, roles, permissions, principal.getId(), accessToken, requireTwoFactorAuth); } return this.apiJsonSerializerService.serialize(authenticatedUserData); } return null; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/UserDetailsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/UserDetailsApiResourceSwagger.java index 1c0413dc6..72cd2729f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/UserDetailsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/api/UserDetailsApiResourceSwagger.java @@ -28,15 +28,18 @@ import org.apache.fineract.useradministration.data.RoleData; * Created by sanyam on 13/8/17. */ final class UserDetailsApiResourceSwagger { + private UserDetailsApiResourceSwagger() { } @ApiModel(value = "GetUserDetailsResponse") public static final class GetUserDetailsResponse { - private GetUserDetailsResponse(){ + + private GetUserDetailsResponse() { } + @ApiModelProperty(example = "mifos") public String username; @ApiModelProperty(example = "1") diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/command/InvalidateTFAccessTokenCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/command/InvalidateTFAccessTokenCommandHandler.java index bbbc3137a..9e5b63d37 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/command/InvalidateTFAccessTokenCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/command/InvalidateTFAccessTokenCommandHandler.java @@ -47,21 +47,18 @@ import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - @Service @CommandType(entity = "TWOFACTOR_ACCESSTOKEN", action = "INVALIDATE") @Profile("twofactor") public class InvalidateTFAccessTokenCommandHandler implements NewCommandSourceHandler { - private final TwoFactorService twoFactorService; private final PlatformSecurityContext securityContext; private final FromJsonHelper fromJsonHelper; @Autowired - public InvalidateTFAccessTokenCommandHandler(TwoFactorService twoFactorService, - PlatformSecurityContext securityContext, - FromJsonHelper fromJsonHelper) { + public InvalidateTFAccessTokenCommandHandler(TwoFactorService twoFactorService, PlatformSecurityContext securityContext, + FromJsonHelper fromJsonHelper) { this.twoFactorService = twoFactorService; this.securityContext = securityContext; this.fromJsonHelper = fromJsonHelper; @@ -76,20 +73,15 @@ public class InvalidateTFAccessTokenCommandHandler implements NewCommandSourceHa final TFAccessToken accessToken = twoFactorService.invalidateAccessToken(user, command); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withResourceIdAsString(accessToken.getToken()) + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withResourceIdAsString(accessToken.getToken()) .build(); } private void validateJson(String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - new HashSet<>(Collections.singletonList("token"))); + this.fromJsonHelper.checkForUnsupportedParameters(typeOfMap, json, new HashSet<>(Collections.singletonList("token"))); final JsonElement element = this.fromJsonHelper.parse(json); final List dataValidationErrors = new ArrayList<>(); @@ -99,8 +91,6 @@ public class InvalidateTFAccessTokenCommandHandler implements NewCommandSourceHa final String token = this.fromJsonHelper.extractStringNamed("token", element); baseDataValidator.reset().parameter("token").value(token).notNull().notBlank(); - if(!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/command/UpdateTwoFactorConfigCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/command/UpdateTwoFactorConfigCommandHandler.java index 3ffe4c3f3..58b027b7f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/command/UpdateTwoFactorConfigCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/command/UpdateTwoFactorConfigCommandHandler.java @@ -41,7 +41,7 @@ public class UpdateTwoFactorConfigCommandHandler implements NewCommandSourceHand @Autowired public UpdateTwoFactorConfigCommandHandler(TwoFactorConfigurationService configurationService, - TwoFactorConfigurationValidator dataValidator) { + TwoFactorConfigurationValidator dataValidator) { this.configurationService = configurationService; this.dataValidator = dataValidator; } @@ -51,9 +51,6 @@ public class UpdateTwoFactorConfigCommandHandler implements NewCommandSourceHand public CommandProcessingResult processCommand(final JsonCommand command) { this.dataValidator.validateForUpdate(command.json()); final Map changes = configurationService.update(command); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .with(changes) - .build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).with(changes).build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/constants/TwoFactorConfigurationConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/constants/TwoFactorConfigurationConstants.java index ffc1e7055..0e77ec92f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/constants/TwoFactorConfigurationConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/constants/TwoFactorConfigurationConstants.java @@ -42,19 +42,17 @@ public class TwoFactorConfigurationConstants { public static final String ACCESS_TOKEN_LIVE_TIME = "access-token-live-time"; public static final String ACCESS_TOKEN_LIVE_TIME_EXTENDED = "access-token-live-time-extended"; - public static final Set REQUEST_DATA_PARAMETERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(ENABLE_EMAIL_DELIVERY, EMAIL_SUBJECT, EMAIL_BODY, - ENABLE_SMS_DELIVERY, SMS_PROVIDER_ID, SMS_MESSAGE_TEXT, OTP_TOKEN_LIVE_TIME, - OTP_TOKEN_LENGTH, ACCESS_TOKEN_LIVE_TIME, ACCESS_TOKEN_LIVE_TIME_EXTENDED))); + public static final Set REQUEST_DATA_PARAMETERS = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList(ENABLE_EMAIL_DELIVERY, EMAIL_SUBJECT, EMAIL_BODY, ENABLE_SMS_DELIVERY, SMS_PROVIDER_ID, + SMS_MESSAGE_TEXT, OTP_TOKEN_LIVE_TIME, OTP_TOKEN_LENGTH, ACCESS_TOKEN_LIVE_TIME, ACCESS_TOKEN_LIVE_TIME_EXTENDED))); - public static final List STRING_PARAMETERS = - Collections.unmodifiableList(Arrays.asList(EMAIL_SUBJECT, EMAIL_BODY, SMS_MESSAGE_TEXT)); + public static final List STRING_PARAMETERS = Collections + .unmodifiableList(Arrays.asList(EMAIL_SUBJECT, EMAIL_BODY, SMS_MESSAGE_TEXT)); - public static final List BOOLEAN_PARAMETERS = - Collections.unmodifiableList(Arrays.asList(ENABLE_EMAIL_DELIVERY, ENABLE_SMS_DELIVERY)); + public static final List BOOLEAN_PARAMETERS = Collections + .unmodifiableList(Arrays.asList(ENABLE_EMAIL_DELIVERY, ENABLE_SMS_DELIVERY)); - public static final List NUMBER_PARAMETERS = - Collections.unmodifiableList(Arrays.asList(SMS_PROVIDER_ID, OTP_TOKEN_LIVE_TIME, OTP_TOKEN_LENGTH, - ACCESS_TOKEN_LIVE_TIME, ACCESS_TOKEN_LIVE_TIME_EXTENDED)); + public static final List NUMBER_PARAMETERS = Collections.unmodifiableList( + Arrays.asList(SMS_PROVIDER_ID, OTP_TOKEN_LIVE_TIME, OTP_TOKEN_LENGTH, ACCESS_TOKEN_LIVE_TIME, ACCESS_TOKEN_LIVE_TIME_EXTENDED)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/AuthenticatedOauthUserData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/AuthenticatedOauthUserData.java index 11a3b9af4..f8c73e5ac 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/AuthenticatedOauthUserData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/AuthenticatedOauthUserData.java @@ -107,4 +107,4 @@ public class AuthenticatedOauthUserData { this.shouldRenewPassword = true; this.isTwoFactorAuthenticationRequired = isTwoFactorAuthenticationRequired; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/AuthenticatedUserData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/AuthenticatedUserData.java index 3a36b84bd..3df75c20e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/AuthenticatedUserData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/AuthenticatedUserData.java @@ -92,7 +92,7 @@ public class AuthenticatedUserData { } public AuthenticatedUserData(final String username, final Long userId, final String base64EncodedAuthenticationKey, - final boolean isTwoFactorAuthenticationRequired) { + final boolean isTwoFactorAuthenticationRequired) { this.username = username; this.officeId = null; this.officeName = null; @@ -107,4 +107,4 @@ public class AuthenticatedUserData { this.shouldRenewPassword = true; this.isTwoFactorAuthenticationRequired = isTwoFactorAuthenticationRequired; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/OTPMetadata.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/OTPMetadata.java index 0365fffe4..253826c9a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/OTPMetadata.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/OTPMetadata.java @@ -27,8 +27,7 @@ public class OTPMetadata { private final boolean extendedAccessToken; private final OTPDeliveryMethod deliveryMethod; - public OTPMetadata(DateTime requestTime, int tokenLiveTimeInSec, - boolean extendedAccessToken, OTPDeliveryMethod deliveryMethod) { + public OTPMetadata(DateTime requestTime, int tokenLiveTimeInSec, boolean extendedAccessToken, OTPDeliveryMethod deliveryMethod) { this.requestTime = requestTime; this.tokenLiveTimeInSec = tokenLiveTimeInSec; this.extendedAccessToken = extendedAccessToken; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/OTPRequest.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/OTPRequest.java index f9f3e2433..f0c623f66 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/OTPRequest.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/OTPRequest.java @@ -31,10 +31,9 @@ public class OTPRequest { this.metadata = metadata; } - public static OTPRequest create(String token, int tokenLiveTimeInSec, boolean extendedAccessToken, - OTPDeliveryMethod deliveryMethod) { - final OTPMetadata metadata = new OTPMetadata(DateUtils.getLocalDateTimeOfTenant().toDateTime(), - tokenLiveTimeInSec, extendedAccessToken, deliveryMethod); + public static OTPRequest create(String token, int tokenLiveTimeInSec, boolean extendedAccessToken, OTPDeliveryMethod deliveryMethod) { + final OTPMetadata metadata = new OTPMetadata(DateUtils.getLocalDateTimeOfTenant().toDateTime(), tokenLiveTimeInSec, + extendedAccessToken, deliveryMethod); return new OTPRequest(token, metadata); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/PlatformRequestLog.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/PlatformRequestLog.java index 1ea8bf39d..b2ccc06d7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/PlatformRequestLog.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/PlatformRequestLog.java @@ -59,4 +59,4 @@ public class PlatformRequestLog { this.url = requestUrl; this.parameters = parameters; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/TwoFactorConfigurationValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/TwoFactorConfigurationValidator.java index c95a8ed79..b1974bfb6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/TwoFactorConfigurationValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/data/TwoFactorConfigurationValidator.java @@ -47,43 +47,39 @@ public class TwoFactorConfigurationValidator { } public void validateForUpdate(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } boolean atLeastOneParameterPassedForUpdate = false; final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - TwoFactorConfigurationConstants.REQUEST_DATA_PARAMETERS); + this.fromJsonHelper.checkForUnsupportedParameters(typeOfMap, json, TwoFactorConfigurationConstants.REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromJsonHelper.parse(json); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(TwoFactorConfigurationConstants.RESOURCE_NAME); - - for(String parameterName : TwoFactorConfigurationConstants.BOOLEAN_PARAMETERS) { - if(this.fromJsonHelper.parameterExists(parameterName, element)) { + for (String parameterName : TwoFactorConfigurationConstants.BOOLEAN_PARAMETERS) { + if (this.fromJsonHelper.parameterExists(parameterName, element)) { atLeastOneParameterPassedForUpdate = true; validateBooleanParameter(parameterName, element, baseDataValidator); } } - for(String parameterName : TwoFactorConfigurationConstants.STRING_PARAMETERS) { - if(this.fromJsonHelper.parameterExists(parameterName, element)) { + for (String parameterName : TwoFactorConfigurationConstants.STRING_PARAMETERS) { + if (this.fromJsonHelper.parameterExists(parameterName, element)) { atLeastOneParameterPassedForUpdate = true; validateStringParameter(parameterName, element, baseDataValidator); } } - for(String parameterName : TwoFactorConfigurationConstants.NUMBER_PARAMETERS) { + for (String parameterName : TwoFactorConfigurationConstants.NUMBER_PARAMETERS) { if (this.fromJsonHelper.parameterExists(parameterName, element)) { atLeastOneParameterPassedForUpdate = true; validateNumberParameter(parameterName, element, baseDataValidator); } } - if(!atLeastOneParameterPassedForUpdate) { + if (!atLeastOneParameterPassedForUpdate) { final Object forceError = null; baseDataValidator.reset().anyOfNotNull(forceError); } @@ -91,28 +87,22 @@ public class TwoFactorConfigurationValidator { throwExceptionIfValidationWarningsExist(dataValidationErrors); } - private void throwExceptionIfValidationWarningsExist( - final List dataValidationErrors) { - if(!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - private void validateBooleanParameter(final String name, final JsonElement element, - final DataValidatorBuilder baseDataValidator) { + private void validateBooleanParameter(final String name, final JsonElement element, final DataValidatorBuilder baseDataValidator) { final String value = this.fromJsonHelper.extractStringNamed(name, element); baseDataValidator.reset().parameter(name).value(value).notNull().trueOrFalseRequired(value); } - private void validateStringParameter(final String name, final JsonElement element, - final DataValidatorBuilder baseDataValidator) { + private void validateStringParameter(final String name, final JsonElement element, final DataValidatorBuilder baseDataValidator) { final String value = this.fromJsonHelper.extractStringNamed(name, element); baseDataValidator.reset().parameter(name).value(value).notBlank().notExceedingLengthOf(1000); } - private void validateNumberParameter(final String name, final JsonElement element, - final DataValidatorBuilder baseDataValidator) { + private void validateNumberParameter(final String name, final JsonElement element, final DataValidatorBuilder baseDataValidator) { final Integer value = this.fromJsonHelper.extractIntegerSansLocaleNamed(name, element); baseDataValidator.reset().parameter(name).value(value).notNull().integerGreaterThanZero(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/BasicPasswordEncodablePlatformUser.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/BasicPasswordEncodablePlatformUser.java index a35e5d3ca..1cbf94bea 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/BasicPasswordEncodablePlatformUser.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/BasicPasswordEncodablePlatformUser.java @@ -71,4 +71,4 @@ public class BasicPasswordEncodablePlatformUser implements PlatformUser { public boolean isEnabled() { return false; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/OTPRequestRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/OTPRequestRepository.java index 3283fa0ec..b4f5929b1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/OTPRequestRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/OTPRequestRepository.java @@ -31,7 +31,6 @@ public class OTPRequestRepository { private final ConcurrentHashMap OTPrequests = new ConcurrentHashMap<>(); - public OTPRequest getOTPRequestForUser(AppUser user) { Assert.notNull(user, "User must not be null"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/PlatformUser.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/PlatformUser.java index f6928f95c..f4dcfc770 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/PlatformUser.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/PlatformUser.java @@ -25,4 +25,4 @@ import org.springframework.security.core.userdetails.UserDetails; */ public interface PlatformUser extends UserDetails { -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/PlatformUserRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/PlatformUserRepository.java index 0afa9f372..8eaf5f349 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/PlatformUserRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/PlatformUserRepository.java @@ -22,4 +22,4 @@ public interface PlatformUserRepository { PlatformUser findByUsernameAndDeletedAndEnabled(String username, boolean deleted, boolean enabled); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/TFAccessToken.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/TFAccessToken.java index 8ae59be15..72fdbca36 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/TFAccessToken.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/TFAccessToken.java @@ -35,8 +35,8 @@ import org.joda.time.DateTime; import org.joda.time.LocalDateTime; @Entity -@Table(name = "twofactor_access_token", - uniqueConstraints = {@UniqueConstraint(columnNames = { "token", "appuser_id" }, name = "token_appuser_UNIQUE")}) +@Table(name = "twofactor_access_token", uniqueConstraints = { + @UniqueConstraint(columnNames = { "token", "appuser_id" }, name = "token_appuser_UNIQUE") }) public class TFAccessToken extends AbstractPersistableCustom { @Column(name = "token", nullable = false, length = 32) @@ -57,8 +57,7 @@ public class TFAccessToken extends AbstractPersistableCustom { @Column(name = "enabled", nullable = false) private boolean enabled; - public TFAccessToken() { - } + public TFAccessToken() {} public static TFAccessToken create(String token, AppUser user, int tokenLiveTimeInSec) { DateTime validFrom = DateUtils.getLocalDateTimeOfTenant().toDateTime(); @@ -76,13 +75,11 @@ public class TFAccessToken extends AbstractPersistableCustom { } public boolean isValid() { - return this.enabled && isDateInTheFuture(getValidToDate()) - && isDateInThePast(getValidFromDate()); + return this.enabled && isDateInTheFuture(getValidToDate()) && isDateInThePast(getValidFromDate()); } public AccessTokenData toTokenData() { - return new AccessTokenData(this.token, getValidFromDate().toDateTime(), - getValidToDate().toDateTime()); + return new AccessTokenData(this.token, getValidFromDate().toDateTime(), getValidToDate().toDateTime()); } public String getToken() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/TFAccessTokenRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/TFAccessTokenRepository.java index cbdbc8fcf..b840eae9e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/TFAccessTokenRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/domain/TFAccessTokenRepository.java @@ -28,4 +28,4 @@ public interface TFAccessTokenRepository extends JpaRepository, JpaSpecificationExecutor { +public interface TwoFactorConfigurationRepository + extends JpaRepository, JpaSpecificationExecutor { TwoFactorConfiguration findByName(final String name); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/ForcePasswordResetException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/ForcePasswordResetException.java index c2eddd998..6b5887a6d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/ForcePasswordResetException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/ForcePasswordResetException.java @@ -22,8 +22,9 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class ForcePasswordResetException extends AbstractPlatformDomainRuleException { - public ForcePasswordResetException(){ - super("error.msg.password.reset.days.value.must.be.greater.than.zero" , "For enabling 'Force Password Reset Days' configuration , the value (number of days after which a user is forced to reset his password) must be set to a number greater than 0."); + public ForcePasswordResetException() { + super("error.msg.password.reset.days.value.must.be.greater.than.zero", + "For enabling 'Force Password Reset Days' configuration , the value (number of days after which a user is forced to reset his password) must be set to a number greater than 0."); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/InvalidTenantIdentiferException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/InvalidTenantIdentiferException.java index 314c14aad..c5fbcba2f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/InvalidTenantIdentiferException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/InvalidTenantIdentiferException.java @@ -29,4 +29,4 @@ public class InvalidTenantIdentiferException extends RuntimeException { public InvalidTenantIdentiferException(final String message) { super(message); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/NoAuthorizationException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/NoAuthorizationException.java index ff6ab94ea..29b759c0a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/NoAuthorizationException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/NoAuthorizationException.java @@ -27,4 +27,4 @@ public class NoAuthorizationException extends RuntimeException { public NoAuthorizationException(final String message) { super(message); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/OTPDeliveryMethodInvalidException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/OTPDeliveryMethodInvalidException.java index 0fe02376e..7d6f7f9a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/OTPDeliveryMethodInvalidException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/OTPDeliveryMethodInvalidException.java @@ -23,7 +23,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class OTPDeliveryMethodInvalidException extends AbstractPlatformDomainRuleException { public OTPDeliveryMethodInvalidException() { - super("error.msg.twofactor.otp.delivery.invalid", "The requested OTP delivery method " + - "is not supported or not currently unavailable."); + super("error.msg.twofactor.otp.delivery.invalid", + "The requested OTP delivery method " + "is not supported or not currently unavailable."); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/ResetPasswordException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/ResetPasswordException.java index b5f69b858..db2a26aa9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/ResetPasswordException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/exception/ResetPasswordException.java @@ -32,9 +32,8 @@ public class ResetPasswordException extends PlatformApiDataValidationException { public ResetPasswordException(final Long userId) { super("error.msg.password.outdated", "The password of the user with id " + userId + " has expired, please reset it", - new ArrayList (List.of( - ApiParameterError.parameterError("error.msg.password.outdated", "The password of the user with id " + userId - + " has expired, please reset it", "userId", userId))) + new ArrayList(List.of(ApiParameterError.parameterError("error.msg.password.outdated", + "The password of the user with id " + userId + " has expired, please reset it", "userId", userId))) ); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/InsecureTwoFactorAuthenticationFilter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/InsecureTwoFactorAuthenticationFilter.java index b70b60a75..b6625c1bf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/InsecureTwoFactorAuthenticationFilter.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/InsecureTwoFactorAuthenticationFilter.java @@ -55,23 +55,20 @@ public class InsecureTwoFactorAuthenticationFilter extends TwoFactorAuthenticati SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = null; - if(context != null) { + if (context != null) { authentication = context.getAuthentication(); } // Add two-factor authenticated authority if user is authenticated - if(authentication != null && authentication.isAuthenticated() && authentication.getPrincipal() instanceof AppUser) { + if (authentication != null && authentication.isAuthenticated() && authentication.getPrincipal() instanceof AppUser) { AppUser user = (AppUser) authentication.getPrincipal(); - if(user == null) { - return; - } + if (user == null) { return; } List updatedAuthorities = new ArrayList<>(authentication.getAuthorities()); updatedAuthorities.add(new SimpleGrantedAuthority("TWOFACTOR_AUTHENTICATED")); - UsernamePasswordAuthenticationToken updatedAuthentication = - new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), - authentication.getCredentials(), updatedAuthorities); + UsernamePasswordAuthenticationToken updatedAuthentication = new UsernamePasswordAuthenticationToken( + authentication.getPrincipal(), authentication.getCredentials(), updatedAuthorities); context.setAuthentication(updatedAuthentication); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TenantAwareBasicAuthenticationFilter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TenantAwareBasicAuthenticationFilter.java index 110e418c4..c6d34c839 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TenantAwareBasicAuthenticationFilter.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TenantAwareBasicAuthenticationFilter.java @@ -92,7 +92,8 @@ public class TenantAwareBasicAuthenticationFilter extends BasicAuthenticationFil } @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { final StopWatch task = new StopWatch(); task.start(); @@ -110,9 +111,10 @@ public class TenantAwareBasicAuthenticationFilter extends BasicAuthenticationFil tenantIdentifier = request.getParameter("tenantIdentifier"); } - if (tenantIdentifier == null && this.exceptionIfHeaderMissing) { throw new InvalidTenantIdentiferException( - "No tenant identifier found: Add request header of '" + this.tenantRequestHeader - + "' or add the parameter 'tenantIdentifier' to query string of request URL."); } + if (tenantIdentifier == null && this.exceptionIfHeaderMissing) { + throw new InvalidTenantIdentiferException("No tenant identifier found: Add request header of '" + + this.tenantRequestHeader + "' or add the parameter 'tenantIdentifier' to query string of request URL."); + } String pathInfo = request.getRequestURI(); boolean isReportRequest = false; @@ -157,8 +159,7 @@ public class TenantAwareBasicAuthenticationFilter extends BasicAuthenticationFil } @Override - protected void onSuccessfulAuthentication(HttpServletRequest request, - HttpServletResponse response, Authentication authResult) + protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException { super.onSuccessfulAuthentication(request, response, authResult); AppUser user = (AppUser) authResult.getPrincipal(); @@ -172,11 +173,8 @@ public class TenantAwareBasicAuthenticationFilter extends BasicAuthenticationFil String pathURL = request.getRequestURI(); boolean isSelfServiceRequest = pathURL != null && pathURL.contains("/self/"); - boolean notAllowed = (isSelfServiceRequest && !user.isSelfServiceUser()) - || (!isSelfServiceRequest && user.isSelfServiceUser()); + boolean notAllowed = (isSelfServiceRequest && !user.isSelfServiceUser()) || (!isSelfServiceRequest && user.isSelfServiceUser()); - if(notAllowed){ - throw new BadCredentialsException("User not authorised to use the requested resource."); - } + if (notAllowed) { throw new BadCredentialsException("User not authorised to use the requested resource."); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TenantAwareTenantIdentifierFilter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TenantAwareTenantIdentifierFilter.java index 5eebe17f7..324f119cb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TenantAwareTenantIdentifierFilter.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TenantAwareTenantIdentifierFilter.java @@ -49,12 +49,13 @@ import org.springframework.web.filter.GenericFilterBean; * setting Cross-Origin details to response. * * If multi-tenant are valid, the details of the tenant are stored in - * {@link FineractPlatformTenant} and stored in a {@link ThreadLocal} variable for - * this request using {@link ThreadLocalContextUtil}. + * {@link FineractPlatformTenant} and stored in a {@link ThreadLocal} variable + * for this request using {@link ThreadLocalContextUtil}. * * If multi-tenant are invalid, a http error response is returned. * - * Used to support Oauth2 authentication and the service is loaded only when "oauth" profile is active. + * Used to support Oauth2 authentication and the service is loaded only when + * "oauth" profile is active. */ @Service(value = "tenantIdentifierProcessingFilter") @Profile("oauth") @@ -83,7 +84,8 @@ public class TenantAwareTenantIdentifierFilter extends GenericFilterBean { } @Override - public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { + public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) + throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; @@ -110,9 +112,10 @@ public class TenantAwareTenantIdentifierFilter extends GenericFilterBean { tenantIdentifier = request.getParameter("tenantIdentifier"); } - if (tenantIdentifier == null && this.exceptionIfHeaderMissing) { throw new InvalidTenantIdentiferException( - "No tenant identifier found: Add request header of '" + this.tenantRequestHeader - + "' or add the parameter 'tenantIdentifier' to query string of request URL."); } + if (tenantIdentifier == null && this.exceptionIfHeaderMissing) { + throw new InvalidTenantIdentiferException("No tenant identifier found: Add request header of '" + + this.tenantRequestHeader + "' or add the parameter 'tenantIdentifier' to query string of request URL."); + } String pathInfo = request.getRequestURI(); boolean isReportRequest = false; @@ -129,8 +132,8 @@ public class TenantAwareTenantIdentifierFilter extends GenericFilterBean { } if (!firstRequestProcessed) { - final String baseUrl = request.getRequestURL().toString() - .replace(request.getRequestURI(), request.getContextPath() + apiUri); + final String baseUrl = request.getRequestURL().toString().replace(request.getRequestURI(), + request.getContextPath() + apiUri); System.setProperty("baseUrl", baseUrl); final boolean ehcacheEnabled = this.configurationDomainService.isEhcacheEnabled(); @@ -156,4 +159,4 @@ public class TenantAwareTenantIdentifierFilter extends GenericFilterBean { } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TwoFactorAuthenticationFilter.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TwoFactorAuthenticationFilter.java index ed51291c7..7b6ec5e95 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TwoFactorAuthenticationFilter.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/filter/TwoFactorAuthenticationFilter.java @@ -43,20 +43,20 @@ import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.stereotype.Service; import org.springframework.web.filter.GenericFilterBean; - /** - * This filter is responsible for handling two-factor authentication. - * The filter is enabled when 'twofactor' environment profile is active, otherwise + * This filter is responsible for handling two-factor authentication. The filter + * is enabled when 'twofactor' environment profile is active, otherwise * {@link InsecureTwoFactorAuthenticationFilter} is used. * - * This filter validates an access-token provided as a header 'Fineract-Platform-TFA-Token'. - * If a valid token is provided, a 'TWOFACTOR_AUTHENTICATED' authority is added to the current - * authentication. - * If an invalid(non-existent or invalid) token is provided, 403 response is returned. + * This filter validates an access-token provided as a header + * 'Fineract-Platform-TFA-Token'. If a valid token is provided, a + * 'TWOFACTOR_AUTHENTICATED' authority is added to the current authentication. + * If an invalid(non-existent or invalid) token is provided, 403 response is + * returned. * - * An authenticated platform user with permission 'BYPASS_TWOFACTOR' will always be granted - * 'TWOFACTOR_AUTHENTICATED' authority regardless of the value of the 'Fineract-Platform-TFA-Token' - * header. + * An authenticated platform user with permission 'BYPASS_TWOFACTOR' will always + * be granted 'TWOFACTOR_AUTHENTICATED' authority regardless of the value of the + * 'Fineract-Platform-TFA-Token' header. */ @Service(value = "twoFactorAuthFilter") @Profile("twofactor") @@ -70,37 +70,33 @@ public class TwoFactorAuthenticationFilter extends GenericFilterBean { } @Override - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) - throws IOException, ServletException { + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = null; - if(context != null) { + if (context != null) { authentication = context.getAuthentication(); } // Process two-factor only when user is authenticated - if(authentication != null && authentication.isAuthenticated()) { + if (authentication != null && authentication.isAuthenticated()) { AppUser user = (AppUser) authentication.getPrincipal(); - if(user == null) { - return; - } + if (user == null) { return; } - if(!user.hasSpecificPermissionTo(TwoFactorConstants.BYPASS_TWO_FACTOR_PERMISSION)) { - // User can't bypass two-factor auth, check two-factor access token + if (!user.hasSpecificPermissionTo(TwoFactorConstants.BYPASS_TWO_FACTOR_PERMISSION)) { + // User can't bypass two-factor auth, check two-factor access + // token String token = request.getHeader("Fineract-Platform-TFA-Token"); - if(token != null) { + if (token != null) { TFAccessToken accessToken = twoFactorService.fetchAccessTokenForUser(user, token); // Token is non-existent or invalid - if(accessToken == null || !accessToken.isValid()) { - response.addHeader("WWW-Authenticate", - "Basic realm=\"Fineract Platform API Two Factor\""); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, - "Invalid two-factor access token provided"); + if (accessToken == null || !accessToken.isValid()) { + response.addHeader("WWW-Authenticate", "Basic realm=\"Fineract Platform API Two Factor\""); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid two-factor access token provided"); return; } } else { @@ -112,8 +108,7 @@ public class TwoFactorAuthenticationFilter extends GenericFilterBean { List updatedAuthorities = new ArrayList<>(authentication.getAuthorities()); updatedAuthorities.add(new SimpleGrantedAuthority("TWOFACTOR_AUTHENTICATED")); - final Authentication updatedAuthentication = createUpdatedAuthentication(authentication, - updatedAuthorities); + final Authentication updatedAuthentication = createUpdatedAuthentication(authentication, updatedAuthorities); context.setAuthentication(updatedAuthentication); } @@ -124,15 +119,14 @@ public class TwoFactorAuthenticationFilter extends GenericFilterBean { private Authentication createUpdatedAuthentication(final Authentication currentAuthentication, final List updatedAuthorities) { - final UsernamePasswordAuthenticationToken authentication = new - UsernamePasswordAuthenticationToken(currentAuthentication.getPrincipal(), - currentAuthentication.getCredentials(), updatedAuthorities); + final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( + currentAuthentication.getPrincipal(), currentAuthentication.getCredentials(), updatedAuthorities); - if(currentAuthentication instanceof OAuth2Authentication) { + if (currentAuthentication instanceof OAuth2Authentication) { final OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) currentAuthentication; return new OAuth2Authentication(oAuth2Authentication.getOAuth2Request(), authentication); } return authentication; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/BasicAuthTenantDetailsService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/BasicAuthTenantDetailsService.java index 11eef228a..ebda0827a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/BasicAuthTenantDetailsService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/BasicAuthTenantDetailsService.java @@ -23,4 +23,4 @@ import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant; public interface BasicAuthTenantDetailsService { FineractPlatformTenant loadTenantById(String tenantId, boolean isReport); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/BasicAuthTenantDetailsServiceJdbc.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/BasicAuthTenantDetailsServiceJdbc.java index 14f513e0d..720b9198d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/BasicAuthTenantDetailsServiceJdbc.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/BasicAuthTenantDetailsServiceJdbc.java @@ -67,9 +67,9 @@ public class BasicAuthTenantDetailsServiceJdbc implements BasicAuthTenantDetails } public String schema() { - if(this.isReport){ + if (this.isReport) { this.sqlBuilder.append(" on t.report_Id = ts.id"); - }else{ + } else { this.sqlBuilder.append(" on t.oltp_Id = ts.id"); } return this.sqlBuilder.toString(); @@ -141,4 +141,4 @@ public class BasicAuthTenantDetailsServiceJdbc implements BasicAuthTenantDetails throw new InvalidTenantIdentiferException("The tenant identifier: " + tenantIdentifier + " is not valid."); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/JdbcTenantDetailsService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/JdbcTenantDetailsService.java index 1fe690cdf..12544cfad 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/JdbcTenantDetailsService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/JdbcTenantDetailsService.java @@ -143,4 +143,4 @@ public class JdbcTenantDetailsService implements TenantDetailsService { final List fineractPlatformTenants = this.jdbcTemplate.query(sql, rm, new Object[] {}); return fineractPlatformTenants; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformPasswordEncoder.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformPasswordEncoder.java index eedeae67c..7775798b7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformPasswordEncoder.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformPasswordEncoder.java @@ -23,4 +23,4 @@ import org.apache.fineract.infrastructure.security.domain.PlatformUser; public interface PlatformPasswordEncoder { String encode(PlatformUser appUser); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformSecurityContext.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformSecurityContext.java index 34b9938de..33f64b0fa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformSecurityContext.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformSecurityContext.java @@ -43,4 +43,4 @@ public interface PlatformSecurityContext { boolean doesPasswordHasToBeRenewed(AppUser currentUser); AppUser authenticatedUser(CommandWrapper commandWrapper); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformUserDetailsService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformUserDetailsService.java index d855739a8..ee9291c31 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformUserDetailsService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/PlatformUserDetailsService.java @@ -25,4 +25,4 @@ import org.springframework.security.core.userdetails.UserDetailsService; */ public interface PlatformUserDetailsService extends UserDetailsService { // no added behaviour -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/RandomOTPGenerator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/RandomOTPGenerator.java index 5884ab7e4..c53e6e769 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/RandomOTPGenerator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/RandomOTPGenerator.java @@ -29,7 +29,7 @@ public class RandomOTPGenerator { public String generate() { StringBuilder builder = new StringBuilder(); - for(int i = 0; i < tokenLength; i++) { + for (int i = 0; i < tokenLength; i++) { builder.append(allowedCharacters.charAt((int) (Math.random() * allowedCharacters.length()))); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/RandomPasswordGenerator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/RandomPasswordGenerator.java index 938c91358..41fc82666 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/RandomPasswordGenerator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/RandomPasswordGenerator.java @@ -34,4 +34,4 @@ public class RandomPasswordGenerator { } return passwordBuilder.toString(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/SpringSecurityPlatformSecurityContext.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/SpringSecurityPlatformSecurityContext.java index 9dcde6c58..2ebc8bbc8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/SpringSecurityPlatformSecurityContext.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/SpringSecurityPlatformSecurityContext.java @@ -49,9 +49,8 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo private final ConfigurationDomainService configurationDomainService; - protected static final List EXEMPT_FROM_PASSWORD_RESET_CHECK = new ArrayList(List.of( - new CommandWrapperBuilder().updateUser(null).build()) - ); + protected static final List EXEMPT_FROM_PASSWORD_RESET_CHECK = new ArrayList( + List.of(new CommandWrapperBuilder().updateUser(null).build())); @Autowired SpringSecurityPlatformSecurityContext(final ConfigurationDomainService configurationDomainService) { @@ -110,8 +109,9 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo if (currentUser == null) { throw new UnAuthenticatedUserException(); } - if (this.shouldCheckForPasswordForceReset(commandWrapper) && this.doesPasswordHasToBeRenewed(currentUser)) { throw new ResetPasswordException( - currentUser.getId()); } + if (this.shouldCheckForPasswordForceReset(commandWrapper) && this.doesPasswordHasToBeRenewed(currentUser)) { + throw new ResetPasswordException(currentUser.getId()); + } return currentUser; @@ -123,8 +123,9 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo final AppUser user = authenticatedUser(); final String userOfficeHierarchy = user.getOffice().getHierarchy(); - if (!resourceOfficeHierarchy.startsWith(userOfficeHierarchy)) { throw new NoAuthorizationException( - "The user doesn't have enough permissions to access the resource."); } + if (!resourceOfficeHierarchy.startsWith(userOfficeHierarchy)) { + throw new NoAuthorizationException("The user doesn't have enough permissions to access the resource."); + } } @@ -156,7 +157,9 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo private boolean shouldCheckForPasswordForceReset(CommandWrapper commandWrapper) { for (CommandWrapper commandItem : EXEMPT_FROM_PASSWORD_RESET_CHECK) { if (commandItem.actionName().equals(commandWrapper.actionName()) - && commandItem.getEntityName().equals(commandWrapper.getEntityName())) { return false; } + && commandItem.getEntityName().equals(commandWrapper.getEntityName())) { + return false; + } } return true; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TenantAwareJpaPlatformUserDetailsService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TenantAwareJpaPlatformUserDetailsService.java index 5062906f1..b3be93464 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TenantAwareJpaPlatformUserDetailsService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TenantAwareJpaPlatformUserDetailsService.java @@ -52,4 +52,4 @@ public class TenantAwareJpaPlatformUserDetailsService implements PlatformUserDet return appUser; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TenantDetailsService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TenantDetailsService.java index dcf54286d..df3123e50 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TenantDetailsService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TenantDetailsService.java @@ -26,4 +26,4 @@ public interface TenantDetailsService { FineractPlatformTenant loadTenantById(String tenantId); List findAllTenants(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorConfigurationService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorConfigurationService.java index 9e223f989..e611a6863 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorConfigurationService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorConfigurationService.java @@ -25,26 +25,33 @@ import org.apache.fineract.useradministration.domain.AppUser; public interface TwoFactorConfigurationService { - Map retrieveAll(); boolean isSMSEnabled(); + Integer getSMSProviderId(); + String getSmsText(); boolean isEmailEnabled(); + String getEmailSubject(); + String getEmailBody(); String getFormattedEmailSubjectFor(AppUser user, OTPRequest request); + String getFormattedEmailBodyFor(AppUser user, OTPRequest request); + String getFormattedSmsTextFor(AppUser user, OTPRequest request); Integer getOTPTokenLength(); + Integer getOTPTokenLiveTime(); Integer getAccessTokenLiveTime(); + Integer getAccessTokenExtendedLiveTime(); - Map update(JsonCommand command); + Map update(JsonCommand command); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorConfigurationServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorConfigurationServiceImpl.java index abfc75592..bdc3ae637 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorConfigurationServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorConfigurationServiceImpl.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.infrastructure.security.service; - import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; @@ -48,14 +47,11 @@ import org.springframework.stereotype.Service; public class TwoFactorConfigurationServiceImpl implements TwoFactorConfigurationService { private static final String DEFAULT_EMAIL_SUBJECT = "Fineract Two-Factor Authentication Token"; - private static final String DEFAULT_EMAIL_BODY = "Hello {username}.\n" + - "Your OTP login token is {token}."; - private static final String DEFAULT_SMS_TEXT = "Your authentication token for Fineract is " + - "{token}."; + private static final String DEFAULT_EMAIL_BODY = "Hello {username}.\n" + "Your OTP login token is {token}."; + private static final String DEFAULT_SMS_TEXT = "Your authentication token for Fineract is " + "{token}."; private final TwoFactorConfigurationRepository configurationRepository; - @Autowired public TwoFactorConfigurationServiceImpl(TwoFactorConfigurationRepository configurationRepository) { this.configurationRepository = configurationRepository; @@ -66,7 +62,7 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration public Map retrieveAll() { List configurationList = configurationRepository.findAll(); Map configurationMap = new HashMap<>(); - for(final TwoFactorConfiguration configuration : configurationList) { + for (final TwoFactorConfiguration configuration : configurationList) { configurationMap.put(configuration.getName(), configuration.getObjectValue()); } return configurationMap; @@ -77,14 +73,13 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration public Map update(JsonCommand command) { Map actualChanges = new HashMap<>(); - - for(final String parameterName : TwoFactorConfigurationConstants.BOOLEAN_PARAMETERS) { + for (final String parameterName : TwoFactorConfigurationConstants.BOOLEAN_PARAMETERS) { TwoFactorConfiguration configuration = configurationRepository.findByName(parameterName); - if(configuration == null) { + if (configuration == null) { continue; } - if(command.isChangeInBooleanParameterNamed(parameterName, configuration.getBooleanValue())) { + if (command.isChangeInBooleanParameterNamed(parameterName, configuration.getBooleanValue())) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(parameterName); actualChanges.put(parameterName, newValue); configuration.setBooleanValue(newValue); @@ -92,13 +87,13 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration } } - for(final String parameterName : TwoFactorConfigurationConstants.STRING_PARAMETERS) { + for (final String parameterName : TwoFactorConfigurationConstants.STRING_PARAMETERS) { TwoFactorConfiguration configuration = configurationRepository.findByName(parameterName); - if(configuration == null) { + if (configuration == null) { continue; } - if(command.isChangeInStringParameterNamed(parameterName, configuration.getStringValue())) { + if (command.isChangeInStringParameterNamed(parameterName, configuration.getStringValue())) { final String newValue = command.stringValueOfParameterNamed(parameterName).trim(); actualChanges.put(parameterName, newValue); configuration.setStringValue(newValue); @@ -106,13 +101,13 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration } } - for(final String parameterName : TwoFactorConfigurationConstants.NUMBER_PARAMETERS) { + for (final String parameterName : TwoFactorConfigurationConstants.NUMBER_PARAMETERS) { TwoFactorConfiguration configuration = configurationRepository.findByName(parameterName); - if(configuration == null) { + if (configuration == null) { continue; } - if(command.isChangeInIntegerSansLocaleParameterNamed(parameterName, configuration.getIntegerValue())) { + if (command.isChangeInIntegerSansLocaleParameterNamed(parameterName, configuration.getIntegerValue())) { final Long newValue = command.longValueOfParameterNamed(parameterName); actualChanges.put(parameterName, newValue); configuration.setIntegerValue(newValue); @@ -120,7 +115,7 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration } } - if(!actualChanges.isEmpty()) { + if (!actualChanges.isEmpty()) { configurationRepository.flush(); } @@ -136,11 +131,8 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration @Override @Cacheable(value = "tfConfig", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier()+'|smsProvider'") public Integer getSMSProviderId() { - Integer value = getIntegerConfig(TwoFactorConfigurationConstants.SMS_PROVIDER_ID, - null); - if(value < 1) { - return null; - } + Integer value = getIntegerConfig(TwoFactorConfigurationConstants.SMS_PROVIDER_ID, null); + if (value < 1) { return null; } return value; } @@ -190,19 +182,15 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration @Cacheable(value = "tfConfig", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier()+'|otpLength'") public Integer getOTPTokenLength() { Integer defaultValue = 1; - return getIntegerConfig(TwoFactorConfigurationConstants.OTP_TOKEN_LENGTH, - defaultValue); + return getIntegerConfig(TwoFactorConfigurationConstants.OTP_TOKEN_LENGTH, defaultValue); } @Override @Cacheable(value = "tfConfig", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier()+'|otpTime'") public Integer getOTPTokenLiveTime() { Integer defaultValue = 300; - Integer value = getIntegerConfig(TwoFactorConfigurationConstants.OTP_TOKEN_LIVE_TIME, - defaultValue); - if(value < 1) { - return defaultValue; - } + Integer value = getIntegerConfig(TwoFactorConfigurationConstants.OTP_TOKEN_LIVE_TIME, defaultValue); + if (value < 1) { return defaultValue; } return value; } @@ -210,11 +198,8 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration @Cacheable(value = "tfConfig", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier()+'|tokenTime'") public Integer getAccessTokenLiveTime() { Integer defaultValue = 86400; - Integer value = getIntegerConfig(TwoFactorConfigurationConstants.ACCESS_TOKEN_LIVE_TIME, - defaultValue); - if(value < 1) { - return defaultValue; - } + Integer value = getIntegerConfig(TwoFactorConfigurationConstants.ACCESS_TOKEN_LIVE_TIME, defaultValue); + if (value < 1) { return defaultValue; } return value; } @@ -222,41 +207,29 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration @Cacheable(value = "tfConfig", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier()+'|tokenExtendedTime'") public Integer getAccessTokenExtendedLiveTime() { Integer defaultValue = 604800; - Integer value = getIntegerConfig(TwoFactorConfigurationConstants.ACCESS_TOKEN_LIVE_TIME_EXTENDED, - defaultValue); - if(value < 1) { - return defaultValue; - } + Integer value = getIntegerConfig(TwoFactorConfigurationConstants.ACCESS_TOKEN_LIVE_TIME_EXTENDED, defaultValue); + if (value < 1) { return defaultValue; } return value; } private boolean getBooleanConfig(final String name, final boolean defaultValue) { - final TwoFactorConfiguration configuration = - configurationRepository.findByName(name); + final TwoFactorConfiguration configuration = configurationRepository.findByName(name); Boolean value = configuration.getBooleanValue(); - if(value == null) { - return defaultValue; - } + if (value == null) { return defaultValue; } return value; } private String getStringConfig(final String name, final String defaultValue) { - final TwoFactorConfiguration configuration = - configurationRepository.findByName(name); + final TwoFactorConfiguration configuration = configurationRepository.findByName(name); String value = configuration.getStringValue(); - if(value == null) { - return defaultValue; - } + if (value == null) { return defaultValue; } return value; } private Integer getIntegerConfig(final String name, final Integer defaultValue) { - final TwoFactorConfiguration configuration = - configurationRepository.findByName(name); + final TwoFactorConfiguration configuration = configurationRepository.findByName(name); Integer value = configuration.getIntegerValue(); - if(value == null) { - return defaultValue; - } + if (value == null) { return defaultValue; } return value; } @@ -267,7 +240,7 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration templateData.put("email", user.getEmail()); templateData.put("firstname", user.getFirstname()); templateData.put("lastname", user.getLastname()); - if(user.getStaff() != null && user.getStaff().mobileNo() != null) { + if (user.getStaff() != null && user.getStaff().mobileNo() != null) { templateData.put("mobileno", user.getStaff().mobileNo()); } @@ -289,8 +262,7 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration return templateData; } - private String compileTextTemplate(final String template, final String name, - final Map params) { + private String compileTextTemplate(final String template, final String name, final Map params) { final MustacheFactory mf = new DefaultMustacheFactory(); final Mustache mustache = mf.compile(new StringReader(template), name); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorServiceImpl.java index 610c75812..360827820 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorServiceImpl.java @@ -49,8 +49,6 @@ import org.springframework.stereotype.Service; @Profile("twofactor") public class TwoFactorServiceImpl implements TwoFactorService { - - private final AccessTokenGenerationService accessTokenGenerationService; private final PlatformEmailService emailService; private final SmsMessageScheduledJobService smsMessageScheduledJobService; @@ -62,12 +60,9 @@ public class TwoFactorServiceImpl implements TwoFactorService { private final TwoFactorConfigurationService configurationService; @Autowired - public TwoFactorServiceImpl(AccessTokenGenerationService accessTokenGenerationService, - PlatformEmailService emailService, - SmsMessageScheduledJobService smsMessageScheduledJobService, - OTPRequestRepository otpRequestRepository, - TFAccessTokenRepository tfAccessTokenRepository, - SmsMessageRepository smsMessageRepository, + public TwoFactorServiceImpl(AccessTokenGenerationService accessTokenGenerationService, PlatformEmailService emailService, + SmsMessageScheduledJobService smsMessageScheduledJobService, OTPRequestRepository otpRequestRepository, + TFAccessTokenRepository tfAccessTokenRepository, SmsMessageRepository smsMessageRepository, TwoFactorConfigurationService configurationService) { this.accessTokenGenerationService = accessTokenGenerationService; this.emailService = emailService; @@ -78,17 +73,16 @@ public class TwoFactorServiceImpl implements TwoFactorService { this.configurationService = configurationService; } - @Override public List getDeliveryMethodsForUser(final AppUser user) { List deliveryMethods = new ArrayList<>(); OTPDeliveryMethod smsMethod = getSMSDeliveryMethodForUser(user); - if(smsMethod != null) { + if (smsMethod != null) { deliveryMethods.add(smsMethod); } OTPDeliveryMethod emailDelivery = getEmailDeliveryMethodForUser(user); - if(emailDelivery != null) { + if (emailDelivery != null) { deliveryMethods.add(emailDelivery); } @@ -96,27 +90,21 @@ public class TwoFactorServiceImpl implements TwoFactorService { } @Override - public OTPRequest createNewOTPToken(final AppUser user, final String deliveryMethodName, - final boolean extendedAccessToken) { - if(TwoFactorConstants.SMS_DELIVERY_METHOD_NAME.equalsIgnoreCase(deliveryMethodName)) { + public OTPRequest createNewOTPToken(final AppUser user, final String deliveryMethodName, final boolean extendedAccessToken) { + if (TwoFactorConstants.SMS_DELIVERY_METHOD_NAME.equalsIgnoreCase(deliveryMethodName)) { OTPDeliveryMethod smsDelivery = getSMSDeliveryMethodForUser(user); - if(smsDelivery == null) { - throw new OTPDeliveryMethodInvalidException(); - } + if (smsDelivery == null) { throw new OTPDeliveryMethodInvalidException(); } final OTPRequest request = generateNewToken(smsDelivery, extendedAccessToken); final String smsText = configurationService.getFormattedSmsTextFor(user, request); - SmsMessage smsMessage = SmsMessage.pendingSms(null, null, null, user.getStaff(), smsText, - user.getStaff().mobileNo(), null, false); + SmsMessage smsMessage = SmsMessage.pendingSms(null, null, null, user.getStaff(), smsText, user.getStaff().mobileNo(), null, + false); this.smsMessageRepository.save(smsMessage); - smsMessageScheduledJobService.sendTriggeredMessage(Collections.singleton(smsMessage), - configurationService.getSMSProviderId()); + smsMessageScheduledJobService.sendTriggeredMessage(Collections.singleton(smsMessage), configurationService.getSMSProviderId()); otpRequestRepository.addOTPRequest(user, request); return request; - } else if(TwoFactorConstants.EMAIL_DELIVERY_METHOD_NAME.equalsIgnoreCase(deliveryMethodName)) { + } else if (TwoFactorConstants.EMAIL_DELIVERY_METHOD_NAME.equalsIgnoreCase(deliveryMethodName)) { OTPDeliveryMethod emailDelivery = getEmailDeliveryMethodForUser(user); - if(emailDelivery == null) { - throw new OTPDeliveryMethodInvalidException(); - } + if (emailDelivery == null) { throw new OTPDeliveryMethodInvalidException(); } final OTPRequest request = generateNewToken(emailDelivery, extendedAccessToken); final String emailSubject = configurationService.getFormattedEmailSubjectFor(user, request); final String emailBody = configurationService.getFormattedEmailBodyFor(user, request); @@ -131,13 +119,12 @@ public class TwoFactorServiceImpl implements TwoFactorService { } @Override - @CachePut(value = "userTFAccessToken", - key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil)" + - ".getTenant().getTenantIdentifier().concat(#user.username).concat(#result.token + 'tok')") + @CachePut(value = "userTFAccessToken", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil)" + + ".getTenant().getTenantIdentifier().concat(#user.username).concat(#result.token + 'tok')") public TFAccessToken createAccessTokenFromOTP(final AppUser user, final String otpToken) { OTPRequest otpRequest = otpRequestRepository.getOTPRequestForUser(user); - if(otpRequest == null || !otpRequest.isValid() || !otpRequest.getToken().equalsIgnoreCase(otpToken)) { + if (otpRequest == null || !otpRequest.isValid() || !otpRequest.getToken().equalsIgnoreCase(otpToken)) { throw new OTPTokenInvalidException(); } @@ -145,7 +132,7 @@ public class TwoFactorServiceImpl implements TwoFactorService { String token = accessTokenGenerationService.generateRandomToken(); int liveTime; - if(otpRequest.getMetadata().isExtendedAccessToken()) { + if (otpRequest.getMetadata().isExtendedAccessToken()) { liveTime = configurationService.getAccessTokenExtendedLiveTime(); } else { liveTime = configurationService.getAccessTokenLiveTime(); @@ -159,23 +146,18 @@ public class TwoFactorServiceImpl implements TwoFactorService { public void validateTwoFactorAccessToken(AppUser user, String token) { TFAccessToken accessToken = fetchAccessTokenForUser(user, token); - if(accessToken == null || !accessToken.isValid()) { - throw new AccessTokenInvalidIException(); - } + if (accessToken == null || !accessToken.isValid()) { throw new AccessTokenInvalidIException(); } } @Override - @CacheEvict(value = "userTFAccessToken", - key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil)" + - ".getTenant().getTenantIdentifier().concat(#user.username).concat(#result.token + 'tok')") + @CacheEvict(value = "userTFAccessToken", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil)" + + ".getTenant().getTenantIdentifier().concat(#user.username).concat(#result.token + 'tok')") public TFAccessToken invalidateAccessToken(final AppUser user, final JsonCommand command) { final String token = command.stringValueOfParameterNamed("token"); final TFAccessToken accessToken = fetchAccessTokenForUser(user, token); - if(accessToken == null || !accessToken.isValid()) { - throw new AccessTokenInvalidIException(); - } + if (accessToken == null || !accessToken.isValid()) { throw new AccessTokenInvalidIException(); } accessToken.setEnabled(false); tfAccessTokenRepository.save(accessToken); @@ -184,37 +166,26 @@ public class TwoFactorServiceImpl implements TwoFactorService { } @Override - @Cacheable(value = "userTFAccessToken", - key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil)" + - ".getTenant().getTenantIdentifier().concat(#user.username).concat(#token + 'tok')") + @Cacheable(value = "userTFAccessToken", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil)" + + ".getTenant().getTenantIdentifier().concat(#user.username).concat(#token + 'tok')") public TFAccessToken fetchAccessTokenForUser(final AppUser user, final String token) { return tfAccessTokenRepository.findByUserAndToken(user, token); } private OTPDeliveryMethod getSMSDeliveryMethodForUser(final AppUser user) { - if(!configurationService.isSMSEnabled()) { - return null; - } + if (!configurationService.isSMSEnabled()) { return null; } - if(configurationService.getSMSProviderId() == null) { - return null; - } + if (configurationService.getSMSProviderId() == null) { return null; } - if(user.getStaff() == null) { - return null; - } + if (user.getStaff() == null) { return null; } String mobileNo = user.getStaff().mobileNo(); - if(StringUtils.isBlank(mobileNo)) { - return null; - } + if (StringUtils.isBlank(mobileNo)) { return null; } return new OTPDeliveryMethod(TwoFactorConstants.SMS_DELIVERY_METHOD_NAME, mobileNo); } private OTPDeliveryMethod getEmailDeliveryMethodForUser(final AppUser user) { - if(!configurationService.isEmailEnabled()) { - return null; - } + if (!configurationService.isEmailEnabled()) { return null; } return new OTPDeliveryMethod(TwoFactorConstants.EMAIL_DELIVERY_METHOD_NAME, user.getEmail()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorUtils.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorUtils.java index 89292463b..681c20797 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorUtils.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/TwoFactorUtils.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.infrastructure.security.service; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @@ -35,12 +34,9 @@ public class TwoFactorUtils { this.environment = environment; } - public boolean isTwoFactorAuthEnabled() { - for(final String profile : this.environment.getActiveProfiles()) { - if(TWO_FACTOR_PROFILE_NAME.equals(profile)) { - return true; - } + for (final String profile : this.environment.getActiveProfiles()) { + if (TWO_FACTOR_PROFILE_NAME.equals(profile)) { return true; } } return false; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/ColumnValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/ColumnValidator.java index 217dd85d5..5e6df760a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/ColumnValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/ColumnValidator.java @@ -39,6 +39,7 @@ import org.springframework.stereotype.Component; @Component public class ColumnValidator { + private final static Logger LOG = LoggerFactory.getLogger(ColumnValidator.class); private final JdbcTemplate jdbcTemplate; @@ -48,34 +49,27 @@ public class ColumnValidator { } private void validateColumn(Map> tableColumnMap) { - Connection connection = null ; + Connection connection = null; try { - connection = this.jdbcTemplate.getDataSource() - .getConnection() ; + connection = this.jdbcTemplate.getDataSource().getConnection(); DatabaseMetaData dbMetaData = connection.getMetaData(); ResultSet resultSet = null; - for (HashMap.Entry> entry : tableColumnMap - .entrySet()) { + for (HashMap.Entry> entry : tableColumnMap.entrySet()) { Set columns = entry.getValue(); - resultSet = dbMetaData.getColumns(null, null, entry.getKey(), - null); + resultSet = dbMetaData.getColumns(null, null, entry.getKey(), null); Set tableColumns = getTableColumns(resultSet); - if (columns.size() > 0 && tableColumns.size() == 0) { - throw new SQLInjectionException(); - } + if (columns.size() > 0 && tableColumns.size() == 0) { throw new SQLInjectionException(); } for (String requestedColumn : columns) { - if (!tableColumns.contains(requestedColumn)) { - throw new SQLInjectionException(); - } + if (!tableColumns.contains(requestedColumn)) { throw new SQLInjectionException(); } } } } catch (SQLException e) { throw new SQLInjectionException(); - }finally { - if(connection != null) { + } finally { + if (connection != null) { DataSourceUtils.releaseConnection(connection, jdbcTemplate.getDataSource()); } - connection = null ; + connection = null; } } @@ -86,43 +80,37 @@ public class ColumnValidator { columns.add(rs.getString("column_name")); } } catch (SQLException e) { - LOG.error("Problem occurred in getTableColumns function",e); + LOG.error("Problem occurred in getTableColumns function", e); } return columns; } public void validateSqlInjection(String schema, String... conditions) { - for(String condition: conditions) { + for (String condition : conditions) { SQLInjectionValidator.validateSQLInput(condition); - List operator = new ArrayList<>(Arrays.asList("=", ">", "<", - "> =", "< =", "! =", "!=", ">=", "<=")); - condition = condition.trim().replace("( ", "(").replace(" )", ")") - .toLowerCase(); + List operator = new ArrayList<>(Arrays.asList("=", ">", "<", "> =", "< =", "! =", "!=", ">=", "<=")); + condition = condition.trim().replace("( ", "(").replace(" )", ")").toLowerCase(); for (String op : operator) { condition = replaceAll(condition, op).replaceAll(" +", " "); } Set operands = getOperand(condition); schema = schema.trim().replaceAll(" +", " ").toLowerCase(); Map> tableColumnAliasMap = getTableColumnAliasMap(operands); - Map> tableColumnMap = getTableColumnMap(schema, - tableColumnAliasMap); + Map> tableColumnMap = getTableColumnMap(schema, tableColumnAliasMap); validateColumn(tableColumnMap); } } - private static Map> getTableColumnMap(String schema, - Map> tableColumnAliasMap) { + private static Map> getTableColumnMap(String schema, Map> tableColumnAliasMap) { Map> tableColumnMap = new HashMap<>(); schema = schema.substring(schema.indexOf("from")); for (String alias : tableColumnAliasMap.keySet()) { int index = schema.indexOf(" " + alias + " "); if (index > -1) { int startPos = 0; - startPos = schema.substring(0, index - 1).lastIndexOf(' ', - index); + startPos = schema.substring(0, index - 1).lastIndexOf(' ', index); Set columns = tableColumnAliasMap.get(alias); - tableColumnMap.put(schema.substring(startPos, index).trim(), - columns); + tableColumnMap.put(schema.substring(startPos, index).trim(), columns); } else { throw new SQLInjectionException(); } @@ -130,8 +118,7 @@ public class ColumnValidator { return tableColumnMap; } - private static Map> getTableColumnAliasMap( - Set operands) { + private static Map> getTableColumnAliasMap(Set operands) { Map> tableColumnMap = new HashMap<>(); for (String operand : operands) { String[] tableColumn = operand.split("\\."); @@ -153,9 +140,8 @@ public class ColumnValidator { private static Set getOperand(String condition) { Set operandList = new HashSet<>(); - List operatorList = new ArrayList<>(Arrays.asList("!=", "=", - ">", "<", " like ", " between ", " in ", " in(", " is ", - " is not ", " equals ", " not equals ")); + List operatorList = new ArrayList<>( + Arrays.asList("!=", "=", ">", "<", " like ", " between ", " in ", " in(", " is ", " is not ", " equals ", " not equals ")); for (String op : operatorList) { int startIndex = 0; do { @@ -163,15 +149,11 @@ public class ColumnValidator { if (index > -1) { char currentChar = condition.charAt(index - 1); if (op.equals("=")) { - if (!((currentChar + "").equals("!") - || (currentChar + "").equals(">") || (currentChar + "") - .equals("<"))) { - operandList.add(getOperand(condition, index, - currentChar)); + if (!((currentChar + "").equals("!") || (currentChar + "").equals(">") || (currentChar + "").equals("<"))) { + operandList.add(getOperand(condition, index, currentChar)); } } else { - operandList.add(getOperand(condition, index, - currentChar)); + operandList.add(getOperand(condition, index, currentChar)); } startIndex = index + op.length(); @@ -182,12 +164,10 @@ public class ColumnValidator { return operandList; } - private static String getOperand(String condition, int index, - char currentChar) { + private static String getOperand(String condition, int index, char currentChar) { int startPos = 0; if ((currentChar + "").equals(" ")) { - startPos = condition.substring(0, index - 1) - .lastIndexOf(' ', index); + startPos = condition.substring(0, index - 1).lastIndexOf(' ', index); } else { startPos = condition.substring(0, index).lastIndexOf(' ', index); } @@ -201,16 +181,14 @@ public class ColumnValidator { int index = condition.indexOf(op, startIndex); if (index > -1) { if (op.equals("=")) { - if (!((condition.charAt(index - 1) + "").equals("!") - || (condition.charAt(index - 1) + "").equals(">") || (condition - .charAt(index - 1) + "").equals("<"))) { + if (!((condition.charAt(index - 1) + "").equals("!") || (condition.charAt(index - 1) + "").equals(">") + || (condition.charAt(index - 1) + "").equals("<"))) { condition = condition.replace(op, " " + op + " "); return condition; } startIndex = index + 2 + op.length(); - } else if (op.equals("< =") || op.equals("> =") - || op.equals("! =")) { + } else if (op.equals("< =") || op.equals("> =") || op.equals("! =")) { condition = condition.replace(op, op.replace(" ", "")); return condition; } else { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLBuilder.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLBuilder.java index 0a22bd29c..6ee08712b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLBuilder.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/utils/SQLBuilder.java @@ -25,11 +25,13 @@ import java.util.Locale; import java.util.regex.Pattern; /** - * Utility to assemble the WHERE clause of an SQL query without the risk of SQL injection. + * Utility to assemble the WHERE clause of an SQL query without the risk of SQL + * injection. * - *

When using this utility instead of manually assembling SQL queries, then - * {@link SQLInjectionValidator} should not be required anymore. (Correctly using - * this means only ever passing completely fixed String literals to .) + *

+ * When using this utility instead of manually assembling SQL queries, then + * {@link SQLInjectionValidator} should not be required anymore. (Correctly + * using this means only ever passing completely fixed String literals to .) * * @author Michael Vorburger */ @@ -37,47 +39,52 @@ public class SQLBuilder { private final static Pattern ATOZ = Pattern.compile("([a-zA-Z_][a-zA-Z0-9_-]*\\.)?[a-zA-Z_-][a-zA-Z0-9_-]*"); - // This holds the query string, with the '?' placeholders, but no argument values + // This holds the query string, with the '?' placeholders, but no argument + // values private final StringBuilder sb = new StringBuilder(); // This holds the arguments, in the order of the '?' placeholders in sb private final List args = new ArrayList<>(); - // This holds the criterias, where nth element corresponds to nth element in args + // This holds the criterias, where nth element corresponds to nth element in + // args private final ArrayList crts = new ArrayList(); + /** - * Adds a criteria for a SQL WHERE clause. - * All criteria are appended by AND (support for OR, or nesting, can be added when needed). - * @param criteria The name of the column to be filtered, and an operator; e.g. "name =" or "age >" (but without '?' placeholder) - * @param argument The argument to be filtered on (e.g. "Michael" or 123). The null value is explicitly permitted. + * Adds a criteria for a SQL WHERE clause. All criteria are appended by AND + * (support for OR, or nesting, can be added when needed). + * + * @param criteria + * The name of the column to be filtered, and an operator; e.g. + * "name =" or "age >" (but without '?' placeholder) + * @param argument + * The argument to be filtered on (e.g. "Michael" or 123). The + * null value is explicitly permitted. */ public void addCriteria(String criteria, Object argument) { - if (criteria == null || criteria.trim().isEmpty()) { - throw new IllegalArgumentException("criteria cannot be null"); - } + if (criteria == null || criteria.trim().isEmpty()) { throw new IllegalArgumentException("criteria cannot be null"); } String trimmedCriteria = criteria.trim(); - if (trimmedCriteria.isEmpty()) { - throw new IllegalArgumentException("criteria cannot be null"); - } + if (trimmedCriteria.isEmpty()) { throw new IllegalArgumentException("criteria cannot be null"); } if (trimmedCriteria.contains("?")) { - throw new IllegalArgumentException("criteria cannot contain a '?' (that is automatically added at the end): " + trimmedCriteria); + throw new IllegalArgumentException( + "criteria cannot contain a '?' (that is automatically added at the end): " + trimmedCriteria); } int columnOperatorIndex = trimmedCriteria.indexOf(' '); - if (columnOperatorIndex == -1) { - throw new IllegalArgumentException("criteria missing operator: " + trimmedCriteria); - } + if (columnOperatorIndex == -1) { throw new IllegalArgumentException("criteria missing operator: " + trimmedCriteria); } String columnName = trimmedCriteria.substring(0, columnOperatorIndex).trim().toLowerCase(Locale.ROOT); if (!ATOZ.matcher(columnName).matches()) { throw new IllegalArgumentException("criteria column name must match [a-z]: " + trimmedCriteria); } String operator = trimmedCriteria.substring(columnOperatorIndex).trim(); if (operator.indexOf(' ') > -1) { - throw new IllegalArgumentException("criteria cannot contain more than 1 space (between column name and operator): " + trimmedCriteria); + throw new IllegalArgumentException( + "criteria cannot contain more than 1 space (between column name and operator): " + trimmedCriteria); } - if (!operator.equals("=") && !operator.equals("<") && !operator.equals(">") - && !operator.equals("<=") && !operator.equals(">=") && !operator.equals("<>") - && !operator.equals("LIKE") && !operator.equals("like")) { - // add support for SQL's BETWEEN and IN, if/when ever needed.. (it's a little more than just adding above, as it can have multiple arguments) + if (!operator.equals("=") && !operator.equals("<") && !operator.equals(">") && !operator.equals("<=") && !operator.equals(">=") + && !operator.equals("<>") && !operator.equals("LIKE") && !operator.equals("like")) { + // add support for SQL's BETWEEN and IN, if/when ever needed.. (it's + // a little more than just adding above, as it can have multiple + // arguments) throw new IllegalArgumentException("criteria must end with valid SQL operator for WHERE: " + trimmedCriteria); } @@ -91,7 +98,8 @@ public class SQLBuilder { } /** - * Delegates to {@link #addCriteria(String, Object)} if argument is not null, otherwise does nothing. + * Delegates to {@link #addCriteria(String, Object)} if argument is not + * null, otherwise does nothing. */ public void addNonNullCriteria(String criteria, Object argument) { if (argument != null) { @@ -100,19 +108,22 @@ public class SQLBuilder { } /** - * Returns a SQL WHERE clause, created from the {@link #addCriteria(String, Object)}, with '?' placeholders. - * @return SQL WHERE clause, almost always starting with " WHERE ..." (unless no criteria, then empty) + * Returns a SQL WHERE clause, created from the + * {@link #addCriteria(String, Object)}, with '?' placeholders. + * + * @return SQL WHERE clause, almost always starting with " WHERE ..." + * (unless no criteria, then empty) */ public String getSQLTemplate() { - if (sb.length() > 0) { - return " WHERE " + sb.toString(); - } + if (sb.length() > 0) { return " WHERE " + sb.toString(); } return ""; } /** * Returns the arguments for the WHERE clause. - * @return Object array suitable for use with Spring Framework JdbcTemplate (or plain JDBC {@link PreparedStatement}) + * + * @return Object array suitable for use with Spring Framework JdbcTemplate + * (or plain JDBC {@link PreparedStatement}) */ public Object[] getArguments() { return args.toArray(); @@ -120,39 +131,34 @@ public class SQLBuilder { /* * Returns a String representation suitable for debugging and log output. - * This is ONLY intended for debugging in logs, and NEVER for passing to a JDBC database. + * This is ONLY intended for debugging in logs, and NEVER for passing to a + * JDBC database. */ @Override public String toString() { - StringBuilder whereClause = new StringBuilder("SQLBuilder{"); - for (int i=0;i 0) { // Don't remove space before + // = operator inputSqlString = inputSqlString.replaceAll(" =", "="); } - while (inputSqlString.indexOf("= ") > 0) { //Don't remove space after = operator + while (inputSqlString.indexOf("= ") > 0) { // Don't remove space after = + // operator inputSqlString = inputSqlString.replaceAll("= ", "="); } @@ -76,7 +72,7 @@ public class SQLInjectionValidator { } } else { injectionFound = true; - break ; + break; } } if (token.equals("\"")) { @@ -88,7 +84,7 @@ public class SQLInjectionValidator { } } else { injectionFound = true; - break ; + break; } } else if (token.indexOf('=') > 0) { StringTokenizer operatorToken = new StringTokenizer(token, "="); @@ -104,40 +100,34 @@ public class SQLInjectionValidator { } } } - if (injectionFound) { - throw new SQLInjectionException(); - } + if (injectionFound) { throw new SQLInjectionException(); } Pattern pattern = Pattern.compile(SQL_PATTERN); Matcher matcher = pattern.matcher(sqlSearch); - if (!matcher.matches()) { - throw new SQLInjectionException(); - } + if (!matcher.matches()) { throw new SQLInjectionException(); } } + public final static void validateAdhocQuery(final String sqlSearch) { String lowerCaseSQL = sqlSearch.toLowerCase().trim(); for (String ddl : DDL_COMMANDS) { - if (lowerCaseSQL.startsWith(ddl)) { - throw new SQLInjectionException(); - } + if (lowerCaseSQL.startsWith(ddl)) { throw new SQLInjectionException(); } } - for (String comments : COMMENTS) { - if (lowerCaseSQL.contains(comments)) { - throw new SQLInjectionException(); - } + if (lowerCaseSQL.contains(comments)) { throw new SQLInjectionException(); } } - //Removing the space before and after '=' operator - //String s = " \" OR 1 = 1"; For the cases like this + // Removing the space before and after '=' operator + // String s = " \" OR 1 = 1"; For the cases like this boolean injectionFound = false; String inputSqlString = lowerCaseSQL; - while (inputSqlString.indexOf(" =") > 0) { //Don't remove space before = operator + while (inputSqlString.indexOf(" =") > 0) { // Don't remove space before + // = operator inputSqlString = inputSqlString.replaceAll(" =", "="); } - while (inputSqlString.indexOf("= ") > 0) { //Don't remove space after = operator + while (inputSqlString.indexOf("= ") > 0) { // Don't remove space after = + // operator inputSqlString = inputSqlString.replaceAll("= ", "="); } @@ -153,7 +143,7 @@ public class SQLInjectionValidator { } } else { injectionFound = true; - break ; + break; } } if (token.equals("\"")) { @@ -165,7 +155,7 @@ public class SQLInjectionValidator { } } else { injectionFound = true; - break ; + break; } } else if (token.indexOf('=') > 0) { StringTokenizer operatorToken = new StringTokenizer(token, "="); @@ -181,14 +171,10 @@ public class SQLInjectionValidator { } } } - if (injectionFound) { - throw new SQLInjectionException(); - } + if (injectionFound) { throw new SQLInjectionException(); } Pattern pattern = Pattern.compile(SQL_PATTERN); Matcher matcher = pattern.matcher(sqlSearch); - if (!matcher.matches()) { - throw new SQLInjectionException(); - } + if (!matcher.matches()) { throw new SQLInjectionException(); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/vote/SelfServiceUserAccessVote.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/vote/SelfServiceUserAccessVote.java index 2665b08e4..708a9bd53 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/vote/SelfServiceUserAccessVote.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/vote/SelfServiceUserAccessVote.java @@ -29,7 +29,8 @@ public class SelfServiceUserAccessVote implements AccessDecisionVoter attributes) { - if(!"OPTIONS".equalsIgnoreCase(fi.getHttpRequest().getMethod())){ + if (!"OPTIONS".equalsIgnoreCase(fi.getHttpRequest().getMethod())) { AppUser user = (AppUser) authentication.getPrincipal(); String pathURL = fi.getRequestUrl(); boolean isSelfServiceRequest = (pathURL != null && pathURL.contains("/self/")); boolean notAllowed = ((isSelfServiceRequest && !user.isSelfServiceUser()) - ||(!isSelfServiceRequest && user.isSelfServiceUser())); + || (!isSelfServiceRequest && user.isSelfServiceUser())); - if(notAllowed){ - return ACCESS_DENIED; - } + if (notAllowed) { return ACCESS_DENIED; } } return ACCESS_GRANTED; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/SmsApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/SmsApiConstants.java index b9fd6c139..d35dc69b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/SmsApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/SmsApiConstants.java @@ -38,4 +38,4 @@ public class SmsApiConstants { // response parameters public static final String statusParamName = "status"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/api/SmsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/api/SmsApiResource.java index 623c833c7..3d0025f5f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/api/SmsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/api/SmsApiResource.java @@ -130,8 +130,8 @@ public class SmsApiResource { toDate = toDateParam.getDate("toDate", dateFormat, locale); } - final Page smsMessages = this.readPlatformService.retrieveSmsByStatus(campaignId, searchParameters, status.intValue(), fromDate, - toDate); + final Page smsMessages = this.readPlatformService.retrieveSmsByStatus(campaignId, searchParameters, status.intValue(), + fromDate, toDate); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, smsMessages); @@ -158,4 +158,4 @@ public class SmsApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsData.java index 1edda9ed1..ddc0ad4b7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsData.java @@ -89,4 +89,4 @@ public class SmsData { return this.campaignName; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsDataValidator.java index a29193fa0..b63296982 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsDataValidator.java @@ -41,10 +41,9 @@ import org.springframework.stereotype.Component; public final class SmsDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - SmsApiConstants.localeParamName, SmsApiConstants.dateFormatParamName, SmsApiConstants.groupIdParamName, - SmsApiConstants.clientIdParamName, SmsApiConstants.staffIdParamName, SmsApiConstants.messageParamName, - SmsApiConstants.campaignIdParamName)); + private static final Set CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(SmsApiConstants.localeParamName, + SmsApiConstants.dateFormatParamName, SmsApiConstants.groupIdParamName, SmsApiConstants.clientIdParamName, + SmsApiConstants.staffIdParamName, SmsApiConstants.messageParamName, SmsApiConstants.campaignIdParamName)); public static final Set UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(SmsApiConstants.messageParamName, SmsApiConstants.campaignIdParamName)); @@ -142,4 +141,4 @@ public final class SmsDataValidator { private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiQueueResourceData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiQueueResourceData.java index 2bbe19fdd..36ff198d3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiQueueResourceData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiQueueResourceData.java @@ -115,6 +115,7 @@ public class SmsMessageApiQueueResourceData { /** * Returns the JSOPN representation of the current object. + * * @return the JSON representation of the current object */ public String toJsonString() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiReportResourceData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiReportResourceData.java index ab2e9dc71..9f1fd322d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiReportResourceData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiReportResourceData.java @@ -22,10 +22,11 @@ import com.google.gson.Gson; import java.util.List; /** - * Immutable data object representing the API request body sent in the POST request to - * the "/report" resource + * Immutable data object representing the API request body sent in the POST + * request to the "/report" resource **/ public class SmsMessageApiReportResourceData { + private List externalIds; private String mifosTenantIdentifier; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiResponseData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiResponseData.java index 62618ab1f..a7747c9bb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiResponseData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageApiResponseData.java @@ -24,6 +24,7 @@ import java.util.List; * Immutable data object representing an outbound SMS message API response data **/ public class SmsMessageApiResponseData { + private Integer httpStatusCode; private List data; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageDeliveryReportData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageDeliveryReportData.java index d4bd68a28..3e0f51bbb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageDeliveryReportData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/data/SmsMessageDeliveryReportData.java @@ -19,9 +19,11 @@ package org.apache.fineract.infrastructure.sms.data; /** - * Immutable data object representing an outbound SMS message delivery report data + * Immutable data object representing an outbound SMS message delivery report + * data **/ public class SmsMessageDeliveryReportData { + private Long id; private String externalId; private String addedOnDate; @@ -35,8 +37,8 @@ public class SmsMessageDeliveryReportData { * * **/ - private SmsMessageDeliveryReportData(Long id, String externalId, String addedOnDate, String deliveredOnDate, - Integer deliveryStatus, Boolean hasError, String errorMessage) { + private SmsMessageDeliveryReportData(Long id, String externalId, String addedOnDate, String deliveredOnDate, Integer deliveryStatus, + Boolean hasError, String errorMessage) { this.id = id; this.externalId = externalId; this.addedOnDate = addedOnDate; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessage.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessage.java index f222f05b9..b4c7e0154 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessage.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessage.java @@ -70,11 +70,11 @@ public class SmsMessage extends AbstractPersistableCustom { @Column(name = "message", nullable = false) private String message; -// @Column(name = "provider_id", nullable = true) -// private Long providerId; -// -// @Column(name = "campaign_name", nullable = true) -// private String campaignName; + // @Column(name = "provider_id", nullable = true) + // private Long providerId; + // + // @Column(name = "campaign_name", nullable = true) + // private String campaignName; @Column(name = "submittedon_date", nullable = true) @Temporal(TemporalType.DATE) @@ -89,16 +89,19 @@ public class SmsMessage extends AbstractPersistableCustom { public static SmsMessage pendingSms(final String externalId, final Group group, final Client client, final Staff staff, final String message, final String mobileNo, final SmsCampaign smsCampaign, final boolean isNotification) { - return new SmsMessage(externalId, group, client, staff, SmsMessageStatusType.PENDING, message, mobileNo, smsCampaign, isNotification); + return new SmsMessage(externalId, group, client, staff, SmsMessageStatusType.PENDING, message, mobileNo, smsCampaign, + isNotification); } public static SmsMessage sentSms(final String externalId, final Group group, final Client client, final Staff staff, final String message, final String mobileNo, final SmsCampaign smsCampaign, final boolean isNotification) { - return new SmsMessage(externalId, group, client, staff, SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT, message, mobileNo, smsCampaign, isNotification); + return new SmsMessage(externalId, group, client, staff, SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT, message, mobileNo, + smsCampaign, isNotification); } public static SmsMessage instance(String externalId, final Group group, final Client client, final Staff staff, - final SmsMessageStatusType statusType, final String message, final String mobileNo, final SmsCampaign smsCampaign, final boolean isNotification) { + final SmsMessageStatusType statusType, final String message, final String mobileNo, final SmsCampaign smsCampaign, + final boolean isNotification) { return new SmsMessage(externalId, group, client, staff, statusType, message, mobileNo, smsCampaign, isNotification); } @@ -194,5 +197,4 @@ public class SmsMessage extends AbstractPersistableCustom { this.isNotification = isNotification; } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageAssembler.java index e85bdecef..959b10d34 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageAssembler.java @@ -73,8 +73,7 @@ public class SmsMessageAssembler { boolean isNotification = false; if (this.fromApiJsonHelper.parameterExists(SmsApiConstants.campaignIdParamName, element)) { final Long campaignId = this.fromApiJsonHelper.extractLongNamed(SmsApiConstants.campaignIdParamName, element); - smsCampaign = this.smsCampaignRepository.findById(campaignId) - .orElseThrow(() -> new SmsCampaignNotFound(campaignId)); + smsCampaign = this.smsCampaignRepository.findById(campaignId).orElseThrow(() -> new SmsCampaignNotFound(campaignId)); isNotification = smsCampaign.isNotification(); } @@ -98,7 +97,6 @@ public class SmsMessageAssembler { } public SmsMessage assembleFromResourceId(final Long resourceId) { - return this.smsMessageRepository.findById(resourceId) - .orElseThrow(() -> new SmsNotFoundException(resourceId)); + return this.smsMessageRepository.findById(resourceId).orElseThrow(() -> new SmsNotFoundException(resourceId)); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageEnumerations.java index 3f812fdff..cc91d6ffe 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageEnumerations.java @@ -31,12 +31,12 @@ public class SmsMessageEnumerations { SmsMessageStatusType.INVALID.getCode(), "Invalid"); switch (status) { case INVALID: - optionData = new EnumOptionData(SmsMessageStatusType.INVALID.getValue().longValue(), - SmsMessageStatusType.INVALID.getCode(), "Invalid"); + optionData = new EnumOptionData(SmsMessageStatusType.INVALID.getValue().longValue(), SmsMessageStatusType.INVALID.getCode(), + "Invalid"); break; case PENDING: - optionData = new EnumOptionData(SmsMessageStatusType.PENDING.getValue().longValue(), - SmsMessageStatusType.PENDING.getCode(), "Pending"); + optionData = new EnumOptionData(SmsMessageStatusType.PENDING.getValue().longValue(), SmsMessageStatusType.PENDING.getCode(), + "Pending"); break; case WAITING_FOR_DELIVERY_REPORT: optionData = new EnumOptionData(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue().longValue(), @@ -59,4 +59,4 @@ public class SmsMessageEnumerations { return optionData; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageRepository.java index 9dadb5901..f2f24ec71 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageRepository.java @@ -26,4 +26,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface SmsMessageRepository extends JpaRepository, JpaSpecificationExecutor { Page findByStatusType(final Integer status, Pageable pageable); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageStatusType.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageStatusType.java index 687bdd32f..ef5cb96b1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageStatusType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/domain/SmsMessageStatusType.java @@ -22,8 +22,7 @@ public enum SmsMessageStatusType { INVALID(0, "smsMessageStatusType.invalid"), // PENDING(100, "smsMessageStatusType.pending"), // - WAITING_FOR_DELIVERY_REPORT(150, "smsMessageStatusType.waitingForDeliveryReport"), - SENT(200, "smsMessageStatusType.sent"), // + WAITING_FOR_DELIVERY_REPORT(150, "smsMessageStatusType.waitingForDeliveryReport"), SENT(200, "smsMessageStatusType.sent"), // DELIVERED(300, "smsMessageStatusType.delivered"), // FAILED(400, "smsMessageStatusType.failed"); @@ -65,4 +64,4 @@ public enum SmsMessageStatusType { public String getCode() { return this.code; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/exception/SmsNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/exception/SmsNotFoundException.java index 752c3ed06..73a7cf936 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/exception/SmsNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/exception/SmsNotFoundException.java @@ -28,4 +28,4 @@ public class SmsNotFoundException extends AbstractPlatformResourceNotFoundExcept public SmsNotFoundException(final Long resourceId) { super("error.msg.sms.identifier.not.found", "SMS with identifier `" + resourceId + "` does not exist", resourceId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/CreateSmsCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/CreateSmsCommandHandler.java index 2ad4cdc02..978d00306 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/CreateSmsCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/CreateSmsCommandHandler.java @@ -44,4 +44,4 @@ public class CreateSmsCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.create(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/DeleteSmsCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/DeleteSmsCommandHandler.java index 767db1742..de45dfa4a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/DeleteSmsCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/DeleteSmsCommandHandler.java @@ -44,4 +44,4 @@ public class DeleteSmsCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.delete(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/UpdateSmsCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/UpdateSmsCommandHandler.java index 4fe92a7b1..3ea77b7a0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/UpdateSmsCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/handler/UpdateSmsCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateSmsCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.update(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/scheduler/SmsMessageScheduledJobService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/scheduler/SmsMessageScheduledJobService.java index ef19a499d..e12ca82d2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/scheduler/SmsMessageScheduledJobService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/scheduler/SmsMessageScheduledJobService.java @@ -35,14 +35,19 @@ public interface SmsMessageScheduledJobService { /** * sends triggered batch SMS messages to SMS gateway + * * @param smsDataMap */ public void sendTriggeredMessages(Map> smsDataMap); /** - * Sends a triggered batch of SMS messages to SMS gateway using specified provider. - * @param smsMessage the SMS messages to queue for sending. - * @param providerId the provider ID of the SMS gateway to be used + * Sends a triggered batch of SMS messages to SMS gateway using specified + * provider. + * + * @param smsMessage + * the SMS messages to queue for sending. + * @param providerId + * the provider ID of the SMS gateway to be used */ void sendTriggeredMessage(Collection smsMessage, long providerId); @@ -50,4 +55,4 @@ public interface SmsMessageScheduledJobService { * get delivery report from the SMS gateway **/ public void getDeliveryReports(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/scheduler/SmsMessageScheduledJobServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/scheduler/SmsMessageScheduledJobServiceImpl.java index 9109e6eed..bb33e31f5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/scheduler/SmsMessageScheduledJobServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/scheduler/SmsMessageScheduledJobServiceImpl.java @@ -71,12 +71,11 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob private final SmsReadPlatformService smsReadPlatformService; private static final Logger LOG = LoggerFactory.getLogger(SmsMessageScheduledJobServiceImpl.class); private final RestTemplate restTemplate = new RestTemplate(); - private ExecutorService genericExecutorService ; - private ExecutorService triggeredExecutorService ; - private final SmsConfigUtils smsConfigUtils ; + private ExecutorService genericExecutorService; + private ExecutorService triggeredExecutorService; + private final SmsConfigUtils smsConfigUtils; private final NotificationSenderService notificationSenderService; - /** * SmsMessageScheduledJobServiceImpl constructor **/ @@ -85,14 +84,14 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob final SmsConfigUtils smsConfigUtils, final NotificationSenderService notificationSenderService) { this.smsMessageRepository = smsMessageRepository; this.smsReadPlatformService = smsReadPlatformService; - this.smsConfigUtils = smsConfigUtils ; + this.smsConfigUtils = smsConfigUtils; this.notificationSenderService = notificationSenderService; } @PostConstruct public void initializeExecutorService() { genericExecutorService = Executors.newSingleThreadExecutor(); - triggeredExecutorService = Executors.newSingleThreadExecutor() ; + triggeredExecutorService = Executors.newSingleThreadExecutor(); } /** @@ -107,10 +106,10 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob int totalRecords = 0; do { PageRequest pageRequest = PageRequest.of(0, pageLimit); - org.springframework.data.domain.Page pendingMessages = this.smsMessageRepository.findByStatusType( - SmsMessageStatusType.PENDING.getValue(), pageRequest); - List toSaveMessages = new ArrayList<>() ; - List toSendNotificationMessages = new ArrayList<>() ; + org.springframework.data.domain.Page pendingMessages = this.smsMessageRepository + .findByStatusType(SmsMessageStatusType.PENDING.getValue(), pageRequest); + List toSaveMessages = new ArrayList<>(); + List toSendNotificationMessages = new ArrayList<>(); try { if (pendingMessages.getContent().size() > 0) { @@ -119,32 +118,33 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob Collection apiQueueResourceDatas = new ArrayList<>(); while (pendingMessageIterator.hasNext()) { SmsMessage smsData = pendingMessageIterator.next(); - if(smsData.isNotification()){ + if (smsData.isNotification()) { smsData.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); toSendNotificationMessages.add(smsData); - }else{ + } else { SmsMessageApiQueueResourceData apiQueueResourceData = SmsMessageApiQueueResourceData.instance(smsData.getId(), - tenantIdentifier, null, null, smsData.getMobileNo(), smsData.getMessage(), smsData.getSmsCampaign() - .getProviderId()); + tenantIdentifier, null, null, smsData.getMobileNo(), smsData.getMessage(), + smsData.getSmsCampaign().getProviderId()); apiQueueResourceDatas.add(apiQueueResourceData); smsData.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); - toSaveMessages.add(smsData) ; + toSaveMessages.add(smsData); } } - if(toSaveMessages.size()>0){ + if (toSaveMessages.size() > 0) { this.smsMessageRepository.saveAll(toSaveMessages); this.smsMessageRepository.flush(); this.genericExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(), apiQueueResourceDatas)); } - if(!toSendNotificationMessages.isEmpty()){ + if (!toSendNotificationMessages.isEmpty()) { this.notificationSenderService.sendNotification(toSendNotificationMessages); } -// new MyThread(ThreadLocalContextUtil.getTenant(), apiQueueResourceDatas).start(); + // new MyThread(ThreadLocalContextUtil.getTenant(), + // apiQueueResourceDatas).start(); } } catch (Exception e) { throw new ConnectionFailureException(SmsCampaignConstants.SMS); } - page ++; + page++; totalRecords = pendingMessages.getTotalPages(); } while (page < totalRecords); } @@ -173,13 +173,14 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob } private void connectAndSendToIntermediateServer(Collection apiQueueResourceDatas) { - Map hostConfig = this.smsConfigUtils.getMessageGateWayRequestURI("sms", SmsMessageApiQueueResourceData.toJsonString(apiQueueResourceDatas)) ; - URI uri = (URI)hostConfig.get("uri") ; - HttpEntity entity = (HttpEntity)hostConfig.get("entity") ; + Map hostConfig = this.smsConfigUtils.getMessageGateWayRequestURI("sms", + SmsMessageApiQueueResourceData.toJsonString(apiQueueResourceDatas)); + URI uri = (URI) hostConfig.get("uri"); + HttpEntity entity = (HttpEntity) hostConfig.get("entity"); ResponseEntity responseOne = restTemplate.exchange(uri, HttpMethod.POST, entity, new ParameterizedTypeReference() {}); if (responseOne != null) { -// String smsResponse = responseOne.getBody(); + // String smsResponse = responseOne.getBody(); if (!responseOne.getStatusCode().equals(HttpStatus.ACCEPTED)) { LOG.debug("{}", responseOne.getStatusCode().name()); throw new ConnectionFailureException(SmsCampaignConstants.SMS); @@ -191,35 +192,35 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob public void sendTriggeredMessages(Map> smsDataMap) { try { if (!smsDataMap.isEmpty()) { - List toSaveMessages = new ArrayList<>() ; - List toSendNotificationMessages = new ArrayList<>() ; + List toSaveMessages = new ArrayList<>(); + List toSendNotificationMessages = new ArrayList<>(); for (Entry> entry : smsDataMap.entrySet()) { Iterator smsMessageIterator = entry.getValue().iterator(); Collection apiQueueResourceDatas = new ArrayList<>(); StringBuilder request = new StringBuilder(); while (smsMessageIterator.hasNext()) { SmsMessage smsMessage = smsMessageIterator.next(); - if(smsMessage.isNotification()){ + if (smsMessage.isNotification()) { smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); toSendNotificationMessages.add(smsMessage); - }else { - SmsMessageApiQueueResourceData apiQueueResourceData = SmsMessageApiQueueResourceData.instance(smsMessage.getId(), - null, null, null, smsMessage.getMobileNo(), smsMessage.getMessage(), entry.getKey().getProviderId()); + } else { + SmsMessageApiQueueResourceData apiQueueResourceData = SmsMessageApiQueueResourceData.instance( + smsMessage.getId(), null, null, null, smsMessage.getMobileNo(), smsMessage.getMessage(), + entry.getKey().getProviderId()); apiQueueResourceDatas.add(apiQueueResourceData); smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); - toSaveMessages.add(smsMessage) ; + toSaveMessages.add(smsMessage); } } - if(toSaveMessages.size()>0){ + if (toSaveMessages.size() > 0) { this.smsMessageRepository.saveAll(toSaveMessages); this.smsMessageRepository.flush(); this.triggeredExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(), apiQueueResourceDatas)); } - if(!toSendNotificationMessages.isEmpty()){ + if (!toSendNotificationMessages.isEmpty()) { this.notificationSenderService.sendNotification(toSendNotificationMessages); } - } } } catch (Exception e) { @@ -232,19 +233,16 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob try { Collection apiQueueResourceDatas = new ArrayList<>(); StringBuilder request = new StringBuilder(); - for(SmsMessage smsMessage : smsMessages) { - SmsMessageApiQueueResourceData apiQueueResourceData = - SmsMessageApiQueueResourceData.instance(smsMessage.getId(), null, - null, null, smsMessage.getMobileNo(), - smsMessage.getMessage(), providerId); + for (SmsMessage smsMessage : smsMessages) { + SmsMessageApiQueueResourceData apiQueueResourceData = SmsMessageApiQueueResourceData.instance(smsMessage.getId(), null, + null, null, smsMessage.getMobileNo(), smsMessage.getMessage(), providerId); apiQueueResourceDatas.add(apiQueueResourceData); smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); } this.smsMessageRepository.saveAll(smsMessages); request.append(SmsMessageApiQueueResourceData.toJsonString(apiQueueResourceDatas)); LOG.info("Sending triggered SMS to specific provider with request - {}", request); - this.triggeredExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(), - apiQueueResourceDatas)); + this.triggeredExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(), apiQueueResourceDatas)); } catch (Exception e) { LOG.error("Error occured.", e); } @@ -268,11 +266,12 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob if (smsMessageInternalIds.getPageItems().size() > 0) { // make request - Map hostConfig = this.smsConfigUtils.getMessageGateWayRequestURI("sms/report", new Gson().toJson(smsMessageInternalIds.getPageItems())) ; - URI uri = (URI)hostConfig.get("uri") ; - HttpEntity entity = (HttpEntity)hostConfig.get("entity") ; - ResponseEntity> responseOne = restTemplate.exchange(uri, HttpMethod.POST, entity, - new ParameterizedTypeReference>() {}); + Map hostConfig = this.smsConfigUtils.getMessageGateWayRequestURI("sms/report", + new Gson().toJson(smsMessageInternalIds.getPageItems())); + URI uri = (URI) hostConfig.get("uri"); + HttpEntity entity = (HttpEntity) hostConfig.get("entity"); + ResponseEntity> responseOne = restTemplate.exchange(uri, HttpMethod.POST, + entity, new ParameterizedTypeReference>() {}); Collection smsMessageDeliveryReportDatas = responseOne.getBody(); Iterator responseReportIterator = smsMessageDeliveryReportDatas.iterator(); @@ -280,8 +279,7 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob SmsMessageDeliveryReportData smsMessageDeliveryReportData = responseReportIterator.next(); Integer deliveryStatus = smsMessageDeliveryReportData.getDeliveryStatus(); - if (!smsMessageDeliveryReportData.getHasError() - && deliveryStatus != 100) { + if (!smsMessageDeliveryReportData.getHasError() && deliveryStatus != 100) { SmsMessage smsMessage = this.smsMessageRepository.findById(smsMessageDeliveryReportData.getId()).orElse(null); Integer statusType = smsMessage.getStatusType(); @@ -326,7 +324,8 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob } if (smsMessageDeliveryReportDatas.size() > 0) { - LOG.info("{} delivery report(s) successfully received from the intermediate gateway - sms", smsMessageDeliveryReportDatas.size()); + LOG.info("{} delivery report(s) successfully received from the intermediate gateway - sms", + smsMessageDeliveryReportDatas.size()); } } } @@ -334,7 +333,7 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob catch (Exception e) { LOG.error("Error occured.", e); } - page ++; + page++; totalRecords = smsMessageInternalIds.getTotalFilteredRecords(); } while (page < totalRecords); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsReadPlatformServiceImpl.java index d49b95851..6f8bd50b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsReadPlatformServiceImpl.java @@ -52,8 +52,7 @@ public class SmsReadPlatformServiceImpl implements SmsReadPlatformService { private final ColumnValidator columnValidator; @Autowired - public SmsReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + public SmsReadPlatformServiceImpl(final RoutingDataSource dataSource, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.smsRowMapper = new SmsMapper(); this.columnValidator = columnValidator; @@ -86,7 +85,7 @@ public class SmsReadPlatformServiceImpl implements SmsReadPlatformService { public String tableName() { return "sms_messages_outbound"; - } + } @Override public SmsData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { @@ -145,8 +144,9 @@ public class SmsReadPlatformServiceImpl implements SmsReadPlatformService { @Override public Collection retrieveAllSent(final Integer limit) { final String sqlPlusLimit = limit > 0 ? " limit 0, " + limit : ""; - final String sql = "select " + this.smsRowMapper.schema() + " where smo.status_enum IN (" + SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue() - + "," + SmsMessageStatusType.SENT.getValue() + ")" + sqlPlusLimit; + final String sql = "select " + this.smsRowMapper.schema() + " where smo.status_enum IN (" + + SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue() + "," + SmsMessageStatusType.SENT.getValue() + ")" + + sqlPlusLimit; return this.jdbcTemplate.query(sql, this.smsRowMapper, new Object[] {}); } @@ -167,7 +167,8 @@ public class SmsReadPlatformServiceImpl implements SmsReadPlatformService { + SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue() + sqlPlusLimit; final String sqlCountRows = "SELECT FOUND_ROWS()"; return this.paginationHelper.fetchPage(jdbcTemplate, sql, sqlCountRows, Long.class); - //(this.jdbcTemplate, sqlCountRows, new Object [] {}, Long.class); this.jdbcTemplate.queryForList(sql, Long.class); + // (this.jdbcTemplate, sqlCountRows, new Object [] {}, Long.class); + // this.jdbcTemplate.queryForList(sql, Long.class); } @Override @@ -198,7 +199,8 @@ public class SmsReadPlatformServiceImpl implements SmsReadPlatformService { } @Override - public Page retrieveSmsByStatus(final Long campaignId, final SearchParameters searchParameters, final Integer status, final Date dateFrom, final Date dateTo) { + public Page retrieveSmsByStatus(final Long campaignId, final SearchParameters searchParameters, final Integer status, + final Date dateFrom, final Date dateTo) { final StringBuilder sqlBuilder = new StringBuilder(200); final Object[] objectArray = new Object[10]; int arrayPos = 0; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsWritePlatformService.java index 08ef2333f..e44367bfc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsWritePlatformService.java @@ -28,4 +28,4 @@ public interface SmsWritePlatformService { CommandProcessingResult update(Long resourceId, JsonCommand command); CommandProcessingResult delete(Long resourceId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsWritePlatformServiceJpaRepositoryImpl.java index 6b2e68d24..df177cdb1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/sms/service/SmsWritePlatformServiceJpaRepositoryImpl.java @@ -120,14 +120,17 @@ public class SmsWritePlatformServiceJpaRepositoryImpl implements SmsWritePlatfor * Guaranteed to throw an exception no matter what the data integrity issue * is. */ - private void handleDataIntegrityIssues(@SuppressWarnings("unused") final JsonCommand command, final DataIntegrityViolationException dve) { + private void handleDataIntegrityIssues(@SuppressWarnings("unused") final JsonCommand command, + final DataIntegrityViolationException dve) { final Throwable realCause = dve.getMostSpecificCause(); - if (realCause.getMessage().contains("mobile_no")) { throw new PlatformDataIntegrityException("error.msg.sms.no.mobile.no.exists", - "The group, client or staff provided has no mobile no.", "id"); } + if (realCause.getMessage().contains("mobile_no")) { + throw new PlatformDataIntegrityException("error.msg.sms.no.mobile.no.exists", + "The group, client or staff provided has no mobile no.", "id"); + } LOG.error("Error occured.", dve); throw new PlatformDataIntegrityException("error.msg.sms.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + realCause.getMessage()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/PovertyLineApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/PovertyLineApiResource.java index 2f0b354c6..3aaca6970 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/PovertyLineApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/PovertyLineApiResource.java @@ -49,7 +49,8 @@ public class PovertyLineApiResource { @Autowired PovertyLineApiResource(final PlatformSecurityContext context, final DefaultToApiJsonSerializer toApiJsonSerializer, - final PovertyLineService readService, final DefaultToApiJsonSerializer likelihoodToApiJsonSerializer) { + final PovertyLineService readService, + final DefaultToApiJsonSerializer likelihoodToApiJsonSerializer) { this.context = context; this.toApiJsonSerializer = toApiJsonSerializer; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiConstants.java index 56caeb50b..fa9a14bdb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiConstants.java @@ -23,6 +23,5 @@ package org.apache.fineract.infrastructure.survey.api; */ public class SurveyApiConstants { - - final static String SURVEY_RESOURCE_NAME ="Survey"; + final static String SURVEY_RESOURCE_NAME = "Survey"; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiResource.java index b3b30a27c..9d8b46354 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiResource.java @@ -85,7 +85,8 @@ public class SurveyApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieve surveys", notes = "Retrieve surveys. This allows to retrieve the list of survey tables registered .") - @ApiResponses({@ApiResponse(code = 200, message = "", response = SurveyApiResourceSwagger.GetSurveyResponse.class, responseContainer = "List")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = SurveyApiResourceSwagger.GetSurveyResponse.class, responseContainer = "List") }) public String retrieveSurveys() { this.context.authenticatedUser().validateHasReadPermission(SurveyApiConstants.SURVEY_RESOURCE_NAME); @@ -99,7 +100,7 @@ public class SurveyApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieve survey", notes = "Lists a registered survey table details and the Apache Fineract Core application table they are registered to.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = SurveyApiResourceSwagger.GetSurveyResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = SurveyApiResourceSwagger.GetSurveyResponse.class) }) public String retrieveSurvey(@PathParam("surveyName") @ApiParam(value = "surveyName") final String surveyName) { this.context.authenticatedUser().validateHasReadPermission(SurveyApiConstants.SURVEY_RESOURCE_NAME); @@ -114,11 +115,14 @@ public class SurveyApiResource { @Path("{surveyName}/{apptableId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create an entry in the survey table", notes = "Insert and entry in a survey table (full fill the survey)." + "\n" + "\n" + "Refer Link for sample Body: [ https://demo.fineract.dev/fineract-provider/api-docs/apiLive.htm#survey_create ] ") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SurveyApiResourceSwagger.PostSurveySurveyNameApptableIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = SurveyApiResourceSwagger.PostSurveySurveyNameApptableIdResponse.class)}) - public String createDatatableEntry(@PathParam("surveyName") @ApiParam(value = "surveyName") final String datatable, @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, - final String apiRequestBodyAsJson) { + @ApiOperation(value = "Create an entry in the survey table", notes = "Insert and entry in a survey table (full fill the survey)." + "\n" + + "\n" + "Refer Link for sample Body: [ https://demo.fineract.dev/fineract-provider/api-docs/apiLive.htm#survey_create ] ") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SurveyApiResourceSwagger.PostSurveySurveyNameApptableIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = SurveyApiResourceSwagger.PostSurveySurveyNameApptableIdResponse.class) }) + public String createDatatableEntry(@PathParam("surveyName") @ApiParam(value = "surveyName") final String datatable, + @PathParam("apptableId") @ApiParam(value = "apptableId") final Long apptableId, final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .fullFilSurvey(datatable, apptableId) // @@ -166,8 +170,8 @@ public class SurveyApiResource { public String register(@PathParam("surveyName") final String datatable, @PathParam("apptable") final String apptable, final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().registerSurvey(datatable, apptable) - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().registerSurvey(datatable, apptable).withJson(apiRequestBodyAsJson) + .build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiResourceSwagger.java index 6029ed901..aefdc98f8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/api/SurveyApiResourceSwagger.java @@ -28,25 +28,31 @@ import org.joda.time.DateTime; * Created by sanyam on 13/8/17. */ final class SurveyApiResourceSwagger { - private SurveyApiResourceSwagger(){ + + private SurveyApiResourceSwagger() { } @ApiModel(value = "GetSurveyResponse") public static final class GetSurveyResponse { - private GetSurveyResponse(){ + + private GetSurveyResponse() { } + final class GetSurveyResponseDatatableData { + private GetSurveyResponseDatatableData() { } + @ApiModelProperty(example = "m_client") public String applicationTableName; @ApiModelProperty(example = "ppi_kenya_2005") public String registeredTableName; public List columnHeaderData; } + public GetSurveyResponseDatatableData datatableData; @ApiModelProperty(example = "false") public boolean enabled; @@ -54,9 +60,11 @@ final class SurveyApiResourceSwagger { @ApiModel(value = "PostSurveySurveyNameApptableIdRequest") public static final class PostSurveySurveyNameApptableIdRequest { + private PostSurveySurveyNameApptableIdRequest() { } + @ApiModelProperty(example = "167") public Long ppi_household_members_cd_q1_householdmembers; @ApiModelProperty(example = "174") @@ -85,12 +93,13 @@ final class SurveyApiResourceSwagger { public String locale; } - @ApiModel(value = "PostSurveySurveyNameApptableIdResponse") public static final class PostSurveySurveyNameApptableIdResponse { + private PostSurveySurveyNameApptableIdResponse() { } + @ApiModelProperty(example = "2") public Long officeId; @ApiModelProperty(example = "87") diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/LikelihoodDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/LikelihoodDataValidator.java index 66cf50b6c..a5e7855c9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/LikelihoodDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/LikelihoodDataValidator.java @@ -46,8 +46,7 @@ import org.springframework.stereotype.Component; public class LikelihoodDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set UPDATE_LIKELIHOOD_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(LikelihoodApiConstants.ACTIVE)); + private static final Set UPDATE_LIKELIHOOD_DATA_PARAMETERS = new HashSet<>(Arrays.asList(LikelihoodApiConstants.ACTIVE)); @Autowired public LikelihoodDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -62,7 +61,8 @@ public class LikelihoodDataValidator { this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, UPDATE_LIKELIHOOD_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(LikelihoodApiConstants.LIKELIHOOD_RESOURCE_NAME); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(LikelihoodApiConstants.LIKELIHOOD_RESOURCE_NAME); final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists(LikelihoodApiConstants.ACTIVE, element)) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/LikelihoodStatus.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/LikelihoodStatus.java index ced9fe145..3ac0cb398 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/LikelihoodStatus.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/LikelihoodStatus.java @@ -23,6 +23,6 @@ package org.apache.fineract.infrastructure.survey.data; */ public class LikelihoodStatus { - public final static long ENABLED = 200; - public final static long DISABLED =100; + public final static long ENABLED = 200; + public final static long DISABLED = 100; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/PovertyLineData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/PovertyLineData.java index b5b50fa2f..555b641d1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/PovertyLineData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/PovertyLineData.java @@ -28,10 +28,7 @@ public class PovertyLineData { final Long scoreTo; final Double povertyLine; - public PovertyLineData(final Long resourceId, - final Long scoreFrom, - final Long scoreTo, - final Double povertyLine){ + public PovertyLineData(final Long resourceId, final Long scoreFrom, final Long scoreTo, final Double povertyLine) { this.resourceId = resourceId; this.scoreTo = scoreTo; diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/PpiPovertyLineData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/PpiPovertyLineData.java index 955dcb604..133753787 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/PpiPovertyLineData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/PpiPovertyLineData.java @@ -28,14 +28,11 @@ public class PpiPovertyLineData { final String ppi; final List likeliHoodPovertyLineData; - - public PpiPovertyLineData(final List likeliHoodPovertyLineData, - final String ppi){ + public PpiPovertyLineData(final List likeliHoodPovertyLineData, final String ppi) { this.likeliHoodPovertyLineData = likeliHoodPovertyLineData; this.ppi = ppi; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/SurveyData.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/SurveyData.java index 1885e1401..f62827983 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/SurveyData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/data/SurveyData.java @@ -21,5 +21,4 @@ package org.apache.fineract.infrastructure.survey.data; /** * Created by Cieyou on 2/27/14. */ -public class SurveyData { -} +public class SurveyData {} diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/domain/LikelihoodRepository.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/domain/LikelihoodRepository.java index 73be875df..764ac0a05 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/domain/LikelihoodRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/domain/LikelihoodRepository.java @@ -18,17 +18,15 @@ */ package org.apache.fineract.infrastructure.survey.domain; - import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; - public interface LikelihoodRepository extends JpaRepository, JpaSpecificationExecutor { - @Query("select liklihood FROM Likelihood liklihood WHERE ppi_name =:ppiName AND id <>:id") - List findByPpiNameAndLikeliHoodId(@Param("ppiName") String ppiName,@Param("id") Long likeliHoodId); + @Query("select liklihood FROM Likelihood liklihood WHERE ppi_name =:ppiName AND id <>:id") + List findByPpiNameAndLikeliHoodId(@Param("ppiName") String ppiName, @Param("id") Long likeliHoodId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/FullFilSurveyCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/FullFilSurveyCommandHandler.java index 59e8cfd22..12e0787d7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/FullFilSurveyCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/FullFilSurveyCommandHandler.java @@ -33,7 +33,6 @@ import org.springframework.transaction.annotation.Transactional; @Service public class FullFilSurveyCommandHandler implements NewCommandSourceHandler { - private final WriteSurveyService writePlatformService; @Autowired @@ -45,6 +44,6 @@ public class FullFilSurveyCommandHandler implements NewCommandSourceHandler { @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.fullFillSurvey (command.entityName(),command.entityId(),command); + return this.writePlatformService.fullFillSurvey(command.entityName(), command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/RegisterSurveyCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/RegisterSurveyCommandHandler.java index 9264a55e9..2dfcf921e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/RegisterSurveyCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/RegisterSurveyCommandHandler.java @@ -33,7 +33,6 @@ import org.springframework.transaction.annotation.Transactional; @Service public class RegisterSurveyCommandHandler implements NewCommandSourceHandler { - private final WriteSurveyService writePlatformService; @Autowired diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/UpdateLikelihoodCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/UpdateLikelihoodCommandHandler.java index 3eb6f7976..8b4a5cdf7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/UpdateLikelihoodCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/handler/UpdateLikelihoodCommandHandler.java @@ -35,7 +35,6 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "LIKELIHOOD", action = "UPDATE") public class UpdateLikelihoodCommandHandler implements NewCommandSourceHandler { - private final WriteLikelihoodService writePlatformService; @Autowired diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/PovertyLineServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/PovertyLineServiceImpl.java index 68f776e4b..12073c31c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/PovertyLineServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/PovertyLineServiceImpl.java @@ -63,8 +63,8 @@ public class PovertyLineServiceImpl implements PovertyLineService { String likelihoodCode = povertyLines.getString("code"); if (likelihoodCode.equals(codeName)) { - povertyLineDatas.add(new PovertyLineData(povertyLines.getLong("id"), povertyLines.getLong("score_from"), povertyLines - .getLong("score_to"), povertyLines.getDouble("poverty_line"))); + povertyLineDatas.add(new PovertyLineData(povertyLines.getLong("id"), povertyLines.getLong("score_from"), + povertyLines.getLong("score_to"), povertyLines.getDouble("poverty_line"))); } } @@ -73,8 +73,8 @@ public class PovertyLineServiceImpl implements PovertyLineService { // create the likelihood object with the list of povertyLine object // belonging to it - LikeliHoodPovertyLineData likeliHoodPovertyLineData = new LikeliHoodPovertyLineData(likelihoods.getLong("id"), - povertyLineDatas, likelihoods.getString("name"), likelihoods.getString("code"), likelihoods.getLong("enabled")); + LikeliHoodPovertyLineData likeliHoodPovertyLineData = new LikeliHoodPovertyLineData(likelihoods.getLong("id"), povertyLineDatas, + likelihoods.getString("name"), likelihoods.getString("code"), likelihoods.getLong("enabled")); listOfLikeliHoodPovertyLineData.add(likeliHoodPovertyLineData); @@ -94,8 +94,8 @@ public class PovertyLineServiceImpl implements PovertyLineService { while (povertyLines.next()) { - povertyLineDatas.add(new PovertyLineData(povertyLines.getLong("id"), povertyLines.getLong("score_from"), povertyLines - .getLong("score_to"), povertyLines.getDouble("poverty_line"))); + povertyLineDatas.add(new PovertyLineData(povertyLines.getLong("id"), povertyLines.getLong("score_from"), + povertyLines.getLong("score_to"), povertyLines.getDouble("poverty_line"))); } povertyLines.first(); @@ -126,10 +126,8 @@ public class PovertyLineServiceImpl implements PovertyLineService { private SqlRowSet getPovertyLines(final Long likelihoodId) { String sql = "SELECT pl.id, sc.score_from, sc.score_to , pl.poverty_line,lkh.code , lkp.enabled, lkp.id as likelihood_id , lkh.name , lkp.ppi_name " - + " FROM ppi_poverty_line pl " - + " JOIN ppi_likelihoods_ppi lkp on lkp.id = pl.likelihood_ppi_id " - + " JOIN ppi_likelihoods lkh on lkh.id = lkp.likelihood_id " - + " JOIN ppi_scores sc on sc.id = pl.score_id " + + " FROM ppi_poverty_line pl " + " JOIN ppi_likelihoods_ppi lkp on lkp.id = pl.likelihood_ppi_id " + + " JOIN ppi_likelihoods lkh on lkh.id = lkp.likelihood_id " + " JOIN ppi_scores sc on sc.id = pl.score_id " + " WHERE pl.likelihood_ppi_id = ? "; return this.jdbcTemplate.queryForRowSet(sql, new Object[] { likelihoodId }); diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/ReadLikelihoodService.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/ReadLikelihoodService.java index 01c7a1275..66628130a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/ReadLikelihoodService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/ReadLikelihoodService.java @@ -27,5 +27,6 @@ import org.apache.fineract.infrastructure.survey.data.LikelihoodData; public interface ReadLikelihoodService { public List retrieveAll(final String ppiName); + public LikelihoodData retrieve(final Long likelihoodId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/ReadSurveyServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/ReadSurveyServiceImpl.java index b41837718..fc6d515a9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/ReadSurveyServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/ReadSurveyServiceImpl.java @@ -74,8 +74,8 @@ public class ReadSurveyServiceImpl implements ReadSurveyService { final List columnHeaderData = this.genericDataService .fillResultsetColumnHeaders(registeredDatatableName); - surveyDataTables.add(SurveyDataTableData.create(DatatableData.create(appTableName, registeredDatatableName, columnHeaderData), - enabled)); + surveyDataTables.add( + SurveyDataTableData.create(DatatableData.create(appTableName, registeredDatatableName, columnHeaderData), enabled)); } return surveyDataTables; @@ -131,13 +131,14 @@ public class ReadSurveyServiceImpl implements ReadSurveyService { + " JOIN ppi_poverty_line pvl on pvl.likelihood_ppi_id = lkp.id AND pvl.score_id = sc.id" + " JOIN ppi_likelihoods lkh on lkh.id = lkp.likelihood_id " + " WHERE client_id = ? "; - final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql, new Object[] { surveyName, surveyName, LikelihoodStatus.ENABLED, clientId }); + final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql, + new Object[] { surveyName, surveyName, LikelihoodStatus.ENABLED, clientId }); List scoresOverviews = new ArrayList<>(); while (rs.next()) { - scoresOverviews.add(new ClientScoresOverview(rs.getString("code"), rs.getString("name"), rs.getLong("score"), rs - .getDouble("poverty_line"), new LocalDate(rs.getTimestamp("date").getTime()), rs.getLong("id"), surveyName)); + scoresOverviews.add(new ClientScoresOverview(rs.getString("code"), rs.getString("name"), rs.getLong("score"), + rs.getDouble("poverty_line"), new LocalDate(rs.getTimestamp("date").getTime()), rs.getLong("id"), surveyName)); } return scoresOverviews; @@ -165,9 +166,9 @@ public class ReadSurveyServiceImpl implements ReadSurveyService { final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); while (rs.next()) { - scoresOverviews.add(new ClientScoresOverview(rs.getString("code"), rs.getString("name"), rs.getLong("score"), rs - .getDouble("poverty_line"), new LocalDate(rs.getTimestamp("date").getTime()), rs.getLong("id"), rs - .getString("surveyName"))); + scoresOverviews.add(new ClientScoresOverview(rs.getString("code"), rs.getString("name"), rs.getLong("score"), + rs.getDouble("poverty_line"), new LocalDate(rs.getTimestamp("date").getTime()), rs.getLong("id"), + rs.getString("surveyName"))); } } @@ -177,9 +178,8 @@ public class ReadSurveyServiceImpl implements ReadSurveyService { private String retrieveAllSurveyNameSQL() { // PERMITTED datatables - return "select cf.name from x_registered_table " - + " join c_configuration cf on x_registered_table.registered_table_name = cf.name " + " where exists" + " (select 'f'" - + " from m_appuser_role ur " + " join m_role r on r.id = ur.role_id" + return "select cf.name from x_registered_table " + " join c_configuration cf on x_registered_table.registered_table_name = cf.name " + + " where exists" + " (select 'f'" + " from m_appuser_role ur " + " join m_role r on r.id = ur.role_id" + " left join m_role_permission rp on rp.role_id = r.id" + " left join m_permission p on p.id = rp.permission_id" + " where ur.appuser_id = " + this.context.authenticatedUser().getId() + " and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) " diff --git a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/WriteLikelihoodServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/WriteLikelihoodServiceImpl.java index 5baad04d0..4b941d877 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/WriteLikelihoodServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/WriteLikelihoodServiceImpl.java @@ -68,8 +68,8 @@ public class WriteLikelihoodServiceImpl implements WriteLikelihoodService { this.repository.save(likelihood); if (likelihood.isActivateCommand(command)) { - List likelihoods = this.repository - .findByPpiNameAndLikeliHoodId(likelihood.getPpiName(), likelihood.getId()); + List likelihoods = this.repository.findByPpiNameAndLikeliHoodId(likelihood.getPpiName(), + likelihood.getId()); for (Likelihood aLikelihood : likelihoods) { aLikelihood.disable(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/api/InteropApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/api/InteropApiResource.java index 2a45d4ce7..2e0abe071 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/api/InteropApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/api/InteropApiResource.java @@ -68,7 +68,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; -@Path("/interoperation") //api/v1/ +@Path("/interoperation") // api/v1/ @Component @Scope @Api(value = ROOT_PATH, description = "") @@ -83,11 +83,9 @@ public class InteropApiResource { private PortfolioCommandSourceWritePlatformService commandsSourceService; @Autowired - public InteropApiResource(PlatformSecurityContext context, - ApiRequestParameterHelper apiRequestParameterHelper, - DefaultToApiJsonSerializer defaultToApiJsonSerializer, - InteropService interopService, - PortfolioCommandSourceWritePlatformService portfolioCommandSourceWritePlatformService) { + public InteropApiResource(PlatformSecurityContext context, ApiRequestParameterHelper apiRequestParameterHelper, + DefaultToApiJsonSerializer defaultToApiJsonSerializer, InteropService interopService, + PortfolioCommandSourceWritePlatformService portfolioCommandSourceWritePlatformService) { this.context = context; this.apiRequestParameterHelper = apiRequestParameterHelper; this.jsonSerializer = defaultToApiJsonSerializer; @@ -96,21 +94,21 @@ public class InteropApiResource { } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("health") @ApiOperation(value = "Query Interoperation Health Request", httpMethod = "GET", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "OK")}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK") }) public String health(@Context UriInfo uriInfo) { return "OK"; } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("accounts/{accountId}") @ApiOperation(value = "Query Interoperation Account details", httpMethod = "GET", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropAccountData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropAccountData.class) }) public String getAccountDetails(@PathParam("accountId") @ApiParam(value = "accountId") String accountId, @Context UriInfo uriInfo) { InteropAccountData result = interopService.getAccountDetails(accountId); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -119,19 +117,20 @@ public class InteropApiResource { } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("accounts/{accountId}/transactions") @ApiOperation(value = "Query transactions by Account Id", httpMethod = "GET", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropTransactionsData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropTransactionsData.class) }) public String getAccountTransactions(@PathParam("accountId") @ApiParam(value = "accountId") String accountId, - @DefaultValue("true") @QueryParam("debit") @ApiParam(value = "debit") boolean debit, - @DefaultValue("false") @QueryParam("credit") @ApiParam(value = "credit") boolean credit, - @QueryParam("fromBookingDateTime") @ApiParam(value = "fromBookingDateTime") String fromBookingDateTime, - @QueryParam("toBookingDateTime") @ApiParam(value = "toBookingDateTime") String toBookingDateTime, - @Context UriInfo uriInfo) { - LocalDateTime transactionsFrom = fromBookingDateTime == null ? null : LocalDateTime.parse(fromBookingDateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME); - LocalDateTime transactionsTo = toBookingDateTime == null ? null : LocalDateTime.parse(toBookingDateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME); + @DefaultValue("true") @QueryParam("debit") @ApiParam(value = "debit") boolean debit, + @DefaultValue("false") @QueryParam("credit") @ApiParam(value = "credit") boolean credit, + @QueryParam("fromBookingDateTime") @ApiParam(value = "fromBookingDateTime") String fromBookingDateTime, + @QueryParam("toBookingDateTime") @ApiParam(value = "toBookingDateTime") String toBookingDateTime, @Context UriInfo uriInfo) { + LocalDateTime transactionsFrom = fromBookingDateTime == null ? null + : LocalDateTime.parse(fromBookingDateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME); + LocalDateTime transactionsTo = toBookingDateTime == null ? null + : LocalDateTime.parse(toBookingDateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME); InteropTransactionsData result = interopService.getAccountTransactions(accountId, debit, credit, transactionsFrom, transactionsTo); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -140,11 +139,11 @@ public class InteropApiResource { } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("accounts/{accountId}/identifiers") @ApiOperation(value = "Query Interoperation secondary identifiers by Account Id", httpMethod = "GET", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropIdentifiersResponseData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropIdentifiersResponseData.class) }) public String getAccountIdentifiers(@PathParam("accountId") @ApiParam(value = "accountId") String accountId, @Context UriInfo uriInfo) { InteropIdentifiersResponseData result = interopService.getAccountIdentifiers(accountId); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -153,14 +152,13 @@ public class InteropApiResource { } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("parties/{idType}/{idValue}") @ApiOperation(value = "Query Interoperation Account by secondary identifier", httpMethod = "GET", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class) }) public String getAccountByIdentifier(@PathParam("idType") @ApiParam(value = "idType") InteropIdentifierType idType, - @PathParam("idValue") @ApiParam(value = "idValue") String idValue, - @Context UriInfo uriInfo) { + @PathParam("idValue") @ApiParam(value = "idValue") String idValue, @Context UriInfo uriInfo) { InteropIdentifierAccountResponseData result = interopService.getAccountByIdentifier(idType, idValue, null); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -168,15 +166,14 @@ public class InteropApiResource { } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("parties/{idType}/{idValue}/{subIdOrType}") @ApiOperation(value = "Query Interoperation Account by secondary identifier", httpMethod = "GET", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class) }) public String getAccountByIdentifier(@PathParam("idType") @ApiParam(value = "idType") InteropIdentifierType idType, - @PathParam("idValue") @ApiParam(value = "idValue") String idValue, - @PathParam("subIdOrType") @ApiParam(value = "subIdOrType") String subIdOrType, - @Context UriInfo uriInfo) { + @PathParam("idValue") @ApiParam(value = "idValue") String idValue, + @PathParam("subIdOrType") @ApiParam(value = "subIdOrType") String subIdOrType, @Context UriInfo uriInfo) { InteropIdentifierAccountResponseData result = interopService.getAccountByIdentifier(idType, idValue, subIdOrType); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -184,95 +181,95 @@ public class InteropApiResource { } @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("parties/{idType}/{idValue}") @ApiOperation(value = "Interoperation Identifier registration", httpMethod = "POST", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", - dataTypeClass = InteropIdentifierRequestData.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InteropIdentifierRequestData.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class) }) public String registerAccountIdentifier(@PathParam("idType") @ApiParam(value = "idType") InteropIdentifierType idType, - @PathParam("idValue") @ApiParam(value = "idValue") String idValue, - @ApiParam(hidden = true) String identifierJson, @Context UriInfo uriInfo) - { - CommandWrapper commandRequest = new InteropWrapperBuilder().registerAccountIdentifier(idType, idValue, null).withJson(identifierJson).build(); + @PathParam("idValue") @ApiParam(value = "idValue") String idValue, @ApiParam(hidden = true) String identifierJson, + @Context UriInfo uriInfo) { + CommandWrapper commandRequest = new InteropWrapperBuilder().registerAccountIdentifier(idType, idValue, null) + .withJson(identifierJson).build(); - InteropIdentifierAccountResponseData result = (InteropIdentifierAccountResponseData) commandsSourceService.logCommandSource(commandRequest); + InteropIdentifierAccountResponseData result = (InteropIdentifierAccountResponseData) commandsSourceService + .logCommandSource(commandRequest); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return jsonSerializer.serialize(settings, result); } @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("parties/{idType}/{idValue}/{subIdOrType}") @ApiOperation(value = "Interoperation Identifier registration", httpMethod = "POST", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", - dataTypeClass = InteropIdentifierRequestData.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InteropIdentifierRequestData.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class) }) public String registerAccountIdentifier(@PathParam("idType") @ApiParam(value = "idType") InteropIdentifierType idType, - @PathParam("idValue") @ApiParam(value = "idValue") String idValue, - @PathParam("subIdOrType") @ApiParam(value = "subIdOrType") String subIdOrType, - @ApiParam(hidden = true) String identifierJson, @Context UriInfo uriInfo) - { - CommandWrapper commandRequest = new InteropWrapperBuilder().registerAccountIdentifier(idType, idValue, subIdOrType).withJson(identifierJson).build(); + @PathParam("idValue") @ApiParam(value = "idValue") String idValue, + @PathParam("subIdOrType") @ApiParam(value = "subIdOrType") String subIdOrType, @ApiParam(hidden = true) String identifierJson, + @Context UriInfo uriInfo) { + CommandWrapper commandRequest = new InteropWrapperBuilder().registerAccountIdentifier(idType, idValue, subIdOrType) + .withJson(identifierJson).build(); - InteropIdentifierAccountResponseData result = (InteropIdentifierAccountResponseData) commandsSourceService.logCommandSource(commandRequest); + InteropIdentifierAccountResponseData result = (InteropIdentifierAccountResponseData) commandsSourceService + .logCommandSource(commandRequest); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return jsonSerializer.serialize(settings, result); } @DELETE - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("parties/{idType}/{idValue}") @ApiOperation(value = "Allow Interoperation Identifier registration", httpMethod = "DELETE", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", - dataTypeClass = InteropIdentifierRequestData.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InteropIdentifierRequestData.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class) }) public String deleteAccountIdentifier(@PathParam("idType") @ApiParam(value = "idType") InteropIdentifierType idType, - @PathParam("idValue") @ApiParam(value = "idValue") String idValue, - @Context UriInfo uriInfo) - { + @PathParam("idValue") @ApiParam(value = "idValue") String idValue, @Context UriInfo uriInfo) { CommandWrapper commandRequest = new InteropWrapperBuilder().deleteAccountIdentifier(idType, idValue, null).build(); - InteropIdentifierAccountResponseData result = (InteropIdentifierAccountResponseData) commandsSourceService.logCommandSource(commandRequest); + InteropIdentifierAccountResponseData result = (InteropIdentifierAccountResponseData) commandsSourceService + .logCommandSource(commandRequest); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return jsonSerializer.serialize(settings, result); } @DELETE - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("parties/{idType}/{idValue}/{subIdOrType}") @ApiOperation(value = "Allow Interoperation Identifier registration", httpMethod = "DELETE", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", - dataTypeClass = InteropIdentifierRequestData.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InteropIdentifierRequestData.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropIdentifierAccountResponseData.class) }) public String deleteAccountIdentifier(@PathParam("idType") @ApiParam(value = "idType") InteropIdentifierType idType, - @PathParam("idValue") @ApiParam(value = "idValue") String idValue, - @PathParam("subIdOrType") @ApiParam(value = "subIdOrType") String subIdOrType, - @Context UriInfo uriInfo) - { + @PathParam("idValue") @ApiParam(value = "idValue") String idValue, + @PathParam("subIdOrType") @ApiParam(value = "subIdOrType") String subIdOrType, @Context UriInfo uriInfo) { CommandWrapper commandRequest = new InteropWrapperBuilder().deleteAccountIdentifier(idType, idValue, subIdOrType).build(); - InteropIdentifierAccountResponseData result = (InteropIdentifierAccountResponseData) commandsSourceService.logCommandSource(commandRequest); + InteropIdentifierAccountResponseData result = (InteropIdentifierAccountResponseData) commandsSourceService + .logCommandSource(commandRequest); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return jsonSerializer.serialize(settings, result); } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("transactions/{transactionCode}/requests/{requestCode}") @ApiOperation(value = "Query Interoperation Transaction Request", httpMethod = "GET", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropTransactionRequestResponseData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropTransactionRequestResponseData.class) }) public String getTransactionRequest(@PathParam("transactionCode") @ApiParam(value = "transactionCode") String transactionCode, - @PathParam("requestCode") @ApiParam(value = "requestCode") String requestCode, @Context UriInfo uriInfo) { + @PathParam("requestCode") @ApiParam(value = "requestCode") String requestCode, @Context UriInfo uriInfo) { context.authenticatedUser().validateHasReadPermission(ENTITY_NAME_REQUEST); InteropTransactionRequestResponseData result = interopService.getTransactionRequest(transactionCode, requestCode); @@ -282,31 +279,31 @@ public class InteropApiResource { } @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("requests") @ApiOperation(value = "Allow Interoperation Transaction Request", httpMethod = "POST", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", - dataTypeClass = InteropTransactionRequestData.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropTransactionRequestResponseData.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InteropTransactionRequestData.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropTransactionRequestResponseData.class) }) public String createTransactionRequest(@ApiParam(hidden = true) String quotesJson, @Context UriInfo uriInfo) { CommandWrapper commandRequest = new InteropWrapperBuilder().createTransactionRequest().withJson(quotesJson).build(); - InteropTransactionRequestResponseData result = (InteropTransactionRequestResponseData) commandsSourceService.logCommandSource(commandRequest); + InteropTransactionRequestResponseData result = (InteropTransactionRequestResponseData) commandsSourceService + .logCommandSource(commandRequest); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return jsonSerializer.serialize(settings, result); } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("transactions/{transactionCode}/quotes/{quoteCode}") @ApiOperation(value = "Query Interoperation Quote", httpMethod = "GET", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropQuoteResponseData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropQuoteResponseData.class) }) public String getQuote(@PathParam("transactionCode") @ApiParam(value = "transactionCode") String transactionCode, - @PathParam("quoteCode") @ApiParam(value = "quoteCode") String quoteCode, - @Context UriInfo uriInfo) { + @PathParam("quoteCode") @ApiParam(value = "quoteCode") String quoteCode, @Context UriInfo uriInfo) { context.authenticatedUser().validateHasReadPermission(ENTITY_NAME_QUOTE); InteropQuoteResponseData result = interopService.getQuote(transactionCode, quoteCode); @@ -316,13 +313,13 @@ public class InteropApiResource { } @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("quotes") @ApiOperation(value = "Calculate Interoperation Quote", httpMethod = "POST", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", - dataTypeClass = InteropQuoteRequestData.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropQuoteResponseData.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InteropQuoteRequestData.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropQuoteResponseData.class) }) public String createQuote(@ApiParam(hidden = true) String quotesJson, @Context UriInfo uriInfo) { CommandWrapper commandRequest = new InteropWrapperBuilder().createQuotes().withJson(quotesJson).build(); @@ -333,14 +330,13 @@ public class InteropApiResource { } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("transactions/{transactionCode}/transfers/{transferCode}") @ApiOperation(value = "Query Interoperation Transfer", httpMethod = "GET", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropTransferResponseData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropTransferResponseData.class) }) public String getTransfer(@PathParam("transactionCode") @ApiParam(value = "transactionCode") String transactionCode, - @PathParam("transferCode") @ApiParam(value = "transferCode") String transferCode, - @Context UriInfo uriInfo) { + @PathParam("transferCode") @ApiParam(value = "transferCode") String transferCode, @Context UriInfo uriInfo) { context.authenticatedUser().validateHasReadPermission(ENTITY_NAME_QUOTE); InteropTransferResponseData result = interopService.getTransfer(transactionCode, transferCode); @@ -350,20 +346,21 @@ public class InteropApiResource { } @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @Path("transfers") @ApiOperation(value = "Prepare Interoperation Transfer", httpMethod = "POST", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", - dataTypeClass = InteropTransferRequestData.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InteropTransferResponseData.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InteropTransferRequestData.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = InteropTransferResponseData.class) }) public String performTransfer(@QueryParam("action") @ApiParam(value = "action") String action, - @ApiParam(hidden = true) String quotesJson, @Context UriInfo uriInfo) { - CommandWrapper commandRequest = new InteropWrapperBuilder().performTransfer(InteropTransferActionType.valueOf(action)).withJson(quotesJson).build(); + @ApiParam(hidden = true) String quotesJson, @Context UriInfo uriInfo) { + CommandWrapper commandRequest = new InteropWrapperBuilder().performTransfer(InteropTransferActionType.valueOf(action)) + .withJson(quotesJson).build(); InteropTransferResponseData result = (InteropTransferResponseData) commandsSourceService.logCommandSource(commandRequest); ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return jsonSerializer.serialize(settings, result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/api/InteropWrapperBuilder.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/api/InteropWrapperBuilder.java index 3f41cd080..fd92896fc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/api/InteropWrapperBuilder.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/api/InteropWrapperBuilder.java @@ -36,8 +36,8 @@ public class InteropWrapperBuilder { private String json = "{}"; public CommandWrapper build() { - return new CommandWrapper(null, null, null, null, null, actionName, entityName, null, null, href, json, null, null, - null, null, null); + return new CommandWrapper(null, null, null, null, null, actionName, entityName, null, null, href, json, null, null, null, null, + null); } public InteropWrapperBuilder withJson(final String json) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/ExtensionData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/ExtensionData.java index 3e748f2cd..0dd43c02c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/ExtensionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/ExtensionData.java @@ -29,7 +29,7 @@ import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper; public class ExtensionData { - public static final String[] PARAMS = {PARAM_KEY, PARAM_VALUE}; + public static final String[] PARAMS = { PARAM_KEY, PARAM_VALUE }; @NotNull private final String key; @@ -54,14 +54,12 @@ public class ExtensionData { } public static ExtensionData validateAndParse(DataValidatorBuilder dataValidator, JsonObject element, FromJsonHelper jsonHelper) { - if (element == null) { - return null; - } + if (element == null) { return null; } jsonHelper.checkForUnsupportedParameters(element, Arrays.asList(PARAMS)); String key = jsonHelper.extractStringNamed(PARAM_KEY, element); - DataValidatorBuilder dataValidatorCopy = dataValidator.reset().parameter(PARAM_KEY).value(key).notBlank(); + DataValidatorBuilder dataValidatorCopy = dataValidator.reset().parameter(PARAM_KEY).value(key).notBlank(); String value = jsonHelper.extractStringNamed(PARAM_VALUE, element); diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/GeoCodeData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/GeoCodeData.java index 4d1a94e27..861fd739a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/GeoCodeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/GeoCodeData.java @@ -29,7 +29,7 @@ import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper; public class GeoCodeData { - public static final String[] PARAMS = {PARAM_LATITUDE, PARAM_LONGITUDE}; + public static final String[] PARAMS = { PARAM_LATITUDE, PARAM_LONGITUDE }; @NotNull private final String latitude; @@ -50,14 +50,12 @@ public class GeoCodeData { } public static GeoCodeData validateAndParse(DataValidatorBuilder dataValidator, JsonObject element, FromJsonHelper jsonHelper) { - if (element == null) { - return null; - } + if (element == null) { return null; } jsonHelper.checkForUnsupportedParameters(element, Arrays.asList(PARAMS)); String latitude = jsonHelper.extractStringNamed(PARAM_LATITUDE, element); - DataValidatorBuilder dataValidatorCopy = dataValidator.reset().parameter(PARAM_LATITUDE).value(latitude).notBlank(); + DataValidatorBuilder dataValidatorCopy = dataValidator.reset().parameter(PARAM_LATITUDE).value(latitude).notBlank(); String longitude = jsonHelper.extractStringNamed(PARAM_LONGITUDE, element); dataValidatorCopy = dataValidatorCopy.reset().parameter(PARAM_LONGITUDE).value(longitude).notBlank(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropAccountData.java index 2e3e612a0..c60581f55 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropAccountData.java @@ -53,8 +53,11 @@ public class InteropAccountData extends CommandProcessingResult { private final SavingsAccountStatusType status; private final SavingsAccountSubStatusEnum subStatus; - private final AccountType accountType; //differentiate Individual, JLG or Group account - private final DepositAccountType depositType; //differentiate deposit accounts Savings, FD and RD accounts + private final AccountType accountType; // differentiate Individual, JLG or + // Group account + private final DepositAccountType depositType; // differentiate deposit + // accounts Savings, FD and RD + // accounts @NotNull private final LocalDate activatedOn; private final LocalDate statusUpdateOn; @@ -63,11 +66,11 @@ public class InteropAccountData extends CommandProcessingResult { @NotNull private List identifiers; - InteropAccountData(Long resourceId, Long officeId, Long commandId, Map changesOnly, String accountId, - String productId, String productName, String shortProductName, String currency, BigDecimal accountBalance, - BigDecimal availableBalance, SavingsAccountStatusType status, SavingsAccountSubStatusEnum subStatus, - AccountType accountType, DepositAccountType depositType, LocalDate activatedOn, LocalDate statusUpdateOn, - LocalDate withdrawnOn, LocalDate balanceOn, List identifiers) { + InteropAccountData(Long resourceId, Long officeId, Long commandId, Map changesOnly, String accountId, String productId, + String productName, String shortProductName, String currency, BigDecimal accountBalance, BigDecimal availableBalance, + SavingsAccountStatusType status, SavingsAccountSubStatusEnum subStatus, AccountType accountType, DepositAccountType depositType, + LocalDate activatedOn, LocalDate statusUpdateOn, LocalDate withdrawnOn, LocalDate balanceOn, + List identifiers) { super(resourceId, officeId, commandId, changesOnly); this.accountId = accountId; this.savingProductId = productId; @@ -88,18 +91,15 @@ public class InteropAccountData extends CommandProcessingResult { } InteropAccountData(String accountId, String productId, String productName, String shortProductName, String currency, - BigDecimal accountBalance, BigDecimal availableBalance, SavingsAccountStatusType status, SavingsAccountSubStatusEnum subStatus, - AccountType accountType, DepositAccountType depositType, LocalDate activatedOn, LocalDate statusUpdateOn, - LocalDate withdrawnOn, LocalDate balanceOn, List identifiers) { - this(null, null, null, null, accountId, productId, productName, shortProductName, currency, accountBalance, - availableBalance, status, subStatus, accountType, depositType, activatedOn, statusUpdateOn, withdrawnOn, balanceOn, - identifiers); + BigDecimal accountBalance, BigDecimal availableBalance, SavingsAccountStatusType status, SavingsAccountSubStatusEnum subStatus, + AccountType accountType, DepositAccountType depositType, LocalDate activatedOn, LocalDate statusUpdateOn, LocalDate withdrawnOn, + LocalDate balanceOn, List identifiers) { + this(null, null, null, null, accountId, productId, productName, shortProductName, currency, accountBalance, availableBalance, + status, subStatus, accountType, depositType, activatedOn, statusUpdateOn, withdrawnOn, balanceOn, identifiers); } public static InteropAccountData build(SavingsAccount account) { - if (account == null) { - return null; - } + if (account == null) { return null; } List ids = new ArrayList<>(); for (InteropIdentifier identifier : account.getIdentifiers()) { @@ -109,32 +109,20 @@ public class InteropAccountData extends CommandProcessingResult { SavingsProduct product = account.savingsProduct(); SavingsAccountSubStatusEnum subStatus = SavingsAccountSubStatusEnum.fromInt(account.getSubStatus()); - return new InteropAccountData(account.getExternalId(), product.getId().toString(), product.getName(), - product.getShortName(), account.getCurrency().getCode(), account.getAccountBalance(), account.getWithdrawableBalance(), - account.getStatus(), subStatus, account.getAccountType(), account.depositAccountType(), account.getActivationLocalDate(), + return new InteropAccountData(account.getExternalId(), product.getId().toString(), product.getName(), product.getShortName(), + account.getCurrency().getCode(), account.getAccountBalance(), account.getWithdrawableBalance(), account.getStatus(), + subStatus, account.getAccountType(), account.depositAccountType(), account.getActivationLocalDate(), calcStatusUpdateOn(account), account.getWithdrawnOnDate(), account.retrieveLastTransactionDate(), ids); } private static LocalDate calcStatusUpdateOn(@NotNull SavingsAccount account) { LocalDate date = account.getClosedOnDate(); - if (date != null) { - return date; - } - if ((date = account.getWithdrawnOnDate()) != null) { - return date; - } - if ((date = account.getActivationLocalDate()) != null) { - return date; - } - if ((date = account.getRejectedOnDate()) != null) { - return date; - } - if ((date = account.getApprovedOnDate()) != null) { - return date; - } - if ((date = account.getSubmittedOnDate()) != null) { - return date; - } + if (date != null) { return date; } + if ((date = account.getWithdrawnOnDate()) != null) { return date; } + if ((date = account.getActivationLocalDate()) != null) { return date; } + if ((date = account.getRejectedOnDate()) != null) { return date; } + if ((date = account.getApprovedOnDate()) != null) { return date; } + if ((date = account.getSubmittedOnDate()) != null) { return date; } return null; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifierAccountResponseData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifierAccountResponseData.java index 2054c483f..667a60e8f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifierAccountResponseData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifierAccountResponseData.java @@ -28,13 +28,14 @@ public class InteropIdentifierAccountResponseData extends CommandProcessingResul @NotEmpty private String accountId; - - protected InteropIdentifierAccountResponseData(Long resourceId, Long officeId, Long commandId, Map changesOnly, @NotNull String accountId) { + protected InteropIdentifierAccountResponseData(Long resourceId, Long officeId, Long commandId, Map changesOnly, + @NotNull String accountId) { super(resourceId, officeId, commandId, changesOnly); this.accountId = accountId; } - protected static InteropIdentifierAccountResponseData build(Long resourceId, Long officeId, Long commandId, Map changesOnly, @NotNull String accountId) { + protected static InteropIdentifierAccountResponseData build(Long resourceId, Long officeId, Long commandId, + Map changesOnly, @NotNull String accountId) { return new InteropIdentifierAccountResponseData(resourceId, officeId, commandId, changesOnly, accountId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifierRequestData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifierRequestData.java index ea9662256..aac0ef486 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifierRequestData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifierRequestData.java @@ -30,7 +30,7 @@ import org.apache.fineract.interoperation.domain.InteropIdentifierType; public class InteropIdentifierRequestData { - static final String[] PARAMS = {PARAM_ACCOUNT_ID}; + static final String[] PARAMS = { PARAM_ACCOUNT_ID }; @NotEmpty private final InteropIdentifierType idType; @@ -42,7 +42,8 @@ public class InteropIdentifierRequestData { @NotEmpty private final String accountId; - public InteropIdentifierRequestData(@NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType, String accountId) { + public InteropIdentifierRequestData(@NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType, + String accountId) { this.idType = idType; this.idValue = idValue; this.subIdOrType = subIdOrType; @@ -65,12 +66,10 @@ public class InteropIdentifierRequestData { return accountId; } - public static InteropIdentifierRequestData validateAndParse(final DataValidatorBuilder dataValidator, @NotNull InteropIdentifierType idType, - @NotNull String idValue, String subIdOrType, JsonObject element, - FromJsonHelper jsonHelper) { - if (element == null) { - return null; - } + public static InteropIdentifierRequestData validateAndParse(final DataValidatorBuilder dataValidator, + @NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType, JsonObject element, + FromJsonHelper jsonHelper) { + if (element == null) { return null; } jsonHelper.checkForUnsupportedParameters(element, Arrays.asList(PARAMS)); diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifiersResponseData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifiersResponseData.java index 5e61fe860..5de76470e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifiersResponseData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropIdentifiersResponseData.java @@ -31,7 +31,8 @@ public class InteropIdentifiersResponseData extends CommandProcessingResult { @NotNull private List identifiers; - protected InteropIdentifiersResponseData(Long resourceId, Long officeId, Long commandId, Map changesOnly, @NotNull List identifiers) { + protected InteropIdentifiersResponseData(Long resourceId, Long officeId, Long commandId, Map changesOnly, + @NotNull List identifiers) { super(resourceId, officeId, commandId, changesOnly); this.identifiers = identifiers; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropQuoteRequestData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropQuoteRequestData.java index dd134f3de..e0bcb1f5f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropQuoteRequestData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropQuoteRequestData.java @@ -47,20 +47,21 @@ import org.joda.time.LocalDateTime; public class InteropQuoteRequestData extends InteropRequestData { - static final String[] PARAMS = {PARAM_TRANSACTION_CODE, PARAM_REQUEST_CODE, PARAM_ACCOUNT_ID, PARAM_AMOUNT, PARAM_TRANSACTION_TYPE, - PARAM_TRANSACTION_ROLE, PARAM_NOTE, PARAM_GEO_CODE, PARAM_EXPIRATION, PARAM_EXTENSION_LIST, PARAM_QUOTE_CODE, - PARAM_AMOUNT_TYPE, PARAM_FEES, PARAM_LOCALE, PARAM_DATE_FORMAT}; + static final String[] PARAMS = { PARAM_TRANSACTION_CODE, PARAM_REQUEST_CODE, PARAM_ACCOUNT_ID, PARAM_AMOUNT, PARAM_TRANSACTION_TYPE, + PARAM_TRANSACTION_ROLE, PARAM_NOTE, PARAM_GEO_CODE, PARAM_EXPIRATION, PARAM_EXTENSION_LIST, PARAM_QUOTE_CODE, PARAM_AMOUNT_TYPE, + PARAM_FEES, PARAM_LOCALE, PARAM_DATE_FORMAT }; @NotNull private final String quoteCode; @NotNull private final InteropAmountType amountType; - private final MoneyData fees; // only for disclosed Payer fees on the Payee side + private final MoneyData fees; // only for disclosed Payer fees on the Payee + // side - public InteropQuoteRequestData(@NotNull String transactionCode, String requestCode, @NotNull String accountId, @NotNull MoneyData amount, - @NotNull InteropTransactionRole transactionRole, @NotNull InteropTransactionTypeData transactionType, - String note, GeoCodeData geoCode, LocalDateTime expiration, List extensionList, - @NotNull String quoteCode, @NotNull InteropAmountType amountType, MoneyData fees) { + public InteropQuoteRequestData(@NotNull String transactionCode, String requestCode, @NotNull String accountId, + @NotNull MoneyData amount, @NotNull InteropTransactionRole transactionRole, @NotNull InteropTransactionTypeData transactionType, + String note, GeoCodeData geoCode, LocalDateTime expiration, List extensionList, @NotNull String quoteCode, + @NotNull InteropAmountType amountType, MoneyData fees) { super(transactionCode, requestCode, accountId, amount, transactionRole, transactionType, note, geoCode, expiration, extensionList); this.quoteCode = quoteCode; this.amountType = amountType; @@ -68,17 +69,17 @@ public class InteropQuoteRequestData extends InteropRequestData { } public InteropQuoteRequestData(@NotNull String transactionCode, @NotNull String accountId, @NotNull InteropAmountType amountType, - @NotNull MoneyData amount, @NotNull InteropTransactionRole transactionRole, @NotNull InteropTransactionTypeData transactionType, - @NotNull String quoteCode) { - this(transactionCode, null, accountId, amount, transactionRole, transactionType, null, null, null, null, quoteCode, - amountType, null); + @NotNull MoneyData amount, @NotNull InteropTransactionRole transactionRole, @NotNull InteropTransactionTypeData transactionType, + @NotNull String quoteCode) { + this(transactionCode, null, accountId, amount, transactionRole, transactionType, null, null, null, null, quoteCode, amountType, + null); } private InteropQuoteRequestData(@NotNull InteropRequestData other, @NotNull String quoteCode, @NotNull InteropAmountType amountType, - MoneyData fees) { + MoneyData fees) { this(other.getTransactionCode(), other.getRequestCode(), other.getAccountId(), other.getAmount(), other.getTransactionRole(), - other.getTransactionType(), other.getNote(), other.getGeoCode(), other.getExpiration(), other.getExtensionList(), - quoteCode, amountType, fees); + other.getTransactionType(), other.getNote(), other.getGeoCode(), other.getExpiration(), other.getExtensionList(), quoteCode, + amountType, fees); } public String getQuoteCode() { @@ -101,10 +102,9 @@ public class InteropQuoteRequestData extends InteropRequestData { } } - public static InteropQuoteRequestData validateAndParse(final DataValidatorBuilder dataValidator, JsonObject element, FromJsonHelper jsonHelper) { - if (element == null) { - return null; - } + public static InteropQuoteRequestData validateAndParse(final DataValidatorBuilder dataValidator, JsonObject element, + FromJsonHelper jsonHelper) { + if (element == null) { return null; } jsonHelper.checkForUnsupportedParameters(element, Arrays.asList(PARAMS)); diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropQuoteResponseData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropQuoteResponseData.java index 21c367de4..398ef5ec4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropQuoteResponseData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropQuoteResponseData.java @@ -33,10 +33,9 @@ public class InteropQuoteResponseData extends InteropResponseData { private MoneyData fspCommission; - private InteropQuoteResponseData(Long resourceId, Long officeId, Long commandId, Map changesOnly, - @NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, - List extensionList, @NotNull String quoteCode, MoneyData fspFee, MoneyData fspCommission) { + @NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, List extensionList, + @NotNull String quoteCode, MoneyData fspFee, MoneyData fspCommission) { super(resourceId, officeId, commandId, changesOnly, transactionCode, state, expiration, extensionList); this.quoteCode = quoteCode; this.fspFee = fspFee; @@ -44,24 +43,25 @@ public class InteropQuoteResponseData extends InteropResponseData { } public static InteropQuoteResponseData build(Long commandId, @NotNull String transactionCode, @NotNull InteropActionState state, - LocalDateTime expiration, List extensionList, @NotNull String quoteCode, - MoneyData fspFee, MoneyData fspCommission) { - return new InteropQuoteResponseData(null, null, commandId, null, transactionCode, state, expiration, extensionList, - quoteCode, fspFee, fspCommission); + LocalDateTime expiration, List extensionList, @NotNull String quoteCode, MoneyData fspFee, + MoneyData fspCommission) { + return new InteropQuoteResponseData(null, null, commandId, null, transactionCode, state, expiration, extensionList, quoteCode, + fspFee, fspCommission); } - public static InteropQuoteResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, - List extensionList, @NotNull String quoteCode, MoneyData fspFee, - MoneyData fspCommission) { + public static InteropQuoteResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, + LocalDateTime expiration, List extensionList, @NotNull String quoteCode, MoneyData fspFee, + MoneyData fspCommission) { return build(null, transactionCode, state, expiration, extensionList, quoteCode, fspFee, fspCommission); } public static InteropQuoteResponseData build(Long commandId, @NotNull String transactionCode, @NotNull InteropActionState state, - @NotNull String quoteCode) { + @NotNull String quoteCode) { return build(commandId, transactionCode, state, null, null, quoteCode, null, null); } - public static InteropQuoteResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, @NotNull String quoteCode) { + public static InteropQuoteResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, + @NotNull String quoteCode) { return build(null, transactionCode, state, quoteCode); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropRequestData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropRequestData.java index f1f63591c..36e3263f8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropRequestData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropRequestData.java @@ -72,8 +72,8 @@ public class InteropRequestData { private List extensionList; protected InteropRequestData(@NotNull String transactionCode, String requestCode, @NotNull String accountId, @NotNull MoneyData amount, - @NotNull InteropTransactionRole transactionRole, InteropTransactionTypeData transactionType, String note, - GeoCodeData geoCode, LocalDateTime expiration, List extensionList) { + @NotNull InteropTransactionRole transactionRole, InteropTransactionTypeData transactionType, String note, GeoCodeData geoCode, + LocalDateTime expiration, List extensionList) { this.transactionCode = transactionCode; this.requestCode = requestCode; this.accountId = accountId; @@ -86,7 +86,8 @@ public class InteropRequestData { this.extensionList = extensionList; } - protected InteropRequestData(@NotNull String transactionCode, @NotNull String accountId, @NotNull MoneyData amount, @NotNull InteropTransactionRole transactionRole) { + protected InteropRequestData(@NotNull String transactionCode, @NotNull String accountId, @NotNull MoneyData amount, + @NotNull InteropTransactionRole transactionRole) { this(transactionCode, null, accountId, amount, transactionRole, null, null, null, null, null); } @@ -158,13 +159,12 @@ public class InteropRequestData { amount.normalizeAmount(currency); } - public static InteropRequestData validateAndParse(final DataValidatorBuilder dataValidator, JsonObject element, FromJsonHelper jsonHelper) { - if (element == null) { - return null; - } + public static InteropRequestData validateAndParse(final DataValidatorBuilder dataValidator, JsonObject element, + FromJsonHelper jsonHelper) { + if (element == null) { return null; } String transactionCode = jsonHelper.extractStringNamed(PARAM_TRANSACTION_CODE, element); - DataValidatorBuilder dataValidatorCopy = dataValidator.reset().parameter(PARAM_TRANSACTION_CODE).value(transactionCode).notBlank(); + DataValidatorBuilder dataValidatorCopy = dataValidator.reset().parameter(PARAM_TRANSACTION_CODE).value(transactionCode).notBlank(); String requestCode = jsonHelper.extractStringNamed(PARAM_REQUEST_CODE, element); @@ -177,10 +177,12 @@ public class InteropRequestData { MoneyData amount = MoneyData.validateAndParse(dataValidator, moneyElement, jsonHelper); JsonObject transactionTypeElement = jsonHelper.extractJsonObjectNamed(PARAM_TRANSACTION_TYPE, element); - InteropTransactionTypeData transactionType = InteropTransactionTypeData.validateAndParse(dataValidator, transactionTypeElement, jsonHelper); + InteropTransactionTypeData transactionType = InteropTransactionTypeData.validateAndParse(dataValidator, transactionTypeElement, + jsonHelper); String transactionRoleString = jsonHelper.extractStringNamed(PARAM_TRANSACTION_ROLE, element); - InteropTransactionRole transactionRole = transactionRoleString == null ? InteropTransactionRole.PAYER : InteropTransactionRole.valueOf(transactionRoleString); + InteropTransactionRole transactionRole = transactionRoleString == null ? InteropTransactionRole.PAYER + : InteropTransactionRole.valueOf(transactionRoleString); String note = jsonHelper.extractStringNamed(PARAM_NOTE, element); @@ -190,7 +192,11 @@ public class InteropRequestData { String locale = jsonHelper.extractStringNamed(PARAM_LOCALE, element); LocalDateTime expiration = locale == null ? jsonHelper.extractLocalTimeNamed(PARAM_EXPIRATION, element, ISO8601_DATE_TIME_FORMAT, DEFAULT_LOCALE) - : jsonHelper.extractLocalTimeNamed(PARAM_EXPIRATION, element); // PARAM_DATE_FORMAT also must be set + : jsonHelper.extractLocalTimeNamed(PARAM_EXPIRATION, element); // PARAM_DATE_FORMAT + // also + // must + // be + // set JsonArray extensionArray = jsonHelper.extractJsonArrayNamed(PARAM_EXTENSION_LIST, element); ArrayList extensionList = null; @@ -198,13 +204,13 @@ public class InteropRequestData { extensionList = new ArrayList<>(extensionArray.size()); for (JsonElement jsonElement : extensionArray) { if (jsonElement.isJsonObject()) { - extensionList.add( - ExtensionData.validateAndParse(dataValidator, jsonElement.getAsJsonObject(), jsonHelper)); + extensionList.add(ExtensionData.validateAndParse(dataValidator, jsonElement.getAsJsonObject(), jsonHelper)); } } } - return dataValidator.hasError() ? null : new InteropRequestData(transactionCode, requestCode, accountId, amount, - transactionRole, transactionType, note, geoCode, expiration, extensionList); + return dataValidator.hasError() ? null + : new InteropRequestData(transactionCode, requestCode, accountId, amount, transactionRole, transactionType, note, geoCode, + expiration, extensionList); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropResponseData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropResponseData.java index 6c8c97da5..6d818daff 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropResponseData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropResponseData.java @@ -31,7 +31,8 @@ import org.joda.time.format.DateTimeFormatter; public class InteropResponseData extends CommandProcessingResult { public static final String ISO_DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ"; -// public static final SimpleDateFormat ISO_DATE_TIME_FORMATTER = new SimpleDateFormat(ISO_DATE_TIME_PATTERN); // TODO: not synchronized + // public static final SimpleDateFormat ISO_DATE_TIME_FORMATTER = new + // SimpleDateFormat(ISO_DATE_TIME_PATTERN); // TODO: not synchronized public static final DateTimeFormatter ISO_DATE_TIME_FORMATTER = DateTimeFormat.forPattern(ISO_DATE_TIME_PATTERN); @NotNull @@ -44,9 +45,9 @@ public class InteropResponseData extends CommandProcessingResult { private final List extensionList; - - protected InteropResponseData(Long resourceId, Long officeId, Long commandId, Map changesOnly, @NotNull String transactionCode, - @NotNull InteropActionState state, LocalDateTime expiration, List extensionList) { + protected InteropResponseData(Long resourceId, Long officeId, Long commandId, Map changesOnly, + @NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, + List extensionList) { super(resourceId, officeId, commandId, changesOnly); this.transactionCode = transactionCode; this.state = state; @@ -55,12 +56,12 @@ public class InteropResponseData extends CommandProcessingResult { } protected static InteropResponseData build(Long commandId, @NotNull String transactionCode, @NotNull InteropActionState state, - LocalDateTime expiration, List extensionList) { + LocalDateTime expiration, List extensionList) { return new InteropResponseData(null, null, commandId, null, transactionCode, state, expiration, extensionList); } - public static InteropResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, - LocalDateTime expiration, List extensionList) { + public static InteropResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, + List extensionList) { return build(null, transactionCode, state, expiration, extensionList); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionData.java index 2432c6264..e2c5da23b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionData.java @@ -32,29 +32,29 @@ import org.joda.time.LocalDate; public class InteropTransactionData extends CommandProcessingResult { -// private final SavingsAccountTransactionEnumData transactionType; -// private final PaymentDetailData paymentDetailData; -// private final BigDecimal outstandingChargeAmount; -// private final boolean reversed; -// private final AccountTransferData transfer; -// private final LocalDate submittedOnDate; -// private final boolean interestedPostedAsOn; -// private final String submittedByUsername; -// // templates -// final Collection paymentTypeOptions; -// //import fields -// private Long paymentTypeId; -// private String checkNumber; -// private String routingCode; -// private String receiptNumber; -// private String bankNumber; + // private final SavingsAccountTransactionEnumData transactionType; + // private final PaymentDetailData paymentDetailData; + // private final BigDecimal outstandingChargeAmount; + // private final boolean reversed; + // private final AccountTransferData transfer; + // private final LocalDate submittedOnDate; + // private final boolean interestedPostedAsOn; + // private final String submittedByUsername; + // // templates + // final Collection paymentTypeOptions; + // //import fields + // private Long paymentTypeId; + // private String checkNumber; + // private String routingCode; + // private String receiptNumber; + // private String bankNumber; -// private String transactionReference; -// private String statementReference; -// private CreditDebitType creditDebit; -// private TransactionStatus status; -// private String transactionInformation; -// private String addressLine; + // private String transactionReference; + // private String statementReference; + // private CreditDebitType creditDebit; + // private TransactionStatus status; + // private String transactionInformation; + // private String addressLine; @NotNull private final String accountId; @@ -77,9 +77,9 @@ public class InteropTransactionData extends CommandProcessingResult { private final String note; - - public InteropTransactionData(Long entityId, String accountId, String transactionId, SavingsAccountTransactionType transactionType, BigDecimal amount, BigDecimal chargeAmount, - String currency, BigDecimal accountBalance, LocalDate bookingDateTime, LocalDate valueDateTime, String note) { + public InteropTransactionData(Long entityId, String accountId, String transactionId, SavingsAccountTransactionType transactionType, + BigDecimal amount, BigDecimal chargeAmount, String currency, BigDecimal accountBalance, LocalDate bookingDateTime, + LocalDate valueDateTime, String note) { super(entityId); this.accountId = accountId; this.savingTransactionId = transactionId; @@ -94,9 +94,7 @@ public class InteropTransactionData extends CommandProcessingResult { } public static InteropTransactionData build(SavingsAccountTransaction transaction) { - if (transaction == null) { - return null; - } + if (transaction == null) { return null; } SavingsAccount savingsAccount = transaction.getSavingsAccount(); @@ -143,7 +141,7 @@ public class InteropTransactionData extends CommandProcessingResult { sb.append(SavingsEnumerations.transactionType(transactionType).getValue()); } - return new InteropTransactionData(savingsAccount.getId(), savingsAccount.getExternalId(), transactionId, transactionType, amount, chargeAmount, currency, - runningBalance, bookingDateTime, valueDateTime, sb.toString()); + return new InteropTransactionData(savingsAccount.getId(), savingsAccount.getExternalId(), transactionId, transactionType, amount, + chargeAmount, currency, runningBalance, bookingDateTime, valueDateTime, sb.toString()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionRequestData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionRequestData.java index 6df5c217a..533b41066 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionRequestData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionRequestData.java @@ -42,18 +42,18 @@ import org.joda.time.LocalDateTime; public class InteropTransactionRequestData extends InteropRequestData { - static final String[] PARAMS = {PARAM_TRANSACTION_CODE, PARAM_REQUEST_CODE, PARAM_ACCOUNT_ID, PARAM_AMOUNT, PARAM_TRANSACTION_ROLE, - PARAM_TRANSACTION_TYPE, PARAM_NOTE, PARAM_GEO_CODE, PARAM_EXPIRATION, PARAM_EXTENSION_LIST, PARAM_LOCALE, PARAM_DATE_FORMAT}; - + static final String[] PARAMS = { PARAM_TRANSACTION_CODE, PARAM_REQUEST_CODE, PARAM_ACCOUNT_ID, PARAM_AMOUNT, PARAM_TRANSACTION_ROLE, + PARAM_TRANSACTION_TYPE, PARAM_NOTE, PARAM_GEO_CODE, PARAM_EXPIRATION, PARAM_EXTENSION_LIST, PARAM_LOCALE, PARAM_DATE_FORMAT }; public InteropTransactionRequestData(@NotNull String transactionCode, @NotNull String requestCode, @NotNull String accountId, - @NotNull MoneyData amount, @NotNull InteropTransactionTypeData transactionType, String note, - GeoCodeData geoCode, LocalDateTime expiration, List extensionList) { - super(transactionCode, requestCode, accountId, amount, InteropTransactionRole.PAYER, transactionType, note, geoCode, expiration, extensionList); + @NotNull MoneyData amount, @NotNull InteropTransactionTypeData transactionType, String note, GeoCodeData geoCode, + LocalDateTime expiration, List extensionList) { + super(transactionCode, requestCode, accountId, amount, InteropTransactionRole.PAYER, transactionType, note, geoCode, expiration, + extensionList); } public InteropTransactionRequestData(@NotNull String transactionCode, @NotNull String requestCode, @NotNull String accountId, - @NotNull MoneyData amount, @NotNull InteropTransactionTypeData transactionType) { + @NotNull MoneyData amount, @NotNull InteropTransactionTypeData transactionType) { this(transactionCode, requestCode, accountId, amount, transactionType, null, null, null, null); } @@ -62,19 +62,20 @@ public class InteropTransactionRequestData extends InteropRequestData { other.getNote(), other.getGeoCode(), other.getExpiration(), other.getExtensionList()); } - public static InteropTransactionRequestData validateAndParse(final DataValidatorBuilder dataValidator, JsonObject element, FromJsonHelper jsonHelper) { - if (element == null) { - return null; - } + public static InteropTransactionRequestData validateAndParse(final DataValidatorBuilder dataValidator, JsonObject element, + FromJsonHelper jsonHelper) { + if (element == null) { return null; } jsonHelper.checkForUnsupportedParameters(element, Arrays.asList(PARAMS)); InteropRequestData interopRequestData = InteropRequestData.validateAndParse(dataValidator, element, jsonHelper); - DataValidatorBuilder dataValidatorCopy = dataValidator.reset().parameter(PARAM_REQUEST_CODE).value(interopRequestData.getRequestCode()).notNull(); - dataValidatorCopy = dataValidatorCopy.reset().parameter(PARAM_TRANSACTION_TYPE).value(interopRequestData.getTransactionType()).notNull(); - dataValidatorCopy = dataValidatorCopy.reset().parameter(PARAM_TRANSACTION_ROLE).value(interopRequestData.getTransactionRole()).ignoreIfNull() - .isOneOfTheseValues(InteropTransactionRole.PAYER); + DataValidatorBuilder dataValidatorCopy = dataValidator.reset().parameter(PARAM_REQUEST_CODE) + .value(interopRequestData.getRequestCode()).notNull(); + dataValidatorCopy = dataValidatorCopy.reset().parameter(PARAM_TRANSACTION_TYPE).value(interopRequestData.getTransactionType()) + .notNull(); + dataValidatorCopy = dataValidatorCopy.reset().parameter(PARAM_TRANSACTION_ROLE).value(interopRequestData.getTransactionRole()) + .ignoreIfNull().isOneOfTheseValues(InteropTransactionRole.PAYER); dataValidator.merge(dataValidatorCopy); return dataValidator.hasError() ? null : new InteropTransactionRequestData(interopRequestData); diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionRequestResponseData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionRequestResponseData.java index a884d3bb7..df6169536 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionRequestResponseData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionRequestResponseData.java @@ -29,31 +29,31 @@ public class InteropTransactionRequestResponseData extends InteropResponseData { @NotNull private final String requestCode; - private InteropTransactionRequestResponseData(Long resourceId, Long officeId, Long commandId, Map changesOnly, - @NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, - List extensionList, @NotNull String requestCode) { + @NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, List extensionList, + @NotNull String requestCode) { super(resourceId, officeId, commandId, changesOnly, transactionCode, state, expiration, extensionList); this.requestCode = requestCode; } - public static InteropTransactionRequestResponseData build(Long commandId, @NotNull String transactionCode, @NotNull InteropActionState state, - LocalDateTime expiration, List extensionList, @NotNull String requestCode) { - return new InteropTransactionRequestResponseData(null, null, commandId, null, transactionCode, state, expiration, extensionList, requestCode); + public static InteropTransactionRequestResponseData build(Long commandId, @NotNull String transactionCode, + @NotNull InteropActionState state, LocalDateTime expiration, List extensionList, @NotNull String requestCode) { + return new InteropTransactionRequestResponseData(null, null, commandId, null, transactionCode, state, expiration, extensionList, + requestCode); } public static InteropTransactionRequestResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, - LocalDateTime expiration, List extensionList, @NotNull String requestCode) { + LocalDateTime expiration, List extensionList, @NotNull String requestCode) { return build(null, transactionCode, state, expiration, extensionList, requestCode); } - public static InteropTransactionRequestResponseData build(Long commandId, @NotNull String transactionCode, @NotNull InteropActionState state, - @NotNull String requestCode) { + public static InteropTransactionRequestResponseData build(Long commandId, @NotNull String transactionCode, + @NotNull InteropActionState state, @NotNull String requestCode) { return build(commandId, transactionCode, state, null, null, requestCode); } public static InteropTransactionRequestResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, - @NotNull String requestCode) { + @NotNull String requestCode) { return build(null, transactionCode, state, requestCode); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionTypeData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionTypeData.java index 5bef996eb..2a99783ad 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionTypeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionTypeData.java @@ -37,7 +37,8 @@ import org.apache.fineract.interoperation.domain.InteropTransactionScenario; public class InteropTransactionTypeData { - public static final String[] PARAMS = {PARAM_SCENARIO, PARAM_SUB_SCENARIO, PARAM_INITIATOR, PARAM_INITIATOR_TYPE, PARAM_REFUND_INFO, PARAM_BALANCE_OF_PAYMENTS}; + public static final String[] PARAMS = { PARAM_SCENARIO, PARAM_SUB_SCENARIO, PARAM_INITIATOR, PARAM_INITIATOR_TYPE, PARAM_REFUND_INFO, + PARAM_BALANCE_OF_PAYMENTS }; @NotNull private final InteropTransactionScenario scenario; @@ -47,14 +48,15 @@ public class InteropTransactionTypeData { private final InteropTransactionRole initiator; @NotNull private final InteropInitiatorType initiatorType; - //TODO: SKIP FOR NOW + // TODO: SKIP FOR NOW @Valid private InteropRefundData refundInfo; - private String balanceOfPayments; // 3 digits number, see https://www.imf.org/external/np/sta/bopcode/ + private String balanceOfPayments; // 3 digits number, see + // https://www.imf.org/external/np/sta/bopcode/ - InteropTransactionTypeData(InteropTransactionScenario scenario, String subScenario, InteropTransactionRole initiator, InteropInitiatorType initiatorType, - InteropRefundData refundInfo, String balanceOfPayments) { + InteropTransactionTypeData(InteropTransactionScenario scenario, String subScenario, InteropTransactionRole initiator, + InteropInitiatorType initiatorType, InteropRefundData refundInfo, String balanceOfPayments) { this.scenario = scenario; this.subScenario = subScenario; this.initiator = initiator; @@ -63,7 +65,8 @@ public class InteropTransactionTypeData { this.balanceOfPayments = balanceOfPayments; } - private InteropTransactionTypeData(InteropTransactionScenario scenario, String subScenario, InteropTransactionRole initiator, InteropInitiatorType initiatorType) { + private InteropTransactionTypeData(InteropTransactionScenario scenario, String subScenario, InteropTransactionRole initiator, + InteropInitiatorType initiatorType) { this(scenario, subScenario, initiator, initiatorType, null, null); } @@ -83,11 +86,9 @@ public class InteropTransactionTypeData { return initiatorType; } - - public static InteropTransactionTypeData validateAndParse(DataValidatorBuilder dataValidator, JsonObject element, FromJsonHelper jsonHelper) { - if (element == null) { - return null; - } + public static InteropTransactionTypeData validateAndParse(DataValidatorBuilder dataValidator, JsonObject element, + FromJsonHelper jsonHelper) { + if (element == null) { return null; } jsonHelper.checkForUnsupportedParameters(element, Arrays.asList(PARAMS)); diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionsData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionsData.java index 24353e491..dd098421c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionsData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransactionsData.java @@ -30,16 +30,13 @@ public class InteropTransactionsData extends CommandProcessingResult { List transactions; - public InteropTransactionsData(Long entityId, List transactions) { super(entityId); this.transactions = transactions; } public static InteropTransactionsData build(SavingsAccount account, @NotNull Predicate filter) { - if (account == null) { - return null; - } + if (account == null) { return null; } List trans = account.getTransactions().stream().filter(filter).sorted((t1, t2) -> { int i = t2.getDateOf().compareTo(t1.getDateOf()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransferRequestData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransferRequestData.java index 08ce088cc..0db38e2a9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransferRequestData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransferRequestData.java @@ -44,10 +44,9 @@ import org.joda.time.LocalDateTime; public class InteropTransferRequestData extends InteropRequestData { - static final String[] PARAMS = {PARAM_TRANSACTION_CODE, PARAM_ACCOUNT_ID, PARAM_AMOUNT, PARAM_TRANSACTION_ROLE, PARAM_TRANSACTION_TYPE, - PARAM_NOTE, PARAM_EXPIRATION, PARAM_EXTENSION_LIST, PARAM_TRANSFER_CODE, PARAM_FSP_FEE, PARAM_FSP_COMMISSION, - PARAM_LOCALE, PARAM_DATE_FORMAT}; - + static final String[] PARAMS = { PARAM_TRANSACTION_CODE, PARAM_ACCOUNT_ID, PARAM_AMOUNT, PARAM_TRANSACTION_ROLE, PARAM_TRANSACTION_TYPE, + PARAM_NOTE, PARAM_EXPIRATION, PARAM_EXTENSION_LIST, PARAM_TRANSFER_CODE, PARAM_FSP_FEE, PARAM_FSP_COMMISSION, PARAM_LOCALE, + PARAM_DATE_FORMAT }; @NotNull private final String transferCode; @@ -58,8 +57,9 @@ public class InteropTransferRequestData extends InteropRequestData { private MoneyData fspCommission; public InteropTransferRequestData(@NotNull String transactionCode, @NotNull String accountId, @NotNull MoneyData amount, - @NotNull InteropTransactionRole transactionRole, InteropTransactionTypeData transactionType, String note, LocalDateTime expiration, - List extensionList, @NotNull String transferCode, MoneyData fspFee, MoneyData fspCommission) { + @NotNull InteropTransactionRole transactionRole, InteropTransactionTypeData transactionType, String note, + LocalDateTime expiration, List extensionList, @NotNull String transferCode, MoneyData fspFee, + MoneyData fspCommission) { super(transactionCode, null, accountId, amount, transactionRole, transactionType, note, null, expiration, extensionList); this.transferCode = transferCode; this.fspFee = fspFee; @@ -67,7 +67,7 @@ public class InteropTransferRequestData extends InteropRequestData { } public InteropTransferRequestData(@NotNull String transactionCode, @NotNull String transferCode, @NotNull String accountId, - @NotNull MoneyData amount, @NotNull InteropTransactionRole transactionRole) { + @NotNull MoneyData amount, @NotNull InteropTransactionRole transactionRole) { this(transactionCode, accountId, amount, transactionRole, null, null, null, null, transferCode, null, null); } @@ -96,10 +96,9 @@ public class InteropTransferRequestData extends InteropRequestData { } } - public static InteropTransferRequestData validateAndParse(final DataValidatorBuilder dataValidator, JsonObject element, FromJsonHelper jsonHelper) { - if (element == null) { - return null; - } + public static InteropTransferRequestData validateAndParse(final DataValidatorBuilder dataValidator, JsonObject element, + FromJsonHelper jsonHelper) { + if (element == null) { return null; } jsonHelper.checkForUnsupportedParameters(element, Arrays.asList(PARAMS)); diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransferResponseData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransferResponseData.java index 9e8d4fb73..42f579f18 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransferResponseData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/InteropTransferResponseData.java @@ -34,32 +34,31 @@ public class InteropTransferResponseData extends InteropResponseData { private String completedTimestamp; private InteropTransferResponseData(Long resourceId, Long officeId, Long commandId, Map changesOnly, - @NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, - List extensionList, @NotNull String transferCode, LocalDateTime completedTimestamp) { + @NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, List extensionList, + @NotNull String transferCode, LocalDateTime completedTimestamp) { super(resourceId, officeId, commandId, changesOnly, transactionCode, state, expiration, extensionList); this.transferCode = transferCode; this.completedTimestamp = format(completedTimestamp); } public static InteropTransferResponseData build(Long commandId, @NotNull String transactionCode, @NotNull InteropActionState state, - LocalDateTime expiration, List extensionList, @NotNull String transferCode, - LocalDateTime completedTimestamp) { - return new InteropTransferResponseData(null, null, commandId, null, transactionCode, state, expiration, extensionList, - transferCode, completedTimestamp); + LocalDateTime expiration, List extensionList, @NotNull String transferCode, LocalDateTime completedTimestamp) { + return new InteropTransferResponseData(null, null, commandId, null, transactionCode, state, expiration, extensionList, transferCode, + completedTimestamp); } public static InteropTransferResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, - List extensionList, @NotNull String transferCode, - LocalDateTime completedTimestamp) { + List extensionList, @NotNull String transferCode, LocalDateTime completedTimestamp) { return build(null, transactionCode, state, null, extensionList, transferCode, completedTimestamp); } public static InteropTransferResponseData build(Long commandId, @NotNull String transactionCode, @NotNull InteropActionState state, - @NotNull String transferCode) { + @NotNull String transferCode) { return build(commandId, transactionCode, state, null, null, transferCode, null); } - public static InteropTransferResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, @NotNull String transferCode) { + public static InteropTransferResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, + @NotNull String transferCode) { return build(null, transactionCode, state, transferCode); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/MoneyData.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/MoneyData.java index e3ba76e60..8b896817b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/MoneyData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/data/MoneyData.java @@ -34,7 +34,7 @@ import org.apache.fineract.organisation.monetary.domain.MonetaryCurrency; public class MoneyData { - public static final String[] PARAMS = {PARAM_AMOUNT, PARAM_CURRENCY, PARAM_LOCALE}; + public static final String[] PARAMS = { PARAM_AMOUNT, PARAM_CURRENCY, PARAM_LOCALE }; @NotNull private final BigDecimal amount; @@ -66,17 +66,15 @@ public class MoneyData { } public static MoneyData validateAndParse(DataValidatorBuilder dataValidator, JsonObject element, FromJsonHelper jsonHelper) { - if (element == null) { - return null; - } + if (element == null) { return null; } jsonHelper.checkForUnsupportedParameters(element, Arrays.asList(PARAMS)); String locale = jsonHelper.extractStringNamed(PARAM_LOCALE, element); - BigDecimal amount = locale == null - ? jsonHelper.extractBigDecimalNamed(PARAM_AMOUNT, element, DEFAULT_LOCALE) + BigDecimal amount = locale == null ? jsonHelper.extractBigDecimalNamed(PARAM_AMOUNT, element, DEFAULT_LOCALE) : jsonHelper.extractBigDecimalWithLocaleNamed(PARAM_AMOUNT, element); - DataValidatorBuilder dataValidatorCopy = dataValidator.reset().parameter(PARAM_AMOUNT).value(amount).notBlank().zeroOrPositiveAmount(); + DataValidatorBuilder dataValidatorCopy = dataValidator.reset().parameter(PARAM_AMOUNT).value(amount).notBlank() + .zeroOrPositiveAmount(); String currency = jsonHelper.extractStringNamed(PARAM_CURRENCY, element); dataValidatorCopy = dataValidatorCopy.reset().parameter(PARAM_CURRENCY).value(currency).notBlank().notExceedingLengthOf(3); diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropActionState.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropActionState.java index 615b002fc..fdec642e3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropActionState.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropActionState.java @@ -19,6 +19,5 @@ package org.apache.fineract.interoperation.domain; public enum InteropActionState { - ACCEPTED, - REJECTED + ACCEPTED, REJECTED } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropAmountType.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropAmountType.java index 609667bda..1ace06b07 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropAmountType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropAmountType.java @@ -19,6 +19,5 @@ package org.apache.fineract.interoperation.domain; public enum InteropAmountType { - SEND, - RECEIVE + SEND, RECEIVE } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifier.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifier.java index 25f1f7d47..463d2098d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifier.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifier.java @@ -35,9 +35,8 @@ import org.apache.fineract.portfolio.savings.domain.SavingsAccount; @Entity @Table(name = "interop_identifier", uniqueConstraints = { - @UniqueConstraint(name = "uk_hathor_identifier_account", columnNames = {"account_id", "type"}), - @UniqueConstraint(name = "uk_hathor_identifier_value", columnNames = {"type", "a_value", "sub_value_or_type"}) -}) + @UniqueConstraint(name = "uk_hathor_identifier_account", columnNames = { "account_id", "type" }), + @UniqueConstraint(name = "uk_hathor_identifier_value", columnNames = { "type", "a_value", "sub_value_or_type" }) }) public class InteropIdentifier extends AbstractPersistableCustom { @ManyToOne(optional = false) @@ -68,12 +67,10 @@ public class InteropIdentifier extends AbstractPersistableCustom { @Column(name = "modified_on") private Date modifiedOn; - - protected InteropIdentifier() { - } + protected InteropIdentifier() {} public InteropIdentifier(@NotNull SavingsAccount account, @NotNull InteropIdentifierType type, @NotNull String value, - String subValueOrType, @NotNull String createdBy, @NotNull Date createdOn) { + String subValueOrType, @NotNull String createdBy, @NotNull Date createdOn) { this.account = account; this.type = type; this.value = value; @@ -83,7 +80,7 @@ public class InteropIdentifier extends AbstractPersistableCustom { } public InteropIdentifier(@NotNull SavingsAccount account, @NotNull InteropIdentifierType type, @NotNull String createdBy, - @NotNull Date createdOn) { + @NotNull Date createdOn) { this(account, type, null, null, createdBy, createdOn); } @@ -153,24 +150,14 @@ public class InteropIdentifier extends AbstractPersistableCustom { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || !(o instanceof InteropIdentifier)) { - return false; - } + if (this == o) { return true; } + if (o == null || !(o instanceof InteropIdentifier)) { return false; } InteropIdentifier that = (InteropIdentifier) o; - if (!account.equals(that.account)) { - return false; - } - if (type != that.type) { - return false; - } - if (!value.equals(that.value)) { - return false; - } + if (!account.equals(that.account)) { return false; } + if (type != that.type) { return false; } + if (!value.equals(that.value)) { return false; } return subValueOrType != null ? subValueOrType.equals(that.subValueOrType) : that.subValueOrType == null; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifierRepository.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifierRepository.java index 15ab03b1b..a20bcd1b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifierRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifierRepository.java @@ -23,5 +23,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; @Repository -public interface InteropIdentifierRepository extends JpaRepository, JpaSpecificationExecutor { -} +public interface InteropIdentifierRepository extends JpaRepository, JpaSpecificationExecutor {} diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifierType.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifierType.java index ff2e1550b..ef1863749 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifierType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropIdentifierType.java @@ -20,12 +20,5 @@ package org.apache.fineract.interoperation.domain; public enum InteropIdentifierType { - MSISDN, - EMAIL, - PERSONAL_ID, - BUSINESS, - DEVICE, - ACCOUNT_ID, - IBAN, - ALIAS + MSISDN, EMAIL, PERSONAL_ID, BUSINESS, DEVICE, ACCOUNT_ID, IBAN, ALIAS } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropInitiatorType.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropInitiatorType.java index 41bfda591..1a57ac665 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropInitiatorType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropInitiatorType.java @@ -19,8 +19,5 @@ package org.apache.fineract.interoperation.domain; public enum InteropInitiatorType { - CONSUMER, - AGENT, - BUSINESS, - DEVICE + CONSUMER, AGENT, BUSINESS, DEVICE } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransactionRole.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransactionRole.java index 93aecc5ed..4238d2cea 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransactionRole.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransactionRole.java @@ -21,9 +21,8 @@ package org.apache.fineract.interoperation.domain; import org.apache.fineract.portfolio.savings.SavingsAccountTransactionType; public enum InteropTransactionRole { - PAYER, - PAYEE, - ; + + PAYER, PAYEE,; public boolean isWithdraw() { return this == PAYER; diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransactionScenario.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransactionScenario.java index e84f8698c..de8e7da31 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransactionScenario.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransactionScenario.java @@ -20,9 +20,5 @@ package org.apache.fineract.interoperation.domain; public enum InteropTransactionScenario { - DEPOSIT, - WITHDRAWAL, - TRANSFER, - PAYMENT, - REFUND + DEPOSIT, WITHDRAWAL, TRANSFER, PAYMENT, REFUND } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransferActionType.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransferActionType.java index 26ebd7743..288e2e9d0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransferActionType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/domain/InteropTransferActionType.java @@ -20,7 +20,5 @@ package org.apache.fineract.interoperation.domain; public enum InteropTransferActionType { - PREPARE, - CREATE, - ; + PREPARE, CREATE,; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CommitInteropTransferHandler.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CommitInteropTransferHandler.java index cb6d73bd3..e6735f650 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CommitInteropTransferHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CommitInteropTransferHandler.java @@ -46,4 +46,4 @@ public class CommitInteropTransferHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.interopService.commitTransfer(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropIdentifierHandler.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropIdentifierHandler.java index 6b0ce34a5..96fa77d54 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropIdentifierHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropIdentifierHandler.java @@ -53,4 +53,4 @@ public class CreateInteropIdentifierHandler implements NewCommandSourceHandler { InteropIdentifierType idType = InteropIdentifierType.valueOf(split[length - 3].toUpperCase()); return this.interopService.registerAccountIdentifier(idType, idValue, subIdOrType, command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropQuoteHandler.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropQuoteHandler.java index b726a1b91..443ed70b0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropQuoteHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropQuoteHandler.java @@ -45,4 +45,4 @@ public class CreateInteropQuoteHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.interopService.createQuote(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropRequestHandler.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropRequestHandler.java index 744f85eda..c7224b6ea 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropRequestHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/CreateInteropRequestHandler.java @@ -45,4 +45,4 @@ public class CreateInteropRequestHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.interopService.createTransactionRequest(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/DeleteInteropIdentifierHandler.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/DeleteInteropIdentifierHandler.java index ce979f071..853ed66df 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/DeleteInteropIdentifierHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/DeleteInteropIdentifierHandler.java @@ -53,4 +53,4 @@ public class DeleteInteropIdentifierHandler implements NewCommandSourceHandler { InteropIdentifierType idType = InteropIdentifierType.valueOf(split[length - 3].toUpperCase()); return this.interopService.deleteAccountIdentifier(idType, idValue, subIdOrType); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/PrepareInteropTransferHandler.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/PrepareInteropTransferHandler.java index 81767d9a6..59de9dda3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/PrepareInteropTransferHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/handler/PrepareInteropTransferHandler.java @@ -46,4 +46,4 @@ public class PrepareInteropTransferHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.interopService.prepareTransfer(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/serialization/InteropDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/serialization/InteropDataValidator.java index 205c1c6fc..34662628f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/serialization/InteropDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/serialization/InteropDataValidator.java @@ -47,11 +47,12 @@ public class InteropDataValidator { } public InteropIdentifierRequestData validateAndParseCreateIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, - String subIdOrType, JsonCommand command) { + String subIdOrType, JsonCommand command) { final DataValidatorBuilder dataValidator = new DataValidatorBuilder(new ArrayList<>()).resource("interoperation.identifier"); JsonObject element = extractJsonObject(command); - InteropIdentifierRequestData result = InteropIdentifierRequestData.validateAndParse(dataValidator, idType, idValue, subIdOrType, element, jsonHelper); + InteropIdentifierRequestData result = InteropIdentifierRequestData.validateAndParse(dataValidator, idType, idValue, subIdOrType, + element, jsonHelper); throwExceptionIfValidationWarningsExist(dataValidator); return result; @@ -93,9 +94,7 @@ public class InteropDataValidator { private JsonObject extractJsonObject(JsonCommand command) { String json = command.json(); - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final JsonElement element = jsonHelper.parse(json); return element.getAsJsonObject(); @@ -103,8 +102,8 @@ public class InteropDataValidator { private void throwExceptionIfValidationWarningsExist(DataValidatorBuilder dataValidator) { if (dataValidator.hasError()) { - throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidator.getDataValidationErrors()); + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidator.getDataValidationErrors()); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/service/InteropService.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/service/InteropService.java index 27c2e911d..284e2dc4d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/service/InteropService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/service/InteropService.java @@ -39,18 +39,20 @@ public interface InteropService { InteropAccountData getAccountDetails(@NotNull String accountId); @NotNull - InteropTransactionsData getAccountTransactions(@NotNull String accountId, boolean debit, boolean credit, LocalDateTime transactionsFrom, LocalDateTime transactionsTo); + InteropTransactionsData getAccountTransactions(@NotNull String accountId, boolean debit, boolean credit, LocalDateTime transactionsFrom, + LocalDateTime transactionsTo); @NotNull - InteropIdentifierAccountResponseData getAccountByIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType); + InteropIdentifierAccountResponseData getAccountByIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, + String subIdOrType); @NotNull InteropIdentifierAccountResponseData registerAccountIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, - String subIdOrType, @NotNull JsonCommand command); + String subIdOrType, @NotNull JsonCommand command); @NotNull InteropIdentifierAccountResponseData deleteAccountIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, - String subIdOrType); + String subIdOrType); InteropTransactionRequestResponseData getTransactionRequest(@NotNull String transactionCode, @NotNull String requestCode); @@ -69,4 +71,4 @@ public interface InteropService { @NotNull InteropTransferResponseData commitTransfer(@NotNull JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/service/InteropServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/service/InteropServiceImpl.java index d3e6423e6..20c4d592c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/service/InteropServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/service/InteropServiceImpl.java @@ -108,19 +108,14 @@ public class InteropServiceImpl implements InteropService { private final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper; private final SavingsAccountDomainService savingsAccountService; + @Autowired - public InteropServiceImpl(PlatformSecurityContext securityContext, - InteropDataValidator interopDataValidator, - SavingsAccountRepository savingsAccountRepository, - SavingsAccountTransactionRepository savingsAccountTransactionRepository, - ApplicationCurrencyRepository applicationCurrencyRepository, - NoteRepository noteRepository, - PaymentTypeRepository paymentTypeRepository, - InteropIdentifierRepository identifierRepository, - SavingsHelper savingsHelper, + public InteropServiceImpl(PlatformSecurityContext securityContext, InteropDataValidator interopDataValidator, + SavingsAccountRepository savingsAccountRepository, SavingsAccountTransactionRepository savingsAccountTransactionRepository, + ApplicationCurrencyRepository applicationCurrencyRepository, NoteRepository noteRepository, + PaymentTypeRepository paymentTypeRepository, InteropIdentifierRepository identifierRepository, SavingsHelper savingsHelper, SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper, - SavingsAccountDomainService savingsAccountService, - PaymentDetailWritePlatformService paymentDetailWritePlatformService) { + SavingsAccountDomainService savingsAccountService, PaymentDetailWritePlatformService paymentDetailWritePlatformService) { this.securityContext = securityContext; this.dataValidator = interopDataValidator; this.savingsAccountRepository = savingsAccountRepository; @@ -145,22 +140,20 @@ public class InteropServiceImpl implements InteropService { @NotNull @Override @Transactional - public InteropTransactionsData getAccountTransactions(@NotNull String accountId, boolean debit, boolean credit, java.time.LocalDateTime transactionsFrom, java.time.LocalDateTime transactionsTo) { + public InteropTransactionsData getAccountTransactions(@NotNull String accountId, boolean debit, boolean credit, + java.time.LocalDateTime transactionsFrom, java.time.LocalDateTime transactionsTo) { SavingsAccount savingsAccount = validateAndGetSavingAccount(accountId); ZoneId zoneId = ZoneId.of(ThreadLocalContextUtil.getTenant().getTimezoneId()); Predicate transFilter = t -> { SavingsAccountTransactionType transactionType = SavingsAccountTransactionType.fromInt(t.getTypeOf()); - if (debit != transactionType.isDebit() && credit != transactionType.isCredit()) { - return false; - } + if (debit != transactionType.isDebit() && credit != transactionType.isCredit()) { return false; } - if (transactionsFrom == null && transactionsTo == null) { - return true; - } + if (transactionsFrom == null && transactionsTo == null) { return true; } - java.time.LocalDateTime transactionDate = t.getTransactionLocalDate().toDateTimeAtStartOfDay().toDate().toInstant().atZone(zoneId).toLocalDateTime(); - return (transactionsTo == null || transactionsTo.compareTo(transactionDate) > 0) - && (transactionsFrom == null || transactionsFrom.compareTo(transactionDate.withHour(23).withMinute(59).withSecond(59)) <= 0); + java.time.LocalDateTime transactionDate = t.getTransactionLocalDate().toDateTimeAtStartOfDay().toDate().toInstant() + .atZone(zoneId).toLocalDateTime(); + return (transactionsTo == null || transactionsTo.compareTo(transactionDate) > 0) && (transactionsFrom == null + || transactionsFrom.compareTo(transactionDate.withHour(23).withMinute(59).withSecond(59)) <= 0); }; return InteropTransactionsData.build(savingsAccount, transFilter); } @@ -176,7 +169,8 @@ public class InteropServiceImpl implements InteropService { @NotNull @Override @Transactional - public InteropIdentifierAccountResponseData getAccountByIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType) { + public InteropIdentifierAccountResponseData getAccountByIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, + String subIdOrType) { InteropIdentifier identifier = findIdentifier(idType, idValue, subIdOrType); return InteropIdentifierAccountResponseData.build(identifier.getAccount().getExternalId()); } @@ -187,7 +181,7 @@ public class InteropServiceImpl implements InteropService { public InteropIdentifierAccountResponseData registerAccountIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType, @NotNull JsonCommand command) { InteropIdentifierRequestData request = dataValidator.validateAndParseCreateIdentifier(idType, idValue, subIdOrType, command); - //TODO: error handling + // TODO: error handling SavingsAccount savingsAccount = validateAndGetSavingAccount(request.getAccountId()); AppUser createdBy = getLoginUser(); @@ -224,7 +218,8 @@ public class InteropServiceImpl implements InteropService { @NotNull @Transactional(propagation = Propagation.MANDATORY) public InteropTransactionRequestResponseData createTransactionRequest(@NotNull JsonCommand command) { - // only when Payee request transaction from Payer, so here role must be always Payer + // only when Payee request transaction from Payer, so here role must be + // always Payer InteropTransactionRequestData request = dataValidator.validateAndParseCreateRequest(command); validateAndGetSavingAccount(request); @@ -244,15 +239,16 @@ public class InteropServiceImpl implements InteropService { public InteropQuoteResponseData createQuote(@NotNull JsonCommand command) { InteropQuoteRequestData request = dataValidator.validateAndParseCreateQuote(command); - //TODO: error handling + // TODO: error handling SavingsAccount savingsAccount = validateAndGetSavingAccount(request); SavingsAccountTransactionType transactionType = request.getTransactionRole().getTransactionType(); - BigDecimal fee = transactionType.isDebit() ? savingsAccount.calculateWithdrawalFee(request.getAmount().getAmount()) : BigDecimal.ZERO; + BigDecimal fee = transactionType.isDebit() ? savingsAccount.calculateWithdrawalFee(request.getAmount().getAmount()) + : BigDecimal.ZERO; return InteropQuoteResponseData.build(command.commandId(), request.getTransactionCode(), InteropActionState.ACCEPTED, - request.getExpiration(), request.getExtensionList(), request.getQuoteCode(), MoneyData.build(fee, savingsAccount.getCurrency().getCode()), - null); + request.getExpiration(), request.getExtensionList(), request.getQuoteCode(), + MoneyData.build(fee, savingsAccount.getCurrency().getCode()), null); } @Override @@ -266,8 +262,8 @@ public class InteropServiceImpl implements InteropService { public InteropTransferResponseData prepareTransfer(@NotNull JsonCommand command) { InteropTransferRequestData request = dataValidator.validateAndParsePrepareTransfer(command); - //TODO: error handling - //TODO: REVERSE + // TODO: error handling + // TODO: REVERSE SavingsAccount savingsAccount = validateAndGetSavingAccount(request); BigDecimal total = validateTransfer(request, savingsAccount); @@ -275,18 +271,16 @@ public class InteropServiceImpl implements InteropService { String transferCode = request.getTransferCode(); LocalDateTime transactionDate = DateUtils.getLocalDateTimeOfTenant(); if (MathUtil.isGreaterThanZero(total)) { - if (MathUtil.isLessThan(savingsAccount.getWithdrawableBalance(), total)) { - throw new UnsupportedOperationException(); - } + if (MathUtil.isLessThan(savingsAccount.getWithdrawableBalance(), total)) { throw new UnsupportedOperationException(); } if (findTransaction(savingsAccount, transferCode, SavingsAccountTransactionType.AMOUNT_HOLD) != null) { throw new UnsupportedOperationException("Transfer amount was already put on hold " + transferCode); } - PaymentDetail paymentDetail = PaymentDetail.instance(findPaymentType(), savingsAccount.getExternalId(), null, getRoutingCode(), transferCode, null); + PaymentDetail paymentDetail = PaymentDetail.instance(findPaymentType(), savingsAccount.getExternalId(), null, getRoutingCode(), + transferCode, null); AppUser appUser = getLoginUser(); SavingsAccountTransaction transaction = SavingsAccountTransaction.holdAmount(savingsAccount, savingsAccount.office(), - paymentDetail, transactionDate.toLocalDate(), Money.of(savingsAccount.getCurrency(), total), new Date(), - appUser); + paymentDetail, transactionDate.toLocalDate(), Money.of(savingsAccount.getCurrency(), total), new Date(), appUser); savingsAccount.holdAmount(total); savingsAccount.addTransaction(transaction); @@ -294,8 +288,8 @@ public class InteropServiceImpl implements InteropService { savingsAccountRepository.save(savingsAccount); } - return InteropTransferResponseData.build(command.commandId(), request.getTransactionCode(), InteropActionState.ACCEPTED, request.getExpiration(), - request.getExtensionList(), transferCode, transactionDate); + return InteropTransferResponseData.build(command.commandId(), request.getTransactionCode(), InteropActionState.ACCEPTED, + request.getExpiration(), request.getExtensionList(), transferCode, transactionDate); } @Override @@ -306,28 +300,32 @@ public class InteropServiceImpl implements InteropService { SavingsAccountTransactionType transactionType = request.getTransactionRole().getTransactionType(); boolean debit = transactionType.isDebit(); - //TODO: error handling - //TODO: REVERSE + // TODO: error handling + // TODO: REVERSE SavingsAccount savingsAccount = validateAndGetSavingAccount(request); validateTransfer(request, savingsAccount); String transferCode = request.getTransferCode(); - if (findTransaction(savingsAccount, transferCode, debit ? SavingsAccountTransactionType.WITHDRAWAL : SavingsAccountTransactionType.DEPOSIT) != null) { + if (findTransaction(savingsAccount, transferCode, + debit ? SavingsAccountTransactionType.WITHDRAWAL : SavingsAccountTransactionType.DEPOSIT) != null) { throw new UnsupportedOperationException("Transfer was already committed " + transferCode); } - PaymentDetail paymentDetail = PaymentDetail.instance(findPaymentType(), savingsAccount.getExternalId(), null, getRoutingCode(), transferCode, null); + PaymentDetail paymentDetail = PaymentDetail.instance(findPaymentType(), savingsAccount.getExternalId(), null, getRoutingCode(), + transferCode, null); LocalDateTime transactionDateTime = DateUtils.getLocalDateTimeOfTenant(); LocalDate transactionDate = transactionDateTime.toLocalDate(); Date createdDate = new Date(); - SavingsAccountTransaction holdTransaction = findTransaction(savingsAccount, transferCode, SavingsAccountTransactionType.AMOUNT_HOLD); + SavingsAccountTransaction holdTransaction = findTransaction(savingsAccount, transferCode, + SavingsAccountTransactionType.AMOUNT_HOLD); if (holdTransaction != null && holdTransaction.getReleaseIdOfHoldAmountTransaction() == null) { AppUser appUser = getLoginUser(); - SavingsAccountTransaction releaseTransaction = SavingsAccountTransaction.releaseAmount(holdTransaction, transactionDate, createdDate, appUser); + SavingsAccountTransaction releaseTransaction = SavingsAccountTransaction.releaseAmount(holdTransaction, transactionDate, + createdDate, appUser); releaseTransaction = savingsAccountTransactionRepository.saveAndFlush(releaseTransaction); holdTransaction.updateReleaseId(releaseTransaction.getId()); @@ -343,12 +341,10 @@ public class InteropServiceImpl implements InteropService { SavingsAccountTransaction transaction; if (debit) { SavingsTransactionBooleanValues transactionValues = new SavingsTransactionBooleanValues(false, true, true, false, false); - transaction = savingsAccountService.handleWithdrawal(savingsAccount, fmt, transactionDate, amount, - paymentDetail, transactionValues); - } - else { - transaction = savingsAccountService.handleDeposit(savingsAccount, fmt, transactionDate, amount, - paymentDetail, false, true); + transaction = savingsAccountService.handleWithdrawal(savingsAccount, fmt, transactionDate, amount, paymentDetail, + transactionValues); + } else { + transaction = savingsAccountService.handleDeposit(savingsAccount, fmt, transactionDate, amount, paymentDetail, false, true); } String note = request.getNote(); @@ -364,21 +360,17 @@ public class InteropServiceImpl implements InteropService { private SavingsAccount validateAndGetSavingAccount(String accountId) { SavingsAccount savingsAccount = savingsAccountRepository.findByExternalId(accountId); - if (savingsAccount == null) { - throw new SavingsAccountNotFoundException(accountId); - } + if (savingsAccount == null) { throw new SavingsAccountNotFoundException(accountId); } return savingsAccount; } private SavingsAccount validateAndGetSavingAccount(@NotNull InteropRequestData request) { - //TODO: error handling + // TODO: error handling SavingsAccount savingsAccount = validateAndGetSavingAccount(request.getAccountId()); savingsAccount.setHelpers(savingsAccountTransactionSummaryWrapper, savingsHelper); ApplicationCurrency currency = currencyRepository.findOneByCode(request.getAmount().getCurrency()); - if (!savingsAccount.getCurrency().getCode().equals(currency.getCode())) { - throw new UnsupportedOperationException(); - } + if (!savingsAccount.getCurrency().getCode().equals(currency.getCode())) { throw new UnsupportedOperationException(); } SavingsAccountTransactionType transactionType = request.getTransactionRole().getTransactionType(); if (!savingsAccount.isTransactionAllowed(transactionType, request.getExpirationLocalDate())) { @@ -400,18 +392,14 @@ public class InteropServiceImpl implements InteropService { BigDecimal total = transactionType.isDebit() ? amount : MathUtil.negate(amount); MoneyData fspFee = request.getFspFee(); if (fspFee != null) { - if (!savingsAccount.getCurrency().getCode().equals(fspFee.getCurrency())) { - throw new UnsupportedOperationException(); - } - //TODO: compare with calculated quote fee + if (!savingsAccount.getCurrency().getCode().equals(fspFee.getCurrency())) { throw new UnsupportedOperationException(); } + // TODO: compare with calculated quote fee total = MathUtil.add(total, fspFee.getAmount()); } MoneyData fspCommission = request.getFspCommission(); if (fspCommission != null) { - if (!savingsAccount.getCurrency().getCode().equals(fspCommission.getCurrency())) { - throw new UnsupportedOperationException(); - } - //TODO: compare with calculated quote commission + if (!savingsAccount.getCurrency().getCode().equals(fspCommission.getCurrency())) { throw new UnsupportedOperationException(); } + // TODO: compare with calculated quote commission total = MathUtil.subtractToZero(total, fspCommission.getAmount()); } return total; @@ -435,15 +423,17 @@ public class InteropServiceImpl implements InteropService { for (PaymentType paymentType : paymentTypes) { if (!paymentType.isCashPayment()) { return paymentType; - //TODO: for now first not cash is retured: + // TODO: for now first not cash is retured: // 1. must be added as initial setup, - // 2. if more than one non-cashe type added then update this code + // 2. if more than one non-cashe type added then update this + // code } } return null; } - SavingsAccountTransaction findTransaction(@NotNull SavingsAccount savingsAccount, @NotNull String transactionCode, SavingsAccountTransactionType transactionType) { + SavingsAccountTransaction findTransaction(@NotNull SavingsAccount savingsAccount, @NotNull String transactionCode, + SavingsAccountTransactionType transactionType) { String routingCode = getRoutingCode(); for (SavingsAccountTransaction transaction : savingsAccount.getTransactions()) { if (transactionType != null && !transactionType.getValue().equals(transaction.getTypeOf())) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/interoperation/util/MathUtil.java b/fineract-provider/src/main/java/org/apache/fineract/interoperation/util/MathUtil.java index b99f69d63..4573420f2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/interoperation/util/MathUtil.java +++ b/fineract-provider/src/main/java/org/apache/fineract/interoperation/util/MathUtil.java @@ -85,29 +85,29 @@ public class MathUtil { return value == null ? 0L : Math.abs(value); } - /** @return calculates minimum of the two values considering null values - * @param notNull if true then null parameter is omitted, otherwise returns null */ + /** + * @return calculates minimum of the two values considering null values + * @param notNull + * if true then null parameter is omitted, otherwise returns null + */ public static Long min(Long first, Long second, boolean notNull) { - if (first == null){ - return notNull ? second : null; - } - if (second == null) { - return notNull ? first : null; - } + if (first == null) { return notNull ? second : null; } + if (second == null) { return notNull ? first : null; } return Math.min(first, second); } - /** @return calculates minimum of the values considering null values - * @param notNull if true then null parameter is omitted, otherwise returns null */ + /** + * @return calculates minimum of the values considering null values + * @param notNull + * if true then null parameter is omitted, otherwise returns null + */ public static Long min(Long first, Long second, Long third, boolean notNull) { return min(min(first, second, notNull), third, notNull); } /** @return sum the two values considering null values */ public static Long add(Long first, Long second) { - return first == null - ? second - : second == null ? first : Math.addExact(first, second); + return first == null ? second : second == null ? first : Math.addExact(first, second); } /** @return sum the values considering null values */ @@ -127,17 +127,19 @@ public class MathUtil { /** @return first minus second considering null values, maybe negative */ public static Long subtract(Long first, Long second) { - return first == null - ? null - : second == null ? first : Math.subtractExact(first, second); + return first == null ? null : second == null ? first : Math.subtractExact(first, second); } - /** @return first minus the others considering null values, maybe negative */ + /** + * @return first minus the others considering null values, maybe negative + */ public static Long subtractToZero(Long first, Long second, Long third) { return subtractToZero(subtract(first, second), third); } - /** @return first minus the others considering null values, maybe negative */ + /** + * @return first minus the others considering null values, maybe negative + */ public static Long subtractToZero(Long first, Long second, Long third, Long fourth) { return subtractToZero(subtract(subtract(first, second), third), fourth); } @@ -152,7 +154,6 @@ public class MathUtil { return isEmpty(amount) ? amount : Math.negateExact(amount); } - // ----------------- BigDecimal ----------------- public static BigDecimal nullToZero(BigDecimal value) { @@ -213,18 +214,21 @@ public class MathUtil { return value == null ? BigDecimal.ZERO : value.abs(); } - /** @return calculates minimum of the two values considering null values - * @param notNull if true then null parameter is omitted, otherwise returns null */ + /** + * @return calculates minimum of the two values considering null values + * @param notNull + * if true then null parameter is omitted, otherwise returns null + */ public static BigDecimal min(BigDecimal first, BigDecimal second, boolean notNull) { - return notNull - ? first == null - ? second - : second == null ? first : min(first, second, false) + return notNull ? first == null ? second : second == null ? first : min(first, second, false) : isLessThan(first, second) ? first : second; } - /** @return calculates minimum of the values considering null values - * @param notNull if true then null parameter is omitted, otherwise returns null */ + /** + * @return calculates minimum of the values considering null values + * @param notNull + * if true then null parameter is omitted, otherwise returns null + */ public static BigDecimal min(BigDecimal first, BigDecimal second, BigDecimal third, boolean notNull) { return min(min(first, second, notNull), third, notNull); } @@ -236,9 +240,7 @@ public class MathUtil { /** @return sum the two values considering null values */ public static BigDecimal add(BigDecimal first, BigDecimal second, MathContext mc) { - return first == null - ? second - : second == null ? first : first.add(second, mc); + return first == null ? second : second == null ? first : first.add(second, mc); } /** @return sum the values considering null values */ @@ -267,7 +269,8 @@ public class MathUtil { } /** @return sum the values considering null values */ - public static BigDecimal add(BigDecimal first, BigDecimal second, BigDecimal third, BigDecimal fourth, BigDecimal fifth, MathContext mc) { + public static BigDecimal add(BigDecimal first, BigDecimal second, BigDecimal third, BigDecimal fourth, BigDecimal fifth, + MathContext mc) { return add(add(add(add(first, second, mc), third, mc), fourth, mc), fifth, mc); } @@ -278,9 +281,7 @@ public class MathUtil { /** @return first minus second considering null values, maybe negative */ public static BigDecimal subtract(BigDecimal first, BigDecimal second, MathContext mc) { - return first == null - ? null - : second == null ? first : first.subtract(second, mc); + return first == null ? null : second == null ? first : first.subtract(second, mc); } /** @return NONE negative first minus second considering null values */ @@ -288,17 +289,24 @@ public class MathUtil { return negativeToZero(subtract(first, second)); } - /** @return first minus the others considering null values, maybe negative */ + /** + * @return first minus the others considering null values, maybe negative + */ public static BigDecimal subtractToZero(BigDecimal first, BigDecimal second, BigDecimal third) { return subtractToZero(subtract(first, second), third); } - /** @return first minus the others considering null values, maybe negative */ + /** + * @return first minus the others considering null values, maybe negative + */ public static BigDecimal subtractToZero(BigDecimal first, BigDecimal second, BigDecimal third, BigDecimal fourth) { return subtractToZero(subtract(subtract(first, second), third), fourth); } - /** @return BigDecimal with scale set to the 'digitsAfterDecimal' of the parameter currency */ + /** + * @return BigDecimal with scale set to the 'digitsAfterDecimal' of the + * parameter currency + */ public static BigDecimal normalizeAmount(BigDecimal amount, @NotNull MonetaryCurrency currency) { return amount == null ? null : amount.setScale(currency.getDigitsAfterDecimal(), MoneyHelper.getRoundingMode()); } @@ -313,7 +321,6 @@ public class MathUtil { return isEmpty(amount) ? amount : amount.negate(mc); } - // ----------------- Money ----------------- public static Money nullToZero(Money value, @NotNull MonetaryCurrency currency) { @@ -358,9 +365,7 @@ public class MathUtil { } public static Money plus(Money first, Money second) { - return first == null - ? second - : second == null ? first : first.plus(second); + return first == null ? second : second == null ? first : first.plus(second); } public static Money plus(Money first, Money second, Money third) { @@ -372,17 +377,19 @@ public class MathUtil { } public static Money minus(Money first, Money second) { - return first == null - ? null - : second == null ? first : first.minus(second); + return first == null ? null : second == null ? first : first.minus(second); } - /** @return first minus the others considering null values, maybe negative */ + /** + * @return first minus the others considering null values, maybe negative + */ public static Money minusToZero(Money first, Money second, Money third) { return minusToZero(minus(first, second), third); } - /** @return first minus the others considering null values, maybe negative */ + /** + * @return first minus the others considering null values, maybe negative + */ public static Money minusToZero(Money first, Money second, Money third, Money fourth) { return minusToZero(minus(minus(first, second), third), fourth); } @@ -392,18 +399,21 @@ public class MathUtil { return negativeToZero(minus(first, second)); } - /** @return calculates minimum of the two values considering null values - * @param notNull if true then null parameter is omitted, otherwise returns null */ + /** + * @return calculates minimum of the two values considering null values + * @param notNull + * if true then null parameter is omitted, otherwise returns null + */ public static Money min(Money first, Money second, boolean notNull) { - return notNull - ? first == null - ? second - : second == null ? first : min(first, second, false) + return notNull ? first == null ? second : second == null ? first : min(first, second, false) : isLessThan(first, second) ? first : second; } - /** @return calculates minimum of the values considering null values - * @param notNull if true then null parameter is omitted, otherwise returns null */ + /** + * @return calculates minimum of the values considering null values + * @param notNull + * if true then null parameter is omitted, otherwise returns null + */ public static Money min(Money first, Money second, Money third, boolean notNull) { return min(min(first, second, notNull), third, notNull); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixReportApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixReportApiResource.java index 81877aaed..8c7bdfef2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixReportApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixReportApiResource.java @@ -37,10 +37,8 @@ import org.springframework.stereotype.Component; @Path("/mixreport") @Component @Scope("singleton") -@Api(tags = {"Mix Report"}) -@SwaggerDefinition(tags = { - @Tag(name = "Mix Report", description = "") -}) +@Api(tags = { "Mix Report" }) +@SwaggerDefinition(tags = { @Tag(name = "Mix Report", description = "") }) public class MixReportApiResource { private final XBRLResultService xbrlResultService; @@ -61,4 +59,4 @@ public class MixReportApiResource { return this.xbrlBuilder.build(data); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixTaxonomyApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixTaxonomyApiResource.java index df7a44fb6..66cf6a75c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixTaxonomyApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixTaxonomyApiResource.java @@ -45,14 +45,12 @@ import org.springframework.stereotype.Component; @Path("/mixtaxonomy") @Component @Scope("singleton") -@Api(tags = {"Mix Taxonomy"}) -@SwaggerDefinition(tags = { - @Tag(name = "Mix Taxonomy", description = "") -}) +@Api(tags = { "Mix Taxonomy" }) +@SwaggerDefinition(tags = { @Tag(name = "Mix Taxonomy", description = "") }) public class MixTaxonomyApiResource { - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("taxonomyId", "name", "namespace", "dimension", - "description")); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("taxonomyId", "name", "namespace", "dimension", "description")); private final PlatformSecurityContext context; private final ToApiJsonSerializer toApiJsonSerializer; @@ -81,4 +79,4 @@ public class MixTaxonomyApiResource { return this.toApiJsonSerializer.serialize(settings, taxonomyDatas, this.RESPONSE_DATA_PARAMETERS); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixTaxonomyMappingApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixTaxonomyMappingApiResource.java index 1d940b539..096a7b406 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixTaxonomyMappingApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/api/MixTaxonomyMappingApiResource.java @@ -49,10 +49,8 @@ import org.springframework.stereotype.Component; @Path("/mixmapping") @Component @Scope("singleton") -@Api(tags = {"Mix Mapping "}) -@SwaggerDefinition(tags = { - @Tag(name = "Mix Mapping", description = "") -}) +@Api(tags = { "Mix Mapping " }) +@SwaggerDefinition(tags = { @Tag(name = "Mix Mapping", description = "") }) public class MixTaxonomyMappingApiResource { private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("identifier", "config")); diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/data/MixTaxonomyData.java b/fineract-provider/src/main/java/org/apache/fineract/mix/data/MixTaxonomyData.java index 58be7a9c0..5fc94b16c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/data/MixTaxonomyData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/data/MixTaxonomyData.java @@ -64,4 +64,4 @@ public class MixTaxonomyData { public boolean isPortfolio() { return this.type == 5; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/data/MixTaxonomyMappingData.java b/fineract-provider/src/main/java/org/apache/fineract/mix/data/MixTaxonomyMappingData.java index 11b6b7ec2..10565923e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/data/MixTaxonomyMappingData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/data/MixTaxonomyMappingData.java @@ -35,4 +35,4 @@ public class MixTaxonomyMappingData { public String getConfig() { return this.config; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/data/NamespaceData.java b/fineract-provider/src/main/java/org/apache/fineract/mix/data/NamespaceData.java index f42bbbfaa..2158cc557 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/data/NamespaceData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/data/NamespaceData.java @@ -36,4 +36,4 @@ public class NamespaceData { public String url() { return this.url; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/data/XBRLData.java b/fineract-provider/src/main/java/org/apache/fineract/mix/data/XBRLData.java index 77e36756d..99032866f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/data/XBRLData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/data/XBRLData.java @@ -51,4 +51,4 @@ public class XBRLData { public String getCurrency() { return this.currency; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/domain/MixTaxonomyMappingRepository.java b/fineract-provider/src/main/java/org/apache/fineract/mix/domain/MixTaxonomyMappingRepository.java index f8c5298dd..44df787b4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/domain/MixTaxonomyMappingRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/domain/MixTaxonomyMappingRepository.java @@ -21,6 +21,7 @@ package org.apache.fineract.mix.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface MixTaxonomyMappingRepository extends JpaRepository, JpaSpecificationExecutor { +public interface MixTaxonomyMappingRepository + extends JpaRepository, JpaSpecificationExecutor { -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/service/MixTaxonomyMappingReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/mix/service/MixTaxonomyMappingReadPlatformServiceImpl.java index e3574b027..2c47d0988 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/service/MixTaxonomyMappingReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/service/MixTaxonomyMappingReadPlatformServiceImpl.java @@ -64,4 +64,4 @@ public class MixTaxonomyMappingReadPlatformServiceImpl implements MixTaxonomyMap } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/service/MixTaxonomyReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/mix/service/MixTaxonomyReadPlatformServiceImpl.java index 69464b70e..31240c0e0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/service/MixTaxonomyReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/service/MixTaxonomyReadPlatformServiceImpl.java @@ -72,4 +72,4 @@ public class MixTaxonomyReadPlatformServiceImpl implements MixTaxonomyReadPlatfo final String sql = "select " + this.mixTaxonomyMapper.schema() + " where tx.id = ? "; return this.jdbcTemplate.queryForObject(sql, this.mixTaxonomyMapper, new Object[] { id }); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/service/NamespaceReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/mix/service/NamespaceReadPlatformServiceImpl.java index 0b8ef0d45..c2816e4fd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/service/NamespaceReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/service/NamespaceReadPlatformServiceImpl.java @@ -68,4 +68,4 @@ public class NamespaceReadPlatformServiceImpl implements NamespaceReadPlatformSe return this.jdbcTemplate.queryForObject(sql, this.namespaceMapper, new Object[] { prefix }); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLBuilder.java b/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLBuilder.java index 0843a876b..c1fe90cd9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLBuilder.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLBuilder.java @@ -89,8 +89,9 @@ public class XBRLBuilder { Element addTaxonomy(final Element rootElement, final MixTaxonomyData taxonomy, final BigDecimal value) { // throw an error is start / endate is null - if (this.startDate == null || this.endDate == null) { throw new XBRLMappingInvalidException( - "start date and end date should not be null"); } + if (this.startDate == null || this.endDate == null) { + throw new XBRLMappingInvalidException("start date and end date should not be null"); + } final String prefix = taxonomy.getNamespace(); String qname = taxonomy.getName(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLResultService.java b/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLResultService.java index f29dd6d6e..585b3e46c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLResultService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLResultService.java @@ -25,4 +25,4 @@ public interface XBRLResultService { XBRLData getXBRLResult(Date startDate, Date endDate, String currency); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLResultServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLResultServiceImpl.java index a183d8080..2b5d2ea81 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLResultServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/mix/service/XBRLResultServiceImpl.java @@ -43,6 +43,7 @@ import org.springframework.stereotype.Component; @Component public class XBRLResultServiceImpl implements XBRLResultService { + private final static Logger LOG = LoggerFactory.getLogger(XBRLResultServiceImpl.class); private static final ScriptEngine SCRIPT_ENGINE = new ScriptEngineManager().getEngineByName("JavaScript"); @@ -52,8 +53,8 @@ public class XBRLResultServiceImpl implements XBRLResultService { private HashMap accountBalanceMap; @Autowired - public XBRLResultServiceImpl(final RoutingDataSource dataSource, - final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService, final MixTaxonomyReadPlatformService readTaxonomyService) { + public XBRLResultServiceImpl(final RoutingDataSource dataSource, final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService, + final MixTaxonomyReadPlatformService readTaxonomyService) { this.readTaxonomyMappingService = readTaxonomyMappingService; this.readTaxonomyService = readTaxonomyService; this.jdbcTemplate = new JdbcTemplate(dataSource); @@ -96,56 +97,36 @@ public class XBRLResultServiceImpl implements XBRLResultService { private String getAccountSql(final Date startDate, final Date endDate) { final String sql = "select debits.glcode as 'glcode', debits.name as 'name', (ifnull(debits.debitamount,0)-ifnull(credits.creditamount,0)) as 'balance' " + "from (select acc_gl_account.gl_code as 'glcode',name,sum(amount) as 'debitamount' " - + "from acc_gl_journal_entry,acc_gl_account " - + "where acc_gl_account.id = acc_gl_journal_entry.account_id " - + "and acc_gl_journal_entry.type_enum=2 " + "and acc_gl_journal_entry.entry_date <= " - + endDate - + " and acc_gl_journal_entry.entry_date > " - + startDate - + - // "and (acc_gl_journal_entry.office_id=${branch} or ${branch}=1) " + + "from acc_gl_journal_entry,acc_gl_account " + "where acc_gl_account.id = acc_gl_journal_entry.account_id " + + "and acc_gl_journal_entry.type_enum=2 " + "and acc_gl_journal_entry.entry_date <= " + endDate + + " and acc_gl_journal_entry.entry_date > " + startDate + + // "and (acc_gl_journal_entry.office_id=${branch} or + // ${branch}=1) " // + - " group by glcode " - + "order by glcode) debits " - + "LEFT OUTER JOIN " + " group by glcode " + "order by glcode) debits " + "LEFT OUTER JOIN " + "(select acc_gl_account.gl_code as 'glcode',name,sum(amount) as 'creditamount' " - + "from acc_gl_journal_entry,acc_gl_account " - + "where acc_gl_account.id = acc_gl_journal_entry.account_id " - + "and acc_gl_journal_entry.type_enum=1 " - + "and acc_gl_journal_entry.entry_date <= " - + endDate - + " and acc_gl_journal_entry.entry_date > " - + startDate - + - // "and (acc_gl_journal_entry.office_id=${branch} or ${branch}=1) " + + "from acc_gl_journal_entry,acc_gl_account " + "where acc_gl_account.id = acc_gl_journal_entry.account_id " + + "and acc_gl_journal_entry.type_enum=1 " + "and acc_gl_journal_entry.entry_date <= " + endDate + + " and acc_gl_journal_entry.entry_date > " + startDate + + // "and (acc_gl_journal_entry.office_id=${branch} or + // ${branch}=1) " // + - " group by glcode " - + "order by glcode) credits " - + "on debits.glcode=credits.glcode " - + "union " + " group by glcode " + "order by glcode) credits " + "on debits.glcode=credits.glcode " + "union " + "select credits.glcode as 'glcode', credits.name as 'name', (ifnull(debits.debitamount,0)-ifnull(credits.creditamount,0)) as 'balance' " + "from (select acc_gl_account.gl_code as 'glcode',name,sum(amount) as 'debitamount' " - + "from acc_gl_journal_entry,acc_gl_account " - + "where acc_gl_account.id = acc_gl_journal_entry.account_id " - + "and acc_gl_journal_entry.type_enum=2 " - + "and acc_gl_journal_entry.entry_date <= " - + endDate - + " and acc_gl_journal_entry.entry_date > " - + startDate - + - // "and (acc_gl_journal_entry.office_id=${branch} or ${branch}=1) " - // + - " group by glcode " - + "order by glcode) debits " - + "RIGHT OUTER JOIN " - + "(select acc_gl_account.gl_code as 'glcode',name,sum(amount) as 'creditamount' " - + "from acc_gl_journal_entry,acc_gl_account " - + "where acc_gl_account.id = acc_gl_journal_entry.account_id " - + "and acc_gl_journal_entry.type_enum=1 " - + "and acc_gl_journal_entry.entry_date <= " - + endDate + + "from acc_gl_journal_entry,acc_gl_account " + "where acc_gl_account.id = acc_gl_journal_entry.account_id " + + "and acc_gl_journal_entry.type_enum=2 " + "and acc_gl_journal_entry.entry_date <= " + endDate + " and acc_gl_journal_entry.entry_date > " + startDate + - // "and (acc_gl_journal_entry.office_id=${branch} or ${branch}=1) " + // "and (acc_gl_journal_entry.office_id=${branch} or + // ${branch}=1) " + // + + " group by glcode " + "order by glcode) debits " + "RIGHT OUTER JOIN " + + "(select acc_gl_account.gl_code as 'glcode',name,sum(amount) as 'creditamount' " + + "from acc_gl_journal_entry,acc_gl_account " + "where acc_gl_account.id = acc_gl_journal_entry.account_id " + + "and acc_gl_journal_entry.type_enum=1 " + "and acc_gl_journal_entry.entry_date <= " + endDate + + " and acc_gl_journal_entry.entry_date > " + startDate + + // "and (acc_gl_journal_entry.office_id=${branch} or + // ${branch}=1) " // + " group by name, glcode " + "order by glcode) credits " + "on debits.glcode=credits.glcode;"; return sql; @@ -178,7 +159,7 @@ public class XBRLResultServiceImpl implements XBRLResultService { eval = value.floatValue(); } } catch (final ScriptException e) { - LOG.error("Problem occurred in processMappingString function",e); + LOG.error("Problem occurred in processMappingString function", e); throw new IllegalArgumentException(e.getMessage()); } @@ -203,4 +184,4 @@ public class XBRLResultServiceImpl implements XBRLResultService { } return placeholders; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/api/NotificationApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/notification/api/NotificationApiResource.java index a2d35c08c..524bc1b36 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/api/NotificationApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/api/NotificationApiResource.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.notification.api; - import io.swagger.annotations.Api; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; @@ -46,10 +45,8 @@ import org.springframework.stereotype.Component; @Path("/notifications") @Component @Scope("singleton") -@Api(tags = {"Notification"}) -@SwaggerDefinition(tags = { - @Tag(name = "Notification", description = "") -}) +@Api(tags = { "Notification" }) +@SwaggerDefinition(tags = { @Tag(name = "Notification", description = "") }) public class NotificationApiResource { private final PlatformSecurityContext context; @@ -58,10 +55,8 @@ public class NotificationApiResource { private final ToApiJsonSerializer toApiJsonSerializer; @Autowired - public NotificationApiResource(PlatformSecurityContext context, - NotificationReadPlatformService notificationReadPlatformService, - ApiRequestParameterHelper apiRequestParameterHelper, - ToApiJsonSerializer toApiJsonSerializer) { + public NotificationApiResource(PlatformSecurityContext context, NotificationReadPlatformService notificationReadPlatformService, + ApiRequestParameterHelper apiRequestParameterHelper, ToApiJsonSerializer toApiJsonSerializer) { this.context = context; this.notificationReadPlatformService = notificationReadPlatformService; this.apiRequestParameterHelper = apiRequestParameterHelper; @@ -69,13 +64,11 @@ public class NotificationApiResource { } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public String getAllNotifications(@Context final UriInfo uriInfo, @QueryParam("orderBy") final String orderBy, - @QueryParam("limit") final Integer limit, - @QueryParam("offset") final Integer offset, - @QueryParam("sortOrder") final String sortOrder, - @QueryParam("isRead") final boolean isRead) { + @QueryParam("limit") final Integer limit, @QueryParam("offset") final Integer offset, + @QueryParam("sortOrder") final String sortOrder, @QueryParam("isRead") final boolean isRead) { this.context.authenticatedUser(); final Page notificationData; @@ -85,14 +78,13 @@ public class NotificationApiResource { } else { notificationData = this.notificationReadPlatformService.getAllNotifications(searchParameters); } - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, notificationData); } @PUT - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public void update() { this.context.authenticatedUser(); this.notificationReadPlatformService.updateNotificationReadStatus(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/cache/CacheNotificationResponseHeader.java b/fineract-provider/src/main/java/org/apache/fineract/notification/cache/CacheNotificationResponseHeader.java index 205050b78..5f2d50c19 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/cache/CacheNotificationResponseHeader.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/cache/CacheNotificationResponseHeader.java @@ -18,14 +18,12 @@ */ package org.apache.fineract.notification.cache; - public class CacheNotificationResponseHeader { private boolean hasNotifications; private Long lastFetch; - public CacheNotificationResponseHeader() { - } + public CacheNotificationResponseHeader() {} public CacheNotificationResponseHeader(boolean hasNotifications, Long lastFetch) { this.hasNotifications = hasNotifications; diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/config/MessagingConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/notification/config/MessagingConfiguration.java index f1f7137bf..30a73d1bf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/config/MessagingConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/config/MessagingConfiguration.java @@ -42,16 +42,18 @@ public class MessagingConfiguration { private NotificationEventListener notificationEventListener; @Bean - public Logger loggerBean() { return LoggerFactory.getLogger(MessagingConfiguration.class); } + public Logger loggerBean() { + return LoggerFactory.getLogger(MessagingConfiguration.class); + } private static final String DEFAULT_BROKER_URL = "tcp://localhost:61616"; @Bean - public ActiveMQConnectionFactory amqConnectionFactory(){ + public ActiveMQConnectionFactory amqConnectionFactory() { ActiveMQConnectionFactory amqConnectionFactory = new ActiveMQConnectionFactory(); try { amqConnectionFactory.setBrokerURL(DEFAULT_BROKER_URL); - } catch(Exception e) { + } catch (Exception e) { amqConnectionFactory.setBrokerURL(this.env.getProperty("brokerUrl")); } return amqConnectionFactory; @@ -64,11 +66,11 @@ public class MessagingConfiguration { } @Bean - public JmsTemplate jmsTemplate(){ - JmsTemplate jmsTemplate ; - jmsTemplate = new JmsTemplate(connectionFactory()); - jmsTemplate.setConnectionFactory(connectionFactory()); - return jmsTemplate; + public JmsTemplate jmsTemplate() { + JmsTemplate jmsTemplate; + jmsTemplate = new JmsTemplate(connectionFactory()); + jmsTemplate.setConnectionFactory(connectionFactory()); + return jmsTemplate; } @Bean @@ -79,9 +81,9 @@ public class MessagingConfiguration { messageListenerContainer.setDestinationName("NotificationQueue"); messageListenerContainer.setMessageListener(notificationEventListener); messageListenerContainer.setExceptionListener(new ExceptionListener() { + @Override - public void onException(JMSException jmse) - { + public void onException(JMSException jmse) { loggerBean().error("Network Error: ActiveMQ Broker Unavailable."); messageListenerContainer.shutdown(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/data/NotificationData.java b/fineract-provider/src/main/java/org/apache/fineract/notification/data/NotificationData.java index bcfb3cf36..978970220 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/data/NotificationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/data/NotificationData.java @@ -36,8 +36,7 @@ public class NotificationData implements Serializable { private Long officeId; private List userIds; - public NotificationData() { - } + public NotificationData() {} public NotificationData(String objectType, Long objectId, String action, Long actorId, String content, boolean isSystemGenerated, boolean isRead, String tenantIdentifier, Long officeId, List userIds) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/data/TopicData.java b/fineract-provider/src/main/java/org/apache/fineract/notification/data/TopicData.java index c6f957390..9ab2ced60 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/data/TopicData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/data/TopicData.java @@ -29,8 +29,7 @@ public class TopicData implements Serializable { private final String entityType; private final String memberType; - public TopicData(Long id, String title, boolean enabled, Long entityId, String entityType, - String memberType) { + public TopicData(Long id, String title, boolean enabled, Long entityId, String entityType, String memberType) { this.id = id; this.title = title; this.enabled = enabled; @@ -39,8 +38,7 @@ public class TopicData implements Serializable { this.memberType = memberType; } - public TopicData(Long id, String title, Long entityId, String entityType, - String memberType) { + public TopicData(Long id, String title, Long entityId, String entityType, String memberType) { this.id = id; this.title = title; this.enabled = true; diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/Notification.java b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/Notification.java index d5ec5800d..fcc403c7d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/Notification.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/Notification.java @@ -115,4 +115,4 @@ public class Notification extends AbstractPersistableCustom { + ", actorId=" + this.actorId + ", isSystemGenerated=" + this.isSystemGenerated + ", notificationContent=" + this.notificationContent + ", createdAt=" + this.createdAt + ", getId()=" + this.getId() + "]"; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/NotificationMapper.java b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/NotificationMapper.java index 13a41cfbc..670a58bdb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/NotificationMapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/NotificationMapper.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.notification.domain; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/NotificationRepository.java b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/NotificationRepository.java index ed0675d73..6b9160ffd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/NotificationRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/NotificationRepository.java @@ -20,5 +20,4 @@ package org.apache.fineract.notification.domain; import org.springframework.data.jpa.repository.JpaRepository; - public interface NotificationRepository extends JpaRepository {} diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/Topic.java b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/Topic.java index 081fa27b2..80a530069 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/Topic.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/Topic.java @@ -43,8 +43,7 @@ public class Topic extends AbstractPersistableCustom { @Column(name = "member_type") private String memberType; - public Topic() { - } + public Topic() {} public Topic(String title, Boolean enabled, Long entityId, String entityType, String memberType) { this.title = title.trim(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicRepository.java b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicRepository.java index 3c1182d3f..c3b3edb76 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicRepository.java @@ -23,6 +23,8 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface TopicRepository extends JpaRepository, JpaSpecificationExecutor { + List findByEntityId(Long entityId); + List findByMemberType(String memberType); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicSubscriber.java b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicSubscriber.java index cf58ceb59..918d4a047 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicSubscriber.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicSubscriber.java @@ -42,8 +42,7 @@ public class TopicSubscriber extends AbstractPersistableCustom { @Column(name = "subscription_date") private Date subscriptionDate; - public TopicSubscriber() { - } + public TopicSubscriber() {} public TopicSubscriber(Topic topic, AppUser subscriber, Date subscriptionDate) { this.topic = topic; diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicSubscriberRepository.java b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicSubscriberRepository.java index b7852ea96..09a75de6c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicSubscriberRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/domain/TopicSubscriberRepository.java @@ -24,5 +24,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface TopicSubscriberRepository extends JpaRepository, JpaSpecificationExecutor { + List findBySubscriber(AppUser subscriber); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/NotificationEventListener.java b/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/NotificationEventListener.java index db830b577..84fbc5fca 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/NotificationEventListener.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/NotificationEventListener.java @@ -47,8 +47,7 @@ public class NotificationEventListener implements SessionAwareMessageListener { @Autowired public NotificationEventListener(BasicAuthTenantDetailsService basicAuthTenantDetailsService, - NotificationWritePlatformService notificationWritePlatformService, - AppUserRepository appUserRepository) { + NotificationWritePlatformService notificationWritePlatformService, AppUserRepository appUserRepository) { this.basicAuthTenantDetailsService = basicAuthTenantDetailsService; this.notificationWritePlatformService = notificationWritePlatformService; this.appUserRepository = appUserRepository; @@ -59,8 +58,8 @@ public class NotificationEventListener implements SessionAwareMessageListener { if (message instanceof ObjectMessage) { NotificationData notificationData = (NotificationData) ((ObjectMessage) message).getObject(); - final FineractPlatformTenant tenant = this.basicAuthTenantDetailsService - .loadTenantById(notificationData.getTenantIdentifier(), false); + final FineractPlatformTenant tenant = this.basicAuthTenantDetailsService.loadTenantById(notificationData.getTenantIdentifier(), + false); ThreadLocalContextUtil.setTenant(tenant); Long appUserId = notificationData.getActor(); @@ -81,15 +80,9 @@ public class NotificationEventListener implements SessionAwareMessageListener { userIds.remove(appUserId); } - notificationWritePlatformService.notify( - userIds, - notificationData.getObjectType(), - notificationData.getObjectIdentfier(), - notificationData.getAction(), - notificationData.getActor(), - notificationData.getContent(), - notificationData.isSystemGenerated() - ); + notificationWritePlatformService.notify(userIds, notificationData.getObjectType(), notificationData.getObjectIdentfier(), + notificationData.getAction(), notificationData.getActor(), notificationData.getContent(), + notificationData.isSystemGenerated()); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/NotificationEventService.java b/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/NotificationEventService.java index 1c16df28d..801754121 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/NotificationEventService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/NotificationEventService.java @@ -40,6 +40,7 @@ public class NotificationEventService { public void broadcastNotification(final Destination destination, final NotificationData notificationData) { this.jmsTemplate.send(destination, new MessageCreator() { + @Override public Message createMessage(Session session) throws JMSException { return session.createObjectMessage(notificationData); diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEventListener.java b/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEventListener.java index f37b7ab88..942ebe82b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEventListener.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEventListener.java @@ -43,8 +43,7 @@ public class SpringEventListener implements ApplicationListener { @Autowired public SpringEventListener(BasicAuthTenantDetailsService basicAuthTenantDetailsService, - NotificationWritePlatformService notificationWritePlatformService, - AppUserRepository appUserRepository) { + NotificationWritePlatformService notificationWritePlatformService, AppUserRepository appUserRepository) { this.basicAuthTenantDetailsService = basicAuthTenantDetailsService; this.notificationWritePlatformService = notificationWritePlatformService; this.appUserRepository = appUserRepository; @@ -54,8 +53,8 @@ public class SpringEventListener implements ApplicationListener { public void onApplicationEvent(SpringEvent event) { NotificationData notificationData = event.getNotificationData(); - final FineractPlatformTenant tenant = this.basicAuthTenantDetailsService - .loadTenantById(notificationData.getTenantIdentifier(), false); + final FineractPlatformTenant tenant = this.basicAuthTenantDetailsService.loadTenantById(notificationData.getTenantIdentifier(), + false); ThreadLocalContextUtil.setTenant(tenant); Long appUserId = notificationData.getActor(); @@ -76,15 +75,9 @@ public class SpringEventListener implements ApplicationListener { userIds.remove(appUserId); } - notificationWritePlatformService.notify( - userIds, - notificationData.getObjectType(), - notificationData.getObjectIdentfier(), - notificationData.getAction(), - notificationData.getActor(), - notificationData.getContent(), - notificationData.isSystemGenerated() - ); + notificationWritePlatformService.notify(userIds, notificationData.getObjectType(), notificationData.getObjectIdentfier(), + notificationData.getAction(), notificationData.getActor(), notificationData.getContent(), + notificationData.isSystemGenerated()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEventPublisher.java b/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEventPublisher.java index 2efc079e0..3de0f1758 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEventPublisher.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/eventandlistener/SpringEventPublisher.java @@ -25,6 +25,7 @@ import org.springframework.stereotype.Service; @Service public class SpringEventPublisher { + @Autowired private ApplicationEventPublisher applicationEventPublisher; diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationDomainServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationDomainServiceImpl.java index 64ccbb6a5..d1a1593de 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationDomainServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationDomainServiceImpl.java @@ -67,9 +67,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService @Autowired public NotificationDomainServiceImpl(final BusinessEventNotifierService businessEventNotifierService, final PlatformSecurityContext context, final RoleRepository roleRepository, - final TopicSubscriberReadPlatformService topicSubscriberReadPlatformService, - final OfficeRepository officeRepository, final NotificationEventService notificationEvent, - final SpringEventPublisher springEventPublisher) { + final TopicSubscriberReadPlatformService topicSubscriberReadPlatformService, final OfficeRepository officeRepository, + final NotificationEventService notificationEvent, final SpringEventPublisher springEventPublisher) { this.businessEventNotifierService = businessEventNotifierService; this.context = context; @@ -82,53 +81,38 @@ public class NotificationDomainServiceImpl implements NotificationDomainService @PostConstruct public void addListeners() { - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.CLIENTS_CREATE, - new ClientCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_APPROVE, - new SavingsAccountApprovedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.CENTERS_CREATE, - new CenterCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.GROUPS_CREATE, - new GroupCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_DEPOSIT, - new SavingsAccountDepositListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.CLIENTS_CREATE, new ClientCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_APPROVE, new SavingsAccountApprovedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.CENTERS_CREATE, new CenterCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.GROUPS_CREATE, new GroupCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_DEPOSIT, new SavingsAccountDepositListener()); businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SHARE_PRODUCT_DIVIDENDS_CREATE, new ShareProductDividendCreatedListener()); businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.FIXED_DEPOSIT_ACCOUNT_CREATE, new FixedDepositAccountCreatedListener()); businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.RECURRING_DEPOSIT_ACCOUNT_CREATE, new RecurringDepositAccountCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_POST_INTEREST, - new SavingsPostInterestListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_CREATE, - new LoanCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_APPROVED, - new LoanApprovedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_CLOSE, - new LoanClosedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_POST_INTEREST, new SavingsPostInterestListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_CREATE, new LoanCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_APPROVED, new LoanApprovedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_CLOSE, new LoanClosedListener()); businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_CLOSE_AS_RESCHEDULE, new LoanCloseAsRescheduledListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_MAKE_REPAYMENT, - new LoanMakeRepaymentListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_PRODUCT_CREATE, - new LoanProductCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_CREATE, - new SavingsAccountCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_CLOSE, - new SavingsAccountClosedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SHARE_ACCOUNT_CREATE, - new ShareAccountCreatedListener()); - businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SHARE_ACCOUNT_APPROVE, - new ShareAccountApprovedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_MAKE_REPAYMENT, new LoanMakeRepaymentListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.LOAN_PRODUCT_CREATE, new LoanProductCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_CREATE, new SavingsAccountCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SAVINGS_CLOSE, new SavingsAccountClosedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SHARE_ACCOUNT_CREATE, new ShareAccountCreatedListener()); + businessEventNotifierService.addBusinessEventPostListners(BusinessEvents.SHARE_ACCOUNT_APPROVE, new ShareAccountApprovedListener()); } private abstract class NotificationBusinessEventAdapter implements BusinessEventListner { + @Override - public void businessEventToBeExecuted(Map businessEventEntity) { - } + public void businessEventToBeExecuted(Map businessEventEntity) {} } - private class ClientCreatedListener extends NotificationBusinessEventAdapter { + private class ClientCreatedListener extends NotificationBusinessEventAdapter { @Override public void businessEventWasExecuted(Map businessEventEntity) { @@ -136,15 +120,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BusinessEntity.CLIENT); if (entity != null) { client = (Client) entity; - buildNotification( - "ACTIVATE_CLIENT", - "client", - client.getId(), - "New client created", - "created", - context.authenticatedUser().getId(), - client.getOffice().getId() - ); + buildNotification("ACTIVATE_CLIENT", "client", client.getId(), "New client created", "created", + context.authenticatedUser().getId(), client.getOffice().getId()); } } } @@ -157,20 +134,13 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.GROUP); if (entity != null) { commandProcessingResult = (CommandProcessingResult) entity; - buildNotification( - "ACTIVATE_CENTER", - "center", - commandProcessingResult.getGroupId(), - "New center created", - "created", - context.authenticatedUser().getId(), - commandProcessingResult.getOfficeId() - ); + buildNotification("ACTIVATE_CENTER", "center", commandProcessingResult.getGroupId(), "New center created", "created", + context.authenticatedUser().getId(), commandProcessingResult.getOfficeId()); } } } - private class GroupCreatedListener extends NotificationBusinessEventAdapter { + private class GroupCreatedListener extends NotificationBusinessEventAdapter { @Override public void businessEventWasExecuted(Map businessEventEntity) { @@ -178,20 +148,13 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.GROUP); if (entity != null) { commandProcessingResult = (CommandProcessingResult) entity; - buildNotification( - "ACTIVATE_GROUP", - "group", - commandProcessingResult.getGroupId(), - "New group created", - "created", - context.authenticatedUser().getId(), - commandProcessingResult.getOfficeId() - ); + buildNotification("ACTIVATE_GROUP", "group", commandProcessingResult.getGroupId(), "New group created", "created", + context.authenticatedUser().getId(), commandProcessingResult.getOfficeId()); } } } - private class SavingsAccountDepositListener extends NotificationBusinessEventAdapter { + private class SavingsAccountDepositListener extends NotificationBusinessEventAdapter { @Override public void businessEventWasExecuted(Map businessEventEntity) { @@ -199,15 +162,9 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.SAVINGS_TRANSACTION); if (entity != null) { savingsAccountTransaction = (SavingsAccountTransaction) entity; - buildNotification( - "READ_SAVINGSACCOUNT", - "savingsAccount", - savingsAccountTransaction.getSavingsAccount().getId(), - "Deposit made", - "depositMade", - context.authenticatedUser().getId(), - savingsAccountTransaction.getSavingsAccount().officeId() - ); + buildNotification("READ_SAVINGSACCOUNT", "savingsAccount", savingsAccountTransaction.getSavingsAccount().getId(), + "Deposit made", "depositMade", context.authenticatedUser().getId(), + savingsAccountTransaction.getSavingsAccount().officeId()); } } } @@ -220,15 +177,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.SHARE_PRODUCT); if (entity != null) { shareProductId = (Long) entity; - buildNotification( - "READ_DIVIDEND_SHAREPRODUCT", - "shareProduct", - shareProductId, - "Dividend posted to account", - "dividendPosted", - context.authenticatedUser().getId(), - context.authenticatedUser().getOffice().getId() - ); + buildNotification("READ_DIVIDEND_SHAREPRODUCT", "shareProduct", shareProductId, "Dividend posted to account", + "dividendPosted", context.authenticatedUser().getId(), context.authenticatedUser().getOffice().getId()); } } } @@ -241,15 +191,9 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.DEPOSIT_ACCOUNT); if (entity != null) { fixedDepositAccount = (FixedDepositAccount) entity; - buildNotification( - "APPROVE_FIXEDDEPOSITACCOUNT", - "fixedDeposit", - fixedDepositAccount.getId(), - "New fixed deposit account created", - "created", - context.authenticatedUser().getId(), - fixedDepositAccount.officeId() - ); + buildNotification("APPROVE_FIXEDDEPOSITACCOUNT", "fixedDeposit", fixedDepositAccount.getId(), + "New fixed deposit account created", "created", context.authenticatedUser().getId(), + fixedDepositAccount.officeId()); } } } @@ -262,15 +206,9 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.DEPOSIT_ACCOUNT); if (entity != null) { recurringDepositAccount = (RecurringDepositAccount) entity; - buildNotification( - "APPROVE_RECURRINGDEPOSITACCOUNT", - "recurringDepositAccount", - recurringDepositAccount.getId(), - "New recurring deposit account created", - "created", - context.authenticatedUser().getId(), - recurringDepositAccount.officeId() - ); + buildNotification("APPROVE_RECURRINGDEPOSITACCOUNT", "recurringDepositAccount", recurringDepositAccount.getId(), + "New recurring deposit account created", "created", context.authenticatedUser().getId(), + recurringDepositAccount.officeId()); } } } @@ -279,43 +217,23 @@ public class NotificationDomainServiceImpl implements NotificationDomainService @Override public void businessEventWasExecuted(Map businessEventEntity) { - SavingsAccount savingsAccount; + SavingsAccount savingsAccount; Object entity = businessEventEntity.get(BusinessEntity.SAVING); if (entity != null) { savingsAccount = (SavingsAccount) entity; if (savingsAccount.depositAccountType().equals(DepositAccountType.FIXED_DEPOSIT)) { - buildNotification( - "ACTIVATE_FIXEDDEPOSITACCOUNT", - "fixedDeposit", - savingsAccount.getId(), - "Fixed deposit account approved", - "approved", - context.authenticatedUser().getId(), - savingsAccount.officeId() - ); + buildNotification("ACTIVATE_FIXEDDEPOSITACCOUNT", "fixedDeposit", savingsAccount.getId(), + "Fixed deposit account approved", "approved", context.authenticatedUser().getId(), savingsAccount.officeId()); } else if (savingsAccount.depositAccountType().equals(DepositAccountType.RECURRING_DEPOSIT)) { - buildNotification( - "ACTIVATE_RECURRINGDEPOSITACCOUNT", - "recurringDepositAccount", - savingsAccount.getId(), - "Recurring deposit account approved", - "approved", - context.authenticatedUser().getId(), - savingsAccount.officeId() - ); + buildNotification("ACTIVATE_RECURRINGDEPOSITACCOUNT", "recurringDepositAccount", savingsAccount.getId(), + "Recurring deposit account approved", "approved", context.authenticatedUser().getId(), + savingsAccount.officeId()); } else if (savingsAccount.depositAccountType().equals(DepositAccountType.SAVINGS_DEPOSIT)) { - buildNotification( - "ACTIVATE_SAVINGSACCOUNT", - "savingsAccount", - savingsAccount.getId(), - "Savings account approved", - "approved", - context.authenticatedUser().getId(), - savingsAccount.officeId() - ); + buildNotification("ACTIVATE_SAVINGSACCOUNT", "savingsAccount", savingsAccount.getId(), "Savings account approved", + "approved", context.authenticatedUser().getId(), savingsAccount.officeId()); } } } @@ -329,15 +247,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.SAVING); if (entity != null) { savingsAccount = (SavingsAccount) entity; - buildNotification( - "READ_SAVINGSACCOUNT", - "savingsAccount", - savingsAccount.getId(), - "Interest posted to account", - "interestPosted", - context.authenticatedUser().getId(), - savingsAccount.officeId() - ); + buildNotification("READ_SAVINGSACCOUNT", "savingsAccount", savingsAccount.getId(), "Interest posted to account", + "interestPosted", context.authenticatedUser().getId(), savingsAccount.officeId()); } } } @@ -350,15 +261,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.LOAN); if (entity != null) { loan = (Loan) entity; - buildNotification( - "APPROVE_LOAN", - "loan", - loan.getId(), - "New loan created", - "created", - context.authenticatedUser().getId(), - loan.getOfficeId() - ); + buildNotification("APPROVE_LOAN", "loan", loan.getId(), "New loan created", "created", context.authenticatedUser().getId(), + loan.getOfficeId()); } } @@ -372,15 +276,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.LOAN); if (entity != null) { loan = (Loan) entity; - buildNotification( - "DISBURSE_LOAN", - "loan", - loan.getId(), - "New loan approved", - "approved", - context.authenticatedUser().getId(), - loan.getOfficeId() - ); + buildNotification("DISBURSE_LOAN", "loan", loan.getId(), "New loan approved", "approved", + context.authenticatedUser().getId(), loan.getOfficeId()); } } } @@ -394,15 +291,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.LOAN); if (entity != null) { loan = (Loan) entity; - buildNotification( - "READ_LOAN", - "loan", - loan.getId(), - "Loan closed", - "loanClosed", - context.authenticatedUser().getId(), - loan.getOfficeId() - ); + buildNotification("READ_LOAN", "loan", loan.getId(), "Loan closed", "loanClosed", context.authenticatedUser().getId(), + loan.getOfficeId()); } } } @@ -415,15 +305,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.LOAN); if (entity != null) { loan = (Loan) entity; - buildNotification( - "READ_Rescheduled Loans", - "loan", - loan.getId(), - "Loan has been rescheduled", - "loanRescheduled", - context.authenticatedUser().getId(), - loan.getOfficeId() - ); + buildNotification("READ_Rescheduled Loans", "loan", loan.getId(), "Loan has been rescheduled", "loanRescheduled", + context.authenticatedUser().getId(), loan.getOfficeId()); } } } @@ -436,15 +319,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.LOAN); if (entity != null) { loan = (Loan) entity; - buildNotification( - "READ_LOAN", - "loan", - loan.getId(), - "Repayment made", - "repaymentMade", - context.authenticatedUser().getId(), - loan.getOfficeId() - ); + buildNotification("READ_LOAN", "loan", loan.getId(), "Repayment made", "repaymentMade", context.authenticatedUser().getId(), + loan.getOfficeId()); } } } @@ -458,15 +334,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.LOAN_PRODUCT); if (entity != null) { loanProduct = (LoanProduct) entity; - buildNotification( - "READ_LOANPRODUCT", - "loanProduct", - loanProduct.getId(), - "New loan product created", - "created", - context.authenticatedUser().getId(), - context.authenticatedUser().getOffice().getId() - ); + buildNotification("READ_LOANPRODUCT", "loanProduct", loanProduct.getId(), "New loan product created", "created", + context.authenticatedUser().getId(), context.authenticatedUser().getOffice().getId()); } } } @@ -475,19 +344,12 @@ public class NotificationDomainServiceImpl implements NotificationDomainService @Override public void businessEventWasExecuted(Map businessEventEntity) { - SavingsAccount savingsAccount; + SavingsAccount savingsAccount; Object entity = businessEventEntity.get(BusinessEntity.SAVING); if (entity != null) { savingsAccount = (SavingsAccount) entity; - buildNotification( - "APPROVE_SAVINGSACCOUNT", - "savingsAccount", - savingsAccount.getId(), - "New savings account created", - "created", - context.authenticatedUser().getId(), - savingsAccount.officeId() - ); + buildNotification("APPROVE_SAVINGSACCOUNT", "savingsAccount", savingsAccount.getId(), "New savings account created", + "created", context.authenticatedUser().getId(), savingsAccount.officeId()); } } } @@ -496,19 +358,12 @@ public class NotificationDomainServiceImpl implements NotificationDomainService @Override public void businessEventWasExecuted(Map businessEventEntity) { - SavingsAccount savingsAccount; + SavingsAccount savingsAccount; Object entity = businessEventEntity.get(BusinessEntity.SAVING); if (entity != null) { savingsAccount = (SavingsAccount) entity; - buildNotification( - "READ_SAVINGSACCOUNT", - "savingsAccount", - savingsAccount.getId(), - "Savings has gone into dormant", - "closed", - context.authenticatedUser().getId(), - savingsAccount.officeId() - ); + buildNotification("READ_SAVINGSACCOUNT", "savingsAccount", savingsAccount.getId(), "Savings has gone into dormant", + "closed", context.authenticatedUser().getId(), savingsAccount.officeId()); } } } @@ -521,15 +376,8 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.SHARE_ACCOUNT); if (entity != null) { shareAccount = (ShareAccount) entity; - buildNotification( - "APPROVE_SHAREACCOUNT", - "shareAccount", - shareAccount.getId(), - "New share account created", - "created", - context.authenticatedUser().getId(), - shareAccount.getOfficeId() - ); + buildNotification("APPROVE_SHAREACCOUNT", "shareAccount", shareAccount.getId(), "New share account created", "created", + context.authenticatedUser().getId(), shareAccount.getOfficeId()); } } } @@ -542,40 +390,23 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Object entity = businessEventEntity.get(BusinessEntity.SHARE_ACCOUNT); if (entity != null) { shareAccount = (ShareAccount) entity; - buildNotification( - "ACTIVATE_SHAREACCOUNT", - "shareAccount", - shareAccount.getId(), - "Share account approved", - "approved", - context.authenticatedUser().getId(), - shareAccount.getOfficeId() - ); + buildNotification("ACTIVATE_SHAREACCOUNT", "shareAccount", shareAccount.getId(), "Share account approved", "approved", + context.authenticatedUser().getId(), shareAccount.getOfficeId()); } } } - private void buildNotification(String permission, String objectType, Long objectIdentifier, - String notificationContent, String eventType, Long appUserId, Long officeId) { + private void buildNotification(String permission, String objectType, Long objectIdentifier, String notificationContent, + String eventType, Long appUserId, Long officeId) { String tenantIdentifier = ThreadLocalContextUtil.getTenant().getTenantIdentifier(); Queue queue = new ActiveMQQueue("NotificationQueue"); List userIds = retrieveSubscribers(officeId, permission); - NotificationData notificationData = new NotificationData( - objectType, - objectIdentifier, - eventType, - appUserId, - notificationContent, - false, - false, - tenantIdentifier, - officeId, - userIds - ); + NotificationData notificationData = new NotificationData(objectType, objectIdentifier, eventType, appUserId, notificationContent, + false, false, tenantIdentifier, officeId, userIds); try { this.notificationEvent.broadcastNotification(queue, notificationData); - } catch(Exception e) { + } catch (Exception e) { this.springEventPublisher.broadcastNotification(notificationData); } } @@ -585,7 +416,7 @@ public class NotificationDomainServiceImpl implements NotificationDomainService Set topicSubscribers = new HashSet<>(); List subscriberIds = new ArrayList<>(); Long entityId = officeId; - String entityType= ""; + String entityType = ""; if (officeRepository.findById(entityId).get().getParent() == null) { entityType = "OFFICE"; } else { @@ -601,7 +432,7 @@ public class NotificationDomainServiceImpl implements NotificationDomainService for (TopicSubscriberData topicSubscriber : topicSubscribers) { subscriberIds.add(topicSubscriber.getUserId()); - } - return subscriberIds; + } + return subscriberIds; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorReadRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorReadRepositoryWrapper.java index 3e85374c6..67cbf3f52 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorReadRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorReadRepositoryWrapper.java @@ -21,10 +21,8 @@ package org.apache.fineract.notification.service; import java.util.List; import org.apache.fineract.notification.domain.Notification; - public interface NotificationGeneratorReadRepositoryWrapper { - Notification findById(Long id); List fetchAllNotifications(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorReadRepositoryWrapperImpl.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorReadRepositoryWrapperImpl.java index fbad3631e..1267aa585 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorReadRepositoryWrapperImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorReadRepositoryWrapperImpl.java @@ -46,7 +46,7 @@ public class NotificationGeneratorReadRepositoryWrapperImpl implements Notificat @Override public void delete(Long id) { - this.notificationRepository.deleteById(id); + this.notificationRepository.deleteById(id); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorWritePlatformService.java index 1941955a2..94feb917d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationGeneratorWritePlatformService.java @@ -20,7 +20,7 @@ package org.apache.fineract.notification.service; import org.apache.fineract.notification.domain.Notification; -public interface NotificationGeneratorWritePlatformService { +public interface NotificationGeneratorWritePlatformService { Long create(Notification notification); diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationMapperReadRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationMapperReadRepositoryWrapper.java index 1dda23574..6abc64b23 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationMapperReadRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationMapperReadRepositoryWrapper.java @@ -23,7 +23,6 @@ import org.apache.fineract.notification.domain.NotificationMapper; public interface NotificationMapperReadRepositoryWrapper { - NotificationMapper findById(Long id); List fetchAllNotifications(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationMapperWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationMapperWritePlatformService.java index 72c2ded9e..fe8b13aba 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationMapperWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationMapperWritePlatformService.java @@ -20,7 +20,6 @@ package org.apache.fineract.notification.service; import org.apache.fineract.notification.domain.NotificationMapper; - public interface NotificationMapperWritePlatformService { Long create(NotificationMapper notificationMapper); diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationReadPlatformServiceImpl.java index 51da4a577..d1fb3127a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationReadPlatformServiceImpl.java @@ -46,12 +46,10 @@ public class NotificationReadPlatformServiceImpl implements NotificationReadPlat private final PaginationHelper paginationHelper = new PaginationHelper<>(); private final NotificationDataRow notificationDataRow = new NotificationDataRow(); private final NotificationMapperRow notificationMapperRow = new NotificationMapperRow(); - private HashMap> - tenantNotificationResponseHeaderCache = new HashMap<>(); + private HashMap> tenantNotificationResponseHeaderCache = new HashMap<>(); @Autowired - public NotificationReadPlatformServiceImpl(final RoutingDataSource dataSource, - final PlatformSecurityContext context, + public NotificationReadPlatformServiceImpl(final RoutingDataSource dataSource, final PlatformSecurityContext context, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.context = context; @@ -61,10 +59,10 @@ public class NotificationReadPlatformServiceImpl implements NotificationReadPlat @Override public boolean hasUnreadNotifications(Long appUserId) { Long tenantId = ThreadLocalContextUtil.getTenant().getId(); - Long now = System.currentTimeMillis()/1000L; + Long now = System.currentTimeMillis() / 1000L; if (this.tenantNotificationResponseHeaderCache.containsKey(tenantId)) { - HashMap notificationResponseHeaderCache = - this.tenantNotificationResponseHeaderCache.get(tenantId); + HashMap notificationResponseHeaderCache = this.tenantNotificationResponseHeaderCache + .get(tenantId); if (notificationResponseHeaderCache.containsKey(appUserId)) { Long lastFetch = notificationResponseHeaderCache.get(appUserId).getLastFetch(); if ((now - lastFetch) > 1) { @@ -87,8 +85,8 @@ public class NotificationReadPlatformServiceImpl implements NotificationReadPlat return this.createUpdateCacheValue(appUserId, now, notificationResponseHeaderCache); } - private boolean createUpdateCacheValue(Long appUserId, Long now, HashMap notificationResponseHeaderCache) { + private boolean createUpdateCacheValue(Long appUserId, Long now, + HashMap notificationResponseHeaderCache) { boolean hasNotifications; Long tenantId = ThreadLocalContextUtil.getTenant().getId(); CacheNotificationResponseHeader cacheNotificationResponseHeader; @@ -100,12 +98,9 @@ public class NotificationReadPlatformServiceImpl implements NotificationReadPlat } private boolean checkForUnreadNotifications(Long appUserId) { - String sql = "SELECT id, notification_id as notificationId, user_id as userId, is_read as isRead, created_at " + - "as createdAt FROM notification_mapper WHERE user_id = ? AND is_read = false"; - List notificationMappers = this.jdbcTemplate.query( - sql, - notificationMapperRow, - appUserId); + String sql = "SELECT id, notification_id as notificationId, user_id as userId, is_read as isRead, created_at " + + "as createdAt FROM notification_mapper WHERE user_id = ? AND is_read = false"; + List notificationMappers = this.jdbcTemplate.query(sql, notificationMapperRow, appUserId); return notificationMappers.size() > 0; } @@ -119,24 +114,23 @@ public class NotificationReadPlatformServiceImpl implements NotificationReadPlat @Override public Page getAllUnreadNotifications(final SearchParameters searchParameters) { final Long appUserId = context.authenticatedUser().getId(); - String sql = "SELECT SQL_CALC_FOUND_ROWS ng.id as id, nm.user_id as userId, ng.object_type as objectType, " + - "ng.object_identifier as objectId, ng.actor as actor, ng.action action, ng.notification_content " + - "as content, ng.is_system_generated as isSystemGenerated, nm.created_at as createdAt " + - "FROM notification_mapper nm INNER JOIN notification_generator ng ON nm.notification_id = ng.id " + - "WHERE nm.user_id = ? AND nm.is_read = false order by nm.created_at desc"; + String sql = "SELECT SQL_CALC_FOUND_ROWS ng.id as id, nm.user_id as userId, ng.object_type as objectType, " + + "ng.object_identifier as objectId, ng.actor as actor, ng.action action, ng.notification_content " + + "as content, ng.is_system_generated as isSystemGenerated, nm.created_at as createdAt " + + "FROM notification_mapper nm INNER JOIN notification_generator ng ON nm.notification_id = ng.id " + + "WHERE nm.user_id = ? AND nm.is_read = false order by nm.created_at desc"; return getNotificationDataPage(searchParameters, appUserId, sql); } - @Override public Page getAllNotifications(SearchParameters searchParameters) { final Long appUserId = context.authenticatedUser().getId(); - String sql = "SELECT SQL_CALC_FOUND_ROWS ng.id as id, nm.user_id as userId, ng.object_type as objectType, " + - "ng.object_identifier as objectId, ng.actor as actor, ng.action action, ng.notification_content " + - "as content, ng.is_system_generated as isSystemGenerated, nm.created_at as createdAt " + - "FROM notification_mapper nm INNER JOIN notification_generator ng ON nm.notification_id = ng.id " + - "WHERE nm.user_id = ? order by nm.created_at desc"; + String sql = "SELECT SQL_CALC_FOUND_ROWS ng.id as id, nm.user_id as userId, ng.object_type as objectType, " + + "ng.object_identifier as objectId, ng.actor as actor, ng.action action, ng.notification_content " + + "as content, ng.is_system_generated as isSystemGenerated, nm.created_at as createdAt " + + "FROM notification_mapper nm INNER JOIN notification_generator ng ON nm.notification_id = ng.id " + + "WHERE nm.user_id = ? order by nm.created_at desc"; return getNotificationDataPage(searchParameters, appUserId, sql); } @@ -162,9 +156,8 @@ public class NotificationReadPlatformServiceImpl implements NotificationReadPlat } final String sqlCountRows = "SELECT FOUND_ROWS()"; - Object[] params = new Object[]{appUserId}; - return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), - params, this.notificationDataRow); + Object[] params = new Object[] { appUserId }; + return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), params, this.notificationDataRow); } private static final class NotificationMapperRow implements RowMapper { @@ -225,4 +218,4 @@ public class NotificationReadPlatformServiceImpl implements NotificationReadPlat return notificationData; } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationWritePlatformService.java index 703cf8e18..e2a51d441 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationWritePlatformService.java @@ -21,9 +21,10 @@ package org.apache.fineract.notification.service; import java.util.List; public interface NotificationWritePlatformService { - Long notify(Long userId, String objectType, Long objectId, String action, - Long actorId, String notificationContent, boolean isSystemGenerated); - Long notify(List userIds, String objectType, Long objectId, String action, - Long actorId, String notificationContent, boolean isSystemGenerated); + Long notify(Long userId, String objectType, Long objectId, String action, Long actorId, String notificationContent, + boolean isSystemGenerated); + + Long notify(List userIds, String objectType, Long objectId, String action, Long actorId, String notificationContent, + boolean isSystemGenerated); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationWritePlatformServiceImpl.java index 8d5b52c1b..3318bdc5b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/NotificationWritePlatformServiceImpl.java @@ -41,8 +41,7 @@ public class NotificationWritePlatformServiceImpl implements NotificationWritePl private final NotificationMapperWritePlatformService notificationMapperWritePlatformService; @Autowired - public NotificationWritePlatformServiceImpl( - final NotificationGeneratorWritePlatformService notificationGeneratorWritePlatformService, + public NotificationWritePlatformServiceImpl(final NotificationGeneratorWritePlatformService notificationGeneratorWritePlatformService, final NotificationGeneratorReadRepositoryWrapper notificationGeneratorReadRepositoryWrapper, final AppUserRepository appUserRepository, final NotificationMapperWritePlatformService notificationMapperWritePlatformService) { @@ -52,13 +51,12 @@ public class NotificationWritePlatformServiceImpl implements NotificationWritePl this.notificationMapperWritePlatformService = notificationMapperWritePlatformService; } - @Override - public Long notify(Long userId, String objectType, Long objectIdentifier, String action, - Long actorId, String notificationContent, boolean isSystemGenerated) { + public Long notify(Long userId, String objectType, Long objectIdentifier, String action, Long actorId, String notificationContent, + boolean isSystemGenerated) { - Long generatedNotificationId = insertIntoNotificationGenerator(objectType, objectIdentifier, action, - actorId, notificationContent, isSystemGenerated); + Long generatedNotificationId = insertIntoNotificationGenerator(objectType, objectIdentifier, action, actorId, notificationContent, + isSystemGenerated); insertIntoNotificationMapper(userId, generatedNotificationId); return generatedNotificationId; } @@ -66,39 +64,27 @@ public class NotificationWritePlatformServiceImpl implements NotificationWritePl private Long insertIntoNotificationMapper(Long userId, Long generatedNotificationId) { AppUser appUser = this.appUserRepository.findById(userId).orElse(null); NotificationMapper notificationMapper = new NotificationMapper( - this.notificationGeneratorReadRepositoryWrapper.findById(generatedNotificationId), - appUser, - false, - getCurrentDateTime() - ); + this.notificationGeneratorReadRepositoryWrapper.findById(generatedNotificationId), appUser, false, getCurrentDateTime()); this.notificationMapperWritePlatformService.create(notificationMapper); return notificationMapper.getId(); } - private Long insertIntoNotificationGenerator(String objectType, Long objectIdentifier, String action, - Long actorId, String notificationContent, - boolean isSystemGenerated) { + private Long insertIntoNotificationGenerator(String objectType, Long objectIdentifier, String action, Long actorId, + String notificationContent, boolean isSystemGenerated) { - Notification notification = new Notification( - objectType, - objectIdentifier, - action, - actorId, - isSystemGenerated, - notificationContent, - getCurrentDateTime() - ); + Notification notification = new Notification(objectType, objectIdentifier, action, actorId, isSystemGenerated, notificationContent, + getCurrentDateTime()); return this.notificationGeneratorWritePlatformService.create(notification); } @Override - public Long notify(List userIds, String objectType, Long objectId, String action, - Long actorId, String notificationContent, boolean isSystemGenerated) { + public Long notify(List userIds, String objectType, Long objectId, String action, Long actorId, String notificationContent, + boolean isSystemGenerated) { - Long generatedNotificationId = insertIntoNotificationGenerator(objectType, objectId, action, - actorId, notificationContent, isSystemGenerated); + Long generatedNotificationId = insertIntoNotificationGenerator(objectType, objectId, action, actorId, notificationContent, + isSystemGenerated); insertIntoNotificationMapper(userIds, generatedNotificationId); return generatedNotificationId; @@ -109,11 +95,8 @@ public class NotificationWritePlatformServiceImpl implements NotificationWritePl for (Long userId : userIds) { AppUser appUser = this.appUserRepository.findById(userId).get(); NotificationMapper notificationMapper = new NotificationMapper( - this.notificationGeneratorReadRepositoryWrapper.findById(generatedNotificationId), - appUser, - false, - getCurrentDateTime() - ); + this.notificationGeneratorReadRepositoryWrapper.findById(generatedNotificationId), appUser, false, + getCurrentDateTime()); this.notificationMapperWritePlatformService.create(notificationMapper); mappedIds.add(notificationMapper.getId()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicDomainService.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicDomainService.java index b670dfcb4..4baf23eed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicDomainService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicDomainService.java @@ -25,20 +25,20 @@ import org.apache.fineract.useradministration.domain.Role; public interface TopicDomainService { - public void createTopic( Office newOffice ); + public void createTopic(Office newOffice); - public void createTopic( Role newRole ); + public void createTopic(Role newRole); - public void updateTopic( Office updatedOffice, Map changes ); + public void updateTopic(Office updatedOffice, Map changes); - public void updateTopic( String previousRolename, Role updatedRole, Map changes ); + public void updateTopic(String previousRolename, Role updatedRole, Map changes); - public void deleteTopic( Role role ); + public void deleteTopic(Role role); - public void subscribeUserToTopic( AppUser newUser ); + public void subscribeUserToTopic(AppUser newUser); - public void updateUserSubscription( AppUser userToUpdate, Map changes ); + public void updateUserSubscription(AppUser userToUpdate, Map changes); - public void unsubcribeUserFromTopic( AppUser user ); + public void unsubcribeUserFromTopic(AppUser user); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicDomainServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicDomainServiceImpl.java index efe70b23f..31dc35e3b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicDomainServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicDomainServiceImpl.java @@ -46,8 +46,8 @@ public class TopicDomainServiceImpl implements TopicDomainService { private final TopicSubscriberRepository topicSubscriberRepository; @Autowired - public TopicDomainServiceImpl(RoleRepository roleRepository, TopicRepository topicRepository, - OfficeRepository officeRepository, TopicSubscriberRepository topicSubscriberRepository) { + public TopicDomainServiceImpl(RoleRepository roleRepository, TopicRepository topicRepository, OfficeRepository officeRepository, + TopicSubscriberRepository topicSubscriberRepository) { this.roleRepository = roleRepository; this.topicRepository = topicRepository; @@ -56,13 +56,13 @@ public class TopicDomainServiceImpl implements TopicDomainService { } @Override - public void createTopic( Office newOffice ) { + public void createTopic(Office newOffice) { Long entityId = newOffice.getId(); String entityType = this.getEntityType(newOffice); List allRoles = roleRepository.findAll(); - for(Role role : allRoles) { + for (Role role : allRoles) { String memberType = role.getName().toUpperCase(); String title = role.getName() + " of " + newOffice.getName(); Topic newTopic = new Topic(title, true, entityId, entityType, memberType); @@ -71,11 +71,11 @@ public class TopicDomainServiceImpl implements TopicDomainService { } @Override - public void createTopic( Role newRole ) { + public void createTopic(Role newRole) { List offices = officeRepository.findAll(); - for (Office office : offices){ + for (Office office : offices) { String entityType = this.getEntityType(office); String title = newRole.getName() + " of " + office.getName(); Topic newTopic = new Topic(title, true, office.getId(), entityType, newRole.getName().toUpperCase()); @@ -84,7 +84,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { } @Override - public void updateTopic( Office updatedOffice, Map changes ) { + public void updateTopic(Office updatedOffice, Map changes) { List entityTopics = topicRepository.findByEntityId(updatedOffice.getId()); @@ -98,7 +98,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { } if (changes.containsKey("name")) { - for (Topic topic: entityTopics) { + for (Topic topic : entityTopics) { Role role = roleRepository.getRoleByName(topic.getMemberType()); String title = role.getName() + " of " + updatedOffice.getName(); topic.setTitle(title); @@ -108,7 +108,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { } @Override - public void updateTopic( String previousRolename, Role updatedRole, Map changes ) { + public void updateTopic(String previousRolename, Role updatedRole, Map changes) { if (changes.containsKey("name")) { List entityTopics = topicRepository.findByMemberType(previousRolename); @@ -123,7 +123,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { } @Override - public void deleteTopic( Role role ) { + public void deleteTopic(Role role) { List topics = topicRepository.findByMemberType(role.getName().toUpperCase()); for (Topic topic : topics) { @@ -132,7 +132,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { } @Override - public void subscribeUserToTopic( AppUser newUser ) { + public void subscribeUserToTopic(AppUser newUser) { List possibleTopics = topicRepository.findByEntityId(newUser.getOffice().getId()); @@ -140,7 +140,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { Set userRoles = newUser.getRoles(); for (Role role : userRoles) { for (Topic topic : possibleTopics) { - if(role.getName().compareToIgnoreCase(topic.getMemberType()) == 0) { + if (role.getName().compareToIgnoreCase(topic.getMemberType()) == 0) { TopicSubscriber topicSubscriber = new TopicSubscriber(topic, newUser, new Date()); topicSubscriberRepository.save(topicSubscriber); } @@ -150,7 +150,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { } @Override - public void updateUserSubscription( AppUser userToUpdate, Map changes ) { + public void updateUserSubscription(AppUser userToUpdate, Map changes) { List oldSubscriptions = topicSubscriberRepository.findBySubscriber(userToUpdate); if (changes.containsKey("officeId")) { @@ -180,7 +180,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { if (changes.containsKey("roles")) { - final Set oldRoles = userToUpdate.getRoles() ; + final Set oldRoles = userToUpdate.getRoles(); final Set tempOldRoles = new HashSet<>(oldRoles); final String[] roleIds = (String[]) changes.get("roles"); @@ -211,7 +211,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { } @Override - public void unsubcribeUserFromTopic( AppUser user ) { + public void unsubcribeUserFromTopic(AppUser user) { List subscriptions = topicSubscriberRepository.findBySubscriber(user); for (TopicSubscriber subscription : subscriptions) { @@ -219,8 +219,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { } } - - private String getEntityType( Office office ) { + private String getEntityType(Office office) { if (office.getParent() == null) { return "OFFICE"; @@ -236,8 +235,7 @@ public class TopicDomainServiceImpl implements TopicDomainService { if (!ObjectUtils.isEmpty(rolesArray)) { for (final String roleId : rolesArray) { final Long id = Long.valueOf(roleId); - final Role role = this.roleRepository.findById(id) - .orElseThrow(() -> new RoleNotFoundException(id)); + final Role role = this.roleRepository.findById(id).orElseThrow(() -> new RoleNotFoundException(id)); allRoles.add(role); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberReadPlatformServiceImpl.java index cc89afbe0..6317f11c3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberReadPlatformServiceImpl.java @@ -31,7 +31,7 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class TopicSubscriberReadPlatformServiceImpl implements TopicSubscriberReadPlatformService{ +public class TopicSubscriberReadPlatformServiceImpl implements TopicSubscriberReadPlatformService { private final JdbcTemplate jdbcTemplate; diff --git a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberWritePlatformServiceJpaRepositoryImpl.java index 64bef4a1f..d45f8af3d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/notification/service/TopicSubscriberWritePlatformServiceJpaRepositoryImpl.java @@ -26,7 +26,7 @@ import org.springframework.stereotype.Service; @Service public class TopicSubscriberWritePlatformServiceJpaRepositoryImpl implements TopicSubscriberWritePlatformService { -private final TopicSubscriberRepository topicSubscriberRepository; + private final TopicSubscriberRepository topicSubscriberRepository; @Autowired public TopicSubscriberWritePlatformServiceJpaRepositoryImpl(TopicSubscriberRepository topicSubscriberRepository) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidaysApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidaysApiResource.java index 6b2ededd1..086dae801 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidaysApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidaysApiResource.java @@ -64,10 +64,13 @@ import org.springframework.stereotype.Component; @Path("/holidays") @Component @Scope("singleton") -@Api(tags = {"Holidays"}) +@Api(tags = { "Holidays" }) @SwaggerDefinition(tags = { - @Tag(name = "Holidays", description = "Some MFI's span large regions where different branch offices might observe different holidays. They need the ability to define holidays for specific branch offices and be able to set the repayment rule to follow during those holidays.\n" + "\n" + "The reschedule of repayments to repaymentsRescheduledTo date during defined holidays is turned on/off by enabling/disabling reschedule-repayments-on-holidays in Global configurations.\n" + "\n" + "Allow Repayment transactions on a defined holidays is turned on/off by enabling/disabling allow-transactions-on-holiday in Global configurations.") -}) + @Tag(name = "Holidays", description = "Some MFI's span large regions where different branch offices might observe different holidays. They need the ability to define holidays for specific branch offices and be able to set the repayment rule to follow during those holidays.\n" + + "\n" + + "The reschedule of repayments to repaymentsRescheduledTo date during defined holidays is turned on/off by enabling/disabling reschedule-repayments-on-holidays in Global configurations.\n" + + "\n" + + "Allow Repayment transactions on a defined holidays is turned on/off by enabling/disabling allow-transactions-on-holiday in Global configurations.") }) public class HolidaysApiResource { private final DefaultToApiJsonSerializer toApiJsonSerializer; @@ -91,9 +94,11 @@ public class HolidaysApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Holiday", notes = "Mandatory Fields: " + "name, description, fromDate, toDate, repaymentsRescheduledTo, offices") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = HolidaysApiResourceSwagger.PostHolidaysRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.PostHolidaysResponse.class)}) + @ApiOperation(value = "Create a Holiday", notes = "Mandatory Fields: " + + "name, description, fromDate, toDate, repaymentsRescheduledTo, offices") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = HolidaysApiResourceSwagger.PostHolidaysRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.PostHolidaysResponse.class) }) public String createNewHoliday(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createHoliday().withJson(apiRequestBodyAsJson).build(); @@ -107,10 +112,13 @@ public class HolidaysApiResource { @Path("{holidayId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Activate a Holiday", notes = "Always Holidays are created in pending state. This API allows to activate a holiday.\n" + "\n" + "Only the active holidays are considered for rescheduling the loan repayment.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = HolidaysApiResourceSwagger.PostHolidaysHolidayIdRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.PostHolidaysHolidayIdResponse.class)}) - public String handleCommands(@PathParam("holidayId") @ApiParam(value = "holidayId") final Long holidayId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiOperation(value = "Activate a Holiday", notes = "Always Holidays are created in pending state. This API allows to activate a holiday.\n" + + "\n" + "Only the active holidays are considered for rescheduling the loan repayment.") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = HolidaysApiResourceSwagger.PostHolidaysHolidayIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.PostHolidaysHolidayIdResponse.class) }) + public String handleCommands(@PathParam("holidayId") @ApiParam(value = "holidayId") final Long holidayId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { String jsonApiRequest = apiRequestBodyAsJson; @@ -136,7 +144,7 @@ public class HolidaysApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieve a Holiday", notes = "Example Requests:\n" + "\n" + "holidays/1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.GetHolidaysResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.GetHolidaysResponse.class) }) public String retrieveOne(@PathParam("holidayId") @ApiParam(value = "holidayId") final Long holidayId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(HOLIDAY_RESOURCE_NAME); @@ -153,9 +161,11 @@ public class HolidaysApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Holiday", notes = "If a holiday is in pending state (created and not activated) then all fields are allowed to modify. Once holidays become active only name and descriptions are allowed to modify.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = HolidaysApiResourceSwagger.PutHolidaysHolidayIdRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.PutHolidaysHolidayIdResponse.class)}) - public String update(@PathParam("holidayId") @ApiParam(value = "holidayId") final Long holidayId, @ApiParam(hidden = true) final String jsonRequestBody) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = HolidaysApiResourceSwagger.PutHolidaysHolidayIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.PutHolidaysHolidayIdResponse.class) }) + public String update(@PathParam("holidayId") @ApiParam(value = "holidayId") final Long holidayId, + @ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateHoliday(holidayId).withJson(jsonRequestBody).build(); @@ -169,7 +179,7 @@ public class HolidaysApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Holiday", notes = "This API allows to delete a holiday. This is a soft delete the deleted holiday status is marked as deleted.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.DeleteHolidaysHolidayIdResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.DeleteHolidaysHolidayIdResponse.class) }) public String delete(@PathParam("holidayId") @ApiParam(value = "holidayId") final Long holidayId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteHoliday(holidayId).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -184,10 +194,14 @@ public class HolidaysApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "List Holidays", notes = "Example Requests:\n" + "\n" + "holidays?officeId=1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.GetHolidaysResponse.class, responseContainer = "List")}) - public String retrieveAllHolidays(@Context final UriInfo uriInfo, @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, - @QueryParam("fromDate") @ApiParam(value = "fromDate") final DateParam fromDateParam, @QueryParam("toDate") @ApiParam(value = "toDate") final DateParam toDateParam, - @QueryParam("locale") @ApiParam(value = "locale") final String locale, @QueryParam("dateFormat") @ApiParam(value = "dateFormat") final String dateFormat) { + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = HolidaysApiResourceSwagger.GetHolidaysResponse.class, responseContainer = "List") }) + public String retrieveAllHolidays(@Context final UriInfo uriInfo, + @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, + @QueryParam("fromDate") @ApiParam(value = "fromDate") final DateParam fromDateParam, + @QueryParam("toDate") @ApiParam(value = "toDate") final DateParam toDateParam, + @QueryParam("locale") @ApiParam(value = "locale") final String locale, + @QueryParam("dateFormat") @ApiParam(value = "dateFormat") final String dateFormat) { this.context.authenticatedUser().validateHasReadPermission(HOLIDAY_RESOURCE_NAME); @@ -209,9 +223,9 @@ public class HolidaysApiResource { @GET @Path("/template") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public String retrieveRepaymentScheduleUpdationTyeOptions(@Context final UriInfo uriInfo){ + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveRepaymentScheduleUpdationTyeOptions(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(HOLIDAY_RESOURCE_NAME); return this.toApiJsonSerializer.serialize(this.holidayReadPlatformService.retrieveRepaymentScheduleUpdationTyeOptions()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidaysApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidaysApiResourceSwagger.java index e576c3a35..5146bdc72 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidaysApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/api/HolidaysApiResourceSwagger.java @@ -28,15 +28,18 @@ import org.joda.time.LocalDate; * Created by sanyam on 14/8/17. */ final class HolidaysApiResourceSwagger { + private HolidaysApiResourceSwagger() { } @ApiModel(value = "GetHolidaysResponse") public static final class GetHolidaysResponse { + private GetHolidaysResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Good Friday") @@ -54,16 +57,21 @@ final class HolidaysApiResourceSwagger { @ApiModel(value = "PostHolidaysRequest") public static final class PostHolidaysRequest { - private PostHolidaysRequest(){ + + private PostHolidaysRequest() { } + final class PostHolidaysRequestOffices { - private PostHolidaysRequestOffices(){ + + private PostHolidaysRequestOffices() { } + @ApiModelProperty(example = "1") public Long officeId; } + @ApiModelProperty(example = "Good Friday") public String name; @ApiModelProperty(example = "Good Friday") @@ -83,15 +91,18 @@ final class HolidaysApiResourceSwagger { @ApiModel(value = "PostHolidaysResponse") public static final class PostHolidaysResponse { + private PostHolidaysResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "PostHolidaysHolidayIdRequest") public static final class PostHolidaysHolidayIdRequest { + private PostHolidaysHolidayIdRequest() { } @@ -99,18 +110,22 @@ final class HolidaysApiResourceSwagger { @ApiModel(value = "PostHolidaysHolidayIdResponse") public static final class PostHolidaysHolidayIdResponse { + private PostHolidaysHolidayIdResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "PutHolidaysHolidayIdRequest") public static final class PutHolidaysHolidayIdRequest { + private PutHolidaysHolidayIdRequest() { } + @ApiModelProperty(example = "Independence day") public String name; @ApiModelProperty(example = "Holiday for Independence day celebration") @@ -119,16 +134,21 @@ final class HolidaysApiResourceSwagger { @ApiModel(value = "PutHolidaysHolidayIdResponse") public static final class PutHolidaysHolidayIdResponse { + private PutHolidaysHolidayIdResponse() { } - final class PutHolidaysHolidayIdResponseChanges{ - private PutHolidaysHolidayIdResponseChanges(){} + + final class PutHolidaysHolidayIdResponseChanges { + + private PutHolidaysHolidayIdResponseChanges() {} + @ApiModelProperty(example = "Independence day") public String name; @ApiModelProperty(example = "Holiday for Independence day celebration") public String description; } + @ApiModelProperty(example = "1") public Long resourceId; public PutHolidaysHolidayIdResponseChanges changes; @@ -136,9 +156,11 @@ final class HolidaysApiResourceSwagger { @ApiModel(value = "DeleteHolidaysHolidayIdResponse") public static final class DeleteHolidaysHolidayIdResponse { + private DeleteHolidaysHolidayIdResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/data/HolidayDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/data/HolidayDataValidator.java index a695d223d..4c241caef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/data/HolidayDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/data/HolidayDataValidator.java @@ -47,9 +47,8 @@ public class HolidayDataValidator { private final FromJsonHelper fromApiJsonHelper; private static final Set HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(HolidayApiConstants.localeParamName, HolidayApiConstants.dateFormatParamName, - HolidayApiConstants.nameParamName, HolidayApiConstants.fromDateParamName, - HolidayApiConstants.toDateParamName, HolidayApiConstants.descriptionParamName, + Arrays.asList(HolidayApiConstants.localeParamName, HolidayApiConstants.dateFormatParamName, HolidayApiConstants.nameParamName, + HolidayApiConstants.fromDateParamName, HolidayApiConstants.toDateParamName, HolidayApiConstants.descriptionParamName, HolidayApiConstants.officesParamName, HolidayApiConstants.repaymentsRescheduledToParamName, HolidayApiConstants.reschedulingType)); @@ -63,8 +62,7 @@ public class HolidayDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); final List dataValidationErrors = new ArrayList<>(); @@ -82,15 +80,16 @@ public class HolidayDataValidator { baseDataValidator.reset().parameter(HolidayApiConstants.toDateParamName).value(toDate).notNull(); Integer reschedulingType = null; - if(this.fromApiJsonHelper.parameterExists(HolidayApiConstants.reschedulingType, element)){ + if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.reschedulingType, element)) { reschedulingType = this.fromApiJsonHelper.extractIntegerNamed(HolidayApiConstants.reschedulingType, element, Locale.ENGLISH); } LocalDate repaymentsRescheduledTo = null; - if(reschedulingType == null || reschedulingType.equals(RescheduleType.RESCHEDULETOSPECIFICDATE.getValue())){ - repaymentsRescheduledTo = this.fromApiJsonHelper.extractLocalDateNamed( - HolidayApiConstants.repaymentsRescheduledToParamName, element); - baseDataValidator.reset().parameter(HolidayApiConstants.repaymentsRescheduledToParamName).value(repaymentsRescheduledTo).notNull(); + if (reschedulingType == null || reschedulingType.equals(RescheduleType.RESCHEDULETOSPECIFICDATE.getValue())) { + repaymentsRescheduledTo = this.fromApiJsonHelper.extractLocalDateNamed(HolidayApiConstants.repaymentsRescheduledToParamName, + element); + baseDataValidator.reset().parameter(HolidayApiConstants.repaymentsRescheduledToParamName).value(repaymentsRescheduledTo) + .notNull(); } Set offices = null; final JsonObject topLevelJsonElement = element.getAsJsonObject(); @@ -118,8 +117,7 @@ public class HolidayDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); final List dataValidationErrors = new ArrayList<>(); @@ -143,8 +141,8 @@ public class HolidayDataValidator { } if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.repaymentsRescheduledToParamName, element)) { - final LocalDate repaymentsRescheduledTo = this.fromApiJsonHelper.extractLocalDateNamed( - HolidayApiConstants.repaymentsRescheduledToParamName, element); + final LocalDate repaymentsRescheduledTo = this.fromApiJsonHelper + .extractLocalDateNamed(HolidayApiConstants.repaymentsRescheduledToParamName, element); baseDataValidator.reset().parameter(HolidayApiConstants.repaymentsRescheduledToParamName).value(repaymentsRescheduledTo) .notNull(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/Holiday.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/Holiday.java index ae7468f67..5f0cdf486 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/Holiday.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/Holiday.java @@ -95,13 +95,12 @@ public class Holiday extends AbstractPersistableCustom { final LocalDate fromDate = command.localDateValueOfParameterNamed(HolidayApiConstants.fromDateParamName); final LocalDate toDate = command.localDateValueOfParameterNamed(HolidayApiConstants.toDateParamName); Integer reschedulingType = null; - if(command.parameterExists(HolidayApiConstants.reschedulingType)){ + if (command.parameterExists(HolidayApiConstants.reschedulingType)) { reschedulingType = command.integerValueOfParameterNamed(HolidayApiConstants.reschedulingType); } LocalDate repaymentsRescheduledTo = null; - if(reschedulingType == null || reschedulingType.equals(RescheduleType.RESCHEDULETOSPECIFICDATE.getValue())){ - repaymentsRescheduledTo = command - .localDateValueOfParameterNamed(HolidayApiConstants.repaymentsRescheduledToParamName); + if (reschedulingType == null || reschedulingType.equals(RescheduleType.RESCHEDULETOSPECIFICDATE.getValue())) { + repaymentsRescheduledTo = command.localDateValueOfParameterNamed(HolidayApiConstants.repaymentsRescheduledToParamName); } final Integer status = HolidayStatusType.PENDING_FOR_ACTIVATION.getValue(); final boolean processed = false;// default it to false. Only batch job @@ -134,12 +133,11 @@ public class Holiday extends AbstractPersistableCustom { this.description = StringUtils.defaultIfEmpty(newValue, null); } - - if (command.isChangeInIntegerParameterNamed(HolidayApiConstants.reschedulingType,this.reschedulingType)) { - final Integer newValue =command.integerValueOfParameterNamed(HolidayApiConstants.reschedulingType); + if (command.isChangeInIntegerParameterNamed(HolidayApiConstants.reschedulingType, this.reschedulingType)) { + final Integer newValue = command.integerValueOfParameterNamed(HolidayApiConstants.reschedulingType); actualChanges.put(HolidayApiConstants.reschedulingType, newValue); this.reschedulingType = RescheduleType.fromInt(newValue).getValue(); - if(newValue.equals(RescheduleType.RESCHEDULETONEXTREPAYMENTDATE.getValue())){ + if (newValue.equals(RescheduleType.RESCHEDULETONEXTREPAYMENTDATE.getValue())) { this.repaymentsRescheduledTo = null; } } @@ -223,7 +221,8 @@ public class Holiday extends AbstractPersistableCustom { } private Holiday(final String name, final LocalDate fromDate, final LocalDate toDate, final LocalDate repaymentsRescheduledTo, - final Integer status, final boolean processed, final String description, final Set offices, final int reschedulingType) { + final Integer status, final boolean processed, final String description, final Set offices, + final int reschedulingType) { if (StringUtils.isNotBlank(name)) { this.name = name.trim(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/HolidayRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/HolidayRepositoryWrapper.java index b4878ad8d..479336ca5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/HolidayRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/HolidayRepositoryWrapper.java @@ -43,8 +43,7 @@ public class HolidayRepositoryWrapper { } public Holiday findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new HolidayNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new HolidayNotFoundException(id)); } public void save(final Holiday holiday) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/HolidayStatusType.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/HolidayStatusType.java index 4dd476006..d862bc417 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/HolidayStatusType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/HolidayStatusType.java @@ -75,4 +75,4 @@ public enum HolidayStatusType { public boolean isDeleted() { return this.value.equals(HolidayStatusType.DELETED.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/RescheduleType.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/RescheduleType.java index 0c04d6ced..291a8e44a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/RescheduleType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/domain/RescheduleType.java @@ -27,38 +27,37 @@ public enum RescheduleType { private final String code; private RescheduleType(Integer value, String code) { - this.value = value; - this.code = code; + this.value = value; + this.code = code; } public static RescheduleType fromInt(int rescheduleTypeValue) { - RescheduleType enumerration = RescheduleType.INVALID; - switch (rescheduleTypeValue) { + RescheduleType enumerration = RescheduleType.INVALID; + switch (rescheduleTypeValue) { case 1: - enumerration = RescheduleType.RESCHEDULETONEXTREPAYMENTDATE; - break; + enumerration = RescheduleType.RESCHEDULETONEXTREPAYMENTDATE; + break; case 2: - enumerration = RescheduleType.RESCHEDULETOSPECIFICDATE; - break; - } - return enumerration; + enumerration = RescheduleType.RESCHEDULETOSPECIFICDATE; + break; + } + return enumerration; } - public boolean isRescheduleToSpecificDate(){ - return this.value.equals(RescheduleType.RESCHEDULETOSPECIFICDATE.getValue()); + public boolean isRescheduleToSpecificDate() { + return this.value.equals(RescheduleType.RESCHEDULETOSPECIFICDATE.getValue()); } - public boolean isResheduleToNextRepaymentDate(){ - return this.value.equals(RescheduleType.RESCHEDULETONEXTREPAYMENTDATE.getValue()); + public boolean isResheduleToNextRepaymentDate() { + return this.value.equals(RescheduleType.RESCHEDULETONEXTREPAYMENTDATE.getValue()); } - public Integer getValue() { - return this.value; + return this.value; } public String getCode() { - return this.code; + return this.code; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/exception/HolidayNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/exception/HolidayNotFoundException.java index 18adf6a83..88fc0cf45 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/exception/HolidayNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/exception/HolidayNotFoundException.java @@ -28,4 +28,4 @@ public class HolidayNotFoundException extends AbstractPlatformResourceNotFoundEx public HolidayNotFoundException(final Long id) { super("error.msg.holiday.id.invalid", "Holiday with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayEnumerations.java index 63b7c37bd..c28e8c14d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayEnumerations.java @@ -55,7 +55,6 @@ public class HolidayEnumerations { return rescheduleType(RescheduleType.fromInt(id)); } - public static EnumOptionData rescheduleType(final RescheduleType type) { EnumOptionData optionData = null; switch (type) { @@ -69,8 +68,7 @@ public class HolidayEnumerations { break; default: - optionData = new EnumOptionData(RescheduleType.INVALID.getValue().longValue(), - RescheduleType.INVALID.getCode(), "Invalid"); + optionData = new EnumOptionData(RescheduleType.INVALID.getValue().longValue(), RescheduleType.INVALID.getCode(), "Invalid"); break; } return optionData; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayReadPlatformServiceImpl.java index 78b279e94..70c3636c6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayReadPlatformServiceImpl.java @@ -59,7 +59,8 @@ public class HolidayReadPlatformServiceImpl implements HolidayReadPlatformServic public HolidayMapper() { final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("h.id as id, h.name as name, h.description as description, h.from_date as fromDate, h.to_date as toDate, "); - sqlBuilder.append("h.repayments_rescheduled_to as repaymentsScheduleTO, h.rescheduling_type as reschedulingType, h.status_enum as statusEnum "); + sqlBuilder.append( + "h.repayments_rescheduled_to as repaymentsScheduleTO, h.rescheduling_type as reschedulingType, h.status_enum as statusEnum "); sqlBuilder.append("from m_holiday h "); this.schema = sqlBuilder.toString(); } @@ -137,7 +138,7 @@ public class HolidayReadPlatformServiceImpl implements HolidayReadPlatformServic } @Override - public List retrieveRepaymentScheduleUpdationTyeOptions(){ + public List retrieveRepaymentScheduleUpdationTyeOptions() { final List repSchUpdationTypeOptions = Arrays.asList( HolidayEnumerations.rescheduleType(RescheduleType.RESCHEDULETOSPECIFICDATE), diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayUtil.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayUtil.java index acbb1696e..52e3debe6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayUtil.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayUtil.java @@ -51,7 +51,9 @@ public class HolidayUtil { public static boolean isHoliday(final LocalDate date, final List holidays) { for (final Holiday holiday : holidays) { if (date.isEqual(holiday.getFromDateLocalDate()) || date.isEqual(holiday.getToDateLocalDate()) - || (date.isAfter(holiday.getFromDateLocalDate()) && date.isBefore(holiday.getToDateLocalDate()))) { return true; } + || (date.isAfter(holiday.getFromDateLocalDate()) && date.isBefore(holiday.getToDateLocalDate()))) { + return true; + } } return false; @@ -66,6 +68,7 @@ public class HolidayUtil { } return referedHoliday; } + public static void updateRepaymentRescheduleDateToWorkingDayIfItIsHoliday(final AdjustedDateDetailsDTO adjustedDateDetailsDTO, final Holiday holiday) { if (holiday.getReScheduleType().isRescheduleToSpecificDate()) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayWritePlatformServiceJpaRepositoryImpl.java index 101c6d4b2..0b6e5c118 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/holiday/service/HolidayWritePlatformServiceJpaRepositoryImpl.java @@ -96,8 +96,8 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -130,8 +130,8 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -192,15 +192,14 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit final LocalDate fromDate = command.localDateValueOfParameterNamed(HolidayApiConstants.fromDateParamName); final LocalDate toDate = command.localDateValueOfParameterNamed(HolidayApiConstants.toDateParamName); Integer reshedulingType = null; - if(command.parameterExists(HolidayApiConstants.reschedulingType)){ + if (command.parameterExists(HolidayApiConstants.reschedulingType)) { reshedulingType = command.integerValueOfParameterNamed(HolidayApiConstants.reschedulingType); } LocalDate repaymentsRescheduledTo = null; - if(reshedulingType != null && reshedulingType.equals(2)){ - repaymentsRescheduledTo = command - .localDateValueOfParameterNamed(HolidayApiConstants.repaymentsRescheduledToParamName); + if (reshedulingType != null && reshedulingType.equals(2)) { + repaymentsRescheduledTo = command.localDateValueOfParameterNamed(HolidayApiConstants.repaymentsRescheduledToParamName); } - if(repaymentsRescheduledTo != null){ + if (repaymentsRescheduledTo != null) { this.validateInputDates(fromDate, toDate, repaymentsRescheduledTo); } } @@ -214,13 +213,13 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit throw new HolidayDateException("to.date.cannot.be.before.from.date", defaultUserMessage, fromDate.toString(), toDate.toString()); } - if(repaymentsRescheduledTo != null){ + if (repaymentsRescheduledTo != null) { if ((repaymentsRescheduledTo.isEqual(fromDate) || repaymentsRescheduledTo.isEqual(toDate) || (repaymentsRescheduledTo.isAfter(fromDate) && repaymentsRescheduledTo.isBefore(toDate)))) { defaultUserMessage = "Repayments rescheduled date should be before from date or after to date."; - throw new HolidayDateException("repayments.rescheduled.date.should.be.before.from.date.or.after.to.date", defaultUserMessage, - repaymentsRescheduledTo.toString()); + throw new HolidayDateException("repayments.rescheduled.date.should.be.before.from.date.or.after.to.date", + defaultUserMessage, repaymentsRescheduledTo.toString()); } final WorkingDays workingDays = this.daysRepositoryWrapper.findOne(); @@ -238,7 +237,8 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit // 3. Holiday should not be on an repaymentsRescheduledTo date of // another holiday.//TBD - // restricting repaymentsRescheduledTo date to be within 7 days range + // restricting repaymentsRescheduledTo date to be within 7 days + // range // before or after from date and to date. if (repaymentsRescheduledTo.isBefore(fromDate.minusDays(7)) || repaymentsRescheduledTo.isAfter(toDate.plusDays(7))) { defaultUserMessage = "Repayments Rescheduled to date must be within 7 days before or after from and to dates"; @@ -247,7 +247,6 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit } } - } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/api/CurrenciesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/api/CurrenciesApiResource.java index 7d9016821..dd5797d8a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/api/CurrenciesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/api/CurrenciesApiResource.java @@ -55,10 +55,9 @@ import org.springframework.stereotype.Component; @Path("/currencies") @Component @Scope("singleton") -@Api(tags = {"Currency"}) +@Api(tags = { "Currency" }) @SwaggerDefinition(tags = { - @Tag(name = "Currency", description = "Application related configuration around viewing/updating the currencies permitted for use within the MFI.") -}) + @Tag(name = "Currency", description = "Application related configuration around viewing/updating the currencies permitted for use within the MFI.") }) public class CurrenciesApiResource { private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("selectedCurrencyOptions", "currencyOptions")); @@ -86,8 +85,9 @@ public class CurrenciesApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Currency Configuration", notes = "Returns the list of currencies permitted for use AND the list of currencies not selected (but available for selection).\n" + "\n" + "Example Requests:\n" + "\n" + "currencies\n" + "\n" + "\n" + "currencies?fields=selectedCurrencyOptions") - @ApiResponses({@ApiResponse(code = 200, message = "", response = CurrenciesApiResourceSwagger.GetCurrenciesResponse.class)}) + @ApiOperation(value = "Retrieve Currency Configuration", notes = "Returns the list of currencies permitted for use AND the list of currencies not selected (but available for selection).\n" + + "\n" + "Example Requests:\n" + "\n" + "currencies\n" + "\n" + "\n" + "currencies?fields=selectedCurrencyOptions") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CurrenciesApiResourceSwagger.GetCurrenciesResponse.class) }) public String retrieveCurrencies(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -102,8 +102,9 @@ public class CurrenciesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update Currency Configuration", notes = "Updates the list of currencies permitted for use.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CurrenciesApiResourceSwagger.PutCurrenciesRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = CurrenciesApiResourceSwagger.PutCurrenciesResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CurrenciesApiResourceSwagger.PutCurrenciesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = CurrenciesApiResourceSwagger.PutCurrenciesResponse.class) }) public String updateCurrencies(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -115,4 +116,4 @@ public class CurrenciesApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/api/CurrenciesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/api/CurrenciesApiResourceSwagger.java index 2a87e7323..9335fd813 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/api/CurrenciesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/api/CurrenciesApiResourceSwagger.java @@ -27,49 +27,44 @@ import org.apache.fineract.organisation.monetary.data.CurrencyData; * Created by sanyam on 14/8/17. */ final class CurrenciesApiResourceSwagger { + private CurrenciesApiResourceSwagger() { } @ApiModel(value = "GetCurrenciesResponse") public static final class GetCurrenciesResponse { - private GetCurrenciesResponse(){ + + private GetCurrenciesResponse() { } + public Collection selectedCurrencyOptions; public Collection currencyOptions; } @ApiModel(value = "PutCurrenciesRequest") public static final class PutCurrenciesRequest { + private PutCurrenciesRequest() { } - @ApiModelProperty(example = "[\"KES\",\n" + - " \"BND\",\n" + - " \"LBP\",\n" + - " \"GHC\",\n" + - " \"USD\",\n" + - " \"XOF\",\n" + - " \"AED\",\n" + - " \"AMD\"]") + + @ApiModelProperty(example = "[\"KES\",\n" + " \"BND\",\n" + " \"LBP\",\n" + " \"GHC\",\n" + + " \"USD\",\n" + " \"XOF\",\n" + " \"AED\",\n" + " \"AMD\"]") public String currencies; } @ApiModel(value = "PutCurrenciesResponse") public static final class PutCurrenciesResponse { + private PutCurrenciesResponse() { } - @ApiModelProperty(example = "[\"KES\",\n" + - " \"BND\",\n" + - " \"LBP\",\n" + - " \"GHC\",\n" + - " \"USD\",\n" + - " \"XOF\",\n" + - " \"AED\",\n" + - " \"AMD\"]") + + @ApiModelProperty(example = "[\"KES\",\n" + " \"BND\",\n" + " \"LBP\",\n" + " \"GHC\",\n" + + " \"USD\",\n" + " \"XOF\",\n" + " \"AED\",\n" + " \"AMD\"]") public String currencies; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/ApplicationCurrencyConfigurationData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/ApplicationCurrencyConfigurationData.java index de768c9a4..5cc81a5f3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/ApplicationCurrencyConfigurationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/ApplicationCurrencyConfigurationData.java @@ -35,4 +35,4 @@ public class ApplicationCurrencyConfigurationData { this.currencyOptions = currencyOptions; this.selectedCurrencyOptions = selectedCurrencyOptions; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/CurrencyData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/CurrencyData.java index fedfd31c6..be224c96f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/CurrencyData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/CurrencyData.java @@ -43,7 +43,7 @@ public class CurrencyData implements Serializable { public CurrencyData(String code) { this.code = code; this.name = null; - this.decimalPlaces =0; + this.decimalPlaces = 0; this.inMultiplesOf = null; this.displaySymbol = null; this.nameCode = null; @@ -92,24 +92,16 @@ public class CurrencyData implements Serializable { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof CurrencyData)) { - return false; - } + if (this == o) { return true; } + if (!(o instanceof CurrencyData)) { return false; } CurrencyData that = (CurrencyData) o; - return Objects.equals(decimalPlaces, that.decimalPlaces) && - Objects.equals(code, that.code) && - Objects.equals(name, that.name) && - Objects.equals(inMultiplesOf, that.inMultiplesOf) && - Objects.equals(displaySymbol, that.displaySymbol) && - Objects.equals(nameCode, that.nameCode) && - Objects.equals(displayLabel, that.displayLabel); + return Objects.equals(decimalPlaces, that.decimalPlaces) && Objects.equals(code, that.code) && Objects.equals(name, that.name) + && Objects.equals(inMultiplesOf, that.inMultiplesOf) && Objects.equals(displaySymbol, that.displaySymbol) + && Objects.equals(nameCode, that.nameCode) && Objects.equals(displayLabel, that.displayLabel); } @Override public int hashCode() { return Objects.hash(code, name, decimalPlaces, inMultiplesOf, displaySymbol, nameCode, displayLabel); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/MoneyData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/MoneyData.java index d376920cc..3bca6dcd6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/MoneyData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/data/MoneyData.java @@ -47,4 +47,4 @@ public class MoneyData { return this.decimalPlaces; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrency.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrency.java index 4308f2829..1b43bb124 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrency.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrency.java @@ -106,4 +106,4 @@ public class ApplicationCurrency extends AbstractPersistableCustom { public OrganisationCurrency toOrganisationCurrency() { return new OrganisationCurrency(this.code, this.name, this.decimalPlaces, this.inMultiplesOf, this.nameCode, this.displaySymbol); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrencyRepository.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrencyRepository.java index 7c9f38265..efba417c2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrencyRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrencyRepository.java @@ -21,8 +21,8 @@ package org.apache.fineract.organisation.monetary.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface ApplicationCurrencyRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface ApplicationCurrencyRepository + extends JpaRepository, JpaSpecificationExecutor { ApplicationCurrency findOneByCode(String currencyCode); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrencyRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrencyRepositoryWrapper.java index 0ee770ac2..1f1228c8a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrencyRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/ApplicationCurrencyRepositoryWrapper.java @@ -65,4 +65,4 @@ public class ApplicationCurrencyRepositoryWrapper { if (applicationCurrency == null) { throw new CurrencyNotFoundException(currencyCode); } return applicationCurrency; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/MonetaryCurrency.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/MonetaryCurrency.java index f5d0f5221..74f84a941 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/MonetaryCurrency.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/MonetaryCurrency.java @@ -65,4 +65,4 @@ public class MonetaryCurrency { public Integer getCurrencyInMultiplesOf() { return this.inMultiplesOf; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/Money.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/Money.java index 479482151..791a12259 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/Money.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/Money.java @@ -240,11 +240,13 @@ public class Money implements Comparable { final BigDecimal newAmount = this.amount.multiply(percentage).divide(BigDecimal.valueOf(100), roundingMode); return Money.of(monetaryCurrency(), newAmount); } + @Override public int compareTo(final Money other) { final Money otherMoney = other; - if (this.currencyCode - .equals(otherMoney.currencyCode) == false) { throw new UnsupportedOperationException("currencies arent different"); } + if (this.currencyCode.equals(otherMoney.currencyCode) == false) { + throw new UnsupportedOperationException("currencies arent different"); + } return this.amount.compareTo(otherMoney.amount); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java index b6bfbe21a..6b755ab19 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java @@ -39,13 +39,13 @@ public class MoneyHelper { private ConfigurationDomainService configurationDomainService; @PostConstruct - // This is a hack, but fixing this is not trivial, because some @Entity domain classes use this helper + // This is a hack, but fixing this is not trivial, because some @Entity + // domain classes use this helper @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") - public void someFunction () { + public void someFunction() { staticConfigurationDomainService = configurationDomainService; } - public static RoundingMode getRoundingMode() { if (roundingMode == null) { roundingMode = RoundingMode.valueOf(staticConfigurationDomainService.getRoundingMode()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/CurrencyInUseException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/CurrencyInUseException.java index fb7c798f8..30ac3ca13 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/CurrencyInUseException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/CurrencyInUseException.java @@ -28,8 +28,7 @@ public class CurrencyInUseException extends AbstractPlatformDomainRuleException public CurrencyInUseException(final String currencyCode) { super("error.msg.currency.currencyCode.inUse", - "Cannot remove currency with identifier " + currencyCode - + " while it is still in use", currencyCode); + "Cannot remove currency with identifier " + currencyCode + " while it is still in use", currencyCode); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/CurrencyNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/CurrencyNotFoundException.java index 1dac243cb..770e7bcc6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/CurrencyNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/CurrencyNotFoundException.java @@ -28,4 +28,4 @@ public class CurrencyNotFoundException extends AbstractPlatformResourceNotFoundE public CurrencyNotFoundException(final String currencyCode) { super("error.msg.currency.currencyCode.invalid", "Currency with identifier " + currencyCode + " does not exist", currencyCode); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/OrganizationalCurrencyNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/OrganizationalCurrencyNotFoundException.java index 151fb59d3..dfaf2b885 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/OrganizationalCurrencyNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/exception/OrganizationalCurrencyNotFoundException.java @@ -27,7 +27,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class OrganizationalCurrencyNotFoundException extends AbstractPlatformResourceNotFoundException { public OrganizationalCurrencyNotFoundException(final String currencyCode) { - super("error.msg.currency.currencyCode.invalid.or.not.supported", "Currency with identifier " + currencyCode - + " does not exist or is not supported by the Organization", currencyCode); + super("error.msg.currency.currencyCode.invalid.or.not.supported", + "Currency with identifier " + currencyCode + " does not exist or is not supported by the Organization", currencyCode); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/handler/UpdateCurrencyCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/handler/UpdateCurrencyCommandHandler.java index 3cfd7b191..3421a4eff 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/handler/UpdateCurrencyCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/handler/UpdateCurrencyCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateCurrencyCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.updateAllowedCurrencies(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/serialization/CurrencyCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/serialization/CurrencyCommandFromApiJsonDeserializer.java index 11aa1ca40..b7accc424 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/serialization/CurrencyCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/serialization/CurrencyCommandFromApiJsonDeserializer.java @@ -69,7 +69,9 @@ public final class CurrencyCommandFromApiJsonDeserializer { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyReadPlatformService.java index 7eff2eba2..1a58adac0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyReadPlatformService.java @@ -28,4 +28,4 @@ public interface CurrencyReadPlatformService { Collection retrieveAllPlatformCurrencies(); CurrencyData retrieveCurrency(String code); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyReadPlatformServiceImpl.java index 344194360..83fbce50b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyReadPlatformServiceImpl.java @@ -89,4 +89,4 @@ public class CurrencyReadPlatformServiceImpl implements CurrencyReadPlatformServ return " c.code as code, c.name as name, c.decimal_places as decimalPlaces,c.currency_multiplesof as inMultiplesOf, c.display_symbol as displaySymbol, c.internationalized_name_code as nameCode "; } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyWritePlatformService.java index 725fc7cc1..282fb4175 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyWritePlatformService.java @@ -25,4 +25,4 @@ public interface CurrencyWritePlatformService { CommandProcessingResult updateAllowedCurrencies(JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java index 872f20bb8..1657c4757 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java @@ -95,8 +95,9 @@ public class CurrencyWritePlatformServiceJpaRepositoryImpl implements CurrencyWr // Check if it's safe to remove this currency. if (!loanProductService.retrieveAllLoanProductsForCurrency(priorCurrency.getCode()).isEmpty() || !savingsProductService.retrieveAllForCurrency(priorCurrency.getCode()).isEmpty() - || !chargeService.retrieveAllChargesForCurrency(priorCurrency.getCode()).isEmpty()) { throw new CurrencyInUseException( - priorCurrency.getCode()); } + || !chargeService.retrieveAllChargesForCurrency(priorCurrency.getCode()).isEmpty()) { + throw new CurrencyInUseException(priorCurrency.getCode()); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/OrganisationCurrencyReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/OrganisationCurrencyReadPlatformService.java index b13ab2171..5816bf3c3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/OrganisationCurrencyReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/OrganisationCurrencyReadPlatformService.java @@ -24,4 +24,4 @@ public interface OrganisationCurrencyReadPlatformService { ApplicationCurrencyConfigurationData retrieveCurrencyConfiguration(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/OrganisationCurrencyReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/OrganisationCurrencyReadPlatformServiceImpl.java index 4e58ec0b1..9135c11f7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/OrganisationCurrencyReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/monetary/service/OrganisationCurrencyReadPlatformServiceImpl.java @@ -45,4 +45,4 @@ public class OrganisationCurrencyReadPlatformServiceImpl implements Organisation return new ApplicationCurrencyConfigurationData(currencyOptions, selectedCurrencyOptions); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficeTransactionsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficeTransactionsApiResource.java index 7cde1cd77..929fe9cd8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficeTransactionsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficeTransactionsApiResource.java @@ -53,9 +53,9 @@ import org.springframework.stereotype.Component; @Api(value = "officetransactions", description = "") public class OfficeTransactionsApiResource { - private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "transactionDate", "fromOfficeId", - "fromOfficeName", "toOfficeId", "toOfficeIdName", "currencyCode", "digitsAfterDecimal", "inMultiplesOf", "transactionAmount", - "description", "allowedOffices", "currencyOptions")); + private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "transactionDate", "fromOfficeId", "fromOfficeName", "toOfficeId", "toOfficeIdName", "currencyCode", + "digitsAfterDecimal", "inMultiplesOf", "transactionAmount", "description", "allowedOffices", "currencyOptions")); private final String resourceNameForReadPermissions = "OFFICE"; @@ -128,4 +128,4 @@ public class OfficeTransactionsApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficesApiResource.java index 40a8e2cf6..d3a8f9baf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficesApiResource.java @@ -68,10 +68,9 @@ import org.springframework.stereotype.Component; @Path("/offices") @Component @Scope("singleton") -@Api(tags = {"Offices"}) +@Api(tags = { "Offices" }) @SwaggerDefinition(tags = { - @Tag(name = "Offices", description = "Offices are used to model an MFIs structure. A hierarchical representation of offices is supported. There will always be at least one office (which represents the MFI or an MFIs head office). All subsequent offices added must have a parent office.") -}) + @Tag(name = "Offices", description = "Offices are used to model an MFIs structure. A hierarchical representation of offices is supported. There will always be at least one office (which represents the MFI or an MFIs head office). All subsequent offices added must have a parent office.") }) public class OfficesApiResource { /** @@ -91,7 +90,6 @@ public class OfficesApiResource { private final BulkImportWorkbookService bulkImportWorkbookService; private final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService; - @Autowired public OfficesApiResource(final PlatformSecurityContext context, final OfficeReadPlatformService readPlatformService, final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, @@ -103,18 +101,21 @@ public class OfficesApiResource { this.toApiJsonSerializer = toApiJsonSerializer; this.apiRequestParameterHelper = apiRequestParameterHelper; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; } @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Offices", notes = "Example Requests:\n" + "\n" + "offices\n" + "\n" + "\n" + "offices?fields=id,name,openingDate") - @ApiResponses({@ApiResponse(code = 200, message = "", response = OfficesApiResourceSwagger.GetOfficesResponse.class, responseContainer = "List")}) + @ApiOperation(value = "List Offices", notes = "Example Requests:\n" + "\n" + "offices\n" + "\n" + "\n" + + "offices?fields=id,name,openingDate") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = OfficesApiResourceSwagger.GetOfficesResponse.class, responseContainer = "List") }) public String retrieveOffices(@Context final UriInfo uriInfo, @DefaultValue("false") @QueryParam("includeAllOffices") @ApiParam(value = "includeAllOffices") final boolean onlyManualEntries, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -130,8 +131,9 @@ public class OfficesApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Office Details Template", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "offices/template") - @ApiResponses({@ApiResponse(code = 200, message = "", response = OfficesApiResourceSwagger.GetOfficesTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Office Details Template", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "offices/template") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = OfficesApiResourceSwagger.GetOfficesTemplateResponse.class) }) public String retrieveOfficeTemplate(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -149,8 +151,9 @@ public class OfficesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create an Office", notes = "Mandatory Fields\n" + "name, openingDate, parentId") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = OfficesApiResourceSwagger.PostOfficesRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = OfficesApiResourceSwagger.PostOfficesResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = OfficesApiResourceSwagger.PostOfficesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = OfficesApiResourceSwagger.PostOfficesResponse.class) }) public String createOffice(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -167,8 +170,9 @@ public class OfficesApiResource { @Path("{officeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve an Office", notes = "Example Requests:\n" + "\n" + "offices/1\n" + "\n" + "\n" + "offices/1?template=true\n" + "\n" + "\n" + "offices/1?fields=id,name,parentName") - @ApiResponses({@ApiResponse(code = 200, message = "", response = OfficesApiResourceSwagger.GetOfficesResponse.class)}) + @ApiOperation(value = "Retrieve an Office", notes = "Example Requests:\n" + "\n" + "offices/1\n" + "\n" + "\n" + + "offices/1?template=true\n" + "\n" + "\n" + "offices/1?fields=id,name,parentName") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = OfficesApiResourceSwagger.GetOfficesResponse.class) }) public String retreiveOffice(@PathParam("officeId") @ApiParam(value = "officeId") final Long officeId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -189,9 +193,11 @@ public class OfficesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update Office", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = OfficesApiResourceSwagger.PutOfficesOfficeIdRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = OfficesApiResourceSwagger.PutOfficesOfficeIdResponse.class)}) - public String updateOffice(@PathParam("officeId") @ApiParam(value = "officeId") final Long officeId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = OfficesApiResourceSwagger.PutOfficesOfficeIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = OfficesApiResourceSwagger.PutOfficesOfficeIdResponse.class) }) + public String updateOffice(@PathParam("officeId") @ApiParam(value = "officeId") final Long officeId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .updateOffice(officeId) // @@ -207,17 +213,17 @@ public class OfficesApiResource { @Path("downloadtemplate") @Produces("application/vnd.ms-excel") public Response getOfficeTemplate(@QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.OFFICES.toString(), null,null,dateFormat); + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.OFFICES.toString(), null, null, dateFormat); } @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postOfficeTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, @FormDataParam("dateFormat") final String dateFormat){ + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.OFFICES.toString(), - uploadedInputStream,fileDetail, locale,dateFormat); + uploadedInputStream, fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficesApiResourceSwagger.java index 1e1571248..b74923937 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/api/OfficesApiResourceSwagger.java @@ -27,15 +27,18 @@ import org.joda.time.LocalDate; * Created by sanyam on 14/8/17. */ final class OfficesApiResourceSwagger { + private OfficesApiResourceSwagger() { } @ApiModel(value = "GetOfficesResponse") public static final class GetOfficesResponse { + private GetOfficesResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Head Office") @@ -48,17 +51,19 @@ final class OfficesApiResourceSwagger { public LocalDate openingDate; @ApiModelProperty(example = ".") public String hierarchy; -// @ApiModelProperty(example = "") -// public Long parentId; -// @ApiModelProperty(example = "") -// public String parentName; + // @ApiModelProperty(example = "") + // public Long parentId; + // @ApiModelProperty(example = "") + // public String parentName; } @ApiModel(value = "GetOfficesTemplateResponse") public static final class GetOfficesTemplateResponse { + private GetOfficesTemplateResponse() { } + @ApiModelProperty(example = "[2009, 1, 1]") public LocalDate openingDate; public Collection allowedParents; @@ -66,9 +71,11 @@ final class OfficesApiResourceSwagger { @ApiModel(value = "PostOfficesRequest") public static final class PostOfficesRequest { + private PostOfficesRequest() { } + @ApiModelProperty(example = "Good Friday") public String name; @ApiModelProperty(example = "dd MMMM yyyy") @@ -86,9 +93,11 @@ final class OfficesApiResourceSwagger { @ApiModel(value = "PostOfficesResponse") public static final class PostOfficesResponse { + private PostOfficesResponse() { } + @ApiModelProperty(example = "3") public Long officeId; @ApiModelProperty(example = "3") @@ -97,25 +106,32 @@ final class OfficesApiResourceSwagger { @ApiModel(value = "PutOfficesOfficeIdRequest") public static final class PutOfficesOfficeIdRequest { + private PutOfficesOfficeIdRequest() { } + @ApiModelProperty(example = "Name is updated") public String name; } @ApiModel(value = "PutOfficesOfficeIdResponse") public static final class PutOfficesOfficeIdResponse { + private PutOfficesOfficeIdResponse() { } + final class PutOfficesOfficeIdResponseChanges { - private PutOfficesOfficeIdResponseChanges(){ + + private PutOfficesOfficeIdResponseChanges() { } + @ApiModelProperty(example = "Name is updated") public String name; } + @ApiModelProperty(example = "3") public Long officeId; @ApiModelProperty(example = "3") diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/data/OfficeData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/data/OfficeData.java index 2723feea9..65f09a1db 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/data/OfficeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/data/OfficeData.java @@ -39,24 +39,25 @@ public class OfficeData implements Serializable { @SuppressWarnings("unused") private final Collection allowedParents; - //import fields + // import fields private transient Integer rowIndex; private String locale; private String dateFormat; - public static OfficeData importInstance(final String name, final Long parentId, final LocalDate openingDate,final String externalId) { + public static OfficeData importInstance(final String name, final Long parentId, final LocalDate openingDate, final String externalId) { return new OfficeData(null, name, null, externalId, openingDate, null, parentId, null, null); } + public void setImportFields(final Integer rowIndex, final String locale, final String dateFormat) { this.rowIndex = rowIndex; this.locale = locale; this.dateFormat = dateFormat; } - public static OfficeData testInstance(final Long id,final String name){ - return new OfficeData(id,name,null,null, - null,null,null,null, - null); + + public static OfficeData testInstance(final Long id, final String name) { + return new OfficeData(id, name, null, null, null, null, null, null, null); } + public LocalDate getOpeningDate() { return openingDate; } @@ -106,4 +107,4 @@ public class OfficeData implements Serializable { public String getHierarchy() { return this.hierarchy; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/data/OfficeTransactionData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/data/OfficeTransactionData.java index 23a1269b1..9e603e052 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/data/OfficeTransactionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/data/OfficeTransactionData.java @@ -78,4 +78,4 @@ public class OfficeTransactionData { this.allowedOffices = allowedOffices; this.currencyOptions = currencyOptions; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/Office.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/Office.java index 65b2febb8..fe4ba6cef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/Office.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/Office.java @@ -243,6 +243,6 @@ public class Office extends AbstractPersistableCustom implements Serializable { } public void loadLazyCollections() { - this.children.size() ; + this.children.size(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OfficeRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OfficeRepositoryWrapper.java index f61d1892f..376cdf603 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OfficeRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OfficeRepositoryWrapper.java @@ -40,18 +40,17 @@ public class OfficeRepositoryWrapper { } public Office findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new OfficeNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new OfficeNotFoundException(id)); } - @Transactional(readOnly=true) + @Transactional(readOnly = true) public Office findOfficeHierarchy(final Long id) { - final Office office = this.repository.findById(id) - .orElseThrow(() -> new OfficeNotFoundException(id)); + final Office office = this.repository.findById(id).orElseThrow(() -> new OfficeNotFoundException(id)); office.loadLazyCollections(); - return office ; + return office; } + public Office save(final Office entity) { return this.repository.save(entity); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OfficeTransaction.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OfficeTransaction.java index 362f0defa..246469b8d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OfficeTransaction.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OfficeTransaction.java @@ -60,7 +60,8 @@ public class OfficeTransaction extends AbstractPersistableCustom { @Column(name = "description", nullable = true, length = 100) private String description; - public static OfficeTransaction fromJson(final Office fromOffice, final Office toOffice, final Money amount, final JsonCommand command) { + public static OfficeTransaction fromJson(final Office fromOffice, final Office toOffice, final Money amount, + final JsonCommand command) { final LocalDate transactionLocalDate = command.localDateValueOfParameterNamed("transactionDate"); final String description = command.stringValueOfParameterNamed("description"); @@ -83,4 +84,4 @@ public class OfficeTransaction extends AbstractPersistableCustom { this.transactionAmount = amount.getAmount(); this.description = description; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrency.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrency.java index f236fa400..ac639c624 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrency.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrency.java @@ -75,4 +75,4 @@ public class OrganisationCurrency extends AbstractPersistableCustom { public final MonetaryCurrency toMonetaryCurrency() { return new MonetaryCurrency(this.code, this.decimalPlaces, this.inMultiplesOf); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrencyRepository.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrencyRepository.java index 496e1d42d..6657569b8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrencyRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrencyRepository.java @@ -21,8 +21,8 @@ package org.apache.fineract.organisation.office.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface OrganisationCurrencyRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface OrganisationCurrencyRepository + extends JpaRepository, JpaSpecificationExecutor { OrganisationCurrency findOneByCode(String currencyCode); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrencyRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrencyRepositoryWrapper.java index fe9e26bec..1b3200419 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrencyRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/domain/OrganisationCurrencyRepositoryWrapper.java @@ -49,4 +49,4 @@ public class OrganisationCurrencyRepositoryWrapper { if (organisationCurrency == null) { throw new OrganizationalCurrencyNotFoundException(currencyCode); } return organisationCurrency; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/exception/OfficeNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/exception/OfficeNotFoundException.java index 198e9376c..798f3bc7b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/exception/OfficeNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/exception/OfficeNotFoundException.java @@ -28,4 +28,4 @@ public class OfficeNotFoundException extends AbstractPlatformResourceNotFoundExc public OfficeNotFoundException(final Long id) { super("error.msg.office.id.invalid", "Office with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/exception/OfficeTransactionNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/exception/OfficeTransactionNotFoundException.java index 53796e6a3..ad6cdd265 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/exception/OfficeTransactionNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/exception/OfficeTransactionNotFoundException.java @@ -29,4 +29,4 @@ public class OfficeTransactionNotFoundException extends AbstractPlatformResource public OfficeTransactionNotFoundException(final Long id) { super("error.msg.officetransaction.id.invalid", "Office transaction with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/CreateOfficeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/CreateOfficeCommandHandler.java index c99396a9e..282303944 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/CreateOfficeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/CreateOfficeCommandHandler.java @@ -44,4 +44,4 @@ public class CreateOfficeCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createOffice(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/CreateOfficeTransactionCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/CreateOfficeTransactionCommandHandler.java index 8ea0290a5..877820221 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/CreateOfficeTransactionCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/CreateOfficeTransactionCommandHandler.java @@ -44,4 +44,4 @@ public class CreateOfficeTransactionCommandHandler implements NewCommandSourceHa return this.writePlatformService.officeTransaction(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/DeleteOfficeTransactionCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/DeleteOfficeTransactionCommandHandler.java index 90ab4e5e5..4a2c55333 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/DeleteOfficeTransactionCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/DeleteOfficeTransactionCommandHandler.java @@ -44,4 +44,4 @@ public class DeleteOfficeTransactionCommandHandler implements NewCommandSourceHa return this.writePlatformService.deleteOfficeTransaction(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/UpdateOfficeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/UpdateOfficeCommandHandler.java index 77539d276..b505455ef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/UpdateOfficeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/handler/UpdateOfficeCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateOfficeCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.updateOffice(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/serialization/OfficeCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/serialization/OfficeCommandFromApiJsonDeserializer.java index dd43a4445..6166b95d2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/serialization/OfficeCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/serialization/OfficeCommandFromApiJsonDeserializer.java @@ -46,8 +46,8 @@ public final class OfficeCommandFromApiJsonDeserializer { /** * The parameters supported for this command. */ - private final Set supportedParameters = new HashSet<>(Arrays.asList("name", "parentId", "openingDate", "externalId", - "locale", "dateFormat")); + private final Set supportedParameters = new HashSet<>( + Arrays.asList("name", "parentId", "openingDate", "externalId", "locale", "dateFormat")); private final FromJsonHelper fromApiJsonHelper; @@ -87,8 +87,10 @@ public final class OfficeCommandFromApiJsonDeserializer { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForUpdate(final String json) { @@ -124,4 +126,4 @@ public final class OfficeCommandFromApiJsonDeserializer { throwExceptionIfValidationWarningsExist(dataValidationErrors); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/serialization/OfficeTransactionCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/serialization/OfficeTransactionCommandFromApiJsonDeserializer.java index b53761d90..50124e2cc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/serialization/OfficeTransactionCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/serialization/OfficeTransactionCommandFromApiJsonDeserializer.java @@ -94,7 +94,9 @@ public final class OfficeTransactionCommandFromApiJsonDeserializer { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeReadPlatformService.java index 3951fdce4..7ec66dd4a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeReadPlatformService.java @@ -38,4 +38,4 @@ public interface OfficeReadPlatformService { Collection retrieveAllOfficeTransactions(); OfficeTransactionData retrieveNewOfficeTransactionDetails(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeReadPlatformServiceImpl.java index 1ebba68aa..7b6761138 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeReadPlatformServiceImpl.java @@ -53,8 +53,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService @Autowired public OfficeReadPlatformServiceImpl(final PlatformSecurityContext context, - final CurrencyReadPlatformService currencyReadPlatformService, - final RoutingDataSource dataSource, + final CurrencyReadPlatformService currencyReadPlatformService, final RoutingDataSource dataSource, final ColumnValidator columnValidator) { this.context = context; this.currencyReadPlatformService = currencyReadPlatformService; @@ -65,8 +64,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService private static final class OfficeMapper implements RowMapper { public String officeSchema() { - return " o.id as id, o.name as name, " - + nameDecoratedBaseOnHierarchy + return " o.id as id, o.name as name, " + nameDecoratedBaseOnHierarchy + " as nameDecorated, o.external_id as externalId, o.opening_date as openingDate, o.hierarchy as hierarchy, parent.id as parentId, parent.name as parentName " + "from m_office o LEFT JOIN m_office AS parent ON parent.id = o.parent_id "; } @@ -111,8 +109,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService + " ot.to_office_id as toOfficeId, tooff.name as toOfficeName, ot.transaction_amount as transactionAmount, ot.description as description, " + " ot.currency_code as currencyCode, rc.decimal_places as currencyDigits, rc.currency_multiplesof as inMultiplesOf, " + " rc.name as currencyName, rc.internationalized_name_code as currencyNameCode, rc.display_symbol as currencyDisplaySymbol " - + " from m_office_transaction ot " - + " left join m_office fromoff on fromoff.id = ot.from_office_id " + + " from m_office_transaction ot " + " left join m_office fromoff on fromoff.id = ot.from_office_id " + " left join m_office tooff on tooff.id = ot.to_office_id " + " join m_currency rc on rc.`code` = ot.currency_code"; } @@ -139,8 +136,8 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService final BigDecimal transactionAmount = rs.getBigDecimal("transactionAmount"); final String description = rs.getString("description"); - return OfficeTransactionData.instance(id, transactionDate, fromOfficeId, fromOfficeName, toOfficeId, toOfficeName, - currencyData, transactionAmount, description); + return OfficeTransactionData.instance(id, transactionDate, fromOfficeId, fromOfficeName, toOfficeId, toOfficeName, currencyData, + transactionAmount, description); } } @@ -160,7 +157,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService sqlBuilder.append("select "); sqlBuilder.append(rm.officeSchema()); sqlBuilder.append(" where o.hierarchy like ? "); - if(searchParameters!=null) { + if (searchParameters != null) { if (searchParameters.isOrderByRequested()) { sqlBuilder.append("order by ").append(searchParameters.getOrderBy()); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy()); @@ -266,4 +263,4 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService public PlatformSecurityContext getContext() { return this.context; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeWritePlatformService.java index 56253c3e6..5cf0fbd8a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeWritePlatformService.java @@ -30,4 +30,4 @@ public interface OfficeWritePlatformService { CommandProcessingResult officeTransaction(JsonCommand command); CommandProcessingResult deleteOfficeTransaction(Long id, JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java index 21ae535fe..ba0f606c4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java @@ -113,8 +113,8 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP } catch (final DataIntegrityViolationException dve) { handleOfficeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleOfficeDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -162,8 +162,8 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP } catch (final DataIntegrityViolationException dve) { handleOfficeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleOfficeDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -231,8 +231,8 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP if (realCause.getMessage().contains("externalid_org")) { final String externalId = command.stringValueOfParameterNamed("externalId"); - throw new PlatformDataIntegrityException("error.msg.office.duplicate.externalId", "Office with externalId `" + externalId - + "` already exists", "externalId", externalId); + throw new PlatformDataIntegrityException("error.msg.office.duplicate.externalId", + "Office with externalId `" + externalId + "` already exists", "externalId", externalId); } else if (realCause.getMessage().contains("name_org")) { final String name = command.stringValueOfParameterNamed("name"); throw new PlatformDataIntegrityException("error.msg.office.duplicate.name", "Office with name `" + name + "` already exists", @@ -252,8 +252,9 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP final Long userOfficeId = currentUser.getOffice().getId(); final Office userOffice = this.officeRepositoryWrapper.findOfficeHierarchy(userOfficeId); - if (userOffice.doesNotHaveAnOfficeInHierarchyWithId(officeId)) { throw new NoAuthorizationException( - "User does not have sufficient priviledges to act on the provided office."); } + if (userOffice.doesNotHaveAnOfficeInHierarchyWithId(officeId)) { + throw new NoAuthorizationException("User does not have sufficient priviledges to act on the provided office."); + } Office officeToReturn = userOffice; if (!userOffice.identifiedBy(officeId)) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCategoryApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCategoryApiResource.java index 9062b1d0c..9b7a86553 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCategoryApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCategoryApiResource.java @@ -50,10 +50,8 @@ import org.springframework.stereotype.Component; @Path("/provisioningcategory") @Component @Scope("singleton") -@Api(tags = {"Provisioning Category"}) -@SwaggerDefinition(tags = { - @Tag(name = "Provisioning Category", description = "") -}) +@Api(tags = { "Provisioning Category" }) +@SwaggerDefinition(tags = { @Tag(name = "Provisioning Category", description = "") }) public class ProvisioningCategoryApiResource { private final PlatformSecurityContext platformSecurityContext; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCriteriaApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCriteriaApiResource.java index 8e7ccdf12..e3ad1d281 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCriteriaApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCriteriaApiResource.java @@ -60,10 +60,8 @@ import org.springframework.stereotype.Component; @Path("/provisioningcriteria") @Component @Scope("singleton") -@Api(tags = {"Provisioning Criteria"}) -@SwaggerDefinition(tags = { - @Tag(name = "Provisioning Criteria", description = "This defines the Provisioning Criteria") -}) +@Api(tags = { "Provisioning Criteria" }) +@SwaggerDefinition(tags = { @Tag(name = "Provisioning Criteria", description = "This defines the Provisioning Criteria") }) public class ProvisioningCriteriaApiResource { private final PlatformSecurityContext platformSecurityContext; @@ -73,16 +71,16 @@ public class ProvisioningCriteriaApiResource { private final DefaultToApiJsonSerializer toApiJsonSerializer; private static final Set PROVISIONING_CRITERIA_TEMPLATE_PARAMETER = new HashSet<>( - Arrays.asList(ProvisioningCriteriaConstants.DEFINITIONS_PARAM, - ProvisioningCriteriaConstants.LOANPRODUCTS_PARAM, ProvisioningCriteriaConstants.GLACCOUNTS_PARAM)); + Arrays.asList(ProvisioningCriteriaConstants.DEFINITIONS_PARAM, ProvisioningCriteriaConstants.LOANPRODUCTS_PARAM, + ProvisioningCriteriaConstants.GLACCOUNTS_PARAM)); private static final Set PROVISIONING_CRITERIA_PARAMETERS = new HashSet<>( - Arrays.asList(ProvisioningCriteriaConstants.CRITERIA_PARAM, - ProvisioningCriteriaConstants.LOANPRODUCTS_PARAM, ProvisioningCriteriaConstants.DEFINITIONS_PARAM)); + Arrays.asList(ProvisioningCriteriaConstants.CRITERIA_PARAM, ProvisioningCriteriaConstants.LOANPRODUCTS_PARAM, + ProvisioningCriteriaConstants.DEFINITIONS_PARAM)); private static final Set ALL_PROVISIONING_CRITERIA_PARAMETERS = new HashSet<>( - Arrays.asList(ProvisioningCriteriaConstants.CRITERIA_ID_PARAM, - ProvisioningCriteriaConstants.CRITERIA_NAME_PARAM, ProvisioningCriteriaConstants.CREATED_BY_PARAM)); + Arrays.asList(ProvisioningCriteriaConstants.CRITERIA_ID_PARAM, ProvisioningCriteriaConstants.CRITERIA_NAME_PARAM, + ProvisioningCriteriaConstants.CREATED_BY_PARAM)); @Autowired public ProvisioningCriteriaApiResource(final PlatformSecurityContext platformSecurityContext, @@ -93,8 +91,8 @@ public class ProvisioningCriteriaApiResource { this.platformSecurityContext = platformSecurityContext; this.apiRequestParameterHelper = apiRequestParameterHelper; this.provisioningCriteriaReadPlatformService = provisioningCriteriaReadPlatformService; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService ; - this.toApiJsonSerializer = toApiJsonSerializer ; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; } @GET @@ -113,12 +111,14 @@ public class ProvisioningCriteriaApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieves a Provisioning Criteria", notes = "Retrieves a Provisioning Criteria") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ProvisioningCriteriaApiResourceSwagger.GetProvisioningCriteriaCriteriaIdResponse.class)}) - public String retrieveProvisioningCriteria(@PathParam("criteriaId") @ApiParam(value = "criteriaId") final Long criteriaId, @Context final UriInfo uriInfo) { - platformSecurityContext.authenticatedUser() ; - ProvisioningCriteriaData criteria = this.provisioningCriteriaReadPlatformService.retrieveProvisioningCriteria(criteriaId) ; + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ProvisioningCriteriaApiResourceSwagger.GetProvisioningCriteriaCriteriaIdResponse.class) }) + public String retrieveProvisioningCriteria(@PathParam("criteriaId") @ApiParam(value = "criteriaId") final Long criteriaId, + @Context final UriInfo uriInfo) { + platformSecurityContext.authenticatedUser(); + ProvisioningCriteriaData criteria = this.provisioningCriteriaReadPlatformService.retrieveProvisioningCriteria(criteriaId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - if(settings.isTemplate()) { + if (settings.isTemplate()) { criteria = this.provisioningCriteriaReadPlatformService.retrievePrivisiongCriteriaTemplate(criteria); } return this.toApiJsonSerializer.serialize(settings, criteria, PROVISIONING_CRITERIA_PARAMETERS); @@ -128,10 +128,11 @@ public class ProvisioningCriteriaApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieves all created Provisioning Criterias", notes = "Retrieves all created Provisioning Criterias") - @ApiResponses({@ApiResponse(code = 200, message = "", responseContainer = "List",response = ProvisioningCriteriaApiResourceSwagger.GetProvisioningCriteriaResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", responseContainer = "List", response = ProvisioningCriteriaApiResourceSwagger.GetProvisioningCriteriaResponse.class) }) public String retrieveAllProvisioningCriterias(@Context final UriInfo uriInfo) { - platformSecurityContext.authenticatedUser() ; - Collection data = this.provisioningCriteriaReadPlatformService.retrieveAllProvisioningCriterias() ; + platformSecurityContext.authenticatedUser(); + Collection data = this.provisioningCriteriaReadPlatformService.retrieveAllProvisioningCriterias(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, data, ALL_PROVISIONING_CRITERIA_PARAMETERS); } @@ -139,9 +140,12 @@ public class ProvisioningCriteriaApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a new Provisioning Criteria", notes = "Creates a new Provisioning Criteria\n" + "\n" + "Mandatory Fields: \n" + "criteriaName\n" + "provisioningcriteria\n" + "\n" + "Optional Fields: \n" + "loanProducts") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ProvisioningCriteriaApiResourceSwagger.PostProvisioningCriteriaRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ProvisioningCriteriaApiResourceSwagger.PostProvisioningCriteriaResponse.class)}) + @ApiOperation(value = "Create a new Provisioning Criteria", notes = "Creates a new Provisioning Criteria\n" + "\n" + + "Mandatory Fields: \n" + "criteriaName\n" + "provisioningcriteria\n" + "\n" + "Optional Fields: \n" + "loanProducts") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ProvisioningCriteriaApiResourceSwagger.PostProvisioningCriteriaRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ProvisioningCriteriaApiResourceSwagger.PostProvisioningCriteriaResponse.class) }) public String createProvisioningCriteria(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { CommandWrapper commandWrapper = null; this.platformSecurityContext.authenticatedUser(); @@ -154,10 +158,14 @@ public class ProvisioningCriteriaApiResource { @Path("{criteriaId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Updates a new Provisioning Criteria", notes = "Updates a new Provisioning Criteria\n" + "\n" + "Optional Fields\n" + "criteriaName, loanProducts, provisioningcriteria") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ProvisioningCriteriaApiResourceSwagger.PutProvisioningCriteriaRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ProvisioningCriteriaApiResourceSwagger.PutProvisioningCriteriaResponse.class)}) - public String updateProvisioningCriteria(@PathParam("criteriaId") @ApiParam(value = "criteriaId") final Long criteriaId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Updates a new Provisioning Criteria", notes = "Updates a new Provisioning Criteria\n" + "\n" + + "Optional Fields\n" + "criteriaName, loanProducts, provisioningcriteria") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ProvisioningCriteriaApiResourceSwagger.PutProvisioningCriteriaRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ProvisioningCriteriaApiResourceSwagger.PutProvisioningCriteriaResponse.class) }) + public String updateProvisioningCriteria(@PathParam("criteriaId") @ApiParam(value = "criteriaId") final Long criteriaId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { this.platformSecurityContext.authenticatedUser(); final CommandWrapper commandRequest = new CommandWrapperBuilder().updateProvisioningCriteria(criteriaId) .withJson(apiRequestBodyAsJson).build(); @@ -170,7 +178,8 @@ public class ProvisioningCriteriaApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Deletes Provisioning Criteria", notes = "Deletes Provisioning Criteria") - @ApiResponses({@ApiResponse(code = 200, message = "", response = ProvisioningCriteriaApiResourceSwagger.DeleteProvisioningCriteriaResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ProvisioningCriteriaApiResourceSwagger.DeleteProvisioningCriteriaResponse.class) }) public String deleteProvisioningCriteria(@PathParam("criteriaId") @ApiParam(value = "criteriaId") final Long criteriaId) { this.platformSecurityContext.authenticatedUser(); final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteProvisioningCriteria(criteriaId).build(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCriteriaApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCriteriaApiResourceSwagger.java index 56b9afc53..8612a660f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCriteriaApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/api/ProvisioningCriteriaApiResourceSwagger.java @@ -28,15 +28,18 @@ import org.apache.fineract.portfolio.loanproduct.data.LoanProductData; * Created by sanyam on 18/8/17. */ final class ProvisioningCriteriaApiResourceSwagger { + private ProvisioningCriteriaApiResourceSwagger() { } @ApiModel(value = "PostProvisioningCriteriaRequest") public static final class PostProvisioningCriteriaRequest { + private PostProvisioningCriteriaRequest() { } + @ApiModelProperty(example = "High Risk Products Criteria") public String criteriaName; public Collection loanProducts; @@ -45,18 +48,22 @@ final class ProvisioningCriteriaApiResourceSwagger { @ApiModel(value = "PostProvisioningCriteriaResponse") public static final class PostProvisioningCriteriaResponse { + private PostProvisioningCriteriaResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "GetProvisioningCriteriaResponse") public static final class GetProvisioningCriteriaResponse { + private GetProvisioningCriteriaResponse() { } + @ApiModelProperty(example = "1") public Long criteriaId; @ApiModelProperty(example = "High Risk Products Criteria") @@ -67,9 +74,11 @@ final class ProvisioningCriteriaApiResourceSwagger { @ApiModel(value = "GetProvisioningCriteriaCriteriaIdResponse") public static final class GetProvisioningCriteriaCriteriaIdResponse { + private GetProvisioningCriteriaCriteriaIdResponse() { } + @ApiModelProperty(example = "1") public Long criteriaId; @ApiModelProperty(example = "High Risk Products Criteria") @@ -82,9 +91,11 @@ final class ProvisioningCriteriaApiResourceSwagger { @ApiModel(value = "PutProvisioningCriteriaRequest") public static final class PutProvisioningCriteriaRequest { + private PutProvisioningCriteriaRequest() { } + @ApiModelProperty(example = "High Risk Products Criteria") public String criteriaName; public Collection loanProducts; @@ -93,14 +104,19 @@ final class ProvisioningCriteriaApiResourceSwagger { @ApiModel(value = "PutProvisioningCriteriaResponse") public static final class PutProvisioningCriteriaResponse { + private PutProvisioningCriteriaResponse() { } - final class PutProvisioningCriteriaResponseChanges{ - private PutProvisioningCriteriaResponseChanges(){} + + final class PutProvisioningCriteriaResponseChanges { + + private PutProvisioningCriteriaResponseChanges() {} + @ApiModelProperty(example = "High Risk Products Criteria") public String criteriaName; } + @ApiModelProperty(example = "1") public Long resourceId; public PutProvisioningCriteriaResponseChanges changes; @@ -108,9 +124,11 @@ final class ProvisioningCriteriaApiResourceSwagger { @ApiModel(value = "DeleteProvisioningCriteriaResponse") public static final class DeleteProvisioningCriteriaResponse { + private DeleteProvisioningCriteriaResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/constants/ProvisioningCriteriaConstants.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/constants/ProvisioningCriteriaConstants.java index 55ce52e1c..eed3d865b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/constants/ProvisioningCriteriaConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/constants/ProvisioningCriteriaConstants.java @@ -19,6 +19,7 @@ package org.apache.fineract.organisation.provisioning.constants; public interface ProvisioningCriteriaConstants { + public final static String JSON_LOCALE_PARAM = "locale"; public final static String JSON_CRITERIAID_PARAM = "criteriaId"; public final static String JSON_CRITERIANAME_PARAM = "criteriaName"; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/data/ProvisioningCategoryData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/data/ProvisioningCategoryData.java index 40a3081a3..7e184d7e5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/data/ProvisioningCategoryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/data/ProvisioningCategoryData.java @@ -49,9 +49,7 @@ public class ProvisioningCategoryData implements Comparable loanProducts; - private Collection selectedLoanProducts ; + private Collection selectedLoanProducts; private final Collection definitions; private final Collection glAccounts; @@ -49,15 +49,16 @@ public class ProvisioningCriteriaData implements Comparable glAccounts) { this.criteriaId = data.criteriaId; this.criteriaName = data.criteriaName; - this.selectedLoanProducts = data.loanProducts ; + this.selectedLoanProducts = data.loanProducts; this.loanProducts = loanProducts; - this.loanProducts.removeAll(selectedLoanProducts) ; + this.loanProducts.removeAll(selectedLoanProducts); this.definitions = data.definitions; this.glAccounts = glAccounts; this.createdBy = data.createdBy; } - public static ProvisioningCriteriaData toLookup(final Long criteriaId, final String criteriaName, final Collection loanProducts, - final List definitions) { + + public static ProvisioningCriteriaData toLookup(final Long criteriaId, final String criteriaName, + final Collection loanProducts, final List definitions) { Collection glAccounts = null; String createdBy = null; return new ProvisioningCriteriaData(criteriaId, criteriaName, loanProducts, definitions, glAccounts, createdBy); @@ -78,14 +79,15 @@ public class ProvisioningCriteriaData implements Comparable definitions, - final Collection loanProducts, final Collection glAccounts) { + public static ProvisioningCriteriaData toTemplate(final ProvisioningCriteriaData data, + final Collection definitions, final Collection loanProducts, + final Collection glAccounts) { return new ProvisioningCriteriaData(data, loanProducts, glAccounts); } @Override public int compareTo(ProvisioningCriteriaData obj) { - if (obj == null ) { return -1; } + if (obj == null) { return -1; } return obj.criteriaId.compareTo(this.criteriaId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/data/ProvisioningCriteriaDefinitionData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/data/ProvisioningCriteriaDefinitionData.java index e8c5b3670..59a733b07 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/data/ProvisioningCriteriaDefinitionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/data/ProvisioningCriteriaDefinitionData.java @@ -31,10 +31,10 @@ public final class ProvisioningCriteriaDefinitionData implements Comparable, JpaSpecificationExecutor{ +public interface ProvisioningCategoryRepository + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteria.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteria.java index e9a1555bd..0f0e63c5f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteria.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteria.java @@ -41,16 +41,17 @@ import org.apache.fineract.useradministration.domain.AppUser; import org.joda.time.DateTime; @Entity -@Table(name = "m_provisioning_criteria", uniqueConstraints = { @UniqueConstraint(columnNames = { "criteria_name" }, name = "criteria_name") }) +@Table(name = "m_provisioning_criteria", uniqueConstraints = { + @UniqueConstraint(columnNames = { "criteria_name" }, name = "criteria_name") }) public class ProvisioningCriteria extends AbstractAuditableCustom { @Column(name = "criteria_name", nullable = false) private String criteriaName; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "criteria", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "criteria", orphanRemoval = true, fetch = FetchType.EAGER) Set provisioningCriteriaDefinition = new HashSet<>(); - @OneToMany(cascade = CascadeType.ALL, mappedBy = "criteria", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "criteria", orphanRemoval = true, fetch = FetchType.EAGER) Set loanProductMapping = new HashSet<>(); public String getCriteriaName() { @@ -65,11 +66,12 @@ public class ProvisioningCriteria extends AbstractAuditableCustom { } - public ProvisioningCriteria(String criteriaName, AppUser createdBy, DateTime createdDate, AppUser lastModifiedBy, DateTime lastModifiedDate) { + public ProvisioningCriteria(String criteriaName, AppUser createdBy, DateTime createdDate, AppUser lastModifiedBy, + DateTime lastModifiedDate) { this.criteriaName = criteriaName; - setCreatedBy(createdBy) ; + setCreatedBy(createdBy); setCreatedDate(Instant.ofEpochMilli(createdDate.getMillis())); - setLastModifiedBy(lastModifiedBy) ; + setLastModifiedBy(lastModifiedBy); setLastModifiedDate(Instant.ofEpochMilli(lastModifiedDate.getMillis())); } @@ -85,39 +87,39 @@ public class ProvisioningCriteria extends AbstractAuditableCustom { public Map update(JsonCommand command, List loanProducts) { final Map actualChanges = new LinkedHashMap<>(7); - if(command.isChangeInStringParameterNamed(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM, criteriaName)) { + if (command.isChangeInStringParameterNamed(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM, criteriaName)) { final String valueAsInput = command.stringValueOfParameterNamed(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM); actualChanges.put(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM, valueAsInput); - this.criteriaName = valueAsInput ; + this.criteriaName = valueAsInput; } - Set temp = new HashSet<>() ; - Set productsTemp = new HashSet<>() ; + Set temp = new HashSet<>(); + Set productsTemp = new HashSet<>(); - for(LoanProductProvisionCriteria mapping: loanProductMapping) { - if(!loanProducts.contains(mapping.getLoanProduct())) { - temp.add(mapping) ; - }else { - productsTemp.add(mapping.getLoanProduct()) ; + for (LoanProductProvisionCriteria mapping : loanProductMapping) { + if (!loanProducts.contains(mapping.getLoanProduct())) { + temp.add(mapping); + } else { + productsTemp.add(mapping.getLoanProduct()); } } - loanProductMapping.removeAll(temp) ; + loanProductMapping.removeAll(temp); - for(LoanProduct loanProduct: loanProducts) { - if(!productsTemp.contains(loanProduct)) { - this.loanProductMapping.add( new LoanProductProvisionCriteria(this, loanProduct)) ; + for (LoanProduct loanProduct : loanProducts) { + if (!productsTemp.contains(loanProduct)) { + this.loanProductMapping.add(new LoanProductProvisionCriteria(this, loanProduct)); } } actualChanges.put(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM, loanProductMapping); - return actualChanges ; + return actualChanges; } public void update(ProvisioningCriteriaDefinitionData data, GLAccount liability, GLAccount expense) { - for(ProvisioningCriteriaDefinition def: provisioningCriteriaDefinition) { - if(data.getId().equals(def.getId())) { - def.update(data.getMinAge(), data.getMaxAge(), data.getProvisioningPercentage(), liability, expense) ; - break ; + for (ProvisioningCriteriaDefinition def : provisioningCriteriaDefinition) { + if (data.getId().equals(def.getId())) { + def.update(data.getMinAge(), data.getMaxAge(), data.getProvisioningPercentage(), liability, expense); + break; } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaDefinition.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaDefinition.java index eaa7bf275..465f55530 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaDefinition.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaDefinition.java @@ -80,14 +80,13 @@ public class ProvisioningCriteriaDefinition extends AbstractPersistableCustom { } public void update(Long minAge, Long maxAge, BigDecimal percentage, GLAccount lia, GLAccount exp) { - this.minimumAge = minAge ; - this.maximumAge = maxAge ; - this.provisioningPercentage = percentage ; - this.liabilityAccount = lia ; - this.expenseAccount = exp ; + this.minimumAge = minAge; + this.maximumAge = maxAge; + this.provisioningPercentage = percentage; + this.liabilityAccount = lia; + this.expenseAccount = exp; } - public boolean isOverlapping(ProvisioningCriteriaDefinition def) { return this.minimumAge <= def.maximumAge && def.minimumAge <= this.maximumAge; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaDefinitionRepository.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaDefinitionRepository.java index 03acc0b6a..22089d5c6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaDefinitionRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaDefinitionRepository.java @@ -21,7 +21,7 @@ package org.apache.fineract.organisation.provisioning.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -public interface ProvisioningCriteriaDefinitionRepository extends JpaRepository, JpaSpecificationExecutor { +public interface ProvisioningCriteriaDefinitionRepository + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaRepository.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaRepository.java index 00aff4122..6592a222d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/domain/ProvisioningCriteriaRepository.java @@ -21,7 +21,7 @@ package org.apache.fineract.organisation.provisioning.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -public interface ProvisioningCriteriaRepository extends JpaRepository, JpaSpecificationExecutor{ +public interface ProvisioningCriteriaRepository + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/exception/ProvisioningCriteriaCannotBeDeletedException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/exception/ProvisioningCriteriaCannotBeDeletedException.java index f5caf40c2..874444399 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/exception/ProvisioningCriteriaCannotBeDeletedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/exception/ProvisioningCriteriaCannotBeDeletedException.java @@ -23,7 +23,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class ProvisioningCriteriaCannotBeDeletedException extends AbstractPlatformDomainRuleException { public ProvisioningCriteriaCannotBeDeletedException(Long criteriaId) { - super("error.msg.provisioningcriteria.id.usedin.provisioning.entries", "Provisioningcriteria with identifier " + criteriaId + "associated in journal entries"); + super("error.msg.provisioningcriteria.id.usedin.provisioning.entries", + "Provisioningcriteria with identifier " + criteriaId + "associated in journal entries"); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/DeleteProvisioningCriteriaRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/DeleteProvisioningCriteriaRequestCommandHandler.java index 732ba22cb..9dfb476d4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/DeleteProvisioningCriteriaRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/DeleteProvisioningCriteriaRequestCommandHandler.java @@ -34,14 +34,15 @@ public class DeleteProvisioningCriteriaRequestCommandHandler implements NewComma private final ProvisioningCriteriaWritePlatformService provisioningCriteriaWritePlatformService; @Autowired - public DeleteProvisioningCriteriaRequestCommandHandler(final ProvisioningCriteriaWritePlatformService provisioningCriteriaWritePlatformService) { + public DeleteProvisioningCriteriaRequestCommandHandler( + final ProvisioningCriteriaWritePlatformService provisioningCriteriaWritePlatformService) { this.provisioningCriteriaWritePlatformService = provisioningCriteriaWritePlatformService; } @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { - return this.provisioningCriteriaWritePlatformService.deleteProvisioningCriteria(jsonCommand.entityId()) ; + return this.provisioningCriteriaWritePlatformService.deleteProvisioningCriteria(jsonCommand.entityId()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/UpdateProvisioningCategoryRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/UpdateProvisioningCategoryRequestCommandHandler.java index f19fd7ce4..325b22ec3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/UpdateProvisioningCategoryRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/UpdateProvisioningCategoryRequestCommandHandler.java @@ -34,7 +34,8 @@ public class UpdateProvisioningCategoryRequestCommandHandler implements NewComma private final ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService; @Autowired - public UpdateProvisioningCategoryRequestCommandHandler(ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService) { + public UpdateProvisioningCategoryRequestCommandHandler( + ProvisioningCategoryWritePlatformService provisioningCategoryWritePlatformService) { this.provisioningCategoryWritePlatformService = provisioningCategoryWritePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/UpdateProvisioningCriteriaRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/UpdateProvisioningCriteriaRequestCommandHandler.java index 0fe26a9c6..d62763ea2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/UpdateProvisioningCriteriaRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/handler/UpdateProvisioningCriteriaRequestCommandHandler.java @@ -34,7 +34,8 @@ public class UpdateProvisioningCriteriaRequestCommandHandler implements NewComma private final ProvisioningCriteriaWritePlatformService provisioningCriteriaWritePlatformService; @Autowired - public UpdateProvisioningCriteriaRequestCommandHandler(final ProvisioningCriteriaWritePlatformService provisioningCriteriaWritePlatformService) { + public UpdateProvisioningCriteriaRequestCommandHandler( + final ProvisioningCriteriaWritePlatformService provisioningCriteriaWritePlatformService) { this.provisioningCriteriaWritePlatformService = provisioningCriteriaWritePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/serialization/ProvisioningCriteriaDefinitionJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/serialization/ProvisioningCriteriaDefinitionJsonDeserializer.java index 636332f74..568d120e9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/serialization/ProvisioningCriteriaDefinitionJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/serialization/ProvisioningCriteriaDefinitionJsonDeserializer.java @@ -46,19 +46,18 @@ public class ProvisioningCriteriaDefinitionJsonDeserializer implements Provision private final FromJsonHelper fromApiJsonHelper; - private final static Set supportedParametersForCreate = new HashSet<>(Arrays.asList(JSON_LOCALE_PARAM, + private final static Set supportedParametersForCreate = new HashSet<>( + Arrays.asList(JSON_LOCALE_PARAM, JSON_CRITERIANAME_PARAM, JSON_LOANPRODUCTS_PARAM, JSON_PROVISIONING_DEFINITIONS_PARAM)); + + private final static Set supportedParametersForUpdate = new HashSet<>(Arrays.asList(JSON_CRITERIAID_PARAM, JSON_LOCALE_PARAM, JSON_CRITERIANAME_PARAM, JSON_LOANPRODUCTS_PARAM, JSON_PROVISIONING_DEFINITIONS_PARAM)); - private final static Set supportedParametersForUpdate = new HashSet<>(Arrays.asList(JSON_CRITERIAID_PARAM, - JSON_LOCALE_PARAM, JSON_CRITERIANAME_PARAM, JSON_LOANPRODUCTS_PARAM, JSON_PROVISIONING_DEFINITIONS_PARAM)); - - private final static Set loanProductSupportedParams = new HashSet<>(Arrays - .asList(JSON_LOAN_PRODUCT_ID_PARAM, JSON_LOAN_PRODUCTNAME_PARAM, JSON_LOAN_PRODUCT_BORROWERCYCLE_PARAM)); + private final static Set loanProductSupportedParams = new HashSet<>( + Arrays.asList(JSON_LOAN_PRODUCT_ID_PARAM, JSON_LOAN_PRODUCTNAME_PARAM, JSON_LOAN_PRODUCT_BORROWERCYCLE_PARAM)); private final static Set provisioningcriteriaSupportedParams = new HashSet<>( - Arrays.asList(JSON_CATEOGRYID_PARAM, JSON_CATEOGRYNAME_PARAM, JSON_MINIMUM_AGE_PARAM, - JSON_MAXIMUM_AGE_PARAM, JSON_MINIMUM_AGE_PARAM, JSON_PROVISIONING_PERCENTAGE_PARAM, - JSON_EXPENSE_ACCOUNT_PARAM, JSON_LIABILITY_ACCOUNT_PARAM)); + Arrays.asList(JSON_CATEOGRYID_PARAM, JSON_CATEOGRYNAME_PARAM, JSON_MINIMUM_AGE_PARAM, JSON_MAXIMUM_AGE_PARAM, + JSON_MINIMUM_AGE_PARAM, JSON_PROVISIONING_PERCENTAGE_PARAM, JSON_EXPENSE_ACCOUNT_PARAM, JSON_LIABILITY_ACCOUNT_PARAM)); @Autowired public ProvisioningCriteriaDefinitionJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { @@ -66,9 +65,9 @@ public class ProvisioningCriteriaDefinitionJsonDeserializer implements Provision } public void validateForCreate(final String json) { - if (StringUtils.isBlank(json)) { throw new ProvisioningCriteriaCannotBeCreatedException( - "error.msg.provisioningcriteria.cannot.be.created", - "criterianame, loanproducts[], provisioningcriteria[] params are missing in the request"); + if (StringUtils.isBlank(json)) { + throw new ProvisioningCriteriaCannotBeCreatedException("error.msg.provisioningcriteria.cannot.be.created", + "criterianame, loanproducts[], provisioningcriteria[] params are missing in the request"); } final Type typeOfMap = new TypeToken>() {}.getType(); @@ -90,26 +89,27 @@ public class ProvisioningCriteriaDefinitionJsonDeserializer implements Provision baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM).value(jsonloanProducts) .jsonArrayNotEmpty(); // check for unsupported params - int i = 0 ; + int i = 0; for (JsonElement obj : jsonloanProducts) { - this.fromApiJsonHelper.checkForUnsupportedParameters(obj.getAsJsonObject() , loanProductSupportedParams); + this.fromApiJsonHelper.checkForUnsupportedParameters(obj.getAsJsonObject(), loanProductSupportedParams); Long productId = this.fromApiJsonHelper.extractLongNamed("id", obj.getAsJsonObject()); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM) - .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_LOAN_PRODUCT_ID_PARAM, i + 1).value(productId).notNull() - .longGreaterThanZero(); - i++ ; + .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_LOAN_PRODUCT_ID_PARAM, i + 1).value(productId).notNull() + .longGreaterThanZero(); + i++; } } if (this.fromApiJsonHelper.parameterExists(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, element)) { - JsonArray jsonProvisioningCriteria = this.fromApiJsonHelper.extractJsonArrayNamed( - ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, element); + JsonArray jsonProvisioningCriteria = this.fromApiJsonHelper + .extractJsonArrayNamed(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, element); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM) .value(jsonProvisioningCriteria).jsonArrayNotEmpty(); for (int i = 0; i < jsonProvisioningCriteria.size(); i++) { JsonObject jsonObject = jsonProvisioningCriteria.get(i).getAsJsonObject(); - this.fromApiJsonHelper.checkForUnsupportedParameters(jsonObject , provisioningcriteriaSupportedParams); - final Long categoryId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, jsonObject); + this.fromApiJsonHelper.checkForUnsupportedParameters(jsonObject, provisioningcriteriaSupportedParams); + final Long categoryId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, + jsonObject); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM) .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, i + 1).value(categoryId).notNull() .longGreaterThanZero(); @@ -117,43 +117,42 @@ public class ProvisioningCriteriaDefinitionJsonDeserializer implements Provision Long minimumAge = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, jsonObject); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM) .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, i + 1).value(minimumAge).notNull() - .longZeroOrGreater() ; + .longZeroOrGreater(); Long maximumAge = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, jsonObject); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM) .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, i + 1).value(maximumAge).notNull() - .longGreaterThanNumber(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, minimumAge, (i+1)); + .longGreaterThanNumber(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, minimumAge, (i + 1)); - - BigDecimal provisioningpercentage = this.fromApiJsonHelper.extractBigDecimalNamed( - ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, jsonObject, locale); + BigDecimal provisioningpercentage = this.fromApiJsonHelper + .extractBigDecimalNamed(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, jsonObject, locale); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM) - .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, i + 1).value(provisioningpercentage) - .notNull().zeroOrPositiveAmount(); + .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, i + 1) + .value(provisioningpercentage).notNull().zeroOrPositiveAmount(); - Long liabilityAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, - jsonObject); + Long liabilityAccountId = this.fromApiJsonHelper + .extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, jsonObject); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM) .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, i + 1).value(liabilityAccountId) - .notNull().longGreaterThanZero() ; + .notNull().longGreaterThanZero(); Long expenseAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, jsonObject); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM) - .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, i + 1).value(expenseAccountId).notNull() - .longGreaterThanZero() ; + .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, i + 1).value(expenseAccountId) + .notNull().longGreaterThanZero(); } - }else { - baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM).jsonArrayNotEmpty() ; + } else { + baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM).jsonArrayNotEmpty(); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } public void validateForUpdate(final String json) { - if (StringUtils.isBlank(json)) { throw new ProvisioningCriteriaCannotBeCreatedException( - "error.msg.provisioningcriteria.cannot.be.updated", - "update params are missing in the request"); + if (StringUtils.isBlank(json)) { + throw new ProvisioningCriteriaCannotBeCreatedException("error.msg.provisioningcriteria.cannot.be.updated", + "update params are missing in the request"); } final Type typeOfMap = new TypeToken>() {}.getType(); @@ -164,13 +163,12 @@ public class ProvisioningCriteriaDefinitionJsonDeserializer implements Provision final JsonElement element = this.fromApiJsonHelper.parse(json); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject()); - if(this.fromApiJsonHelper.parameterExists(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM, element)) { + if (this.fromApiJsonHelper.parameterExists(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM, element)) { final String name = this.fromApiJsonHelper.extractStringNamed(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM, element); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM).value(name).notBlank() .notExceedingLengthOf(200); } - // if the param present, then we should have the loan product ids. If // not we will load all loan products if (this.fromApiJsonHelper.parameterExists(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM, element)) { @@ -179,25 +177,26 @@ public class ProvisioningCriteriaDefinitionJsonDeserializer implements Provision baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM).value(jsonloanProducts) .jsonArrayNotEmpty(); // check for unsupported params - int i = 0 ; + int i = 0; for (JsonElement obj : jsonloanProducts) { Long productId = this.fromApiJsonHelper.extractLongNamed("id", obj.getAsJsonObject()); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM) - .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_LOAN_PRODUCT_ID_PARAM, i + 1).value(productId).notNull() - .longGreaterThanZero(); - i++ ; + .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_LOAN_PRODUCT_ID_PARAM, i + 1).value(productId).notNull() + .longGreaterThanZero(); + i++; } } if (this.fromApiJsonHelper.parameterExists(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, element)) { - JsonArray jsonProvisioningCriteria = this.fromApiJsonHelper.extractJsonArrayNamed( - ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, element); + JsonArray jsonProvisioningCriteria = this.fromApiJsonHelper + .extractJsonArrayNamed(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, element); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM) .value(jsonProvisioningCriteria).jsonArrayNotEmpty(); for (int i = 0; i < jsonProvisioningCriteria.size(); i++) { // check for unsupported params JsonObject jsonObject = jsonProvisioningCriteria.get(i).getAsJsonObject(); - final Long categoryId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, jsonObject); + final Long categoryId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, + jsonObject); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM) .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, i + 1).value(categoryId).notNull() .longGreaterThanZero(); @@ -205,30 +204,30 @@ public class ProvisioningCriteriaDefinitionJsonDeserializer implements Provision Long minimumAge = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, jsonObject); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM) .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, i + 1).value(minimumAge).notNull() - .longZeroOrGreater() ; + .longZeroOrGreater(); Long maximumAge = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, jsonObject); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM) - .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, i + 1).value(maximumAge).notNull() - .longGreaterThanNumber(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, minimumAge, (i+1)); + .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, i + 1).value(maximumAge).notNull() + .longGreaterThanNumber(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, minimumAge, (i + 1)); - BigDecimal provisioningpercentage = this.fromApiJsonHelper.extractBigDecimalNamed( - ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, jsonObject, locale); + BigDecimal provisioningpercentage = this.fromApiJsonHelper + .extractBigDecimalNamed(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, jsonObject, locale); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM) - .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, i + 1).value(provisioningpercentage) - .notNull().zeroOrPositiveAmount(); + .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, i + 1) + .value(provisioningpercentage).notNull().zeroOrPositiveAmount(); - Long liabilityAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, - jsonObject); + Long liabilityAccountId = this.fromApiJsonHelper + .extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, jsonObject); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM) .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, i + 1).value(liabilityAccountId) - .notNull().longGreaterThanZero() ; + .notNull().longGreaterThanZero(); Long expenseAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, jsonObject); baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM) - .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, i + 1).value(expenseAccountId).notNull() - .longGreaterThanZero() ; + .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, i + 1).value(expenseAccountId) + .notNull().longGreaterThanZero(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryReadPlatformService.java index 2e12788c1..e8fd059f7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryReadPlatformService.java @@ -21,8 +21,7 @@ package org.apache.fineract.organisation.provisioning.service; import java.util.Collection; import org.apache.fineract.organisation.provisioning.data.ProvisioningCategoryData; - public interface ProvisioningCategoryReadPlatformService { - public Collection retrieveAllProvisionCategories() ; + public Collection retrieveAllProvisionCategories(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryReadPlatformServiceImpl.java index cb9e7ed92..ecc7fa6d4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryReadPlatformServiceImpl.java @@ -43,12 +43,14 @@ public class ProvisioningCategoryReadPlatformServiceImpl implements Provisioning @Override public Collection retrieveAllProvisionCategories() { - //User is already authenticated by API. So we no need to check again here + // User is already authenticated by API. So we no need to check again + // here final String sql = "select " + this.provisionCategoryRowMapper.schema() + " from m_provision_category pc order by pc.id"; return this.jdbcTemplate.query(sql, this.provisionCategoryRowMapper, new Object[] {}); } private static final class ProvisioningCategoryRowMapper implements RowMapper { + @Override public ProvisioningCategoryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = JdbcSupport.getLong(rs, "id"); @@ -61,4 +63,4 @@ public class ProvisioningCategoryReadPlatformServiceImpl implements Provisioning return " pc.id as id, pc.category_name as category_name, pc.description as description"; } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryWritePlatformService.java index 4e7021026..3f652acb5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryWritePlatformService.java @@ -21,12 +21,11 @@ package org.apache.fineract.organisation.provisioning.service; import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; - public interface ProvisioningCategoryWritePlatformService { CommandProcessingResult createProvisioningCateogry(JsonCommand command); - CommandProcessingResult updateProvisioningCategory(final Long categoryId, JsonCommand command) ; + CommandProcessingResult updateProvisioningCategory(final Long categoryId, JsonCommand command); - CommandProcessingResult deleteProvisioningCateogry(JsonCommand command) ; + CommandProcessingResult deleteProvisioningCateogry(JsonCommand command); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl.java index 212e0cf07..cd418981f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl.java @@ -67,8 +67,8 @@ public class ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl implement } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -78,8 +78,8 @@ public class ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl implement public CommandProcessingResult deleteProvisioningCateogry(JsonCommand command) { this.fromApiJsonDeserializer.validateForCreate(command.json()); final ProvisioningCategory provisioningCategory = ProvisioningCategory.fromJson(command); - boolean isProvisioningCategoryInUse = isAnyLoanProductsAssociateWithThisProvisioningCategory(provisioningCategory.getId()) ; - if(isProvisioningCategoryInUse) { + boolean isProvisioningCategoryInUse = isAnyLoanProductsAssociateWithThisProvisioningCategory(provisioningCategory.getId()); + if (isProvisioningCategoryInUse) { throw new ProvisioningCategoryCannotBeDeletedException( "error.msg.provisioningcategory.cannot.be.deleted.it.is.already.used.in.loanproduct", "This provisioning category cannot be deleted, it is already used in loan product"); @@ -102,8 +102,8 @@ public class ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl implement } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -114,6 +114,7 @@ public class ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl implement final String isLoansUsingCharge = this.jdbcTemplate.queryForObject(sql, String.class, new Object[] { categoryID }); return Boolean.valueOf(isLoansUsingCharge); } + /* * Guaranteed to throw an exception no matter what the data integrity issue * is. @@ -122,8 +123,8 @@ public class ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl implement if (realCause.getMessage().contains("category_name")) { final String name = command.stringValueOfParameterNamed("category_name"); - throw new PlatformDataIntegrityException("error.msg.provisioning.duplicate.categoryname", "Provisioning Cateory with name `" - + name + "` already exists", "category name", name); + throw new PlatformDataIntegrityException("error.msg.provisioning.duplicate.categoryname", + "Provisioning Cateory with name `" + name + "` already exists", "category name", name); } LOG.error("Error occured.", dve); throw new PlatformDataIntegrityException("error.msg.charge.unknown.data.integrity.issue", diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaAssembler.java index c3ab0f4bf..0c83e78b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaAssembler.java @@ -76,18 +76,16 @@ public class ProvisioningCriteriaAssembler { } else { loanProducts = loanProductRepository.findAll(); } - return loanProducts ; + return loanProducts; } private void validateRange(Set criteriaDefinitions) { - List def = new ArrayList<>() ; - def.addAll(criteriaDefinitions) ; + List def = new ArrayList<>(); + def.addAll(criteriaDefinitions); for (int i = 0; i < def.size(); i++) { for (int j = i + 1; j < def.size(); j++) { - if (def.get(i).isOverlapping(def.get(j))) { - throw new ProvisioningCriteriaOverlappingDefinitionException() ; - } + if (def.get(i).isOverlapping(def.get(j))) { throw new ProvisioningCriteriaOverlappingDefinitionException(); } } } } @@ -95,18 +93,18 @@ public class ProvisioningCriteriaAssembler { public ProvisioningCriteria fromParsedJson(final JsonElement jsonElement) { ProvisioningCriteria provisioningCriteria = createCriteria(jsonElement); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(jsonElement.getAsJsonObject()); - List loanProducts = parseLoanProducts(jsonElement) ; + List loanProducts = parseLoanProducts(jsonElement); Set criteriaDefinitions = new HashSet<>(); - JsonArray jsonProvisioningCriteria = this.fromApiJsonHelper.extractJsonArrayNamed( - ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, jsonElement); + JsonArray jsonProvisioningCriteria = this.fromApiJsonHelper + .extractJsonArrayNamed(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, jsonElement); for (JsonElement element : jsonProvisioningCriteria) { JsonObject jsonObject = element.getAsJsonObject(); ProvisioningCriteriaDefinition provisioningCriteriaData = createProvisioningCriteriaDefinitions(jsonObject, locale, provisioningCriteria); criteriaDefinitions.add(provisioningCriteriaData); } - validateRange(criteriaDefinitions) ; + validateRange(criteriaDefinitions); Set mapping = new HashSet<>(); for (LoanProduct loanProduct : loanProducts) { mapping.add(new LoanProductProvisionCriteria(provisioningCriteria, loanProduct)); @@ -117,7 +115,8 @@ public class ProvisioningCriteriaAssembler { } private ProvisioningCriteria createCriteria(final JsonElement jsonElement) { - final String criteriaName = this.fromApiJsonHelper.extractStringNamed(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM, jsonElement); + final String criteriaName = this.fromApiJsonHelper.extractStringNamed(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM, + jsonElement); ProvisioningCriteria criteria = new ProvisioningCriteria(criteriaName, platformSecurityContext.authenticatedUser(), new DateTime(), platformSecurityContext.authenticatedUser(), new DateTime()); @@ -129,10 +128,12 @@ public class ProvisioningCriteriaAssembler { Long categoryId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, jsonObject); Long minimumAge = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, jsonObject); Long maximumAge = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, jsonObject); - BigDecimal provisioningpercentage = this.fromApiJsonHelper.extractBigDecimalNamed(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, - jsonObject, locale); - Long liabilityAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, jsonObject); - Long expenseAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, jsonObject); + BigDecimal provisioningpercentage = this.fromApiJsonHelper + .extractBigDecimalNamed(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, jsonObject, locale); + Long liabilityAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, + jsonObject); + Long expenseAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, + jsonObject); ProvisioningCategory provisioningCategory = provisioningCategoryRepository.findById(categoryId).orElse(null); GLAccount liabilityAccount = glAccountRepository.findById(liabilityAccountId).orElse(null); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaReadPlatformService.java index e4e425fb0..457940bf0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaReadPlatformService.java @@ -21,14 +21,13 @@ package org.apache.fineract.organisation.provisioning.service; import java.util.Collection; import org.apache.fineract.organisation.provisioning.data.ProvisioningCriteriaData; - public interface ProvisioningCriteriaReadPlatformService { - public ProvisioningCriteriaData retrievePrivisiongCriteriaTemplate() ; + public ProvisioningCriteriaData retrievePrivisiongCriteriaTemplate(); - public ProvisioningCriteriaData retrieveProvisioningCriteria(Long criteriaId) ; + public ProvisioningCriteriaData retrieveProvisioningCriteria(Long criteriaId); - public Collection retrieveAllProvisioningCriterias() ; + public Collection retrieveAllProvisioningCriterias(); - public ProvisioningCriteriaData retrievePrivisiongCriteriaTemplate(ProvisioningCriteriaData data) ; + public ProvisioningCriteriaData retrievePrivisiongCriteriaTemplate(ProvisioningCriteriaData data); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaReadPlatformServiceImpl.java index c75b59927..fc805c05f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaReadPlatformServiceImpl.java @@ -90,10 +90,11 @@ public class ProvisioningCriteriaReadPlatformServiceImpl implements Provisioning } return definitions; } + @Override public Collection retrieveAllProvisioningCriterias() { - ProvisioningCriteriaRowMapper mapper = new ProvisioningCriteriaRowMapper() ; - final String sql = "select " + mapper.schema() ; + ProvisioningCriteriaRowMapper mapper = new ProvisioningCriteriaRowMapper(); + final String sql = "select " + mapper.schema(); return this.jdbcTemplate.query(sql, mapper, new Object[] {}); } @@ -101,11 +102,12 @@ public class ProvisioningCriteriaReadPlatformServiceImpl implements Provisioning @Override public ProvisioningCriteriaData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - Long criteriaId = rs.getLong("id") ; + Long criteriaId = rs.getLong("id"); String criteriaName = rs.getString("criteriaName"); - String createdBy = rs.getString("username") ; - return ProvisioningCriteriaData.toLookup(criteriaId, criteriaName, createdBy) ; + String createdBy = rs.getString("username"); + return ProvisioningCriteriaData.toLookup(criteriaId, criteriaName, createdBy); } + public String schema() { return "mpc.id as id, mpc.criteria_name as criteriaName, appu.username as username from m_provisioning_criteria as mpc LEFT JOIN m_appuser appu on mpc.createdby_id=appu.id"; } @@ -115,13 +117,13 @@ public class ProvisioningCriteriaReadPlatformServiceImpl implements Provisioning public ProvisioningCriteriaData retrieveProvisioningCriteria(Long criteriaId) { try { String criteriaName = retrieveCriteriaName(criteriaId); - Collection loanProducts = loanProductReaPlatformService - .retrieveAllLoanProductsForLookup("select product_id from m_loanproduct_provisioning_mapping where m_loanproduct_provisioning_mapping.criteria_id=" + Collection loanProducts = loanProductReaPlatformService.retrieveAllLoanProductsForLookup( + "select product_id from m_loanproduct_provisioning_mapping where m_loanproduct_provisioning_mapping.criteria_id=" + criteriaId); List definitions = retrieveProvisioningDefinitions(criteriaId); return ProvisioningCriteriaData.toLookup(criteriaId, criteriaName, loanProducts, definitions); - }catch(EmptyResultDataAccessException e) { - throw new ProvisioningCriteriaNotFoundException(criteriaId) ; + } catch (EmptyResultDataAccessException e) { + throw new ProvisioningCriteriaNotFoundException(criteriaId); } } @@ -137,8 +139,7 @@ public class ProvisioningCriteriaReadPlatformServiceImpl implements Provisioning private final StringBuilder sqlQuery = new StringBuilder() .append("pc.id, pc.criteria_id, pc.category_id, mpc.category_name, pc.min_age, pc.max_age, ") .append("pc.provision_percentage, pc.liability_account, pc.expense_account, lia.gl_code as liabilitycode, expe.gl_code as expensecode, ") - .append("lia.name as liabilityname, expe.name as expensename ") - .append("from m_provisioning_criteria_definition as pc ") + .append("lia.name as liabilityname, expe.name as expensename ").append("from m_provisioning_criteria_definition as pc ") .append("LEFT JOIN acc_gl_account lia ON lia.id = pc.liability_account ") .append("LEFT JOIN acc_gl_account expe ON expe.id = pc.expense_account ") .append("LEFT JOIN m_provision_category mpc ON mpc.id = pc.category_id"); @@ -155,10 +156,10 @@ public class ProvisioningCriteriaReadPlatformServiceImpl implements Provisioning BigDecimal provisioningPercentage = rs.getBigDecimal("provision_percentage"); Long liabilityAccount = rs.getLong("liability_account"); String liabilityAccountCode = rs.getString("liabilitycode"); - String liabilityAccountName = rs.getString("liabilityname") ; + String liabilityAccountName = rs.getString("liabilityname"); Long expenseAccount = rs.getLong("expense_account"); String expenseAccountCode = rs.getString("expensecode"); - String expenseAccountName = rs.getString("expensename") ; + String expenseAccountName = rs.getString("expensename"); return new ProvisioningCriteriaDefinitionData(id, categoryId, categoryName, minAge, maxAge, provisioningPercentage, liabilityAccount, liabilityAccountCode, liabilityAccountName, expenseAccount, expenseAccountCode, expenseAccountName); @@ -186,4 +187,4 @@ public class ProvisioningCriteriaReadPlatformServiceImpl implements Provisioning return " pc.criteria_name as criteriaName"; } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaWritePlatformService.java index 2cef66374..3d6f0a2be 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaWritePlatformService.java @@ -21,12 +21,11 @@ package org.apache.fineract.organisation.provisioning.service; import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; - public interface ProvisioningCriteriaWritePlatformService { CommandProcessingResult createProvisioningCriteria(JsonCommand command); - CommandProcessingResult updateProvisioningCriteria(final Long categoryId, JsonCommand command) ; + CommandProcessingResult updateProvisioningCriteria(final Long categoryId, JsonCommand command); - CommandProcessingResult deleteProvisioningCriteria(Long entryId) ; + CommandProcessingResult deleteProvisioningCriteria(Long entryId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl.java index bc86c2d75..cbef5bef2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/provisioning/service/ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl.java @@ -60,20 +60,21 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement private final ProvisioningCriteriaRepository provisioningCriteriaRepository; private final FromJsonHelper fromApiJsonHelper; private final GLAccountRepository glAccountRepository; - private final ProvisioningEntriesReadPlatformService provisioningEntriesReadPlatformService ; + private final ProvisioningEntriesReadPlatformService provisioningEntriesReadPlatformService; @Autowired - public ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl(final ProvisioningCriteriaDefinitionJsonDeserializer fromApiJsonDeserializer, - final ProvisioningCriteriaAssembler provisioningCriteriaAssembler, final ProvisioningCriteriaRepository provisioningCriteriaRepository, - final FromJsonHelper fromApiJsonHelper, + public ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl( + final ProvisioningCriteriaDefinitionJsonDeserializer fromApiJsonDeserializer, + final ProvisioningCriteriaAssembler provisioningCriteriaAssembler, + final ProvisioningCriteriaRepository provisioningCriteriaRepository, final FromJsonHelper fromApiJsonHelper, final GLAccountRepository glAccountRepository, final ProvisioningEntriesReadPlatformService provisioningEntriesReadPlatformService) { this.fromApiJsonDeserializer = fromApiJsonDeserializer; this.provisioningCriteriaAssembler = provisioningCriteriaAssembler; this.provisioningCriteriaRepository = provisioningCriteriaRepository; - this.fromApiJsonHelper = fromApiJsonHelper ; - this.glAccountRepository = glAccountRepository ; - this.provisioningEntriesReadPlatformService = provisioningEntriesReadPlatformService ; + this.fromApiJsonHelper = fromApiJsonHelper; + this.glAccountRepository = glAccountRepository; + this.provisioningEntriesReadPlatformService = provisioningEntriesReadPlatformService; } @Override @@ -82,12 +83,13 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement this.fromApiJsonDeserializer.validateForCreate(command.json()); ProvisioningCriteria provisioningCriteria = provisioningCriteriaAssembler.fromParsedJson(command.parsedJson()); this.provisioningCriteriaRepository.save(provisioningCriteria); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(provisioningCriteria.getId()).build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(provisioningCriteria.getId()) + .build(); } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -95,10 +97,9 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement @Override public CommandProcessingResult deleteProvisioningCriteria(Long criteriaId) { - this.provisioningCriteriaRepository.findById(criteriaId) - .orElseThrow(() -> new ProvisioningCriteriaNotFoundException(criteriaId)); - if(this.provisioningEntriesReadPlatformService.retrieveProvisioningEntryDataByCriteriaId(criteriaId) != null) { - throw new ProvisioningCriteriaCannotBeDeletedException(criteriaId) ; + this.provisioningCriteriaRepository.findById(criteriaId).orElseThrow(() -> new ProvisioningCriteriaNotFoundException(criteriaId)); + if (this.provisioningEntriesReadPlatformService.retrieveProvisioningEntryDataByCriteriaId(criteriaId) != null) { + throw new ProvisioningCriteriaCannotBeDeletedException(criteriaId); } this.provisioningCriteriaRepository.deleteById(criteriaId); return new CommandProcessingResultBuilder().withEntityId(criteriaId).build(); @@ -109,21 +110,20 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement try { this.fromApiJsonDeserializer.validateForUpdate(command.json()); ProvisioningCriteria provisioningCriteria = provisioningCriteriaRepository.findById(criteriaId).orElse(null); - if(provisioningCriteria == null) { - throw new ProvisioningCategoryNotFoundException(criteriaId) ; + if (provisioningCriteria == null) { throw new ProvisioningCategoryNotFoundException(criteriaId); } + List products = this.provisioningCriteriaAssembler.parseLoanProducts(command.parsedJson()); + final Map changes = provisioningCriteria.update(command, products); + if (!changes.isEmpty()) { + updateProvisioningCriteriaDefinitions(provisioningCriteria, command); + provisioningCriteriaRepository.saveAndFlush(provisioningCriteria); } - List products = this.provisioningCriteriaAssembler.parseLoanProducts(command.parsedJson()) ; - final Map changes = provisioningCriteria.update(command, products) ; - if(!changes.isEmpty()) { - updateProvisioningCriteriaDefinitions(provisioningCriteria, command) ; - provisioningCriteriaRepository.saveAndFlush(provisioningCriteria) ; - } - return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(provisioningCriteria.getId()).build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(provisioningCriteria.getId()) + .build(); } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -131,27 +131,29 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement private void updateProvisioningCriteriaDefinitions(ProvisioningCriteria provisioningCriteria, JsonCommand command) { final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(command.parsedJson().getAsJsonObject()); - JsonArray jsonProvisioningCriteria = this.fromApiJsonHelper.extractJsonArrayNamed( - ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, command.parsedJson()); + JsonArray jsonProvisioningCriteria = this.fromApiJsonHelper + .extractJsonArrayNamed(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, command.parsedJson()); for (JsonElement element : jsonProvisioningCriteria) { JsonObject jsonObject = element.getAsJsonObject(); - Long id = this.fromApiJsonHelper.extractLongNamed("id", jsonObject) ; + Long id = this.fromApiJsonHelper.extractLongNamed("id", jsonObject); Long categoryId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, jsonObject); Long minimumAge = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, jsonObject); Long maximumAge = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, jsonObject); - BigDecimal provisioningpercentage = this.fromApiJsonHelper.extractBigDecimalNamed(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, - jsonObject, locale); - Long liabilityAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, jsonObject); - Long expenseAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, jsonObject); + BigDecimal provisioningpercentage = this.fromApiJsonHelper + .extractBigDecimalNamed(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, jsonObject, locale); + Long liabilityAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, + jsonObject); + Long expenseAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, + jsonObject); GLAccount liabilityAccount = glAccountRepository.findById(liabilityAccountId).orElse(null); GLAccount expenseAccount = glAccountRepository.findById(expenseAccountId).orElse(null); - String categoryName = null ; - String liabilityAccountName = null ; - String expenseAccountName = null ; - ProvisioningCriteriaDefinitionData data = new ProvisioningCriteriaDefinitionData(id, categoryId, - categoryName, minimumAge, maximumAge, provisioningpercentage, - liabilityAccount.getId(), liabilityAccount.getGlCode(), liabilityAccountName, expenseAccount.getId(), expenseAccount.getGlCode(), expenseAccountName) ; - provisioningCriteria.update(data, liabilityAccount, expenseAccount) ; + String categoryName = null; + String liabilityAccountName = null; + String expenseAccountName = null; + ProvisioningCriteriaDefinitionData data = new ProvisioningCriteriaDefinitionData(id, categoryId, categoryName, minimumAge, + maximumAge, provisioningpercentage, liabilityAccount.getId(), liabilityAccount.getGlCode(), liabilityAccountName, + expenseAccount.getId(), expenseAccount.getGlCode(), expenseAccountName); + provisioningCriteria.update(data, liabilityAccount, expenseAccount); } } @@ -162,11 +164,10 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement private void handleDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { if (realCause.getMessage().contains("criteria_name")) { final String name = command.stringValueOfParameterNamed("criteria_name"); - throw new PlatformDataIntegrityException("error.msg.provisioning.duplicate.criterianame", "Provisioning Criteria with name `" - + name + "` already exists", "category name", name); - }else if (realCause.getMessage().contains("product_id")) { - throw new PlatformDataIntegrityException( - "error.msg.provisioning.product.id(s).already.associated.existing.criteria", + throw new PlatformDataIntegrityException("error.msg.provisioning.duplicate.criterianame", + "Provisioning Criteria with name `" + name + "` already exists", "category name", name); + } else if (realCause.getMessage().contains("product_id")) { + throw new PlatformDataIntegrityException("error.msg.provisioning.product.id(s).already.associated.existing.criteria", "The selected products already associated with another Provisioning Criteria"); } LOG.error("Error occured.", dve); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/api/StaffApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/api/StaffApiResource.java index 4f2fc4901..c0390f5f5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/api/StaffApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/api/StaffApiResource.java @@ -69,10 +69,9 @@ import org.springframework.stereotype.Component; @Path("/staff") @Component @Scope("singleton") -@Api(tags = {"Staff"}) +@Api(tags = { "Staff" }) @SwaggerDefinition(tags = { - @Tag(name = "Staff", description = "Allows you to model staff members. At present the key role of significance is whether this staff member is a loan officer or not.") -}) + @Tag(name = "Staff", description = "Allows you to model staff members. At present the key role of significance is whether this staff member is a loan officer or not.") }) public class StaffApiResource { /** @@ -93,7 +92,6 @@ public class StaffApiResource { private final BulkImportWorkbookService bulkImportWorkbookService; private final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService; - @Autowired public StaffApiResource(final PlatformSecurityContext context, final StaffReadPlatformService readPlatformService, final OfficeReadPlatformService officeReadPlatformService, final DefaultToApiJsonSerializer toApiJsonSerializer, @@ -107,16 +105,23 @@ public class StaffApiResource { this.toApiJsonSerializer = toApiJsonSerializer; this.apiRequestParameterHelper = apiRequestParameterHelper; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; } @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Staff", notes = "Returns the list of staff members.\n" + "\n" + "Example Requests:\n" + "\n" + "staff\n\n\n\n" + "\n" + "Retrieve a Staff by status\n" + "\n" + "Returns the details of a Staff based on status.\n" + "\n" + "By default it Returns all the ACTIVE Staff.\n" + "\n" + "If status=INACTIVE, then it returns all INACTIVE Staff.\n" + "\n" + "and for status=ALL, it Returns both ACTIVE and INACTIVE Staff.\n" + "\n" + "Example Requests:\n" + "\n" + "staff?status=active") - @ApiResponses({@ApiResponse(code = 200, message = "", response = StaffApiResourceSwagger.GetStaffResponse.class, responseContainer = "List"), @ApiResponse(code = 200, message = "GET https://DomainName/api/v1/staff?status={ACTIVE|INACTIVE|ALL}", response = StaffApiResourceSwagger.GetStaffResponse.class)}) - public String retrieveStaff(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, + @ApiOperation(value = "Retrieve Staff", notes = "Returns the list of staff members.\n" + "\n" + "Example Requests:\n" + "\n" + + "staff\n\n\n\n" + "\n" + "Retrieve a Staff by status\n" + "\n" + "Returns the details of a Staff based on status.\n" + "\n" + + "By default it Returns all the ACTIVE Staff.\n" + "\n" + "If status=INACTIVE, then it returns all INACTIVE Staff.\n" + "\n" + + "and for status=ALL, it Returns both ACTIVE and INACTIVE Staff.\n" + "\n" + "Example Requests:\n" + "\n" + + "staff?status=active") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = StaffApiResourceSwagger.GetStaffResponse.class, responseContainer = "List"), + @ApiResponse(code = 200, message = "GET https://DomainName/api/v1/staff?status={ACTIVE|INACTIVE|ALL}", response = StaffApiResourceSwagger.GetStaffResponse.class) }) + public String retrieveStaff(@Context final UriInfo uriInfo, + @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, @DefaultValue("false") @QueryParam("staffInOfficeHierarchy") @ApiParam(value = "staffInOfficeHierarchy") final boolean staffInOfficeHierarchy, @DefaultValue("false") @QueryParam("loanOfficersOnly") @ApiParam(value = "loanOfficersOnly") final boolean loanOfficersOnly, @@ -138,9 +143,11 @@ public class StaffApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a staff member", notes = "Creates a staff member.\n" + "\n" + "Mandatory Fields: \n" + "officeId, firstname, lastname\n" + "\n" + "Optional Fields: \n" + "isLoanOfficer, isActive") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = StaffApiResourceSwagger.PostStaffRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = StaffApiResourceSwagger.PostStaffResponse.class)}) + @ApiOperation(value = "Create a staff member", notes = "Creates a staff member.\n" + "\n" + "Mandatory Fields: \n" + + "officeId, firstname, lastname\n" + "\n" + "Optional Fields: \n" + "isLoanOfficer, isActive") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = StaffApiResourceSwagger.PostStaffRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = StaffApiResourceSwagger.PostStaffResponse.class) }) public String createStaff(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createStaff().withJson(apiRequestBodyAsJson).build(); @@ -154,8 +161,9 @@ public class StaffApiResource { @Path("{staffId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Staff Member", notes = "Returns the details of a Staff Member.\n" + "\n" + "Example Requests:\n" + "\n" + "staff/1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = StaffApiResourceSwagger.GetStaffResponse.class)}) + @ApiOperation(value = "Retrieve a Staff Member", notes = "Returns the details of a Staff Member.\n" + "\n" + "Example Requests:\n" + + "\n" + "staff/1") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = StaffApiResourceSwagger.GetStaffResponse.class) }) public String retreiveStaff(@PathParam("staffId") @ApiParam(value = "staffId") final Long staffId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -175,9 +183,11 @@ public class StaffApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Staff Member", notes = "Updates the details of a staff member.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = StaffApiResourceSwagger.PutStaffRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = StaffApiResourceSwagger.PutStaffResponse.class)}) - public String updateStaff(@PathParam("staffId") @ApiParam(value = "staffId") final Long staffId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = StaffApiResourceSwagger.PutStaffRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = StaffApiResourceSwagger.PutStaffResponse.class) }) + public String updateStaff(@PathParam("staffId") @ApiParam(value = "staffId") final Long staffId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateStaff(staffId).withJson(apiRequestBodyAsJson).build(); @@ -189,20 +199,18 @@ public class StaffApiResource { @GET @Path("downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getStaffTemplate(@QueryParam("officeId")final Long officeId, - @QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.STAFF.toString(), officeId,null,dateFormat); + public Response getStaffTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("dateFormat") final String dateFormat) { + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.STAFF.toString(), officeId, null, dateFormat); } @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postStaffTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, - @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId = this. bulkImportWorkbookService.importWorkbook(GlobalEntityType.STAFF.toString(), uploadedInputStream, - fileDetail,locale,dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.STAFF.toString(), uploadedInputStream, + fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/api/StaffApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/api/StaffApiResourceSwagger.java index 9c81819a5..b4dbd8a19 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/api/StaffApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/api/StaffApiResourceSwagger.java @@ -27,15 +27,18 @@ import org.joda.time.LocalDate; */ final class StaffApiResourceSwagger { + private StaffApiResourceSwagger() { } @ApiModel(value = "PostStaffRequest") public static final class PostStaffRequest { + private PostStaffRequest() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "John") @@ -61,9 +64,11 @@ final class StaffApiResourceSwagger { @ApiModel(value = "PostStaffResponse") public static final class PostStaffResponse { + private PostStaffResponse() { } + @ApiModelProperty(example = "1") public Long officeId; @ApiModelProperty(example = "1") @@ -72,9 +77,11 @@ final class StaffApiResourceSwagger { @ApiModel(value = "GetStaffResponse") public static final class GetStaffResponse { + private GetStaffResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "John") @@ -100,9 +107,11 @@ final class StaffApiResourceSwagger { @ApiModel(value = "PutStaffRequest") public static final class PutStaffRequest { + private PutStaffRequest() { } + @ApiModelProperty(example = "false") public Boolean isLoanOfficer; @ApiModelProperty(example = "17Hbb") @@ -112,16 +121,21 @@ final class StaffApiResourceSwagger { @ApiModel(value = "PutStaffResponse") public static final class PutStaffResponse { + private PutStaffResponse() { } + final class PutStaffResponseChanges { - private PutStaffResponseChanges(){} + + private PutStaffResponseChanges() {} + @ApiModelProperty(example = "false") public Boolean isLoanOfficer; @ApiModelProperty(example = "17Hbb") public String externalId; } + @ApiModelProperty(example = "1") public Long officeId; @ApiModelProperty(example = "1") diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/BulkTransferLoanOfficerData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/BulkTransferLoanOfficerData.java index f5063ba9a..b46827547 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/BulkTransferLoanOfficerData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/BulkTransferLoanOfficerData.java @@ -64,4 +64,4 @@ public class BulkTransferLoanOfficerData { this.loanOfficerOptions = loanOfficerOptions; this.accountSummaryCollection = accountSummaryCollection; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/StaffAccountSummaryCollectionData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/StaffAccountSummaryCollectionData.java index 6885cbebd..8d9fb9199 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/StaffAccountSummaryCollectionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/StaffAccountSummaryCollectionData.java @@ -66,4 +66,4 @@ public class StaffAccountSummaryCollectionData { } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/StaffData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/StaffData.java index 43d74dd89..017efda43 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/StaffData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/data/StaffData.java @@ -40,19 +40,20 @@ public class StaffData implements Serializable { private final Boolean isActive; private final LocalDate joiningDate; - //import fields + // import fields private transient Integer rowIndex; private String dateFormat; private String locale; - public static StaffData importInstance(String externalId, String firstname, String lastname, String mobileNo, Long officeId, Boolean isLoanOfficer, - Boolean isActive, LocalDate joinedOnDate, Integer rowIndex,String locale, String dateFormat){ - return new StaffData(externalId,firstname,lastname,mobileNo,officeId,isLoanOfficer,isActive, - joinedOnDate,rowIndex,locale,dateFormat); + public static StaffData importInstance(String externalId, String firstname, String lastname, String mobileNo, Long officeId, + Boolean isLoanOfficer, Boolean isActive, LocalDate joinedOnDate, Integer rowIndex, String locale, String dateFormat) { + return new StaffData(externalId, firstname, lastname, mobileNo, officeId, isLoanOfficer, isActive, joinedOnDate, rowIndex, locale, + dateFormat); } + private StaffData(String externalId, String firstname, String lastname, String mobileNo, Long officeId, Boolean isLoanOfficer, - Boolean isActive, LocalDate joiningDate, Integer rowIndex,String locale, String dateFormat) { + Boolean isActive, LocalDate joiningDate, Integer rowIndex, String locale, String dateFormat) { this.externalId = externalId; this.firstname = firstname; @@ -63,8 +64,8 @@ public class StaffData implements Serializable { this.isActive = isActive; this.joiningDate = joiningDate; this.rowIndex = rowIndex; - this.dateFormat= dateFormat; - this.locale= locale; + this.dateFormat = dateFormat; + this.locale = locale; this.allowedOffices = null; this.id = null; this.officeName = null; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffEnumerations.java index 9a5312f72..7c513b628 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffEnumerations.java @@ -47,4 +47,4 @@ public class StaffEnumerations { } return optionData; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffOrganisationalRoleType.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffOrganisationalRoleType.java index b2bd26394..ec5750fac 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffOrganisationalRoleType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffOrganisationalRoleType.java @@ -60,4 +60,4 @@ public enum StaffOrganisationalRoleType { } return chargeCalculationType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffRepository.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffRepository.java index e716a00ab..7ab0f273b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffRepository.java @@ -33,4 +33,4 @@ public interface StaffRepository extends JpaRepository, JpaSpecific @Query(FIND_BY_OFFICE_QUERY) public Staff findByOffice(@Param("id") Long id, @Param("officeId") Long officeId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffRepositoryWrapper.java old mode 100755 new mode 100644 index d2f84ea57..26c1dba02 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/domain/StaffRepositoryWrapper.java @@ -39,8 +39,7 @@ public class StaffRepositoryWrapper { } public Staff findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new StaffNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new StaffNotFoundException(id)); } public Staff findByOfficeWithNotFoundDetection(final Long staffId, final Long officeId) { @@ -50,13 +49,13 @@ public class StaffRepositoryWrapper { } public Staff findByOfficeHierarchyWithNotFoundDetection(final Long staffId, final String hierarchy) { - final Staff staff = this.repository.findById(staffId) - .orElseThrow(() -> new StaffNotFoundException(staffId)); + final Staff staff = this.repository.findById(staffId).orElseThrow(() -> new StaffNotFoundException(staffId)); final String staffhierarchy = staff.office().getHierarchy(); if (!hierarchy.startsWith(staffhierarchy)) { throw new StaffNotFoundException(staffId); } return staff; } - public void save(final Staff staff){ + + public void save(final Staff staff) { this.repository.save(staff); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/exception/StaffNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/exception/StaffNotFoundException.java index cfa5c3239..cee4520e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/exception/StaffNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/exception/StaffNotFoundException.java @@ -28,4 +28,4 @@ public class StaffNotFoundException extends AbstractPlatformResourceNotFoundExce public StaffNotFoundException(final Long id) { super("error.msg.staff.id.invalid", "Staff with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/exception/StaffRoleException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/exception/StaffRoleException.java index ec782e4f1..30f1d774d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/exception/StaffRoleException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/exception/StaffRoleException.java @@ -26,7 +26,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class StaffRoleException extends AbstractPlatformResourceNotFoundException { public static enum StaffRole { - LOAN_OFFICER, BRANCH_MANAGER,SAVINGS_OFFICER; + + LOAN_OFFICER, BRANCH_MANAGER, SAVINGS_OFFICER; @Override public String toString() { @@ -37,4 +38,4 @@ public class StaffRoleException extends AbstractPlatformResourceNotFoundExceptio public StaffRoleException(final Long id, final StaffRole role) { super("error.msg.staff.id.invalid.role", "Staff with identifier " + id + " is not a " + role.toString(), id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/handler/CreateStaffCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/handler/CreateStaffCommandHandler.java index 75a17b256..34aff96b0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/handler/CreateStaffCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/handler/CreateStaffCommandHandler.java @@ -44,4 +44,4 @@ public class CreateStaffCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createStaff(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/handler/UpdateStaffCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/handler/UpdateStaffCommandHandler.java index 37ba16783..32707e3aa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/handler/UpdateStaffCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/handler/UpdateStaffCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateStaffCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.updateStaff(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/serialization/StaffCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/serialization/StaffCommandFromApiJsonDeserializer.java index f88f2902a..356809aaf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/serialization/StaffCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/serialization/StaffCommandFromApiJsonDeserializer.java @@ -52,7 +52,6 @@ public final class StaffCommandFromApiJsonDeserializer { private final StaffReadPlatformService staffReadPlatformService; - @Autowired public StaffCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper, final StaffReadPlatformService staffReadPlatformService) { @@ -121,7 +120,7 @@ public final class StaffCommandFromApiJsonDeserializer { validateForUpdate(json, null); } - public void validateForUpdate(final String json,Long staffId) { + public void validateForUpdate(final String json, Long staffId) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); @@ -162,14 +161,15 @@ public final class StaffCommandFromApiJsonDeserializer { final Boolean activeFlag = this.fromApiJsonHelper.extractBooleanNamed("isActive", element); - //Need to add here check to see if any clients, group, account and loans are assigned to this staff if staff is being set to inactive --LJB + // Need to add here check to see if any clients, group, account and + // loans are assigned to this staff if staff is being set to + // inactive --LJB final Boolean forceStatus = this.fromApiJsonHelper.extractBooleanNamed("forceStatus", element); - if ((!activeFlag && forceStatus == null) || - (!activeFlag && forceStatus)) { - Object[] result = staffReadPlatformService.hasAssociatedItems(staffId); + if ((!activeFlag && forceStatus == null) || (!activeFlag && forceStatus)) { + Object[] result = staffReadPlatformService.hasAssociatedItems(staffId); if (result != null && result.length > 0) { - baseDataValidator.reset().parameter("isactive").failWithCode("staff.is.assigned",result); + baseDataValidator.reset().parameter("isactive").failWithCode("staff.is.assigned", result); } } @@ -200,7 +200,9 @@ public final class StaffCommandFromApiJsonDeserializer { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffReadPlatformService.java index 5b2048ea7..29008405b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffReadPlatformService.java @@ -38,4 +38,4 @@ public interface StaffReadPlatformService { Collection retrieveAllStaff(String sqlSearch, Long officeId, boolean loanOfficersOnly, String status); Object[] hasAssociatedItems(final Long staffId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffReadPlatformServiceImpl.java index 4803cf8ed..4f183b05f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffReadPlatformServiceImpl.java @@ -64,8 +64,7 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { public String schema() { return " s.id as id,s.office_id as officeId, o.name as officeName, s.firstname as firstname, s.lastname as lastname," + " s.display_name as displayName, s.is_loan_officer as isLoanOfficer, s.external_id as externalId, s.mobile_no as mobileNo," - + " s.is_active as isActive, s.joining_date as joiningDate from m_staff s " - + " join m_office o on o.id = s.office_id"; + + " s.is_active as isActive, s.joining_date as joiningDate from m_staff s " + " join m_office o on o.id = s.office_id"; } @Override @@ -166,8 +165,10 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { @Override public Collection retrieveAllStaffForDropdown(final Long officeId) { - //adding the Authorization criteria so that a user cannot see an employee who does not belong to his office or a sub office for his office. - final String hierarchy = this.context.authenticatedUser().getOffice().getHierarchy()+"%"; + // adding the Authorization criteria so that a user cannot see an + // employee who does not belong to his office or a sub office for his + // office. + final String hierarchy = this.context.authenticatedUser().getOffice().getHierarchy() + "%"; final Long defaultOfficeId = defaultToUsersOfficeIfNull(officeId); @@ -187,13 +188,14 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { @Override public StaffData retrieveStaff(final Long staffId) { - //adding the Authorization criteria so that a user cannot see an employee who does not belong to his office or a sub office for his office. - final String hierarchy = this.context.authenticatedUser().getOffice().getHierarchy()+ "%"; - + // adding the Authorization criteria so that a user cannot see an + // employee who does not belong to his office or a sub office for his + // office. + final String hierarchy = this.context.authenticatedUser().getOffice().getHierarchy() + "%"; try { final StaffMapper rm = new StaffMapper(); - final String sql = "select " + rm.schema() + " where s.id = ? and o.hierarchy like ? " ; + final String sql = "select " + rm.schema() + " where s.id = ? and o.hierarchy like ? "; return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { staffId, hierarchy }); } catch (final EmptyResultDataAccessException e) { @@ -212,15 +214,13 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { final StaffMapper rm = new StaffMapper(); String sql = "select " + rm.schema(); - final String hierarchy = this.context.authenticatedUser().getOffice().getHierarchy()+"%"; - if (StringUtils.isNotBlank(extraCriteria)){ + final String hierarchy = this.context.authenticatedUser().getOffice().getHierarchy() + "%"; + if (StringUtils.isNotBlank(extraCriteria)) { sql += " where " + extraCriteria; } sql = sql + " order by s.lastname"; - if(officeId==null){ - return this.jdbcTemplate.query(sql, rm, new Object[] {hierarchy }); - } - return this.jdbcTemplate.query(sql, rm, new Object[] {officeId, hierarchy }); + if (officeId == null) { return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchy }); } + return this.jdbcTemplate.query(sql, rm, new Object[] { officeId, hierarchy }); } private String getStaffCriteria(final String sqlSearch, final Long officeId, final boolean loanOfficersOnly, final String status) { @@ -240,18 +240,20 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { } // Passing status parameter to get ACTIVE (By Default), INACTIVE or ALL // (Both active and Inactive) employees - if (status!=null) { + if (status != null) { if (status.equalsIgnoreCase("active")) { extraCriteria.append(" and s.is_active = 1 "); } else if (status.equalsIgnoreCase("inActive")) { extraCriteria.append(" and s.is_active = 0 "); - } else{ + } else { if (!status.equalsIgnoreCase("all")) { - throw new UnrecognizedQueryParamException("status", status, new Object[]{"all", "active", "inactive"}); + throw new UnrecognizedQueryParamException("status", status, new Object[] { "all", "active", "inactive" }); } } } - //adding the Authorization criteria so that a user cannot see an employee who does not belong to his office or a sub office for his office. + // adding the Authorization criteria so that a user cannot see an + // employee who does not belong to his office or a sub office for his + // office. extraCriteria.append(" and o.hierarchy like ? "); @@ -272,41 +274,33 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { } @Override - public Object[] hasAssociatedItems(final Long staffId){ + public Object[] hasAssociatedItems(final Long staffId) { ArrayList params = new ArrayList(); - String sql = "select c.display_name as client, g.display_name as grp,l.loan_officer_id as loan, s.field_officer_id as sav"+ - " from m_staff staff "+ - " left outer join m_client c on staff.id = c.staff_id AND c.status_enum < ? "+ - " left outer join m_group g on staff.id = g.staff_id " + - " left outer join m_loan l on staff.id = l.loan_officer_id and l.loan_status_id < ? " + - " left outer join m_savings_account s on c.staff_id = s.field_officer_id and s.status_enum < ? "+ - " where staff.id = ? "+ - " group by staff.id, client, grp, loan, sav"; + String sql = "select c.display_name as client, g.display_name as grp,l.loan_officer_id as loan, s.field_officer_id as sav" + + " from m_staff staff " + " left outer join m_client c on staff.id = c.staff_id AND c.status_enum < ? " + + " left outer join m_group g on staff.id = g.staff_id " + + " left outer join m_loan l on staff.id = l.loan_officer_id and l.loan_status_id < ? " + + " left outer join m_savings_account s on c.staff_id = s.field_officer_id and s.status_enum < ? " + + " where staff.id = ? " + " group by staff.id, client, grp, loan, sav"; - - List> result = this.jdbcTemplate.queryForList( - sql, - new Object[] { - ClientStatus.CLOSED.getValue(), - LoanStatus.WITHDRAWN_BY_CLIENT.getValue(), - SavingsAccountStatusType.WITHDRAWN_BY_APPLICANT - .getValue(), staffId }); + List> result = this.jdbcTemplate.queryForList(sql, new Object[] { ClientStatus.CLOSED.getValue(), + LoanStatus.WITHDRAWN_BY_CLIENT.getValue(), SavingsAccountStatusType.WITHDRAWN_BY_APPLICANT.getValue(), staffId }); if (result != null) { - for (Map map : result) { - if (map.get("client") != null) { - params.add("client"); - } - if (map.get("grp") != null) { - params.add("group"); - } - if (map.get("loan") != null) { - params.add("loan"); - } - if (map.get("sav") != null) { - params.add("savings account"); - } - } + for (Map map : result) { + if (map.get("client") != null) { + params.add("client"); + } + if (map.get("grp") != null) { + params.add("group"); + } + if (map.get("loan") != null) { + params.add("loan"); + } + if (map.get("sav") != null) { + params.add("savings account"); + } + } } return params.toArray(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffWritePlatformService.java index c3682b407..a88dadcb1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffWritePlatformService.java @@ -26,4 +26,4 @@ public interface StaffWritePlatformService { CommandProcessingResult createStaff(final JsonCommand command); CommandProcessingResult updateStaff(final Long staffId, final JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java index 44ad74037..907f67467 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java @@ -77,8 +77,8 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla } catch (final DataIntegrityViolationException dve) { handleStaffDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleStaffDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -91,8 +91,7 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla try { this.fromApiJsonDeserializer.validateForUpdate(command.json(), staffId); - final Staff staffForUpdate = this.staffRepository.findById(staffId) - .orElseThrow(() -> new StaffNotFoundException(staffId)); + final Staff staffForUpdate = this.staffRepository.findById(staffId).orElseThrow(() -> new StaffNotFoundException(staffId)); final Map changesOnly = staffForUpdate.update(command); if (changesOnly.containsKey("officeId")) { @@ -110,8 +109,8 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla } catch (final DataIntegrityViolationException dve) { handleStaffDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleStaffDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -126,8 +125,8 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla if (realCause.getMessage().contains("external_id")) { final String externalId = command.stringValueOfParameterNamed("externalId"); - throw new PlatformDataIntegrityException("error.msg.staff.duplicate.externalId", "Staff with externalId `" + externalId - + "` already exists", "externalId", externalId); + throw new PlatformDataIntegrityException("error.msg.staff.duplicate.externalId", + "Staff with externalId `" + externalId + "` already exists", "externalId", externalId); } else if (realCause.getMessage().contains("display_name")) { final String lastname = command.stringValueOfParameterNamed("lastname"); String displayName = lastname; @@ -135,8 +134,8 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla final String firstname = command.stringValueOfParameterNamed("firstname"); displayName = lastname + ", " + firstname; } - throw new PlatformDataIntegrityException("error.msg.staff.duplicate.displayName", "A staff with the given display name '" - + displayName + "' already exists", "displayName", displayName); + throw new PlatformDataIntegrityException("error.msg.staff.duplicate.displayName", + "A staff with the given display name '" + displayName + "' already exists", "displayName", displayName); } LOG.error("Error occured.", dve); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/CashierApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/CashierApiResource.java index 8fa1a7238..e85ee4f04 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/CashierApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/CashierApiResource.java @@ -41,10 +41,8 @@ import org.springframework.stereotype.Component; @Path("cashiers") @Component @Scope("singleton") -@Api(tags = {"Cashiers"}) -@SwaggerDefinition(tags = { - @Tag(name = "Cashiers", description = "") -}) +@Api(tags = { "Cashiers" }) +@SwaggerDefinition(tags = { @Tag(name = "Cashiers", description = "") }) public class CashierApiResource { private final DefaultToApiJsonSerializer jsonSerializer; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerApiResource.java index 9dfd0e512..be06cae6a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerApiResource.java @@ -64,10 +64,9 @@ import org.springframework.stereotype.Component; @Path("tellers") @Component @Scope("singleton") -@Api(tags = {"Teller Cash Management"}) +@Api(tags = { "Teller Cash Management" }) @SwaggerDefinition(tags = { - @Tag(name = "Teller Cash Management", description = "Teller cash management which will allow an organization to manage their cash transactions at branches or head office more effectively.") -}) + @Tag(name = "Teller Cash Management", description = "Teller cash management which will allow an organization to manage their cash transactions at branches or head office more effectively.") }) public class TellerApiResource { private final PlatformSecurityContext securityContext; @@ -90,7 +89,8 @@ public class TellerApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "List all tellers", notes = "Retrieves list tellers") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersResponse.class, responseContainer = "List")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersResponse.class, responseContainer = "List") }) public String getTellerData(@QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId) { final Collection foundTellers = this.readPlatformService.getTellers(officeId); @@ -102,7 +102,7 @@ public class TellerApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Retrieve tellers", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersResponse.class) }) public String findTeller(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId) { final TellerData teller = this.readPlatformService.findTeller(tellerId); @@ -112,9 +112,11 @@ public class TellerApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create teller", notes = "Mandatory Fields\n" + "Teller name, OfficeId, Description, Start Date, Status\n" + "Optional Fields\n" + "End Date") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PostTellersRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PostTellersResponse.class)}) + @ApiOperation(value = "Create teller", notes = "Mandatory Fields\n" + "Teller name, OfficeId, Description, Start Date, Status\n" + + "Optional Fields\n" + "End Date") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PostTellersRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PostTellersResponse.class) }) public String createTeller(@ApiParam(hidden = true) final String tellerData) { final CommandWrapper request = new CommandWrapperBuilder().createTeller().withJson(tellerData).build(); @@ -128,9 +130,11 @@ public class TellerApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update teller", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PutTellersRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PutTellersResponse.class)}) - public String updateTeller(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @ApiParam(hidden = true) final String tellerData) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PutTellersRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PutTellersResponse.class) }) + public String updateTeller(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @ApiParam(hidden = true) final String tellerData) { final CommandWrapper request = new CommandWrapperBuilder().updateTeller(tellerId).withJson(tellerData).build(); final CommandProcessingResult result = this.commandWritePlatformService.logCommandSource(request); @@ -155,8 +159,9 @@ public class TellerApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "List Cashiers", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersResponse.class)}) - public String getCashierData(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @QueryParam("fromdate") @ApiParam(value = "fromdate") final String fromDateStr, + @ApiResponses({ @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersResponse.class) }) + public String getCashierData(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @QueryParam("fromdate") @ApiParam(value = "fromdate") final String fromDateStr, @QueryParam("todate") @ApiParam(value = "todate") final String toDateStr) { final DateTimeFormatter dateFormatter = ISODateTimeFormat.basicDate(); @@ -181,8 +186,10 @@ public class TellerApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Retrieve a cashier", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersCashierIdResponse.class)}) - public String findCashierData(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId) { + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersCashierIdResponse.class) }) + public String findCashierData(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId) { final CashierData cashier = this.readPlatformService.findCashier(cashierId); return this.jsonSerializer.serialize(cashier); @@ -193,7 +200,8 @@ public class TellerApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Find Cashiers", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersTemplateResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersTemplateResponse.class) }) public String getCashierTemplate(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId) { final TellerData teller = this.readPlatformService.findTeller(tellerId); @@ -208,10 +216,14 @@ public class TellerApiResource { @Path("{tellerId}/cashiers") @Consumes({ MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Cashiers", notes = "Mandatory Fields: \n" + "Cashier/staff, Fromm Date, To Date, Full Day or From time and To time\n" + "\n\n\n" + "Optional Fields: \n" + "Description/Notes") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PostTellersTellerIdCashiersRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PostTellersTellerIdCashiersResponse.class)}) - public String createCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @ApiParam(hidden = true) final String cashierData) { + @ApiOperation(value = "Create Cashiers", notes = "Mandatory Fields: \n" + + "Cashier/staff, Fromm Date, To Date, Full Day or From time and To time\n" + "\n\n\n" + "Optional Fields: \n" + + "Description/Notes") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PostTellersTellerIdCashiersRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PostTellersTellerIdCashiersResponse.class) }) + public String createCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @ApiParam(hidden = true) final String cashierData) { final CommandWrapper request = new CommandWrapperBuilder().allocateTeller(tellerId).withJson(cashierData).build(); final CommandProcessingResult result = this.commandWritePlatformService.logCommandSource(request); @@ -224,9 +236,12 @@ public class TellerApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update Cashier", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PutTellersTellerIdCashiersCashierIdRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PutTellersTellerIdCashiersCashierIdResponse.class)}) - public String updateCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId, + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PutTellersTellerIdCashiersCashierIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PutTellersTellerIdCashiersCashierIdResponse.class) }) + public String updateCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId, @ApiParam(hidden = true) final String cashierDate) { final CommandWrapper request = new CommandWrapperBuilder().updateAllocationTeller(tellerId, cashierId).withJson(cashierDate) .build(); @@ -241,8 +256,10 @@ public class TellerApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Delete Cashier", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.DeleteTellersTellerIdCashiersCashierIdResponse.class)}) - public String deleteCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId) { + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.DeleteTellersTellerIdCashiersCashierIdResponse.class) }) + public String deleteCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId) { final CommandWrapper request = new CommandWrapperBuilder().deleteAllocationTeller(tellerId, cashierId).build(); final CommandProcessingResult result = this.commandWritePlatformService.logCommandSource(request); @@ -255,9 +272,12 @@ public class TellerApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Allocate Cash To Cashier", notes = "Mandatory Fields: \n" + "Date, Amount, Currency, Notes/Comments") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PostTellersTellerIdCashiersCashierIdAllocateRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PostTellersTellerIdCashiersCashierIdAllocateResponse.class)}) - public String allocateCashToCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId, + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PostTellersTellerIdCashiersCashierIdAllocateRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PostTellersTellerIdCashiersCashierIdAllocateResponse.class) }) + public String allocateCashToCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId, @ApiParam(hidden = true) final String cashierTxnData) { final CommandWrapper request = new CommandWrapperBuilder().allocateCashToCashier(tellerId, cashierId).withJson(cashierTxnData) .build(); @@ -273,9 +293,12 @@ public class TellerApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Settle Cash From Cashier", notes = "Mandatory Fields\n" + "Date, Amount, Currency, Notes/Comments") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PostTellersTellerIdCashiersCashierIdSettleRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PostTellersTellerIdCashiersCashierIdSettleResponse.class)}) - public String settleCashFromCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId, + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TellerApiResourceSwagger.PostTellersTellerIdCashiersCashierIdSettleRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.PostTellersTellerIdCashiersCashierIdSettleResponse.class) }) + public String settleCashFromCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId, @ApiParam(hidden = true) final String cashierTxnData) { final CommandWrapper request = new CommandWrapperBuilder().settleCashFromCashier(tellerId, cashierId).withJson(cashierTxnData) .build(); @@ -291,18 +314,23 @@ public class TellerApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Retrieve Cashier Transaction", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersCashiersIdTransactionsResponse.class, responseContainer = "List")}) - public String getTransactionsForCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId, - @QueryParam("currencyCode") @ApiParam(value = "currencyCode") final String currencyCode, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersCashiersIdTransactionsResponse.class, responseContainer = "List") }) + public String getTransactionsForCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId, + @QueryParam("currencyCode") @ApiParam(value = "currencyCode") final String currencyCode, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { final TellerData teller = this.readPlatformService.findTeller(tellerId); final CashierData cashier = this.readPlatformService.findCashier(cashierId); final Date fromDate = null; final Date toDate = null; final SearchParameters searchParameters = SearchParameters.forPagination(offset, limit, orderBy, sortOrder); - final Page cashierTxns = this.readPlatformService.retrieveCashierTransactions(cashierId, false, - fromDate, toDate, currencyCode, searchParameters); + final Page cashierTxns = this.readPlatformService.retrieveCashierTransactions(cashierId, false, fromDate, + toDate, currencyCode, searchParameters); return this.jsonSerializer.serialize(cashierTxns); } @@ -312,11 +340,15 @@ public class TellerApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Transactions Wtih Summary For Cashier", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersCashiersIdSummaryAndTransactionsResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersCashiersIdSummaryAndTransactionsResponse.class) }) public String getTransactionsWtihSummaryForCashier(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, - @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId, @QueryParam("currencyCode") @ApiParam(value = "currencyCode") final String currencyCode, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { + @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId, + @QueryParam("currencyCode") @ApiParam(value = "currencyCode") final String currencyCode, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { final TellerData teller = this.readPlatformService.findTeller(tellerId); final CashierData cashier = this.readPlatformService.findCashier(cashierId); @@ -325,8 +357,8 @@ public class TellerApiResource { final SearchParameters searchParameters = SearchParameters.forPagination(offset, limit, orderBy, sortOrder); - final CashierTransactionsWithSummaryData cashierTxnWithSummary = this.readPlatformService.retrieveCashierTransactionsWithSummary( - cashierId, false, fromDate, toDate, currencyCode, searchParameters); + final CashierTransactionsWithSummaryData cashierTxnWithSummary = this.readPlatformService + .retrieveCashierTransactionsWithSummary(cashierId, false, fromDate, toDate, currencyCode, searchParameters); return this.jsonSerializer.serialize(cashierTxnWithSummary); } @@ -336,8 +368,10 @@ public class TellerApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Retrieve Cashier Transaction Template", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersCashiersIdTransactionsTemplateResponse.class)}) - public String getCashierTxnTemplate(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId) { + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TellerApiResourceSwagger.GetTellersTellerIdCashiersCashiersIdTransactionsTemplateResponse.class) }) + public String getCashierTxnTemplate(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @PathParam("cashierId") @ApiParam(value = "cashierId") final Long cashierId) { final CashierTransactionData cashierTxnTemplate = this.readPlatformService.retrieveCashierTxnTemplate(cashierId); @@ -348,7 +382,8 @@ public class TellerApiResource { @Path("{tellerId}/transactions") @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) - public String getTransactionData(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @QueryParam("dateRange") @ApiParam(value = "dateRange") final String dateRange) { + public String getTransactionData(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @QueryParam("dateRange") @ApiParam(value = "dateRange") final String dateRange) { final DateRange dateRangeHolder = DateRange.fromString(dateRange); final Collection transactions = this.readPlatformService.fetchTellerTransactionsByTellerId(tellerId, @@ -361,7 +396,8 @@ public class TellerApiResource { @Path("{tellerId}/transactions/{transactionId}") @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) - public String findTransactionData(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerid, @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId) { + public String findTransactionData(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerid, + @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId) { final TellerTransactionData transaction = this.readPlatformService.findTellerTransaction(transactionId); return this.jsonSerializer.serialize(transaction); @@ -371,7 +407,8 @@ public class TellerApiResource { @Path("{tellerId}/journals") @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) - public String getJournalData(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, @QueryParam("cashierId") @ApiParam(value = "cashierId") final Long cashierDate, + public String getJournalData(@PathParam("tellerId") @ApiParam(value = "tellerId") final Long tellerId, + @QueryParam("cashierId") @ApiParam(value = "cashierId") final Long cashierDate, @QueryParam("dateRange") @ApiParam(value = "dateRange") final String dateRange) { final DateRange dateRangeHolder = DateRange.fromString(dateRange); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerApiResourceSwagger.java index 858cd577c..2edac30c5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerApiResourceSwagger.java @@ -36,15 +36,18 @@ import org.joda.time.LocalDate; * Created by sanyam on 20/8/17. */ final class TellerApiResourceSwagger { - private TellerApiResourceSwagger(){ + + private TellerApiResourceSwagger() { } @ApiModel(value = "GetTellersResponse") public static final class GetTellersResponse { + private GetTellersResponse() { } + @ApiModelProperty(example = "3") public Long id; @ApiModelProperty(example = "1") @@ -65,9 +68,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PostTellersRequest") public static final class PostTellersRequest { + private PostTellersRequest() { } + @ApiModelProperty(example = "1") public Long officeId; @ApiModelProperty(example = "Teller3") @@ -87,9 +92,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PostTellersResponse") public static final class PostTellersResponse { + private PostTellersResponse() { } + @ApiModelProperty(example = "1") public Long officeId; @ApiModelProperty(example = "5") @@ -98,9 +105,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PutTellersRequest") public static final class PutTellersRequest { + private PutTellersRequest() { } + @ApiModelProperty(example = "Teller3") public String name; @ApiModelProperty(example = "1") @@ -122,11 +131,15 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PutTellersResponse") public static final class PutTellersResponse { + private PutTellersResponse() { } + final class PutTellersResponseChanges { + private PutTellersResponseChanges() {} + @ApiModelProperty(example = "teller cash handling") public String description; @ApiModelProperty(example = "28 February 2015") @@ -138,6 +151,7 @@ final class TellerApiResourceSwagger { @ApiModelProperty(example = "dd-MM-yyyy") public String dateFormat; } + @ApiModelProperty(example = "1") public Long officeId; @ApiModelProperty(example = "5") @@ -148,9 +162,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "GetTellersTellerIdCashiersResponse") public static final class GetTellersTellerIdCashiersResponse { + private GetTellersTellerIdCashiersResponse() { } + @ApiModelProperty(example = "1") public Long tellerId; @ApiModelProperty(example = "Teller1") @@ -165,9 +181,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PostTellersTellerIdCashiersRequest") public static final class PostTellersTellerIdCashiersRequest { + private PostTellersTellerIdCashiersRequest() { } + @ApiModelProperty(example = "28 February 2015") public LocalDate endDate; @ApiModelProperty(example = "teller cash handling") @@ -187,9 +205,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PostTellersTellerIdCashiersResponse") public static final class PostTellersTellerIdCashiersResponse { + private PostTellersTellerIdCashiersResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; @ApiModelProperty(example = "2") @@ -199,9 +219,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "GetTellersTellerIdCashiersCashierIdResponse") public static final class GetTellersTellerIdCashiersCashierIdResponse { + private GetTellersTellerIdCashiersCashierIdResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "1") @@ -229,9 +251,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PutTellersTellerIdCashiersCashierIdRequest") public static final class PutTellersTellerIdCashiersCashierIdRequest { + private PutTellersTellerIdCashiersCashierIdRequest() { } + @ApiModelProperty(example = "25 February 2015") public LocalDate endDate; @ApiModelProperty(example = "Cashier updated.") @@ -251,11 +275,15 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PutTellersTellerIdCashiersCashierIdResponse") public static final class PutTellersTellerIdCashiersCashierIdResponse { + private PutTellersTellerIdCashiersCashierIdResponse() { } + final class PutTellersTellerIdCashiersCashierIdResponseChanges { + private PutTellersTellerIdCashiersCashierIdResponseChanges() {} + @ApiModelProperty(example = "25 February 2015") public LocalDate endDate; @ApiModelProperty(example = "Cashier updated.") @@ -265,6 +293,7 @@ final class TellerApiResourceSwagger { @ApiModelProperty(example = "dd-MM-yyyy") public String dateFormat; } + @ApiModelProperty(example = "1") public Long resourceId; @ApiModelProperty(example = "2") @@ -274,18 +303,22 @@ final class TellerApiResourceSwagger { @ApiModel(value = "DeleteTellersTellerIdCashiersCashierIdResponse") public static final class DeleteTellersTellerIdCashiersCashierIdResponse { + private DeleteTellersTellerIdCashiersCashierIdResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } @ApiModel(value = "GetTellersTellerIdCashiersTemplateResponse") public static final class GetTellersTellerIdCashiersTemplateResponse { + private GetTellersTellerIdCashiersTemplateResponse() { } + @ApiModelProperty(example = "1") public Long tellerId; @ApiModelProperty(example = "Teller1") @@ -299,9 +332,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "GetTellersTellerIdCashiersCashiersIdTransactionsResponse") public static final class GetTellersTellerIdCashiersCashiersIdTransactionsResponse { + private GetTellersTellerIdCashiersCashiersIdTransactionsResponse() { } + @ApiModelProperty(example = "8") public Long id; @ApiModelProperty(example = "15") @@ -331,9 +366,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PostTellersTellerIdCashiersCashierIdAllocateRequest") public static final class PostTellersTellerIdCashiersCashierIdAllocateRequest { + private PostTellersTellerIdCashiersCashierIdAllocateRequest() { } + @ApiModelProperty(example = "USD") public String currencyCode; @ApiModelProperty(example = "5000") @@ -350,9 +387,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PostTellersTellerIdCashiersCashierIdAllocateResponse") public static final class PostTellersTellerIdCashiersCashierIdAllocateResponse { + private PostTellersTellerIdCashiersCashierIdAllocateResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; @ApiModelProperty(example = "4") @@ -361,9 +400,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PostTellersTellerIdCashiersCashierIdSettleRequest") public static final class PostTellersTellerIdCashiersCashierIdSettleRequest { + private PostTellersTellerIdCashiersCashierIdSettleRequest() { } + @ApiModelProperty(example = "USD") public String currencyCode; @ApiModelProperty(example = "2000") @@ -381,9 +422,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "PostTellersTellerIdCashiersCashierIdSettleResponse") public static final class PostTellersTellerIdCashiersCashierIdSettleResponse { + private PostTellersTellerIdCashiersCashierIdSettleResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; @ApiModelProperty(example = "5") @@ -392,9 +435,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "GetTellersTellerIdCashiersCashiersIdSummaryAndTransactionsResponse") public static final class GetTellersTellerIdCashiersCashiersIdSummaryAndTransactionsResponse { + private GetTellersTellerIdCashiersCashiersIdSummaryAndTransactionsResponse() { } + @ApiModelProperty(example = "7000.000000") public BigDecimal sumCashAllocation; @ApiModelProperty(example = "0") @@ -421,9 +466,11 @@ final class TellerApiResourceSwagger { @ApiModel(value = "GetTellersTellerIdCashiersCashiersIdTransactionsTemplateResponse") public static final class GetTellersTellerIdCashiersCashiersIdTransactionsTemplateResponse { + private GetTellersTellerIdCashiersCashiersIdTransactionsTemplateResponse() { } + @ApiModelProperty(example = "1") public Long cashierId; @ApiModelProperty(example = "Head Office") diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerJournalApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerJournalApiResource.java index 0f0c63c5f..ac0b01484 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerJournalApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/api/TellerJournalApiResource.java @@ -41,10 +41,8 @@ import org.springframework.stereotype.Component; @Path("cashiersjournal") @Component @Scope("singleton") -@Api(tags = {"Cashier Journals"}) -@SwaggerDefinition(tags = { - @Tag(name = "Cashier Journals", description = "") -}) +@Api(tags = { "Cashier Journals" }) +@SwaggerDefinition(tags = { @Tag(name = "Cashier Journals", description = "") }) public class TellerJournalApiResource { private final PlatformSecurityContext securityContext; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierData.java index ffcb26be4..7bd815cff 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierData.java @@ -28,7 +28,7 @@ import org.apache.fineract.organisation.staff.data.StaffData; * information, teller, and more. * * @author Markus Geiss - + * * @since 2.0.0 * @see org.apache.fineract.organisation.teller.domain.Cashier * @since 2.0.0 @@ -55,11 +55,9 @@ public final class CashierData implements Serializable { /* * Creates a new cashier. */ - private CashierData(final Long id, final Long officeId, String officeName, - final Long staffId, final String staffName, final Long tellerId, final String tellerName, - final String description, - final Date startDate, final Date endDate, final Boolean isFullDay, - final String startTime, final String endTime, Collection staffOptions) { + private CashierData(final Long id, final Long officeId, String officeName, final Long staffId, final String staffName, + final Long tellerId, final String tellerName, final String description, final Date startDate, final Date endDate, + final Boolean isFullDay, final String startTime, final String endTime, Collection staffOptions) { this.id = id; this.officeId = officeId; this.staffId = staffId; @@ -81,42 +79,56 @@ public final class CashierData implements Serializable { /** * Creates a new cashier. * - *

The valid from/to dates may be used to define a time period in which - * the cashier is assignable to a teller.

+ *

+ * The valid from/to dates may be used to define a time period in which the + * cashier is assignable to a teller. + *

* - *

The start/end times may be used to define a time period in which - * the cashier works part time.

+ *

+ * The start/end times may be used to define a time period in which the + * cashier works part time. + *

* - * @param id the primary key of this cashier - * @param officeId the primary key of the related office - * @param officeName the primary key of the related staff - * @param staffId the primary key of the related teller + * @param id + * the primary key of this cashier + * @param officeId + * the primary key of the related office + * @param officeName + * the primary key of the related staff + * @param staffId + * the primary key of the related teller * @param staffName - * @param tellerId the primary key of the related teller + * @param tellerId + * the primary key of the related teller * @param tellerName - * @param description the description of this cashier - * @param startDate the valid from date of this cashier - * @param endDate the valid to date of this cashier - * @param isFullDay the part time flag of this cashier - * @param startTime the start time of this cashier - * @param endTime the end time of this cashier + * @param description + * the description of this cashier + * @param startDate + * the valid from date of this cashier + * @param endDate + * the valid to date of this cashier + * @param isFullDay + * the part time flag of this cashier + * @param startTime + * the start time of this cashier + * @param endTime + * the end time of this cashier * @return */ - public static CashierData instance(final Long id, final Long officeId, String officeName, - final Long staffId, final String staffName, final Long tellerId, final String tellerName, - final String description, final Date startDate, final Date endDate, + public static CashierData instance(final Long id, final Long officeId, String officeName, final Long staffId, final String staffName, + final Long tellerId, final String tellerName, final String description, final Date startDate, final Date endDate, final Boolean isFullDay, final String startTime, final String endTime) { - return new CashierData(id, officeId, officeName, staffId, staffName, tellerId, tellerName, - description, startDate, endDate, isFullDay, startTime, endTime, null); + return new CashierData(id, officeId, officeName, staffId, staffName, tellerId, tellerName, description, startDate, endDate, + isFullDay, startTime, endTime, null); } /* * Creates a new cashier. */ - public static CashierData template (final Long officeId, final String officeName, - final Long tellerId, final String tellerName, final Collection staffOptions) { - return new CashierData(null, officeId, officeName, null, null, tellerId, tellerName, - null, null, null, null, null, null, staffOptions); + public static CashierData template(final Long officeId, final String officeName, final Long tellerId, final String tellerName, + final Collection staffOptions) { + return new CashierData(null, officeId, officeName, null, null, tellerId, tellerName, null, null, null, null, null, null, + staffOptions); } /** @@ -167,8 +179,10 @@ public final class CashierData implements Serializable { /** * Returns the valid from date of this cashier. * - *

The valid from/to dates may be used to define a time period in which - * the cashier is assignable to a teller.

+ *

+ * The valid from/to dates may be used to define a time period in which the + * cashier is assignable to a teller. + *

* * @return the valid from date of this cashier */ @@ -179,8 +193,10 @@ public final class CashierData implements Serializable { /** * Returns the valid to date of this cashier. * - *

The valid from/to dates may be used to define a time period in which - * the cashier is assignable to a teller.

+ *

+ * The valid from/to dates may be used to define a time period in which the + * cashier is assignable to a teller. + *

* * @return the valid to date of this cashier */ @@ -191,7 +207,8 @@ public final class CashierData implements Serializable { /** * Returns whether this cashier works part time or not. * - * @return {@code true} if this cashier works part time; {@code false} otherwise + * @return {@code true} if this cashier works part time; {@code false} + * otherwise */ public Boolean isFullDay() { return isFullDay; @@ -200,8 +217,10 @@ public final class CashierData implements Serializable { /** * Returns the start time of this cashier. * - *

The start/end times may be used to define a time period in which - * the cashier works part time.

+ *

+ * The start/end times may be used to define a time period in which the + * cashier works part time. + *

* * @return the start time of this cashier */ @@ -212,8 +231,10 @@ public final class CashierData implements Serializable { /** * Returns the end time of this cashier. * - *

The start/end times may be used to define a time period in which - * the cashier works part time.

+ *

+ * The start/end times may be used to define a time period in which the + * cashier works part time. + *

* * @return the start time of this cashier */ diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionData.java index 9fb62f2df..c15af97f7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionData.java @@ -53,11 +53,10 @@ public final class CashierTransactionData implements Serializable { /* * Creates a new cashier. */ - private CashierTransactionData(final Long id, final Long cashierId, CashierTxnType txnType, - final BigDecimal txnAmount, final Date txnDate, String txnNote, - String entityType, Long entityId, Date createdDate, - Long officeId, String officeName, Long tellerId, String tellerName, String cashierName, - CashierData cashierData, Date startDate, Date endDate, final Collection currencyOptions) { + private CashierTransactionData(final Long id, final Long cashierId, CashierTxnType txnType, final BigDecimal txnAmount, + final Date txnDate, String txnNote, String entityType, Long entityId, Date createdDate, Long officeId, String officeName, + Long tellerId, String tellerName, String cashierName, CashierData cashierData, Date startDate, Date endDate, + final Collection currencyOptions) { this.id = id; this.cashierId = cashierId; this.txnType = txnType; @@ -81,24 +80,19 @@ public final class CashierTransactionData implements Serializable { this.currencyOptions = currencyOptions; } - public static CashierTransactionData instance(final Long id, final Long cashierId, CashierTxnType txnType, - final BigDecimal txnAmount, final Date txnDate, final String txnNote, - final String entityType, final Long entityId, final Date createdDate, - final Long officeId, final String officeName, final Long tellerId, - final String tellerName, final String cashierName, final CashierData cashierData, - Date startDate, Date endDate) { - return new CashierTransactionData(id, cashierId, txnType, txnAmount, txnDate, txnNote, entityType, - entityId, createdDate, officeId, officeName, tellerId, - tellerName, cashierName, cashierData, startDate, endDate, null); + public static CashierTransactionData instance(final Long id, final Long cashierId, CashierTxnType txnType, final BigDecimal txnAmount, + final Date txnDate, final String txnNote, final String entityType, final Long entityId, final Date createdDate, + final Long officeId, final String officeName, final Long tellerId, final String tellerName, final String cashierName, + final CashierData cashierData, Date startDate, Date endDate) { + return new CashierTransactionData(id, cashierId, txnType, txnAmount, txnDate, txnNote, entityType, entityId, createdDate, officeId, + officeName, tellerId, tellerName, cashierName, cashierData, startDate, endDate, null); } - public static CashierTransactionData template (final Long cashierId, - final Long tellerId, final String tellerName, - final Long officeId, final String officeName, final String cashierName, - final CashierData cashierData, Date startDate, Date endDate, final Collection currencyOptions) { - return new CashierTransactionData(null, cashierId, null, null, null, null, null, - null, null, officeId, officeName, tellerId, tellerName, cashierName, cashierData, - startDate, endDate, currencyOptions); + public static CashierTransactionData template(final Long cashierId, final Long tellerId, final String tellerName, final Long officeId, + final String officeName, final String cashierName, final CashierData cashierData, Date startDate, Date endDate, + final Collection currencyOptions) { + return new CashierTransactionData(null, cashierId, null, null, null, null, null, null, null, officeId, officeName, tellerId, + tellerName, cashierName, cashierData, startDate, endDate, currencyOptions); } public Long getId() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionDataValidator.java index eac0a79bc..f1fdf2746 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionDataValidator.java @@ -48,15 +48,13 @@ public class CashierTransactionDataValidator { private final static Logger LOG = LoggerFactory.getLogger(CashierTransactionDataValidator.class); @Autowired - public CashierTransactionDataValidator( - final TellerManagementReadPlatformService tellerManagementReadPlatformService, + public CashierTransactionDataValidator(final TellerManagementReadPlatformService tellerManagementReadPlatformService, final RoutingDataSource dataSource) { this.tellerManagementReadPlatformService = tellerManagementReadPlatformService; this.jdbcTemplate = new JdbcTemplate(dataSource); } - public void validateSettleCashAndCashOutTransactions(final Long cashierId, - String currencyCode, final BigDecimal transactionAmount) { + public void validateSettleCashAndCashOutTransactions(final Long cashierId, String currencyCode, final BigDecimal transactionAmount) { final Integer offset = null; final Integer limit = null; @@ -64,29 +62,21 @@ public class CashierTransactionDataValidator { final String sortOrder = null; final Date fromDate = null; final Date toDate = null; - final SearchParameters searchParameters = SearchParameters - .forPagination(offset, limit, orderBy, sortOrder); + final SearchParameters searchParameters = SearchParameters.forPagination(offset, limit, orderBy, sortOrder); final CashierTransactionsWithSummaryData cashierTxnWithSummary = this.tellerManagementReadPlatformService - .retrieveCashierTransactionsWithSummary(cashierId, false, - fromDate, toDate, currencyCode, searchParameters); - if (cashierTxnWithSummary.getNetCash().subtract(transactionAmount) - .compareTo(BigDecimal.ZERO) < 0) { + .retrieveCashierTransactionsWithSummary(cashierId, false, fromDate, toDate, currencyCode, searchParameters); + if (cashierTxnWithSummary.getNetCash().subtract(transactionAmount).compareTo(BigDecimal.ZERO) < 0) { throw new CashierInsufficientAmountException(); } } - public void validateSettleCashAndCashOutTransactions(final Long cashierId, - JsonCommand command) { - String currencyCode = command - .stringValueOfParameterNamed("currencyCode"); - BigDecimal transactionAmount = command - .bigDecimalValueOfParameterNamed("txnAmount"); - validateSettleCashAndCashOutTransactions(cashierId, currencyCode, - transactionAmount); + public void validateSettleCashAndCashOutTransactions(final Long cashierId, JsonCommand command) { + String currencyCode = command.stringValueOfParameterNamed("currencyCode"); + BigDecimal transactionAmount = command.bigDecimalValueOfParameterNamed("txnAmount"); + validateSettleCashAndCashOutTransactions(cashierId, currencyCode, transactionAmount); } - public void validateCashierAllowedDateAndTime(final Cashier cashier, - final Teller teller) { + public void validateCashierAllowedDateAndTime(final Cashier cashier, final Teller teller) { Long staffId = cashier.getStaff().getId(); final LocalDate fromDate = new LocalDate(cashier.getStartDate()); final LocalDate endDate = new LocalDate(cashier.getEndDate()); @@ -95,60 +85,39 @@ public class CashierTransactionDataValidator { /** * to validate cashier date range in range of teller date range */ - if (fromDate.isBefore(tellerFromDate) - || endDate.isBefore(tellerFromDate) - || (tellerEndDate != null && - (fromDate.isAfter(tellerEndDate) - || endDate.isAfter(tellerEndDate)))) { + if (fromDate.isBefore(tellerFromDate) || endDate.isBefore(tellerFromDate) + || (tellerEndDate != null && (fromDate.isAfter(tellerEndDate) || endDate.isAfter(tellerEndDate)))) { throw new CashierDateRangeOutOfTellerDateRangeException(); } /** * to validate cashier has not been assigned for same duration */ - String sql = "select count(*) from m_cashiers c where c.staff_id = " - + staffId + " AND " + "(('" + fromDate - + "' BETWEEN c.start_date AND c.end_date OR '" + endDate - + "' BETWEEN c.start_date AND c.end_date )" - + " OR ( c.start_date BETWEEN '" + fromDate + "' AND '" - + endDate + "' OR c.end_date BETWEEN '" + fromDate + "' AND '" + String sql = "select count(*) from m_cashiers c where c.staff_id = " + staffId + " AND " + "(('" + fromDate + + "' BETWEEN c.start_date AND c.end_date OR '" + endDate + "' BETWEEN c.start_date AND c.end_date )" + + " OR ( c.start_date BETWEEN '" + fromDate + "' AND '" + endDate + "' OR c.end_date BETWEEN '" + fromDate + "' AND '" + endDate + "'))"; if (!cashier.isFullDay()) { String startTime = cashier.getStartTime(); String endTime = cashier.getEndTime(); - sql = sql + " AND ( Time(c.start_time) BETWEEN TIME('" + startTime - + "') and TIME('" + endTime - + "') or Time(c.end_time) BETWEEN TIME('" + startTime - + "') and TIME('" + endTime + "')) "; + sql = sql + " AND ( Time(c.start_time) BETWEEN TIME('" + startTime + "') and TIME('" + endTime + + "') or Time(c.end_time) BETWEEN TIME('" + startTime + "') and TIME('" + endTime + "')) "; } int count = this.jdbcTemplate.queryForObject(sql, Integer.class); - if (count > 0) { - throw new CashierAlreadyAlloacated(); - } + if (count > 0) { throw new CashierAlreadyAlloacated(); } } - public void validateOnLoanDisbursal(AppUser user, String currencyCode, - BigDecimal transactionAmount) { + public void validateOnLoanDisbursal(AppUser user, String currencyCode, BigDecimal transactionAmount) { LocalDateTime localDateTime = DateUtils.getLocalDateTimeOfTenant(); if (user.getStaff() != null) { - String sql = "select c.id from m_cashiers c where c.staff_id = " - + user.getStaff().getId() - + " AND " - + " (case when c.full_day then '" - + localDateTime.toLocalDate() - + "' BETWEEN c.start_date AND c.end_date " - + " else ('" - + localDateTime.toLocalDate() - + "' BETWEEN c.start_date AND c.end_date and " - + " TIME('" - + localDateTime.toDateTime() + String sql = "select c.id from m_cashiers c where c.staff_id = " + user.getStaff().getId() + " AND " + + " (case when c.full_day then '" + localDateTime.toLocalDate() + "' BETWEEN c.start_date AND c.end_date " + " else ('" + + localDateTime.toLocalDate() + "' BETWEEN c.start_date AND c.end_date and " + " TIME('" + localDateTime.toDateTime() + "') BETWEEN TIME(c.start_time) AND TIME(c.end_time) ) end)"; try { - Long cashierId = this.jdbcTemplate.queryForObject(sql, - Long.class); - validateSettleCashAndCashOutTransactions(cashierId, - currencyCode, transactionAmount); + Long cashierId = this.jdbcTemplate.queryForObject(sql, Long.class); + validateSettleCashAndCashOutTransactions(cashierId, currencyCode, transactionAmount); } catch (EmptyResultDataAccessException e) { - LOG.error("Problem occurred in validateOnLoanDisbursal function",e); + LOG.error("Problem occurred in validateOnLoanDisbursal function", e); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionTypeTotalsData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionTypeTotalsData.java index 6e08a000c..a7ae0f5d3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionTypeTotalsData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionTypeTotalsData.java @@ -22,23 +22,17 @@ import java.io.Serializable; import java.math.BigDecimal; public final class CashierTransactionTypeTotalsData implements Serializable { + private final Integer cashierTxnType; private final BigDecimal cashTotal; - private CashierTransactionTypeTotalsData ( - final Integer cashierTxnType, - final BigDecimal cashTotal - ) { + private CashierTransactionTypeTotalsData(final Integer cashierTxnType, final BigDecimal cashTotal) { this.cashierTxnType = cashierTxnType; this.cashTotal = cashTotal; } - public static CashierTransactionTypeTotalsData instance( - final Integer cashierTxnType, - final BigDecimal cashTotal - ) { - return new CashierTransactionTypeTotalsData( - cashierTxnType, cashTotal); + public static CashierTransactionTypeTotalsData instance(final Integer cashierTxnType, final BigDecimal cashTotal) { + return new CashierTransactionTypeTotalsData(cashierTxnType, cashTotal); } public Integer getCashierTxnType() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionsWithSummaryData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionsWithSummaryData.java index 6e228d879..4f8652c04 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionsWithSummaryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/CashierTransactionsWithSummaryData.java @@ -37,19 +37,9 @@ public final class CashierTransactionsWithSummaryData implements Serializable { private final Page cashierTransactions; - private CashierTransactionsWithSummaryData( - final Page cashierTransactions, - final BigDecimal sumCashAllocation, - final BigDecimal sumInwardCash, - final BigDecimal sumOutwardCash, - final BigDecimal sumCashSettlement, - final BigDecimal netCash, - final String officeName, - final Long tellerId, - final String tellerName, - final Long cashierId, - final String cashierName - ) { + private CashierTransactionsWithSummaryData(final Page cashierTransactions, final BigDecimal sumCashAllocation, + final BigDecimal sumInwardCash, final BigDecimal sumOutwardCash, final BigDecimal sumCashSettlement, final BigDecimal netCash, + final String officeName, final Long tellerId, final String tellerName, final Long cashierId, final String cashierName) { this.cashierTransactions = cashierTransactions; this.sumCashAllocation = sumCashAllocation; this.sumInwardCash = sumInwardCash; @@ -63,30 +53,14 @@ public final class CashierTransactionsWithSummaryData implements Serializable { this.cashierName = cashierName; } - public static CashierTransactionsWithSummaryData instance( - final Page cashierTransactions, - final BigDecimal sumCashAllocation, - final BigDecimal sumInwardCash, - final BigDecimal sumOutwardCash, - final BigDecimal sumCashSettlement, - final String officeName, - final Long tellerId, - final String tellerName, - final Long cashierId, - final String cashierName - ) { + public static CashierTransactionsWithSummaryData instance(final Page cashierTransactions, + final BigDecimal sumCashAllocation, final BigDecimal sumInwardCash, final BigDecimal sumOutwardCash, + final BigDecimal sumCashSettlement, final String officeName, final Long tellerId, final String tellerName, final Long cashierId, + final String cashierName) { - final BigDecimal netCash = - sumCashAllocation.add(sumInwardCash). - subtract(sumOutwardCash). - subtract(sumCashSettlement); - return new CashierTransactionsWithSummaryData( - cashierTransactions, - sumCashAllocation, - sumInwardCash, - sumOutwardCash, - sumCashSettlement, netCash, - officeName, tellerId, tellerName, cashierId, cashierName); + final BigDecimal netCash = sumCashAllocation.add(sumInwardCash).subtract(sumOutwardCash).subtract(sumCashSettlement); + return new CashierTransactionsWithSummaryData(cashierTransactions, sumCashAllocation, sumInwardCash, sumOutwardCash, + sumCashSettlement, netCash, officeName, tellerId, tellerName, cashierId, cashierName); } public BigDecimal getSumCashAllocation() { @@ -128,6 +102,7 @@ public final class CashierTransactionsWithSummaryData implements Serializable { public String getCashierName() { return cashierName; } + public Page getCashierTransactions() { return cashierTransactions; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerData.java index b1e279c86..414bb53c6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerData.java @@ -29,7 +29,7 @@ import org.joda.time.LocalDate; * {@code TellerData} represents an immutable data object for teller data. * * @version 1.0 - + * * @since 2.0.0 * @see java.io.Serializable * @since 2.0.0 @@ -57,9 +57,9 @@ public final class TellerData implements Serializable { /* * Sole private CTOR to create a new instance. */ - private TellerData(final Long id, final Long officeId, final Long debitAccountId, final Long creditAccountId, - final String name, final String description, final LocalDate startDate, final LocalDate endDate, - final TellerStatus status, final Boolean hasTransactions, final Boolean hasMappedCashiers) { + private TellerData(final Long id, final Long officeId, final Long debitAccountId, final Long creditAccountId, final String name, + final String description, final LocalDate startDate, final LocalDate endDate, final TellerStatus status, + final Boolean hasTransactions, final Boolean hasMappedCashiers) { super(); this.id = id; this.officeId = officeId; @@ -79,26 +79,37 @@ public final class TellerData implements Serializable { /** * Creates a new teller data object. * - * @param id - id of the teller - * @param officeId - id of the related office - * @param debitAccountId - id of the debit account to use - * @param creditAccountId - id of the credit account to use - * @param name - name of the teller - * @param description - description of the teller - * @param startDate - date when the teller becomes available - * @param endDate - date when the teller becomes unavailable - * @param status - current state of the teller, eg. active, inactive, pending - * @param hasTransactions - indicates that this teller already is used to perform postings - * @param hasMappedCashiers - indicates that the teller already has @code Cashier}s assigned to it + * @param id + * - id of the teller + * @param officeId + * - id of the related office + * @param debitAccountId + * - id of the debit account to use + * @param creditAccountId + * - id of the credit account to use + * @param name + * - name of the teller + * @param description + * - description of the teller + * @param startDate + * - date when the teller becomes available + * @param endDate + * - date when the teller becomes unavailable + * @param status + * - current state of the teller, eg. active, inactive, pending + * @param hasTransactions + * - indicates that this teller already is used to perform + * postings + * @param hasMappedCashiers + * - indicates that the teller already has @code Cashier}s + * assigned to it * @return the new created {@code TellerData} */ - public static TellerData instance(final Long id, final Long officeId, final Long debitAccountId, - final Long creditAccountId, final String name, final String description, - final LocalDate startDate, final LocalDate endDate, final TellerStatus status, - final String officeName, - final Boolean hasTransactions, final Boolean hasMappedCashiers) { - TellerData tellerData = new TellerData(id, officeId, debitAccountId, creditAccountId, name, description, startDate, endDate, - status, hasTransactions, hasMappedCashiers); + public static TellerData instance(final Long id, final Long officeId, final Long debitAccountId, final Long creditAccountId, + final String name, final String description, final LocalDate startDate, final LocalDate endDate, final TellerStatus status, + final String officeName, final Boolean hasTransactions, final Boolean hasMappedCashiers) { + TellerData tellerData = new TellerData(id, officeId, debitAccountId, creditAccountId, name, description, startDate, endDate, status, + hasTransactions, hasMappedCashiers); tellerData.officeName = officeName; return tellerData; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerJournalData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerJournalData.java index 284e7af57..cb5754574 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerJournalData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerJournalData.java @@ -25,7 +25,7 @@ import java.util.Date; * {@code TellerJournalData} represents an immutable journal data object. * * @version 1.0.0 - + * * @since 2.0.0 * @see java.io.Serializable * @since 2.0.0 @@ -45,8 +45,7 @@ public final class TellerJournalData implements Serializable { * Sole private CTOR to create a new instance. */ private TellerJournalData(final Long officeId, final Long tellerId, final Date day, final Double openingBalance, - final Double settledBalance, final Double closingBalance, final Double sumReceipts, - final Double sumPayments) { + final Double settledBalance, final Double closingBalance, final Double sumReceipts, final Double sumPayments) { this.officeId = officeId; this.tellerId = tellerId; this.day = day; @@ -60,22 +59,27 @@ public final class TellerJournalData implements Serializable { /** * Create a new teller journal data object. * - * @param officeId - id of related office - * @param tellerId - id of related teller - * @param day - day of this journals data - * @param openingBalance - balance at the time of opening the teller - * @param settledBalance - balance at the time od settling the teller - * @param closingBalance - balance at the time of closing the teller - * @param sumReceipts - sum of all posted receipts - * @param sumPayments - sum of all posted payments + * @param officeId + * - id of related office + * @param tellerId + * - id of related teller + * @param day + * - day of this journals data + * @param openingBalance + * - balance at the time of opening the teller + * @param settledBalance + * - balance at the time od settling the teller + * @param closingBalance + * - balance at the time of closing the teller + * @param sumReceipts + * - sum of all posted receipts + * @param sumPayments + * - sum of all posted payments * @return the new created {@code TellerJournalData} */ - public static TellerJournalData instance(final Long officeId, final Long tellerId, final Date day, - final Double openingBalance, final Double settledBalance, - final Double closingBalance, final Double sumReceipts, - final Double sumPayments) { - return new TellerJournalData(officeId, tellerId, day, openingBalance, settledBalance, closingBalance, sumReceipts, - sumPayments); + public static TellerJournalData instance(final Long officeId, final Long tellerId, final Date day, final Double openingBalance, + final Double settledBalance, final Double closingBalance, final Double sumReceipts, final Double sumPayments) { + return new TellerJournalData(officeId, tellerId, day, openingBalance, settledBalance, closingBalance, sumReceipts, sumPayments); } public Long getOfficeId() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerTransactionData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerTransactionData.java index 56b59b01f..201cf70c0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerTransactionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/data/TellerTransactionData.java @@ -23,10 +23,11 @@ import java.util.Date; import org.apache.fineract.infrastructure.core.data.EnumOptionData; /** - * {@code TellerTransactionData} represents an immutable data object for a transction. + * {@code TellerTransactionData} represents an immutable data object for a + * transction. * * @version 1.0.0 - + * * @since 2.0.0 * @see java.io.Serializable * @since 2.0.0 @@ -45,9 +46,8 @@ public final class TellerTransactionData implements Serializable { /* * Sole private CTOR to create a new instance */ - private TellerTransactionData(final Long id, final Long officeId, final Long tellerId, final Long cashierId, - final Long clientId, final EnumOptionData type, final Double amount, - final Date postingDate) { + private TellerTransactionData(final Long id, final Long officeId, final Long tellerId, final Long cashierId, final Long clientId, + final EnumOptionData type, final Double amount, final Date postingDate) { this.id = id; this.officeId = officeId; this.tellerId = tellerId; @@ -61,19 +61,27 @@ public final class TellerTransactionData implements Serializable { /** * Creates a new teller transaction data object. * - * @param id - id of the transaction - * @param officeId - id of the related office - * @param tellerId - id of the related teller - * @param cashierId - id of the cashier - * @param clientId - id of the client - * @param type - type of transaction (eg receipt, payment, open, close, settle) - * @param amount - amount of the transaction - * @param postingDate - posting date of the transaction + * @param id + * - id of the transaction + * @param officeId + * - id of the related office + * @param tellerId + * - id of the related teller + * @param cashierId + * - id of the cashier + * @param clientId + * - id of the client + * @param type + * - type of transaction (eg receipt, payment, open, close, + * settle) + * @param amount + * - amount of the transaction + * @param postingDate + * - posting date of the transaction * @return the new created {@code TellerTransactionData} */ public static TellerTransactionData instance(final Long id, final Long officeId, final Long tellerId, final Long cashierId, - final Long clientId, final EnumOptionData type, final Double amount, - final Date postingDate) { + final Long clientId, final EnumOptionData type, final Double amount, final Date postingDate) { return new TellerTransactionData(id, officeId, tellerId, cashierId, clientId, type, amount, postingDate); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/Cashier.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/Cashier.java index af2d2585a..cd8b20392 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/Cashier.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/Cashier.java @@ -46,8 +46,8 @@ import org.joda.time.LocalDate; * @since 2.0.0 */ @Entity -@Table(name = "m_cashiers", uniqueConstraints = { @UniqueConstraint(name = "ux_cashiers_staff_teller", columnNames = { "staff_id", - "teller_id" }) }) +@Table(name = "m_cashiers", uniqueConstraints = { + @UniqueConstraint(name = "ux_cashiers_staff_teller", columnNames = { "staff_id", "teller_id" }) }) public class Cashier extends AbstractPersistableCustom { // ManyToOne(fetch = FetchType.LAZY) @@ -107,8 +107,8 @@ public class Cashier extends AbstractPersistableCustom { return new Cashier(cashierOffice, teller, staff, description, startDate, endDate, isFullDay, startTime, endTime); } - public Cashier(Office office, Teller teller, Staff staff, String description, LocalDate startDate, LocalDate endDate, - Boolean isFullDay, String startTime, String endTime) { + public Cashier(Office office, Teller teller, Staff staff, String description, LocalDate startDate, LocalDate endDate, Boolean isFullDay, + String startTime, String endTime) { this.office = office; this.teller = teller; this.staff = staff; @@ -180,13 +180,13 @@ public class Cashier extends AbstractPersistableCustom { if (command.isChangeInLongParameterNamed(hourStartTimeParamName, this.getHourFromStartTime()) || command.isChangeInLongParameterNamed(minStartTimeParamName, this.getMinFromStartTime())) { newStartHour = command.stringValueOfParameterNamed(hourStartTimeParamName); - if(newEndHour.equalsIgnoreCase("0")){ - newEndHour= newEndHour + "0"; + if (newEndHour.equalsIgnoreCase("0")) { + newEndHour = newEndHour + "0"; } actualChanges.put(hourStartTimeParamName, newStartHour); newStartMin = command.stringValueOfParameterNamed(minStartTimeParamName); - if(newStartMin.equalsIgnoreCase("0")){ - newStartMin= newStartMin + "0"; + if (newStartMin.equalsIgnoreCase("0")) { + newStartMin = newStartMin + "0"; } actualChanges.put(minStartTimeParamName, newStartMin); this.startTime = newStartHour + ":" + newStartMin; @@ -195,13 +195,13 @@ public class Cashier extends AbstractPersistableCustom { if (command.isChangeInLongParameterNamed(hourEndTimeParamName, this.getHourFromEndTime()) || command.isChangeInLongParameterNamed(minEndTimeParamName, this.getMinFromEndTime())) { newEndHour = command.stringValueOfParameterNamed(hourEndTimeParamName); - if(newEndHour.equalsIgnoreCase("0")){ - newEndHour= newEndHour + "0"; + if (newEndHour.equalsIgnoreCase("0")) { + newEndHour = newEndHour + "0"; } actualChanges.put(hourEndTimeParamName, newEndHour); newEndMin = command.stringValueOfParameterNamed(minEndTimeParamName); - if(newEndMin.equalsIgnoreCase("0")){ - newEndMin= newEndMin + "0"; + if (newEndMin.equalsIgnoreCase("0")) { + newEndMin = newEndMin + "0"; } actualChanges.put(minEndTimeParamName, newEndMin); this.endTime = newEndHour + ":" + newEndMin; @@ -360,8 +360,8 @@ public class Cashier extends AbstractPersistableCustom { * cashier is assignable to a teller. *

* - * @param startDate validFrom - * the valid from date of this cashier + * @param startDate + * validFrom the valid from date of this cashier */ public void setStartDate(Date startDate) { this.startDate = startDate; @@ -397,8 +397,8 @@ public class Cashier extends AbstractPersistableCustom { * cashier is assignable to a teller. *

* - * @param endDate validTo - * the valid to date of this cashier + * @param endDate + * validTo the valid to date of this cashier */ public void setEndDate(Date endDate) { this.endDate = endDate; @@ -417,8 +417,8 @@ public class Cashier extends AbstractPersistableCustom { /** * Sets the part time flag of this cashier. * - * @param isFullDay partTime - * the part time flag of this cashier + * @param isFullDay + * partTime the part time flag of this cashier */ public void setFullDay(Boolean isFullDay) { this.isFullDay = isFullDay; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierRepository.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierRepository.java index dce7f1fb2..1cd2fd31e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierRepository.java @@ -22,7 +22,8 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** - * Provides the domain repository for accessing, adding, modifying or deleting cashiers. + * Provides the domain repository for accessing, adding, modifying or deleting + * cashiers. * * @author Markus Geiss * @see org.apache.fineract.organisation.teller.domain.Cashier diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierRepositoryWrapper.java index c7cdc87f9..147c29ad2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierRepositoryWrapper.java @@ -24,6 +24,7 @@ import org.springframework.stereotype.Service; @Service public class CashierRepositoryWrapper { + private final CashierRepository repository; @Autowired @@ -32,7 +33,6 @@ public class CashierRepositoryWrapper { } public Cashier findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new TellerNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new TellerNotFoundException(id)); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTransaction.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTransaction.java index d35910465..43b56bbde 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTransaction.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTransaction.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.organisation.teller.domain; - import java.math.BigDecimal; import java.util.Date; import java.util.LinkedHashMap; @@ -84,9 +83,7 @@ public class CashierTransaction extends AbstractPersistableCustom { super(); } - public static CashierTransaction fromJson( - final Cashier cashier, - final JsonCommand command) { + public static CashierTransaction fromJson(final Cashier cashier, final JsonCommand command) { final Integer txnType = command.integerValueOfParameterNamed("txnType"); final BigDecimal txnAmount = command.bigDecimalValueOfParameterNamed("txnAmount"); final LocalDate txnDate = command.localDateValueOfParameterNamed("txnDate"); @@ -96,13 +93,12 @@ public class CashierTransaction extends AbstractPersistableCustom { final String currencyCode = command.stringValueOfParameterNamed("currencyCode"); // TODO: get client/loan/savings details - return new CashierTransaction (cashier, txnType, txnAmount, txnDate, - entityType, entityId, txnNote, currencyCode); + return new CashierTransaction(cashier, txnType, txnAmount, txnDate, entityType, entityId, txnNote, currencyCode); } - public CashierTransaction (Cashier cashier, Integer txnType, BigDecimal txnAmount, - LocalDate txnDate, String entityType, Long entityId, String txnNote, String currencyCode) { + public CashierTransaction(Cashier cashier, Integer txnType, BigDecimal txnAmount, LocalDate txnDate, String entityType, Long entityId, + String txnNote, String currencyCode) { this.cashier = cashier; this.txnType = txnType; if (txnDate != null) { @@ -165,7 +161,6 @@ public class CashierTransaction extends AbstractPersistableCustom { return actualChanges; } - /** * Returns the office of this cashier transaction. * @@ -179,7 +174,8 @@ public class CashierTransaction extends AbstractPersistableCustom { /** * Sets the office of this cashier transaction. * - * @param office the office of this cashier transaction + * @param office + * the office of this cashier transaction * @see org.apache.fineract.organisation.office.domain.Office */ public void setOffice(Office office) { @@ -199,7 +195,8 @@ public class CashierTransaction extends AbstractPersistableCustom { /** * Sets the teller of this cashier transaction. * - * @param teller the teller of this cashier transaction + * @param teller + * the teller of this cashier transaction * @see org.apache.fineract.organisation.teller.domain.Teller */ public void setTeller(Teller teller) { @@ -207,10 +204,10 @@ public class CashierTransaction extends AbstractPersistableCustom { } /** - * Returns the transaction type of this cashier transaction. - * . + * Returns the transaction type of this cashier transaction. . * - * @return the transaction type of this cashier transaction or {@code null} if not present. + * @return the transaction type of this cashier transaction or {@code null} + * if not present. */ public Integer getTxnType() { return txnType; @@ -219,7 +216,8 @@ public class CashierTransaction extends AbstractPersistableCustom { /** * Sets the transaction type of this cashier transaction. * - * @param txnType description the transaction type of this cashier transaction + * @param txnType + * description the transaction type of this cashier transaction */ public void setTxnType(Integer txnType) { this.txnType = txnType; @@ -245,7 +243,8 @@ public class CashierTransaction extends AbstractPersistableCustom { /** * Sets the transaction date of this cashier transaction. * - * @param txnDate transaction date of this cashier transaction + * @param txnDate + * transaction date of this cashier transaction */ public void setTxnDate(Date txnDate) { this.txnDate = txnDate; @@ -275,7 +274,7 @@ public class CashierTransaction extends AbstractPersistableCustom { return txnAmount; } - public void setTxnNote (String txnNote) { + public void setTxnNote(String txnNote) { this.txnNote = txnNote; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTransactionRepository.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTransactionRepository.java index 23099c212..5e3dbbada 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTransactionRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTransactionRepository.java @@ -21,6 +21,7 @@ package org.apache.fineract.organisation.teller.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface CashierTransactionRepository extends JpaRepository, JpaSpecificationExecutor { +public interface CashierTransactionRepository + extends JpaRepository, JpaSpecificationExecutor { // no added behavior } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTxnType.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTxnType.java index 903443202..dfaaac344 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTxnType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/CashierTxnType.java @@ -25,44 +25,43 @@ public class CashierTxnType implements Serializable { private Integer id; private String value; - public static final CashierTxnType ALLOCATE = new CashierTxnType (101, "Allocate Cash"); - public static final CashierTxnType SETTLE = new CashierTxnType (102, "Settle Cash"); - public static final CashierTxnType INWARD_CASH_TXN = new CashierTxnType (103, "Cash In"); - public static final CashierTxnType OUTWARD_CASH_TXN = new CashierTxnType (104, "Cash Out"); + public static final CashierTxnType ALLOCATE = new CashierTxnType(101, "Allocate Cash"); + public static final CashierTxnType SETTLE = new CashierTxnType(102, "Settle Cash"); + public static final CashierTxnType INWARD_CASH_TXN = new CashierTxnType(103, "Cash In"); + public static final CashierTxnType OUTWARD_CASH_TXN = new CashierTxnType(104, "Cash Out"); - private CashierTxnType () { - } + private CashierTxnType() {} - private CashierTxnType (Integer id, String value) { + private CashierTxnType(Integer id, String value) { this.id = id; this.value = value; } - public Integer getId () { + public Integer getId() { return id; } - public String getValue () { + public String getValue() { return value; } - public static CashierTxnType getCashierTxnType (Integer id) { + public static CashierTxnType getCashierTxnType(Integer id) { CashierTxnType retVal = null; - switch(id) { - case 101: - retVal = ALLOCATE; + switch (id) { + case 101: + retVal = ALLOCATE; break; - case 102: - retVal = SETTLE; + case 102: + retVal = SETTLE; break; - case 103: - retVal = INWARD_CASH_TXN; + case 103: + retVal = INWARD_CASH_TXN; break; - case 104: - retVal = OUTWARD_CASH_TXN; + case 104: + retVal = OUTWARD_CASH_TXN; break; - default: + default: break; } return retVal; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/Teller.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/Teller.java index 081a0e12f..137ea9bde 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/Teller.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/Teller.java @@ -40,9 +40,7 @@ import org.apache.fineract.organisation.office.domain.Office; import org.joda.time.LocalDate; @Entity -@Table(name = "m_tellers", uniqueConstraints = { - @UniqueConstraint(name = "ux_tellers_name", columnNames = {"name"}) -}) +@Table(name = "m_tellers", uniqueConstraints = { @UniqueConstraint(name = "ux_tellers_name", columnNames = { "name" }) }) public class Teller extends AbstractPersistableCustom { @ManyToOne(fetch = FetchType.LAZY) @@ -81,7 +79,7 @@ public class Teller extends AbstractPersistableCustom { super(); } - private Teller (final Office staffOffice, final String name, final String description, final LocalDate startDate, + private Teller(final Office staffOffice, final String name, final String description, final LocalDate startDate, final LocalDate endDate, final TellerStatus status) { this.name = StringUtils.defaultIfEmpty(name, null); @@ -98,21 +96,15 @@ public class Teller extends AbstractPersistableCustom { this.office = staffOffice; /* - if (StringUtils.isNotBlank(name)) { - this.name = name.trim(); - } else { - this.name = null; - } - - if (StringUtils.isNotBlank(description)) { - this.description = description.trim(); - } else { - this.description = null; - } */ + * if (StringUtils.isNotBlank(name)) { this.name = name.trim(); } else { + * this.name = null; } + * + * if (StringUtils.isNotBlank(description)) { this.description = + * description.trim(); } else { this.description = null; } + */ } - public static Teller fromJson(final Office tellerOffice, final JsonCommand command) { final String name = command.stringValueOfParameterNamed("name"); final String description = command.stringValueOfParameterNamed("description"); @@ -121,7 +113,7 @@ public class Teller extends AbstractPersistableCustom { final Integer tellerStatusInt = command.integerValueOfParameterNamed("status"); final TellerStatus status = TellerStatus.fromInt(tellerStatusInt); - return new Teller (tellerOffice, name, description, startDate, endDate, status); + return new Teller(tellerOffice, name, description, startDate, endDate, status); } public Map update(Office tellerOffice, final JsonCommand command) { @@ -188,8 +180,6 @@ public class Teller extends AbstractPersistableCustom { return actualChanges; } - - public Office getOffice() { return office; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerJournal.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerJournal.java index 2b815b965..67697438e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerJournal.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerJournal.java @@ -18,5 +18,4 @@ */ package org.apache.fineract.organisation.teller.domain; -public class TellerJournal { -} +public class TellerJournal {} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerRepository.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerRepository.java index d0f4a91e5..9dd7caad6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerRepository.java @@ -23,11 +23,13 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** - * Provides the domain repository for accessing, adding, modifying or deleting tellers. + * Provides the domain repository for accessing, adding, modifying or deleting + * tellers. * * @see org.apache.fineract.organisation.teller.domain.Teller * @since 2.0.0 */ public interface TellerRepository extends JpaRepository, JpaSpecificationExecutor { + Collection findTellerByOfficeId(Long officeId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerRepositoryWrapper.java index 87b5fdb1b..f0b335d1e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerRepositoryWrapper.java @@ -33,20 +33,19 @@ public class TellerRepositoryWrapper { this.repository = repository; } - @Transactional(readOnly=true) + @Transactional(readOnly = true) public Teller findOneWithNotFoundDetection(final Long id) { - final Teller teller = this.repository.findById(id) - .orElseThrow(() -> new TellerNotFoundException(id)); + final Teller teller = this.repository.findById(id).orElseThrow(() -> new TellerNotFoundException(id)); teller.initializeLazyCollections(); return teller; } public Teller save(final Teller teller) { - return this.repository.save(teller) ; + return this.repository.save(teller); } public Teller saveAndFlush(final Teller teller) { - return this.repository.saveAndFlush(teller) ; + return this.repository.saveAndFlush(teller); } public void delete(final Teller teller) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerStatus.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerStatus.java index 6c2be91b6..d714d362a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerStatus.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerStatus.java @@ -24,11 +24,8 @@ package org.apache.fineract.organisation.teller.domain; public enum TellerStatus { - INVALID(0, "tellerStatusType.invalid"), - PENDING(100, "tellerStatusType.pending"), - ACTIVE(300, "tellerStatusType.active"), - INACTIVE(400, "tellerStatusType.inactive"), - CLOSED(600, "tellerStatusType.closed"); + INVALID(0, "tellerStatusType.invalid"), PENDING(100, "tellerStatusType.pending"), ACTIVE(300, "tellerStatusType.active"), INACTIVE(400, + "tellerStatusType.inactive"), CLOSED(600, "tellerStatusType.closed"); private final Integer value; private final String code; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerTransactionRepository.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerTransactionRepository.java index 3b4dce8a7..ca95fad2f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerTransactionRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/domain/TellerTransactionRepository.java @@ -22,12 +22,12 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** - * Provides the domain repository for accessing, adding, modifying or deleting teller transactions. + * Provides the domain repository for accessing, adding, modifying or deleting + * teller transactions. * * @see org.apache.fineract.organisation.teller.domain.TellerTransaction * @since 2.0.0 */ -public interface TellerTransactionRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface TellerTransactionRepository extends JpaRepository, JpaSpecificationExecutor { // no added behavior } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierAlreadyAlloacated.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierAlreadyAlloacated.java index 7002cf5f9..54b9c3bc9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierAlreadyAlloacated.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierAlreadyAlloacated.java @@ -21,12 +21,10 @@ package org.apache.fineract.organisation.teller.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; @SuppressWarnings("serial") -public class CashierAlreadyAlloacated extends - AbstractPlatformDomainRuleException { +public class CashierAlreadyAlloacated extends AbstractPlatformDomainRuleException { public CashierAlreadyAlloacated() { - super("cashier.already.allocated.for.given.data.and.time.exception", - "Cashier already allocated for given date and time range."); + super("cashier.already.allocated.for.given.data.and.time.exception", "Cashier already allocated for given date and time range."); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierDateRangeOutOfTellerDateRangeException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierDateRangeOutOfTellerDateRangeException.java index 45c70c0c8..c9b1aa3bf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierDateRangeOutOfTellerDateRangeException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierDateRangeOutOfTellerDateRangeException.java @@ -21,12 +21,10 @@ package org.apache.fineract.organisation.teller.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; @SuppressWarnings("serial") -public class CashierDateRangeOutOfTellerDateRangeException extends - AbstractPlatformDomainRuleException { +public class CashierDateRangeOutOfTellerDateRangeException extends AbstractPlatformDomainRuleException { public CashierDateRangeOutOfTellerDateRangeException() { - super("cashier.date.range.out.of.teller.date.range.exception", - "Cashier date range should be in teller date range."); + super("cashier.date.range.out.of.teller.date.range.exception", "Cashier date range should be in teller date range."); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierExistForTellerException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierExistForTellerException.java index dfe354cac..f668f5e88 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierExistForTellerException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierExistForTellerException.java @@ -20,8 +20,7 @@ package org.apache.fineract.organisation.teller.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; - -public class CashierExistForTellerException extends AbstractPlatformDomainRuleException{ +public class CashierExistForTellerException extends AbstractPlatformDomainRuleException { private static final String ERROR_MESSAGE_CODE = "error.msg.cashier.is.associated.with.this.teller"; private static final String DEFAULT_ERROR_MESSAGE = "Cannot delete teller, Cashier is associated for this teller "; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierInsufficientAmountException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierInsufficientAmountException.java index 7c5520a01..9c01e156d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierInsufficientAmountException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierInsufficientAmountException.java @@ -21,12 +21,10 @@ package org.apache.fineract.organisation.teller.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; @SuppressWarnings("serial") -public class CashierInsufficientAmountException extends - AbstractPlatformDomainRuleException { +public class CashierInsufficientAmountException extends AbstractPlatformDomainRuleException { public CashierInsufficientAmountException() { - super("cashier.insufficient.amount.exception", - "Cashier do not have sufficient amount for this transaction."); + super("cashier.insufficient.amount.exception", "Cashier do not have sufficient amount for this transaction."); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierNotFoundException.java index 62068fa6d..4f00281aa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/CashierNotFoundException.java @@ -34,7 +34,8 @@ public class CashierNotFoundException extends AbstractPlatformResourceNotFoundEx /** * Creates a new instance. * - * @param cashierId the primary key of the cashier + * @param cashierId + * the primary key of the cashier */ public CashierNotFoundException(Long cashierId) { super(ERROR_MESSAGE_CODE, DEFAULT_ERROR_MESSAGE, cashierId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/InvalidDateInputException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/InvalidDateInputException.java index 36b9acaa5..c099d1d0e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/InvalidDateInputException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/InvalidDateInputException.java @@ -20,10 +20,9 @@ package org.apache.fineract.organisation.teller.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - public class InvalidDateInputException extends AbstractPlatformResourceNotFoundException { - public InvalidDateInputException(final String startDate,final String endDate) { - super("error.msg.invalid.endDate", "EndDate " + endDate + " cannot be before StartDate "+startDate); + public InvalidDateInputException(final String startDate, final String endDate) { + super("error.msg.invalid.endDate", "EndDate " + endDate + " cannot be before StartDate " + startDate); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/TellerNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/TellerNotFoundException.java index 47407efcd..231c4018b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/TellerNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/exception/TellerNotFoundException.java @@ -34,7 +34,8 @@ public class TellerNotFoundException extends AbstractPlatformResourceNotFoundExc /** * Creates a new instance. * - * @param tellerId the primary key of the teller + * @param tellerId + * the primary key of the teller */ public TellerNotFoundException(Long tellerId) { super(ERROR_MESSAGE_CODE, DEFAULT_ERROR_MESSAGE, tellerId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/AllocateCashToCashierCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/AllocateCashToCashierCommandHandler.java index 73bffa1dc..865da7b9d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/AllocateCashToCashierCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/AllocateCashToCashierCommandHandler.java @@ -35,7 +35,9 @@ public class AllocateCashToCashierCommandHandler implements NewCommandSourceHand /** * Creates a new instance. * - * @param writePlatformService the {@code CashierWritePlatformService} used to access the backend + * @param writePlatformService + * the {@code CashierWritePlatformService} used to access the + * backend */ @Autowired public AllocateCashToCashierCommandHandler(final TellerWritePlatformService writePlatformService) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/AllocateCashierToTellerCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/AllocateCashierToTellerCommandHandler.java index 3b5c9b161..77f2515b7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/AllocateCashierToTellerCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/AllocateCashierToTellerCommandHandler.java @@ -35,7 +35,9 @@ public class AllocateCashierToTellerCommandHandler implements NewCommandSourceHa /** * Creates a new instance. * - * @param writePlatformService the {@code CashierWritePlatformService} used to access the backend + * @param writePlatformService + * the {@code CashierWritePlatformService} used to access the + * backend */ @Autowired public AllocateCashierToTellerCommandHandler(final TellerWritePlatformService writePlatformService) { @@ -46,7 +48,6 @@ public class AllocateCashierToTellerCommandHandler implements NewCommandSourceHa @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.allocateCashierToTeller( - command.entityId(), command); + return this.writePlatformService.allocateCashierToTeller(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/CreateTellerCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/CreateTellerCommandHandler.java index 3f605b6d6..4731ace57 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/CreateTellerCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/CreateTellerCommandHandler.java @@ -42,7 +42,9 @@ public class CreateTellerCommandHandler implements NewCommandSourceHandler { /** * Creates a new instance * - * @param writePlatformService the {@code TellerWritePlatformService} used to access the backend + * @param writePlatformService + * the {@code TellerWritePlatformService} used to access the + * backend */ @Autowired public CreateTellerCommandHandler(final TellerWritePlatformService writePlatformService) { @@ -54,4 +56,3 @@ public class CreateTellerCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createTeller(command); } } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/DeleteCashierAllocationCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/DeleteCashierAllocationCommandHandler.java index 376511ae4..4772cab06 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/DeleteCashierAllocationCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/DeleteCashierAllocationCommandHandler.java @@ -42,7 +42,9 @@ public class DeleteCashierAllocationCommandHandler implements NewCommandSourceHa /** * Creates a new instance. * - * @param writePlatformService the {@code CashierWritePlatformService} used to access the backend + * @param writePlatformService + * the {@code CashierWritePlatformService} used to access the + * backend */ @Autowired public DeleteCashierAllocationCommandHandler(final TellerWritePlatformService writePlatformService) { @@ -52,7 +54,6 @@ public class DeleteCashierAllocationCommandHandler implements NewCommandSourceHa @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.deleteCashierAllocation(command.entityId(), - command.subentityId(), command); + return this.writePlatformService.deleteCashierAllocation(command.entityId(), command.subentityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/DeleteTellerCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/DeleteTellerCommandHandler.java index 92110e63f..eb03283f5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/DeleteTellerCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/DeleteTellerCommandHandler.java @@ -42,7 +42,9 @@ public class DeleteTellerCommandHandler implements NewCommandSourceHandler { /** * Creates a new instance * - * @param writePlatformService the {@code TellerWritePlatformService} used to access the backend + * @param writePlatformService + * the {@code TellerWritePlatformService} used to access the + * backend */ @Autowired public DeleteTellerCommandHandler(final TellerWritePlatformService writePlatformService) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/ModifyCashierCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/ModifyCashierCommandHandler.java index 1c948b7fb..902918461 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/ModifyCashierCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/ModifyCashierCommandHandler.java @@ -38,7 +38,9 @@ public class ModifyCashierCommandHandler implements NewCommandSourceHandler { /** * Creates a new instance. * - * @param writePlatformService the {@code CashierWritePlatformService} used to access the backend + * @param writePlatformService + * the {@code CashierWritePlatformService} used to access the + * backend */ @Autowired public ModifyCashierCommandHandler(final CashierWritePlatformService writePlatformService) { @@ -46,7 +48,6 @@ public class ModifyCashierCommandHandler implements NewCommandSourceHandler { this.writePlatformService = writePlatformService; } - @Override public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.modifyCashier(command.entityId(), command); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/SettleCashFromCashierCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/SettleCashFromCashierCommandHandler.java index 5e131f5a1..d721bc2af 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/SettleCashFromCashierCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/SettleCashFromCashierCommandHandler.java @@ -35,7 +35,9 @@ public class SettleCashFromCashierCommandHandler implements NewCommandSourceHand /** * Creates a new instance. * - * @param writePlatformService the {@code CashierWritePlatformService} used to access the backend + * @param writePlatformService + * the {@code CashierWritePlatformService} used to access the + * backend */ @Autowired public SettleCashFromCashierCommandHandler(final TellerWritePlatformService writePlatformService) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/UpdateCashierAllocationCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/UpdateCashierAllocationCommandHandler.java index 6563e11f2..b92fefafb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/UpdateCashierAllocationCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/UpdateCashierAllocationCommandHandler.java @@ -42,7 +42,9 @@ public class UpdateCashierAllocationCommandHandler implements NewCommandSourceHa /** * Creates a new instance * - * @param writePlatformService the {@code TellerWritePlatformService} used to access the backend + * @param writePlatformService + * the {@code TellerWritePlatformService} used to access the + * backend */ @Autowired public UpdateCashierAllocationCommandHandler(final TellerWritePlatformService writePlatformService) { @@ -52,7 +54,6 @@ public class UpdateCashierAllocationCommandHandler implements NewCommandSourceHa @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.updateCashierAllocation(command.entityId(), - command.subentityId(), command); + return this.writePlatformService.updateCashierAllocation(command.entityId(), command.subentityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/UpdateTellerCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/UpdateTellerCommandHandler.java index 38681395b..fbf8e6bbe 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/UpdateTellerCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/handler/UpdateTellerCommandHandler.java @@ -42,7 +42,9 @@ public class UpdateTellerCommandHandler implements NewCommandSourceHandler { /** * Creates a new instance * - * @param writePlatformService the {@code TellerWritePlatformService} used to access the backend + * @param writePlatformService + * the {@code TellerWritePlatformService} used to access the + * backend */ @Autowired public UpdateTellerCommandHandler(final TellerWritePlatformService writePlatformService) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/serialization/TellerCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/serialization/TellerCommandFromApiJsonDeserializer.java index 2275a0c56..38ed7964f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/serialization/TellerCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/serialization/TellerCommandFromApiJsonDeserializer.java @@ -96,8 +96,10 @@ public final class TellerCommandFromApiJsonDeserializer { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForAllocateCashier(final String json) { @@ -164,4 +166,4 @@ public final class TellerCommandFromApiJsonDeserializer { final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element); baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notExceedingLengthOf(3); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/CashierWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/CashierWritePlatformService.java index 8462a7e5d..ce7a7196b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/CashierWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/CashierWritePlatformService.java @@ -33,8 +33,7 @@ public class CashierWritePlatformService { return null; } - public CommandProcessingResult modifyCashier(Long entityId, - JsonCommand command) { + public CommandProcessingResult modifyCashier(Long entityId, JsonCommand command) { // TODO Auto-generated method stub return null; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerManagementReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerManagementReadPlatformService.java index 3c1557126..6effccd7c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerManagementReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerManagementReadPlatformService.java @@ -61,8 +61,8 @@ public interface TellerManagementReadPlatformService { public Collection retrieveCashiersForTellers(String sqlSearch, Long tellerId); - public Page retrieveCashierTransactions(Long cashierId, boolean includeAllTellers, Date fromDate, - Date toDate, String currencyCode, final SearchParameters searchParameters); + public Page retrieveCashierTransactions(Long cashierId, boolean includeAllTellers, Date fromDate, Date toDate, + String currencyCode, final SearchParameters searchParameters); public CashierTransactionsWithSummaryData retrieveCashierTransactionsWithSummary(Long cashierId, boolean includeAllTellers, Date fromDate, Date toDate, String currencyCode, final SearchParameters searchParameters); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerManagementReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerManagementReadPlatformServiceImpl.java index d4f01273b..2d37db2d0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerManagementReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerManagementReadPlatformServiceImpl.java @@ -237,9 +237,7 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sql += " where " + extraCriteria; } sql = sql + " order by t.teller_name"; - if(officeId!=null){ - return this.jdbcTemplate.query(sql, tm, new Object[] {officeId}); - } + if (officeId != null) { return this.jdbcTemplate.query(sql, tm, new Object[] { officeId }); } return this.jdbcTemplate.query(sql, tm, new Object[] {}); } @@ -262,8 +260,8 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement } else if (status.equalsIgnoreCase("inActive")) { extraCriteria.append(" and status = 0 "); } else { - if (!status.equalsIgnoreCase("all")){ - throw new UnrecognizedQueryParamException("status", status, new Object[] { "all", "active", "inactive" }); + if (!status.equalsIgnoreCase("all")) { + throw new UnrecognizedQueryParamException("status", status, new Object[] { "all", "active", "inactive" }); } } @@ -470,9 +468,9 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement final CashierTransactionSummaryMapper ctsm = new CashierTransactionSummaryMapper(); final String sql = "select " + ctsm.cashierTxnSummarySchema() + " limit 1000"; - Collection cashierTxnTypeTotals = this.jdbcTemplate.query(sql, ctsm, new Object[] { cashierId, - currencyCode, hierarchySearchString, cashierId, currencyCode, hierarchySearchString, cashierId, currencyCode, - hierarchySearchString, cashierId, currencyCode, hierarchySearchString }); + Collection cashierTxnTypeTotals = this.jdbcTemplate.query(sql, ctsm, + new Object[] { cashierId, currencyCode, hierarchySearchString, cashierId, currencyCode, hierarchySearchString, cashierId, + currencyCode, hierarchySearchString, cashierId, currencyCode, hierarchySearchString }); Iterator itr = cashierTxnTypeTotals.iterator(); BigDecimal allocAmount = new BigDecimal(0); @@ -495,8 +493,8 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement } } - final Page cashierTransactions = retrieveCashierTransactions(cashierId, includeAllTellers, fromDate, - toDate, currencyCode, searchParameters); + final Page cashierTransactions = retrieveCashierTransactions(cashierId, includeAllTellers, fromDate, toDate, + currencyCode, searchParameters); CashierTransactionData cashierTxnTemplate = retrieveCashierTxnTemplate(cashierId); @@ -523,33 +521,25 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement final CashierTransactionMapper ctm = new CashierTransactionMapper(); - - String sql = "select * from (select " + ctm.cashierTxnSchema() + " where txn.cashier_id = ? and txn.currency_code = ? and o.hierarchy like ? " + "AND ((case when c.full_day then Date(txn.created_date) between c.start_date AND c.end_date else ( Date(txn.created_date) between c.start_date AND c.end_date" + " ) and ( TIME(txn.created_date) between TIME(c.start_time) AND TIME(c.end_time)) end) or txn.txn_type = 101)) cashier_txns " - + " union (select " - + ctm.savingsTxnSchema() + + " union (select " + ctm.savingsTxnSchema() + " where sav_txn.is_reversed = 0 and c.id = ? and sav.currency_code = ? and o.hierarchy like ? and " + " sav_txn.transaction_date between c.start_date and date_add(c.end_date, interval 1 day) " + " and renum.enum_value in ('deposit','withdrawal fee', 'Pay Charge', 'withdrawal', 'Annual Fee', 'Waive Charge', 'Interest Posting', 'Overdraft Interest') " - + " and (sav_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) " - + " AND acnttrans.id IS NULL ) " - + " union (select " - + ctm.loansTxnSchema() + + " and (sav_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) " + " AND acnttrans.id IS NULL ) " + + " union (select " + ctm.loansTxnSchema() + " where loan_txn.is_reversed = 0 and c.id = ? and loan.currency_code = ? and o.hierarchy like ? and " + " loan_txn.transaction_date between c.start_date and date_add(c.end_date, interval 1 day) " + " and renum.enum_value in ('REPAYMENT_AT_DISBURSEMENT','REPAYMENT', 'RECOVERY_REPAYMENT','DISBURSEMENT', 'CHARGE_PAYMENT', 'WAIVE_CHARGES', 'WAIVE_INTEREST', 'WRITEOFF') " - + " and (loan_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) " - + " AND acnttrans.id IS NULL ) " - + " union (select " - + ctm.clientTxnSchema() + + " and (loan_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) " + " AND acnttrans.id IS NULL ) " + + " union (select " + ctm.clientTxnSchema() + " where cli_txn.is_reversed = 0 and c.id = ? and cli_txn.currency_code = ? and o.hierarchy like ? and cli_txn.transaction_date " + " between c.start_date and date_add(c.end_date, interval 1 day) " + " and renum.enum_value in ('PAY_CHARGE', 'WAIVE_CHARGE') " - + " and (cli_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) ) " - + " order by created_date "; + + " and (cli_txn.payment_detail_id IS NULL OR payType.is_cash_payment = 1) ) " + " order by created_date "; if (searchParameters.isLimited()) { sql = sql + " limit " + searchParameters.getLimit(); @@ -558,10 +548,13 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement } } final String sqlCountRows = "SELECT FOUND_ROWS()"; -// return this.jdbcTemplate.query(sql, ctm, new Object[] { cashierId, currencyCode, hierarchySearchString, cashierId, currencyCode, -// hierarchySearchString, cashierId, currencyCode, hierarchySearchString, cashierId, currencyCode, hierarchySearchString }); - Object[] params = new Object[] {cashierId, currencyCode, hierarchySearchString, cashierId, currencyCode, - hierarchySearchString, cashierId, currencyCode, hierarchySearchString, cashierId, currencyCode, hierarchySearchString }; + // return this.jdbcTemplate.query(sql, ctm, new Object[] { cashierId, + // currencyCode, hierarchySearchString, cashierId, currencyCode, + // hierarchySearchString, cashierId, currencyCode, + // hierarchySearchString, cashierId, currencyCode, hierarchySearchString + // }); + Object[] params = new Object[] { cashierId, currencyCode, hierarchySearchString, cashierId, currencyCode, hierarchySearchString, + cashierId, currencyCode, hierarchySearchString, cashierId, currencyCode, hierarchySearchString }; return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sql, params, ctm); } @@ -617,8 +610,8 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" txn.txn_type as txn_type, "); sqlBuilder.append(" txn.txn_amount as txn_amount, txn.txn_date as txn_date, txn.txn_note as txn_note, "); sqlBuilder.append(" txn.entity_type as entity_type, txn.entity_id as entity_id, txn.created_date as created_date, "); - sqlBuilder - .append(" o.id as office_id, o.name as office_name, t.id as teller_id, t.name as teller_name, s.display_name as cashier_name "); + sqlBuilder.append( + " o.id as office_id, o.name as office_name, t.id as teller_id, t.name as teller_name, s.display_name as cashier_name "); sqlBuilder.append(" from m_cashier_transactions txn "); sqlBuilder.append(" left join m_cashiers c on c.id = txn.cashier_id "); sqlBuilder.append(" left join m_tellers t on t.id = c.teller_id "); @@ -636,20 +629,21 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" case "); sqlBuilder.append(" when renum.enum_value in ('deposit','withdrawal fee', 'Pay Charge', 'Annual Fee') "); sqlBuilder.append(" then 103 "); - sqlBuilder.append(" when renum.enum_value in ('withdrawal', 'Waive Charge', 'Interest Posting', 'Overdraft Interest', '') "); + sqlBuilder + .append(" when renum.enum_value in ('withdrawal', 'Waive Charge', 'Interest Posting', 'Overdraft Interest', '') "); sqlBuilder.append(" then 104 "); sqlBuilder.append(" else "); sqlBuilder.append(" 105 "); sqlBuilder.append(" end as txn_type, "); sqlBuilder.append(" sav_txn.amount as txn_amount, sav_txn.transaction_date as txn_date, "); - sqlBuilder - .append(" concat (renum.enum_value, ', Sav:', sav.id, '-', sav.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); + sqlBuilder.append( + " concat (renum.enum_value, ', Sav:', sav.id, '-', sav.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); sqlBuilder.append(" 'savings' as entity_type, sav.id as entity_id, sav_txn.created_date as created_date, "); - sqlBuilder - .append(" o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); + sqlBuilder.append( + " o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); sqlBuilder.append(" from m_savings_account_transaction sav_txn "); - sqlBuilder - .append(" left join r_enum_value renum on sav_txn.transaction_type_enum = renum.enum_id and renum.enum_name = 'savings_transaction_type_enum' "); + sqlBuilder.append( + " left join r_enum_value renum on sav_txn.transaction_type_enum = renum.enum_id and renum.enum_name = 'savings_transaction_type_enum' "); sqlBuilder.append(" left join m_savings_account sav on sav_txn.savings_account_id = sav.id "); sqlBuilder.append(" left join m_client cl on sav.client_id = cl.id "); sqlBuilder.append(" left join m_office o on cl.office_id = o.id "); @@ -671,7 +665,8 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" loan_txn.id as txn_id, c.id as cashier_id, "); sqlBuilder.append(" case "); - sqlBuilder.append(" when renum.enum_value in ('REPAYMENT_AT_DISBURSEMENT','REPAYMENT', 'RECOVERY_REPAYMENT', 'CHARGE_PAYMENT') "); + sqlBuilder.append( + " when renum.enum_value in ('REPAYMENT_AT_DISBURSEMENT','REPAYMENT', 'RECOVERY_REPAYMENT', 'CHARGE_PAYMENT') "); sqlBuilder.append(" then 103 "); sqlBuilder.append(" when renum.enum_value in ('DISBURSEMENT', 'WAIVE_INTEREST', 'WRITEOFF', 'WAIVE_CHARGES') "); sqlBuilder.append(" then 104 "); @@ -679,14 +674,14 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" 105 "); sqlBuilder.append(" end as cash_txn_type, "); sqlBuilder.append(" loan_txn.amount as txn_amount, loan_txn.transaction_date as txn_date, "); - sqlBuilder - .append(" concat (renum.enum_value, ', Loan:', loan.id, '-', loan.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); + sqlBuilder.append( + " concat (renum.enum_value, ', Loan:', loan.id, '-', loan.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); sqlBuilder.append(" 'loans' as entity_type, loan.id as entity_id, loan_txn.created_date as created_date, "); - sqlBuilder - .append(" o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); + sqlBuilder.append( + " o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); sqlBuilder.append(" from m_loan_transaction loan_txn "); - sqlBuilder - .append(" left join r_enum_value renum on loan_txn.transaction_type_enum = renum.enum_id and renum.enum_name = 'loan_transaction_type_enum' "); + sqlBuilder.append( + " left join r_enum_value renum on loan_txn.transaction_type_enum = renum.enum_id and renum.enum_name = 'loan_transaction_type_enum' "); sqlBuilder.append(" left join m_loan loan on loan_txn.loan_id = loan.id "); sqlBuilder.append(" left join m_client cl on loan.client_id = cl.id "); sqlBuilder.append(" left join m_office o on cl.office_id = o.id "); @@ -716,14 +711,14 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" 105 "); sqlBuilder.append(" end as cash_txn_type, "); sqlBuilder.append(" cli_txn.amount as txn_amount, cli_txn.transaction_date as txn_date, "); - sqlBuilder - .append(" concat (renum.enum_value, ', Client:', cl.id, '-', cl.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); + sqlBuilder.append( + " concat (renum.enum_value, ', Client:', cl.id, '-', cl.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); sqlBuilder.append(" 'client' as entity_type, cl.id as entity_id, cli_txn.created_date as created_date, "); - sqlBuilder - .append(" o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); + sqlBuilder.append( + " o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); sqlBuilder.append(" from m_client_transaction cli_txn "); - sqlBuilder - .append(" left join r_enum_value renum on cli_txn.transaction_type_enum = renum.enum_id AND renum.enum_name = 'client_transaction_type_enum' "); + sqlBuilder.append( + " left join r_enum_value renum on cli_txn.transaction_type_enum = renum.enum_id AND renum.enum_name = 'client_transaction_type_enum' "); sqlBuilder.append(" left join m_client cl on cli_txn.client_id = cl.id "); sqlBuilder.append(" left join m_office o on cl.office_id = o.id "); sqlBuilder.append(" left join m_appuser user on cli_txn.appuser_id = user.id "); @@ -781,18 +776,17 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" txn.txn_type as cash_txn_type, "); sqlBuilder.append(" txn.txn_amount as txn_amount, txn.txn_date as txn_date, txn.txn_note as txn_note, "); sqlBuilder.append(" txn.entity_type as entity_type, txn.entity_id as entity_id, txn.created_date as created_date, "); - sqlBuilder - .append(" o.id as office_id, o.name as office_name, t.id as teller_id, t.name as teller_name, s.display_name as cashier_name "); + sqlBuilder.append( + " o.id as office_id, o.name as office_name, t.id as teller_id, t.name as teller_name, s.display_name as cashier_name "); sqlBuilder.append(" from m_cashier_transactions txn "); sqlBuilder.append(" left join m_cashiers c on c.id = txn.cashier_id "); sqlBuilder.append(" left join m_tellers t on t.id = c.teller_id "); sqlBuilder.append(" left join m_office o on o.id = t.office_id "); sqlBuilder.append(" left join m_staff s on s.id = c.staff_id "); sqlBuilder.append(" where txn.cashier_id = ? "); - sqlBuilder - .append(" AND (( case when c.full_day then Date(txn.created_date) between c.start_date AND c.end_date "); - sqlBuilder - .append(" else ( Date(txn.created_date) between c.start_date AND c.end_date) and ( TIME(txn.created_date) between TIME(c.start_time) AND TIME(c.end_time)) end) or txn.txn_type = 101) "); + sqlBuilder.append(" AND (( case when c.full_day then Date(txn.created_date) between c.start_date AND c.end_date "); + sqlBuilder.append( + " else ( Date(txn.created_date) between c.start_date AND c.end_date) and ( TIME(txn.created_date) between TIME(c.start_time) AND TIME(c.end_time)) end) or txn.txn_type = 101) "); sqlBuilder.append(" and txn.currency_code = ? "); sqlBuilder.append(" and o.hierarchy like ? ) cashier_txns "); sqlBuilder.append(" UNION "); @@ -806,14 +800,14 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" 105 "); sqlBuilder.append(" end as cash_txn_type, "); sqlBuilder.append(" sav_txn.amount as txn_amount, sav_txn.transaction_date as txn_date, "); - sqlBuilder - .append(" concat (renum.enum_value, ', Sav:', sav.id, '-', sav.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); + sqlBuilder.append( + " concat (renum.enum_value, ', Sav:', sav.id, '-', sav.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); sqlBuilder.append(" 'savings' as entity_type, sav.id as entity_id, sav_txn.created_date as created_date, "); - sqlBuilder - .append(" o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); + sqlBuilder.append( + " o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); sqlBuilder.append(" from m_savings_account_transaction sav_txn "); - sqlBuilder - .append(" left join r_enum_value renum on sav_txn.transaction_type_enum = renum.enum_id and renum.enum_name = 'savings_transaction_type_enum' "); + sqlBuilder.append( + " left join r_enum_value renum on sav_txn.transaction_type_enum = renum.enum_id and renum.enum_name = 'savings_transaction_type_enum' "); sqlBuilder.append(" left join m_savings_account sav on sav_txn.savings_account_id = sav.id "); sqlBuilder.append(" left join m_client cl on sav.client_id = cl.id "); sqlBuilder.append(" left join m_office o on cl.office_id = o.id "); @@ -836,7 +830,8 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" ( "); sqlBuilder.append(" select loan_txn.id as txn_id, c.id as cashier_id, "); sqlBuilder.append(" case "); - sqlBuilder.append(" when renum.enum_value in ('REPAYMENT_AT_DISBURSEMENT','REPAYMENT', 'RECOVERY_REPAYMENT', 'CHARGE_PAYMENT') "); + sqlBuilder.append( + " when renum.enum_value in ('REPAYMENT_AT_DISBURSEMENT','REPAYMENT', 'RECOVERY_REPAYMENT', 'CHARGE_PAYMENT') "); sqlBuilder.append(" then 103 "); sqlBuilder.append(" when renum.enum_value in ('DISBURSEMENT', 'WAIVE_INTEREST', 'WRITEOFF', 'WAIVE_CHARGES') "); sqlBuilder.append(" then 104 "); @@ -844,14 +839,14 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" 105 "); sqlBuilder.append(" end as cash_txn_type, "); sqlBuilder.append(" loan_txn.amount as txn_amount, loan_txn.transaction_date as txn_date, "); - sqlBuilder - .append(" concat (renum.enum_value, ', Loan:', loan.id, '-', loan.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); + sqlBuilder.append( + " concat (renum.enum_value, ', Loan:', loan.id, '-', loan.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); sqlBuilder.append(" 'loans' as entity_type, loan.id as entity_id, loan_txn.created_date as created_date, "); - sqlBuilder - .append(" o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); + sqlBuilder.append( + " o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); sqlBuilder.append(" from m_loan_transaction loan_txn "); - sqlBuilder - .append(" left join r_enum_value renum on loan_txn.transaction_type_enum = renum.enum_id and renum.enum_name = 'loan_transaction_type_enum' "); + sqlBuilder.append( + " left join r_enum_value renum on loan_txn.transaction_type_enum = renum.enum_id and renum.enum_name = 'loan_transaction_type_enum' "); sqlBuilder.append(" left join m_loan loan on loan_txn.loan_id = loan.id "); sqlBuilder.append(" left join m_client cl on loan.client_id = cl.id "); sqlBuilder.append(" left join m_office o on cl.office_id = o.id "); @@ -882,14 +877,14 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement sqlBuilder.append(" 105 "); sqlBuilder.append(" end as cash_txn_type, "); sqlBuilder.append(" cli_txn.amount as txn_amount, cli_txn.transaction_date as txn_date, "); - sqlBuilder - .append(" concat (renum.enum_value, ', Client:', cl.id, '-', cl.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); + sqlBuilder.append( + " concat (renum.enum_value, ', Client:', cl.id, '-', cl.account_no, ',Client:', cl.id, '-',cl.display_name) as txn_note, "); sqlBuilder.append(" 'client' as entity_type, cl.id as entity_id, cli_txn.created_date as created_date, "); - sqlBuilder - .append(" o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); + sqlBuilder.append( + " o.id as office_id, o.name as office_name, null as teller_id, null as teller_name, staff.display_name as cashier_name "); sqlBuilder.append(" from m_client_transaction cli_txn "); - sqlBuilder - .append(" left join r_enum_value renum ON cli_txn.transaction_type_enum = renum.enum_id AND renum.enum_name = 'client_transaction_type_enum' "); + sqlBuilder.append( + " left join r_enum_value renum ON cli_txn.transaction_type_enum = renum.enum_id AND renum.enum_name = 'client_transaction_type_enum' "); sqlBuilder.append(" left join m_client cl ON cli_txn.client_id = cl.id "); sqlBuilder.append(" left join m_office o ON cl.office_id = o.id "); sqlBuilder.append(" left join m_appuser user ON cli_txn.appuser_id = user.id "); @@ -910,8 +905,7 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement } @Override - public CashierTransactionTypeTotalsData mapRow(final ResultSet rs, final int rowNum) - throws SQLException { + public CashierTransactionTypeTotalsData mapRow(final ResultSet rs, final int rowNum) throws SQLException { final Integer cashierTxnType = rs.getInt("cash_txn_type"); final BigDecimal txnTotal = rs.getBigDecimal("txn_total"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerTransactionWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerTransactionWritePlatformService.java index eba0ad730..fb4940443 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerTransactionWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerTransactionWritePlatformService.java @@ -32,7 +32,8 @@ public interface TellerTransactionWritePlatformService { /** * Stores teller transactions into the data base. * - * @param command the command containing the teller transaction details + * @param command + * the command containing the teller transaction details * @return the result i */ public CommandProcessingResult createTellerTransaction(JsonCommand command); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerWritePlatformService.java index cbd16518e..2bf52cf8d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerWritePlatformService.java @@ -33,7 +33,8 @@ public interface TellerWritePlatformService { /** * Creates a new teller. * - * @param command the command to create a new teller + * @param command + * the command to create a new teller * @return {@code CommandProcessingResult} if successful * @throws org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException * @throws org.apache.fineract.infrastructure.core.exception.InvalidJsonException @@ -43,8 +44,10 @@ public interface TellerWritePlatformService { /** * Modifies a new teller. * - * @param tellerId the primary key of the teller - * @param command the command to modifya new teller + * @param tellerId + * the primary key of the teller + * @param command + * the command to modifya new teller * @return {@code CommandProcessingResult} if successful * @throws org.apache.fineract.organisation.teller.exception.TellerNotFoundException * @throws org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException @@ -55,7 +58,8 @@ public interface TellerWritePlatformService { /** * deletes a new teller. * - * @param tellerId the primary key of the teller + * @param tellerId + * the primary key of the teller * @return {@code CommandProcessingResult} if successful * @throws org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException * @throws org.apache.fineract.infrastructure.core.exception.InvalidJsonException @@ -63,26 +67,22 @@ public interface TellerWritePlatformService { public CommandProcessingResult deleteTeller(Long tellerId); /** - * Allocates a cashier to an existing teller. The allocation can be for a duration - * from a date to a date - * from a certain start time to an end time. + * Allocates a cashier to an existing teller. The allocation can be for a + * duration from a date to a date from a certain start time to an end time. * - * @param command the command to allocate a cashier for a specific teller + * @param command + * the command to allocate a cashier for a specific teller * @return {@code CommandProcessingResult} if successful * @throws org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException * @throws org.apache.fineract.infrastructure.core.exception.InvalidJsonException */ public CommandProcessingResult allocateCashierToTeller(Long tellerId, JsonCommand command); - CommandProcessingResult updateCashierAllocation(Long tellerId, Long cashierId, - JsonCommand command); + CommandProcessingResult updateCashierAllocation(Long tellerId, Long cashierId, JsonCommand command); - CommandProcessingResult deleteCashierAllocation(final Long tellerId, Long cashierId, - JsonCommand command); + CommandProcessingResult deleteCashierAllocation(final Long tellerId, Long cashierId, JsonCommand command); - CommandProcessingResult allocateCashToCashier(Long cashierId, - JsonCommand command); + CommandProcessingResult allocateCashToCashier(Long cashierId, JsonCommand command); - CommandProcessingResult settleCashFromCashier(Long cashierId, - JsonCommand command); + CommandProcessingResult settleCashFromCashier(Long cashierId, JsonCommand command); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerWritePlatformServiceJpaImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerWritePlatformServiceJpaImpl.java index 68584bd07..cfc733d82 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerWritePlatformServiceJpaImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/service/TellerWritePlatformServiceJpaImpl.java @@ -78,9 +78,9 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer @Autowired public TellerWritePlatformServiceJpaImpl(final PlatformSecurityContext context, - final TellerCommandFromApiJsonDeserializer fromApiJsonDeserializer, - final TellerRepositoryWrapper tellerRepositoryWrapper, final OfficeRepositoryWrapper officeRepositoryWrapper, - final StaffRepository staffRepository, CashierRepository cashierRepository, CashierTransactionRepository cashierTxnRepository, + final TellerCommandFromApiJsonDeserializer fromApiJsonDeserializer, final TellerRepositoryWrapper tellerRepositoryWrapper, + final OfficeRepositoryWrapper officeRepositoryWrapper, final StaffRepository staffRepository, + CashierRepository cashierRepository, CashierTransactionRepository cashierTxnRepository, JournalEntryRepository glJournalEntryRepository, FinancialActivityAccountRepositoryWrapper financialActivityAccountRepositoryWrapper, final CashierTransactionDataValidator cashierTransactionDataValidator) { @@ -122,8 +122,8 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer } catch (final DataIntegrityViolationException dve) { handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleTellerDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -157,8 +157,8 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer } catch (final DataIntegrityViolationException dve) { handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleTellerDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -174,8 +174,9 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer final Office userOffice = this.officeRepositoryWrapper.findOfficeHierarchy(userOfficeId); final Teller tellerToReturn = this.tellerRepositoryWrapper.findOneWithNotFoundDetection(tellerId); final Long tellerOfficeId = tellerToReturn.officeId(); - if (userOffice.doesNotHaveAnOfficeInHierarchyWithId(tellerOfficeId)) { throw new NoAuthorizationException( - "User does not have sufficient priviledges to act on the provided office."); } + if (userOffice.doesNotHaveAnOfficeInHierarchyWithId(tellerOfficeId)) { + throw new NoAuthorizationException("User does not have sufficient priviledges to act on the provided office."); + } return tellerToReturn; } @@ -188,8 +189,9 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer Set isTellerIdPresentInCashier = teller.getCashiers(); for (final Cashier tellerIdInCashier : isTellerIdPresentInCashier) { - if (tellerIdInCashier.getTeller().getId().toString() - .equalsIgnoreCase(tellerId.toString())) { throw new CashierExistForTellerException(tellerId); } + if (tellerIdInCashier.getTeller().getId().toString().equalsIgnoreCase(tellerId.toString())) { + throw new CashierExistForTellerException(tellerId); + } } tellerRepositoryWrapper.delete(teller); @@ -233,8 +235,7 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer this.fromApiJsonDeserializer.validateForAllocateCashier(command.json()); - final Staff staff = this.staffRepository.findById(staffId) - .orElseThrow(() -> new StaffNotFoundException(staffId)); + final Staff staff = this.staffRepository.findById(staffId).orElseThrow(() -> new StaffNotFoundException(staffId)); final Boolean isFullDay = command.booleanObjectValueOfParameterNamed("isFullDay"); if (!isFullDay) { hourStartTime = command.longValueOfParameterNamed("hourStartTime"); @@ -268,8 +269,8 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer } catch (final DataIntegrityViolationException dve) { handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleTellerDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -284,8 +285,7 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer this.fromApiJsonDeserializer.validateForAllocateCashier(command.json()); final Long staffId = command.longValueOfParameterNamed("staffId"); - final Staff staff = this.staffRepository.findById(staffId) - .orElseThrow(() -> new StaffNotFoundException(staffId)); + final Staff staff = this.staffRepository.findById(staffId).orElseThrow(() -> new StaffNotFoundException(staffId)); final Cashier cashier = validateUserPriviledgeOnCashierAndRetrieve(currentUser, tellerId, cashierId); @@ -308,8 +308,8 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer } catch (final DataIntegrityViolationException dve) { handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleTellerDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -333,8 +333,8 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer } catch (final DataIntegrityViolationException dve) { handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleTellerDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -376,8 +376,7 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer try { final AppUser currentUser = this.context.authenticatedUser(); - final Cashier cashier = this.cashierRepository.findById(cashierId) - .orElseThrow(() -> new CashierNotFoundException(cashierId)); + final Cashier cashier = this.cashierRepository.findById(cashierId).orElseThrow(() -> new CashierNotFoundException(cashierId)); this.fromApiJsonDeserializer.validateForCashTxnForCashier(command.json()); @@ -441,7 +440,10 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer transactionId, false, // manual entry cashierTxn.getTxnDate(), JournalEntryType.DEBIT, cashierTxn.getTxnAmount(), cashierTxn.getTxnNote(), // Description null, null, null, // entity Type, entityId, reference number - null, null, clientTransaction, shareTransactionId); // Loan and Savings Txn + null, null, clientTransaction, shareTransactionId); // Loan + // and + // Savings + // Txn final JournalEntry creditJournalEntry = JournalEntry.createNew(cashierOffice, null, // payment // detail @@ -450,7 +452,10 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer transactionId, false, // manual entry cashierTxn.getTxnDate(), JournalEntryType.CREDIT, cashierTxn.getTxnAmount(), cashierTxn.getTxnNote(), // Description null, null, null, // entity Type, entityId, reference number - null, null, clientTransaction, shareTransactionId); // Loan and Savings Txn + null, null, clientTransaction, shareTransactionId); // Loan + // and + // Savings + // Txn this.glJournalEntryRepository.saveAndFlush(debitJournalEntry); this.glJournalEntryRepository.saveAndFlush(creditJournalEntry); @@ -463,8 +468,8 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer } catch (final DataIntegrityViolationException dve) { handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleTellerDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/util/DateRange.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/util/DateRange.java index fc4e843f4..32857d4dd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/util/DateRange.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/teller/util/DateRange.java @@ -27,6 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DateRange { + private final static Logger LOG = LoggerFactory.getLogger(DateRange.class); private static final String ISO_8601_DATE_PATTERN = "yyy-MM-dd"; private static final String RANGE_DELIMITER = ".."; @@ -72,7 +73,7 @@ public class DateRange { try { cal.setTime(sdf.parse(tokenizer.nextToken())); } catch (ParseException ex) { - LOG.error("Problem occurred in DateRange function Could not parse the date recieved.",ex); + LOG.error("Problem occurred in DateRange function Could not parse the date recieved.", ex); } cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); @@ -85,7 +86,7 @@ public class DateRange { try { cal.setTime(sdf.parse(tokenizer.nextToken())); } catch (ParseException ex) { - LOG.error("Problem occurred in DateRange function Could not parse the date recieved.",ex); + LOG.error("Problem occurred in DateRange function Could not parse the date recieved.", ex); } } cal.set(Calendar.HOUR_OF_DAY, 23); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiConstants.java old mode 100755 new mode 100644 index d7357dbc1..6bcc23b10 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiConstants.java @@ -38,10 +38,8 @@ public class WorkingDaysApiConstants { public static final String extendTermForDailyRepayments = "extendTermForDailyRepayments"; public static final String extendTermForRepaymentsOnHolidays = "extendTermForRepaymentsOnHolidays"; - protected static final Set WORKING_DAYS_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, - recurrence,repayment_rescheduling_enum,extendTermForDailyRepayments,extendTermForRepaymentsOnHolidays - )); + protected static final Set WORKING_DAYS_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, recurrence, + repayment_rescheduling_enum, extendTermForDailyRepayments, extendTermForRepaymentsOnHolidays)); - protected static final Set WORKING_DAYS_TEMPLATE_PARAMETERS = new HashSet<>(Arrays.asList - (rescheduleRepaymentTemplate)); + protected static final Set WORKING_DAYS_TEMPLATE_PARAMETERS = new HashSet<>(Arrays.asList(rescheduleRepaymentTemplate)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiResource.java old mode 100755 new mode 100644 index a784e72dc..bfc0ec60d --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiResource.java @@ -52,10 +52,11 @@ import org.springframework.stereotype.Component; @Path("/workingdays") @Component @Scope("singleton") -@Api(tags = {"Working days"}) -@SwaggerDefinition(tags = { - @Tag(name = "Working days", description = "The days of the week that are workdays.\n" + "\n" + "Rescheduling of repayments when it falls on a non-working is turned on /off by enable/disable reschedule-future-repayments parameter in Global configurations\n" + "\n" + "Allow transactions on non-working days is configurable by enabling/disbaling the allow-transactions-on-non_workingday parameter in Global configurations.") -}) +@Api(tags = { "Working days" }) +@SwaggerDefinition(tags = { @Tag(name = "Working days", description = "The days of the week that are workdays.\n" + "\n" + + "Rescheduling of repayments when it falls on a non-working is turned on /off by enable/disable reschedule-future-repayments parameter in Global configurations\n" + + "\n" + + "Allow transactions on non-working days is configurable by enabling/disbaling the allow-transactions-on-non_workingday parameter in Global configurations.") }) public class WorkingDaysApiResource { private final DefaultToApiJsonSerializer toApiJsonSerializer; @@ -80,7 +81,8 @@ public class WorkingDaysApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "List Working days", notes = "Example Requests:\n" + "\n" + "workingdays") - @ApiResponses({@ApiResponse(code = 200, message = "", response = WorkingDaysApiResourceSwagger.GetWorkingDaysResponse.class, responseContainer = "list")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = WorkingDaysApiResourceSwagger.GetWorkingDaysResponse.class, responseContainer = "list") }) public String retrieveAll(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(WorkingDaysApiConstants.WORKING_DAYS_RESOURCE_NAME); final WorkingDaysData workingDaysData = this.workingDaysReadPlatformService.retrieve(); @@ -92,9 +94,11 @@ public class WorkingDaysApiResource { @PUT @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Update a Working Day", notes = "Mandatory Fields\n" + "recurrence,repaymentRescheduleType,extendTermForDailyRepayments,locale") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = WorkingDaysApiResourceSwagger.PutWorkingDaysRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = WorkingDaysApiResourceSwagger.PutWorkingDaysResponse.class)}) + @ApiOperation(value = "Update a Working Day", notes = "Mandatory Fields\n" + + "recurrence,repaymentRescheduleType,extendTermForDailyRepayments,locale") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = WorkingDaysApiResourceSwagger.PutWorkingDaysRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = WorkingDaysApiResourceSwagger.PutWorkingDaysResponse.class) }) public String update(@ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateWorkingDays().withJson(jsonRequestBody).build(); @@ -108,8 +112,9 @@ public class WorkingDaysApiResource { @Path("/template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Working Days Template", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for working days.\n" + "\n" + "Example Request:\n" + "\n" + "workingdays/template") - @ApiResponses({@ApiResponse(code = 200, message = "", response = WorkingDaysApiResourceSwagger.GetWorkingDaysTemplateResponse.class )}) + @ApiOperation(value = "Working Days Template", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for working days.\n" + + "\n" + "Example Request:\n" + "\n" + "workingdays/template") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = WorkingDaysApiResourceSwagger.GetWorkingDaysTemplateResponse.class) }) public String template(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(WorkingDaysApiConstants.WORKING_DAYS_RESOURCE_NAME); diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiResourceSwagger.java index f4956364c..318a26143 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/api/WorkingDaysApiResourceSwagger.java @@ -28,15 +28,18 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; */ final class WorkingDaysApiResourceSwagger { + private WorkingDaysApiResourceSwagger() { } @ApiModel(value = "GetWorkingDaysResponse") public static final class GetWorkingDaysResponse { + private GetWorkingDaysResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR") @@ -48,17 +51,21 @@ final class WorkingDaysApiResourceSwagger { @ApiModel(value = "GetWorkingDaysTemplateResponse") public static final class GetWorkingDaysTemplateResponse { + private GetWorkingDaysTemplateResponse() { } + public Collection repaymentRescheduleOptions; } @ApiModel(value = "PutWorkingDaysRequest") public static final class PutWorkingDaysRequest { + private PutWorkingDaysRequest() { } + @ApiModelProperty(example = "FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR") public String recurrence; @ApiModelProperty(example = "en") @@ -71,9 +78,11 @@ final class WorkingDaysApiResourceSwagger { @ApiModel(value = "PutWorkingDaysResponse") public static final class PutWorkingDaysResponse { + private PutWorkingDaysResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/AdjustedDateDetailsDTO.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/AdjustedDateDetailsDTO.java index 916c2fd52..19ce000bc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/AdjustedDateDetailsDTO.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/AdjustedDateDetailsDTO.java @@ -20,7 +20,6 @@ package org.apache.fineract.organisation.workingdays.data; import org.joda.time.LocalDate; - public class AdjustedDateDetailsDTO { /** @@ -73,4 +72,4 @@ public class AdjustedDateDetailsDTO { public void setNextRepaymentPeriodDueDate(final LocalDate nextRepaymentPeriodDueDate) { this.nextRepaymentPeriodDueDate = nextRepaymentPeriodDueDate; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDayValidator.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDayValidator.java old mode 100755 new mode 100644 index cc4aa79ca..36183d7d2 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDayValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDayValidator.java @@ -55,8 +55,7 @@ public class WorkingDayValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - WORKING_DAYS_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, WORKING_DAYS_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); final List dataValidationErrors = new ArrayList<>(); @@ -71,18 +70,19 @@ public class WorkingDayValidator { baseDataValidator.reset().parameter("repaymentRescheduleType").value(repaymentRescheduleType).ignoreIfNull().inMinMaxRange(1, 4); final Boolean extendTermForDailyRepayments = this.fromApiJsonHelper.extractBooleanNamed("extendTermForDailyRepayments", element); - baseDataValidator.reset().parameter(WorkingDaysApiConstants.extendTermForDailyRepayments).value(extendTermForDailyRepayments).ignoreIfNull().validateForBooleanValue(); + baseDataValidator.reset().parameter(WorkingDaysApiConstants.extendTermForDailyRepayments).value(extendTermForDailyRepayments) + .ignoreIfNull().validateForBooleanValue(); - final Boolean extendTermForRepaymentsOnHolidays = this.fromApiJsonHelper.extractBooleanNamed("extendTermForRepaymentsOnHolidays", element); - baseDataValidator.reset().parameter(WorkingDaysApiConstants.extendTermForRepaymentsOnHolidays).value(extendTermForRepaymentsOnHolidays).ignoreIfNull().validateForBooleanValue(); + final Boolean extendTermForRepaymentsOnHolidays = this.fromApiJsonHelper.extractBooleanNamed("extendTermForRepaymentsOnHolidays", + element); + baseDataValidator.reset().parameter(WorkingDaysApiConstants.extendTermForRepaymentsOnHolidays) + .value(extendTermForRepaymentsOnHolidays).ignoreIfNull().validateForBooleanValue(); throwExceptionIfValidationWarningsExist(dataValidationErrors); } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDaysData.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDaysData.java old mode 100755 new mode 100644 index 9b32a5809..294e27a42 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDaysData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/data/WorkingDaysData.java @@ -37,7 +37,8 @@ public class WorkingDaysData { @SuppressWarnings("unused") private final Collection repaymentRescheduleOptions; - public WorkingDaysData(Long id, String recurrence, EnumOptionData repaymentRescheduleType, Boolean extendTermForDailyRepayments, Boolean extendTermForRepaymentsOnHolidays) { + public WorkingDaysData(Long id, String recurrence, EnumOptionData repaymentRescheduleType, Boolean extendTermForDailyRepayments, + Boolean extendTermForRepaymentsOnHolidays) { this.id = id; this.recurrence = recurrence; this.repaymentRescheduleType = repaymentRescheduleType; @@ -47,7 +48,8 @@ public class WorkingDaysData { } public WorkingDaysData(Long id, String recurrence, EnumOptionData repaymentRescheduleType, - Collection repaymentRescheduleOptions, Boolean extendTermForDailyRepayments, Boolean extendTermForRepaymentsOnHolidays) { + Collection repaymentRescheduleOptions, Boolean extendTermForDailyRepayments, + Boolean extendTermForRepaymentsOnHolidays) { this.id = id; this.recurrence = recurrence; this.repaymentRescheduleType = repaymentRescheduleType; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/RepaymentRescheduleType.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/RepaymentRescheduleType.java index 8ee6555b1..7789933ab 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/RepaymentRescheduleType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/RepaymentRescheduleType.java @@ -25,9 +25,9 @@ public enum RepaymentRescheduleType { INVALID(0, "RepaymentRescheduleType.invalid"), SAME_DAY(1, "RepaymentRescheduleType.same.day"), MOVE_TO_NEXT_WORKING_DAY(2, "RepaymentRescheduleType.move.to.next.working.day"), MOVE_TO_NEXT_REPAYMENT_MEETING_DAY(3, - "RepaymentRescheduleType.move.to.next.repayment.meeting.day"), MOVE_TO_PREVIOUS_WORKING_DAY(4, - "RepaymentRescheduleType.move.to.previous.working.day"), - MOVE_TO_NEXT_MEETING_DAY(5, "RepaymentRescheduleType.move.to.next.meeting.day"); + "RepaymentRescheduleType.move.to.next.repayment.meeting.day"), MOVE_TO_PREVIOUS_WORKING_DAY(4, + "RepaymentRescheduleType.move.to.previous.working.day"), MOVE_TO_NEXT_MEETING_DAY(5, + "RepaymentRescheduleType.move.to.next.meeting.day"); private final Integer value; private final String code; diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDays.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDays.java old mode 100755 new mode 100644 index 132cb7196..69ee3c9fb --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDays.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDays.java @@ -47,7 +47,8 @@ public class WorkingDays extends AbstractPersistableCustom { } - protected WorkingDays(final String recurrence, final Integer repaymentReschedulingType, final Boolean extendTermForDailyRepayments, final Boolean extendTermForRepaymentsOnHolidays) { + protected WorkingDays(final String recurrence, final Integer repaymentReschedulingType, final Boolean extendTermForDailyRepayments, + final Boolean extendTermForRepaymentsOnHolidays) { this.recurrence = recurrence; this.repaymentReschedulingType = repaymentReschedulingType; this.extendTermForDailyRepayments = extendTermForDailyRepayments; @@ -72,11 +73,13 @@ public class WorkingDays extends AbstractPersistableCustom { this.repaymentReschedulingType = repaymentReschedulingType; } - public Boolean getExtendTermForDailyRepayments(){ + public Boolean getExtendTermForDailyRepayments() { return this.extendTermForDailyRepayments; } - public Boolean getExtendTermForRepaymentsOnHolidays() { return this.extendTermForRepaymentsOnHolidays; } + public Boolean getExtendTermForRepaymentsOnHolidays() { + return this.extendTermForRepaymentsOnHolidays; + } public Map update(final JsonCommand command) { final Map actualChanges = new LinkedHashMap<>(7); @@ -90,19 +93,22 @@ public class WorkingDays extends AbstractPersistableCustom { final String repaymentRescheduleTypeParamName = "repaymentRescheduleType"; if (command.isChangeInIntegerParameterNamed(repaymentRescheduleTypeParamName, this.repaymentReschedulingType)) { - final Integer newValue =command.integerValueOfParameterNamed(repaymentRescheduleTypeParamName); - actualChanges.put(repaymentRescheduleTypeParamName, WorkingDaysEnumerations.workingDaysStatusType(newValue)); + final Integer newValue = command.integerValueOfParameterNamed(repaymentRescheduleTypeParamName); + actualChanges.put(repaymentRescheduleTypeParamName, WorkingDaysEnumerations.workingDaysStatusType(newValue)); this.repaymentReschedulingType = RepaymentRescheduleType.fromInt(newValue).getValue(); } - if(command.isChangeInBooleanParameterNamed(WorkingDaysApiConstants.extendTermForDailyRepayments, this.extendTermForDailyRepayments)){ + if (command.isChangeInBooleanParameterNamed(WorkingDaysApiConstants.extendTermForDailyRepayments, + this.extendTermForDailyRepayments)) { final Boolean newValue = command.booleanPrimitiveValueOfParameterNamed(WorkingDaysApiConstants.extendTermForDailyRepayments); actualChanges.put(WorkingDaysApiConstants.extendTermForDailyRepayments, newValue); this.extendTermForDailyRepayments = newValue; } - if (command.isChangeInBooleanParameterNamed(WorkingDaysApiConstants.extendTermForRepaymentsOnHolidays, this.extendTermForRepaymentsOnHolidays)) { - final Boolean newValue = command.booleanPrimitiveValueOfParameterNamed(WorkingDaysApiConstants.extendTermForRepaymentsOnHolidays); + if (command.isChangeInBooleanParameterNamed(WorkingDaysApiConstants.extendTermForRepaymentsOnHolidays, + this.extendTermForRepaymentsOnHolidays)) { + final Boolean newValue = command + .booleanPrimitiveValueOfParameterNamed(WorkingDaysApiConstants.extendTermForRepaymentsOnHolidays); actualChanges.put(WorkingDaysApiConstants.extendTermForRepaymentsOnHolidays, newValue); this.extendTermForRepaymentsOnHolidays = newValue; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDaysEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDaysEnumerations.java old mode 100755 new mode 100644 index ba8a3eb4f..190a268a2 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDaysEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDaysEnumerations.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.organisation.workingdays.domain; - import org.apache.fineract.infrastructure.core.data.EnumOptionData; public class WorkingDaysEnumerations { @@ -27,32 +26,32 @@ public class WorkingDaysEnumerations { return repaymentRescheduleType(RepaymentRescheduleType.fromInt(id)); } - public static EnumOptionData repaymentRescheduleType(final RepaymentRescheduleType type){ + public static EnumOptionData repaymentRescheduleType(final RepaymentRescheduleType type) { EnumOptionData optionData = null; - switch(type){ + switch (type) { case INVALID: - optionData = new EnumOptionData(RepaymentRescheduleType.INVALID.getValue().longValue(),RepaymentRescheduleType.INVALID.getCode(), - "invalid"); + optionData = new EnumOptionData(RepaymentRescheduleType.INVALID.getValue().longValue(), + RepaymentRescheduleType.INVALID.getCode(), "invalid"); break; case SAME_DAY: - optionData = new EnumOptionData(RepaymentRescheduleType.SAME_DAY.getValue().longValue(),RepaymentRescheduleType.SAME_DAY.getCode(), - "same day"); + optionData = new EnumOptionData(RepaymentRescheduleType.SAME_DAY.getValue().longValue(), + RepaymentRescheduleType.SAME_DAY.getCode(), "same day"); - break; + break; case MOVE_TO_NEXT_WORKING_DAY: - optionData = new EnumOptionData(RepaymentRescheduleType.MOVE_TO_NEXT_WORKING_DAY.getValue().longValue(),RepaymentRescheduleType.MOVE_TO_NEXT_WORKING_DAY.getCode(), - "move to next working day"); - break; + optionData = new EnumOptionData(RepaymentRescheduleType.MOVE_TO_NEXT_WORKING_DAY.getValue().longValue(), + RepaymentRescheduleType.MOVE_TO_NEXT_WORKING_DAY.getCode(), "move to next working day"); + break; case MOVE_TO_NEXT_REPAYMENT_MEETING_DAY: - optionData = new EnumOptionData(RepaymentRescheduleType.MOVE_TO_NEXT_REPAYMENT_MEETING_DAY.getValue().longValue(),RepaymentRescheduleType.MOVE_TO_NEXT_REPAYMENT_MEETING_DAY.getCode(), - "move to next repayment meeting day"); - break; + optionData = new EnumOptionData(RepaymentRescheduleType.MOVE_TO_NEXT_REPAYMENT_MEETING_DAY.getValue().longValue(), + RepaymentRescheduleType.MOVE_TO_NEXT_REPAYMENT_MEETING_DAY.getCode(), "move to next repayment meeting day"); + break; case MOVE_TO_PREVIOUS_WORKING_DAY: - optionData = new EnumOptionData(RepaymentRescheduleType.MOVE_TO_PREVIOUS_WORKING_DAY.getValue().longValue(),RepaymentRescheduleType.MOVE_TO_PREVIOUS_WORKING_DAY.getCode(), - "move to previous working day"); - break; + optionData = new EnumOptionData(RepaymentRescheduleType.MOVE_TO_PREVIOUS_WORKING_DAY.getValue().longValue(), + RepaymentRescheduleType.MOVE_TO_PREVIOUS_WORKING_DAY.getCode(), "move to previous working day"); + break; default: } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDaysRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDaysRepositoryWrapper.java index 55e477c45..a29f08df4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDaysRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/domain/WorkingDaysRepositoryWrapper.java @@ -64,4 +64,4 @@ public class WorkingDaysRepositoryWrapper { final WorkingDays workingDays = findOne(); return WorkingDaysUtil.isWorkingDay(workingDays, transactionDate); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/exception/WorkingDaysNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/exception/WorkingDaysNotFoundException.java old mode 100755 new mode 100644 index d090dab6a..8305cb574 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/exception/WorkingDaysNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/exception/WorkingDaysNotFoundException.java @@ -29,4 +29,4 @@ public class WorkingDaysNotFoundException extends AbstractPlatformResourceNotFou super("error.msg.working.days.not.configured", "Must configure the Working days for the organisation."); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/handler/UpdateWorkingDaysCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/handler/UpdateWorkingDaysCommandHandler.java old mode 100755 new mode 100644 index cbd19a4e6..0f1fc6bad --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/handler/UpdateWorkingDaysCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/handler/UpdateWorkingDaysCommandHandler.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.organisation.workingdays.handler; - import org.apache.fineract.commands.annotation.CommandType; import org.apache.fineract.commands.handler.NewCommandSourceHandler; import org.apache.fineract.infrastructure.core.api.JsonCommand; @@ -30,7 +29,7 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "WORKINGDAYS", action = "UPDATE") -public class UpdateWorkingDaysCommandHandler implements NewCommandSourceHandler { +public class UpdateWorkingDaysCommandHandler implements NewCommandSourceHandler { private final WorkingDaysWritePlatformService workingDaysWritePlatformService; @@ -38,6 +37,7 @@ public class UpdateWorkingDaysCommandHandler implements NewCommandSourceHandler public UpdateWorkingDaysCommandHandler(final WorkingDaysWritePlatformService workingDaysWritePlatformService) { this.workingDaysWritePlatformService = workingDaysWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand command) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/service/WorkingDaysReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/service/WorkingDaysReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 63af09443..a2ba37670 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/service/WorkingDaysReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/service/WorkingDaysReadPlatformServiceImpl.java @@ -78,13 +78,13 @@ public class WorkingDaysReadPlatformServiceImpl implements WorkingDaysReadPlatfo @Override public WorkingDaysData retrieve() { - //Check whether template is enabled or not? + // Check whether template is enabled or not? try { final WorkingDaysMapper rm = new WorkingDaysMapper(); final String sql = " select " + rm.schema(); WorkingDaysData data = this.jdbcTemplate.queryForObject(sql, rm, new Object[] {}); - Collection repaymentRescheduleOptions = repaymentRescheduleTypeOptions() ; - return new WorkingDaysData(data, repaymentRescheduleOptions) ; + Collection repaymentRescheduleOptions = repaymentRescheduleTypeOptions(); + return new WorkingDaysData(data, repaymentRescheduleOptions); } catch (final EmptyResultDataAccessException e) { throw new WorkingDaysNotFoundException(); } @@ -97,10 +97,9 @@ public class WorkingDaysReadPlatformServiceImpl implements WorkingDaysReadPlatfo } private Collection repaymentRescheduleTypeOptions() { - return Arrays.asList( - WorkingDaysEnumerations.repaymentRescheduleType(RepaymentRescheduleType.SAME_DAY), - WorkingDaysEnumerations.repaymentRescheduleType(RepaymentRescheduleType.MOVE_TO_NEXT_WORKING_DAY), - WorkingDaysEnumerations.repaymentRescheduleType(RepaymentRescheduleType.MOVE_TO_NEXT_REPAYMENT_MEETING_DAY), - WorkingDaysEnumerations.repaymentRescheduleType(RepaymentRescheduleType.MOVE_TO_PREVIOUS_WORKING_DAY)); + return Arrays.asList(WorkingDaysEnumerations.repaymentRescheduleType(RepaymentRescheduleType.SAME_DAY), + WorkingDaysEnumerations.repaymentRescheduleType(RepaymentRescheduleType.MOVE_TO_NEXT_WORKING_DAY), + WorkingDaysEnumerations.repaymentRescheduleType(RepaymentRescheduleType.MOVE_TO_NEXT_REPAYMENT_MEETING_DAY), + WorkingDaysEnumerations.repaymentRescheduleType(RepaymentRescheduleType.MOVE_TO_PREVIOUS_WORKING_DAY)); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/service/WorkingDaysUtil.java b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/service/WorkingDaysUtil.java index f98064b90..78c6bb58b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/service/WorkingDaysUtil.java +++ b/fineract-provider/src/main/java/org/apache/fineract/organisation/workingdays/service/WorkingDaysUtil.java @@ -58,7 +58,8 @@ public class WorkingDaysUtil { return !isWorkingDay(workingDays, date); } - public static void updateWorkingDayIfRepaymentDateIsNonWorkingDay(final AdjustedDateDetailsDTO adjustedDateDetailsDTO, final WorkingDays workingDays) { + public static void updateWorkingDayIfRepaymentDateIsNonWorkingDay(final AdjustedDateDetailsDTO adjustedDateDetailsDTO, + final WorkingDays workingDays) { final LocalDate changedScheduleDate = getOffSetDateIfNonWorkingDay(adjustedDateDetailsDTO.getChangedScheduleDate(), adjustedDateDetailsDTO.getNextRepaymentPeriodDueDate(), workingDays); adjustedDateDetailsDTO.setChangedScheduleDate(changedScheduleDate); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/AccountDetailConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/AccountDetailConstants.java old mode 100755 new mode 100644 index 3a2d07c56..96f3c74b3 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/AccountDetailConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/AccountDetailConstants.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.portfolio.account; - public class AccountDetailConstants { // general @@ -37,4 +36,4 @@ public class AccountDetailConstants { public static final String toAccountTypeParamName = "toAccountType"; public static final String transferTypeParamName = "transferType"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/PortfolioAccountType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/PortfolioAccountType.java index 264f16ab8..6c2108d09 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/PortfolioAccountType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/PortfolioAccountType.java @@ -77,4 +77,4 @@ public enum PortfolioAccountType { public boolean isLoanAccount() { return this.value.equals(1); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiConstants.java index 6176cb00a..e3134c816 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiConstants.java @@ -41,4 +41,4 @@ public class AccountTransfersApiConstants { */ protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( Arrays.asList(AccountDetailConstants.idParamName, transferDescriptionParamName, currencyParamName)); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiResource.java index 013e02dc5..c7b8441cf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiResource.java @@ -56,10 +56,9 @@ import org.springframework.stereotype.Component; @Path("/accounttransfers") @Component @Scope("singleton") -@Api(tags = {"Account Transfers"}) +@Api(tags = { "Account Transfers" }) @SwaggerDefinition(tags = { - @Tag(name = "Account Transfers", description = "Ability to be able to transfer monetary funds from one account to another.\n\nNote: At present only savings account to savings account transfers are supported.") -}) + @Tag(name = "Account Transfers", description = "Ability to be able to transfer monetary funds from one account to another.\n\nNote: At present only savings account to savings account transfers are supported.") }) public class AccountTransfersApiResource { private final PlatformSecurityContext context; @@ -85,13 +84,21 @@ public class AccountTransfersApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Account Transfer Template", httpMethod = "GET", notes = "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:\n\n" + "\n\n" + "Field Defaults\n\n" + "Allowed Value Lists\n\n" + "Example Requests:\n\n" + "\n\n" + "accounttransfers/template?fromAccountType=2&fromOfficeId=1\n\n" + "\n\n" + "accounttransfers/template?fromAccountType=2&fromOfficeId=1&fromClientId=1\n\n" + "\n\n" + "accounttransfers/template?fromClientId=1&fromAccountType=2&fromAccountId=1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.GetAccountTransfersTemplateResponse.class)}) - public String template(@QueryParam("fromOfficeId") @ApiParam(value = "fromOfficeId") final Long fromOfficeId, @QueryParam("fromClientId") @ApiParam(value = "fromClientId") final Long fromClientId, - @QueryParam("fromAccountId") @ApiParam(value = "fromAccountId") final Long fromAccountId, @QueryParam("fromAccountType") @ApiParam(value = "fromAccountType") final Integer fromAccountType, - @QueryParam("toOfficeId") @ApiParam(value = "toOfficeId") final Long toOfficeId, @QueryParam("toClientId") @ApiParam(value = "toClientId") final Long toClientId, - @QueryParam("toAccountId") @ApiParam(value = "toAccountId") final Long toAccountId, @QueryParam("toAccountType") @ApiParam(value = "toAccountType") final Integer toAccountType, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve Account Transfer Template", httpMethod = "GET", notes = "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:\n\n" + + "\n\n" + "Field Defaults\n\n" + "Allowed Value Lists\n\n" + "Example Requests:\n\n" + "\n\n" + + "accounttransfers/template?fromAccountType=2&fromOfficeId=1\n\n" + "\n\n" + + "accounttransfers/template?fromAccountType=2&fromOfficeId=1&fromClientId=1\n\n" + "\n\n" + + "accounttransfers/template?fromClientId=1&fromAccountType=2&fromAccountId=1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.GetAccountTransfersTemplateResponse.class) }) + public String template(@QueryParam("fromOfficeId") @ApiParam(value = "fromOfficeId") final Long fromOfficeId, + @QueryParam("fromClientId") @ApiParam(value = "fromClientId") final Long fromClientId, + @QueryParam("fromAccountId") @ApiParam(value = "fromAccountId") final Long fromAccountId, + @QueryParam("fromAccountType") @ApiParam(value = "fromAccountType") final Integer fromAccountType, + @QueryParam("toOfficeId") @ApiParam(value = "toOfficeId") final Long toOfficeId, + @QueryParam("toClientId") @ApiParam(value = "toClientId") final Long toClientId, + @QueryParam("toAccountId") @ApiParam(value = "toAccountId") final Long toAccountId, + @QueryParam("toAccountType") @ApiParam(value = "toAccountType") final Integer toAccountType, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); @@ -106,8 +113,10 @@ public class AccountTransfersApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create new Transfer", httpMethod = "POST", notes = "Ability to create new transfer of monetary funds from one account to another.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountTransfersApiResourceSwagger.PostAccountTransfersRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.PostAccountTransfersResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountTransfersApiResourceSwagger.PostAccountTransfersRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.PostAccountTransfersResponse.class) }) public String create(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createAccountTransfer().withJson(apiRequestBodyAsJson).build(); @@ -120,12 +129,18 @@ public class AccountTransfersApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List account transfers", httpMethod = "GET", notes = "Lists account's transfers\n\n" + "Example Requests:\n\n" + "\n\n" + "accounttransfers") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.GetAccountTransfersResponse.class)}) - public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, - @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, - @QueryParam("limit") @ApiParam(example = "limit") final Integer limit, @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, - @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder,@QueryParam("accountDetailId") @ApiParam(value = "accountDetailId") final Long accountDetailId) { + @ApiOperation(value = "List account transfers", httpMethod = "GET", notes = "Lists account's transfers\n\n" + "Example Requests:\n\n" + + "\n\n" + "accounttransfers") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.GetAccountTransfersResponse.class) }) + public String retrieveAll(@Context final UriInfo uriInfo, + @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, + @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(example = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, + @QueryParam("accountDetailId") @ApiParam(value = "accountDetailId") final Long accountDetailId) { this.context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); @@ -142,9 +157,12 @@ public class AccountTransfersApiResource { @Path("{transferId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve account transfer", httpMethod = "GET", notes = "Retrieves account transfer\n\n" + "Example Requests :\n\n" + "\n\n" + "accounttransfers/1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.GetAccountTransfersResponse.GetAccountTransfersPageItems.class)}) - public String retrieveOne(@PathParam("transferId") @ApiParam(value = "transferId") final Long transferId, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve account transfer", httpMethod = "GET", notes = "Retrieves account transfer\n\n" + + "Example Requests :\n\n" + "\n\n" + "accounttransfers/1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.GetAccountTransfersResponse.GetAccountTransfersPageItems.class) }) + public String retrieveOne(@PathParam("transferId") @ApiParam(value = "transferId") final Long transferId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); @@ -158,18 +176,24 @@ public class AccountTransfersApiResource { @Path("templateRefundByTransfer") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Refund of an Active Loan by Transfer Template", httpMethod = "GET", notes = "Retrieves Refund of an Active Loan by Transfer Template" + "Example Requests :\n\n" + "\n\n" + "accounttransfers/templateRefundByTransfer?fromAccountId=2&fromAccountType=1& toAccountId=1&toAccountType=2&toClientId=1&toOfficeId=1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.GetAccountTransfersTemplateRefundByTransferResponse.class)}) - public String templateRefundByTransfer(@QueryParam("fromOfficeId") @ApiParam(value = "fromOfficeId") final Long fromOfficeId, @QueryParam("fromClientId") @ApiParam(value = "fromClientId") final Long fromClientId, - @QueryParam("fromAccountId") @ApiParam(value = "fromAccountId") final Long fromAccountId, @QueryParam("fromAccountType") @ApiParam(value = "fromAccountType") final Integer fromAccountType, - @QueryParam("toOfficeId") @ApiParam(value = "toOfficeId") final Long toOfficeId, @QueryParam("toClientId") @ApiParam(value = "toClientId") final Long toClientId, - @QueryParam("toAccountId") @ApiParam(value = "toAccountId") final Long toAccountId, @QueryParam("toAccountType") @ApiParam(value = "toAccountType") final Integer toAccountType, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve Refund of an Active Loan by Transfer Template", httpMethod = "GET", notes = "Retrieves Refund of an Active Loan by Transfer Template" + + "Example Requests :\n\n" + "\n\n" + + "accounttransfers/templateRefundByTransfer?fromAccountId=2&fromAccountType=1& toAccountId=1&toAccountType=2&toClientId=1&toOfficeId=1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.GetAccountTransfersTemplateRefundByTransferResponse.class) }) + public String templateRefundByTransfer(@QueryParam("fromOfficeId") @ApiParam(value = "fromOfficeId") final Long fromOfficeId, + @QueryParam("fromClientId") @ApiParam(value = "fromClientId") final Long fromClientId, + @QueryParam("fromAccountId") @ApiParam(value = "fromAccountId") final Long fromAccountId, + @QueryParam("fromAccountType") @ApiParam(value = "fromAccountType") final Integer fromAccountType, + @QueryParam("toOfficeId") @ApiParam(value = "toOfficeId") final Long toOfficeId, + @QueryParam("toClientId") @ApiParam(value = "toClientId") final Long toClientId, + @QueryParam("toAccountId") @ApiParam(value = "toAccountId") final Long toAccountId, + @QueryParam("toAccountType") @ApiParam(value = "toAccountType") final Integer toAccountType, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); - final AccountTransferData transferData = this.accountTransfersReadPlatformService.retrieveRefundByTransferTemplate(fromOfficeId, fromClientId, - fromAccountId, fromAccountType, toOfficeId, toClientId, toAccountId, toAccountType); + final AccountTransferData transferData = this.accountTransfersReadPlatformService.retrieveRefundByTransferTemplate(fromOfficeId, + fromClientId, fromAccountId, fromAccountType, toOfficeId, toClientId, toAccountId, toAccountType); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, transferData, AccountTransfersApiConstants.RESPONSE_DATA_PARAMETERS); @@ -180,8 +204,10 @@ public class AccountTransfersApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Refund of an Active Loan by Transfer", httpMethod = "POST", notes = "Ability to refund an active loan by transferring to a savings account.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountTransfersApiResourceSwagger.PostAccountTransfersRefundByTransferRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.PostAccountTransfersRefundByTransferResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountTransfersApiResourceSwagger.PostAccountTransfersRefundByTransferRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = AccountTransfersApiResourceSwagger.PostAccountTransfersRefundByTransferResponse.class) }) public String templateRefundByTransferPost(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().refundByTransfer().withJson(apiRequestBodyAsJson).build(); @@ -190,4 +216,4 @@ public class AccountTransfersApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiResourceSwagger.java index 39e2c96e6..d131c51c0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/AccountTransfersApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/16/17. */ final class AccountTransfersApiResourceSwagger { - private AccountTransfersApiResourceSwagger() { - } + + private AccountTransfersApiResourceSwagger() {} @ApiModel(value = "GetAccountTransfersTemplateResponse") public final static class GetAccountTransfersTemplateResponse { - private GetAccountTransfersTemplateResponse() { - } + + private GetAccountTransfersTemplateResponse() {} final class GetAccountTransfersFromOffice { - private GetAccountTransfersFromOffice() { - } + + private GetAccountTransfersFromOffice() {} @ApiModelProperty(example = "1") public Integer id; @@ -54,8 +54,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersFromAccountType { - private GetAccountTransfersFromAccountType() { - } + + private GetAccountTransfersFromAccountType() {} @ApiModelProperty(example = "2") public Integer id; @@ -66,8 +66,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersFromOfficeOptions { - private GetAccountTransfersFromOfficeOptions() { - } + + private GetAccountTransfersFromOfficeOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -78,8 +78,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersFromClientOptions { - private GetAccountTransfersFromClientOptions() { - } + + private GetAccountTransfersFromClientOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -92,8 +92,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersFromAccountTypeOptions { - private GetAccountTransfersFromAccountTypeOptions() { - } + + private GetAccountTransfersFromAccountTypeOptions() {} @ApiModelProperty(example = "2") public Integer id; @@ -104,8 +104,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersToOfficeOptions { - private GetAccountTransfersToOfficeOptions() { - } + + private GetAccountTransfersToOfficeOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -116,8 +116,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersToAccountTypeOptions { - private GetAccountTransfersToAccountTypeOptions() { - } + + private GetAccountTransfersToAccountTypeOptions() {} @ApiModelProperty(example = "2") public Integer id; @@ -142,8 +142,8 @@ final class AccountTransfersApiResourceSwagger { @ApiModel(value = "PostAccountTransfersRequest") public final static class PostAccountTransfersRequest { - private PostAccountTransfersRequest() { - } + + private PostAccountTransfersRequest() {} @ApiModelProperty(example = "1") public Integer fromOfficeId; @@ -175,8 +175,8 @@ final class AccountTransfersApiResourceSwagger { @ApiModel(value = "PostAccountTransfersResponse") public final static class PostAccountTransfersResponse { - private PostAccountTransfersResponse() { - } + + private PostAccountTransfersResponse() {} @ApiModelProperty(example = "1") public Integer savingsId; @@ -186,16 +186,16 @@ final class AccountTransfersApiResourceSwagger { @ApiModel(value = "GetAccountTransfersResponse") public final static class GetAccountTransfersResponse { - private GetAccountTransfersResponse() { - } + + private GetAccountTransfersResponse() {} final class GetAccountTransfersPageItems { - private GetAccountTransfersPageItems() { - } + + private GetAccountTransfersPageItems() {} final class GetAccountTransfersPageItemsCurrency { - private GetAccountTransfersPageItemsCurrency() { - } + + private GetAccountTransfersPageItemsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -212,8 +212,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersPageItemsFromOffice { - private GetAccountTransfersPageItemsFromOffice() { - } + + private GetAccountTransfersPageItemsFromOffice() {} @ApiModelProperty(example = "1") public Integer id; @@ -222,8 +222,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersPageItemsFromAccount { - private GetAccountTransfersPageItemsFromAccount() { - } + + private GetAccountTransfersPageItemsFromAccount() {} @ApiModelProperty(example = "1") public Integer id; @@ -232,8 +232,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersPageItemsToAccountType { - private GetAccountTransfersPageItemsToAccountType() { - } + + private GetAccountTransfersPageItemsToAccountType() {} @ApiModelProperty(example = "1") public Integer id; @@ -243,7 +243,6 @@ final class AccountTransfersApiResourceSwagger { public String value; } - @ApiModelProperty(example = "1") public Integer id; @ApiModelProperty(example = "false") @@ -272,12 +271,12 @@ final class AccountTransfersApiResourceSwagger { @ApiModel(value = "GetAccountTransfersTemplateRefundByTransferResponse") public static final class GetAccountTransfersTemplateRefundByTransferResponse { - private GetAccountTransfersTemplateRefundByTransferResponse() { - } + + private GetAccountTransfersTemplateRefundByTransferResponse() {} final class GetAccountTransfersTemplateRefundByTransferCurrency { - private GetAccountTransfersTemplateRefundByTransferCurrency() { - } + + private GetAccountTransfersTemplateRefundByTransferCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -296,8 +295,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersTemplateRefundByTransferFromOffice { - private GetAccountTransfersTemplateRefundByTransferFromOffice() { - } + + private GetAccountTransfersTemplateRefundByTransferFromOffice() {} @ApiModelProperty(example = "1") public Integer id; @@ -314,12 +313,12 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersTemplateRefundByTransferFromClient { - private GetAccountTransfersTemplateRefundByTransferFromClient() { - } + + private GetAccountTransfersTemplateRefundByTransferFromClient() {} final class GetAccountTransfersStatus { - private GetAccountTransfersStatus() { - } + + private GetAccountTransfersStatus() {} @ApiModelProperty(example = "300") public Integer id; @@ -330,23 +329,23 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersGender { - private GetAccountTransfersGender() { - } + + private GetAccountTransfersGender() {} } final class GetAccountTransfersClientType { - private GetAccountTransfersClientType() { - } + + private GetAccountTransfersClientType() {} } final class GetAccountTransfersClientClassification { - private GetAccountTransfersClientClassification() { - } + + private GetAccountTransfersClientClassification() {} } final class GetAccountTransfersTimeline { - private GetAccountTransfersTimeline() { - } + + private GetAccountTransfersTimeline() {} @ApiModelProperty(example = "[2012, 2, 1]") public LocalDate submittedOnDate; @@ -367,8 +366,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersGroups { - private GetAccountTransfersGroups() { - } + + private GetAccountTransfersGroups() {} } @ApiModelProperty(example = "1") @@ -398,8 +397,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersTemplateRefundByTransferFromAccount { - private GetAccountTransfersTemplateRefundByTransferFromAccount() { - } + + private GetAccountTransfersTemplateRefundByTransferFromAccount() {} @ApiModelProperty(example = "2") public Integer id; @@ -421,8 +420,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersTemplateRefundByTransferToClient { - private GetAccountTransfersTemplateRefundByTransferToClient() { - } + + private GetAccountTransfersTemplateRefundByTransferToClient() {} @ApiModelProperty(example = "1") public Integer id; @@ -435,8 +434,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersTemplateRefundByTransferToAccount { - private GetAccountTransfersTemplateRefundByTransferToAccount() { - } + + private GetAccountTransfersTemplateRefundByTransferToAccount() {} @ApiModelProperty(example = "1") public Integer id; @@ -456,8 +455,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersTemplateRefundByTransferFromOfficeOptions { - private GetAccountTransfersTemplateRefundByTransferFromOfficeOptions() { - } + + private GetAccountTransfersTemplateRefundByTransferFromOfficeOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -468,8 +467,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersTemplateRefundByTransferFromClientOptions { - private GetAccountTransfersTemplateRefundByTransferFromClientOptions() { - } + + private GetAccountTransfersTemplateRefundByTransferFromClientOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -482,8 +481,8 @@ final class AccountTransfersApiResourceSwagger { } final class GetAccountTransfersTemplateRefundByTransferFromAccountOptions { - private GetAccountTransfersTemplateRefundByTransferFromAccountOptions() { - } + + private GetAccountTransfersTemplateRefundByTransferFromAccountOptions() {} @ApiModelProperty(example = "2") public Integer id; @@ -527,8 +526,8 @@ final class AccountTransfersApiResourceSwagger { @ApiModel(value = "PostAccountTransfersRefundByTransferRequest") public static final class PostAccountTransfersRefundByTransferRequest { - private PostAccountTransfersRefundByTransferRequest() { - } + + private PostAccountTransfersRefundByTransferRequest() {} @ApiModelProperty(example = "2") public Integer fromAccountId; @@ -560,8 +559,8 @@ final class AccountTransfersApiResourceSwagger { @ApiModel(value = "PostAccountTransfersRefundByTransferResponse") public final static class PostAccountTransfersRefundByTransferResponse { - private PostAccountTransfersRefundByTransferResponse() { - } + + private PostAccountTransfersRefundByTransferResponse() {} @ApiModelProperty(example = "1") public Integer savingsId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiConstants.java old mode 100755 new mode 100644 index f879811cd..2f33abd8a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiConstants.java @@ -40,9 +40,8 @@ public class StandingInstructionApiConstants { public static final String recurrenceOnMonthDayParamName = "recurrenceOnMonthDay"; public static final String monthDayFormatParamName = "monthDayFormat"; - protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(AccountDetailConstants - .idParamName, - nameParamName, priorityParamName, instructionTypeParamName, statusParamName, AccountDetailConstants.transferTypeParamName, - validFromParamName, validTillParamName)); + protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(AccountDetailConstants.idParamName, nameParamName, priorityParamName, instructionTypeParamName, statusParamName, + AccountDetailConstants.transferTypeParamName, validFromParamName, validTillParamName)); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiResource.java old mode 100755 new mode 100644 index 192afa34f..5d2efb665 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiResource.java @@ -66,10 +66,11 @@ import org.springframework.stereotype.Component; @Path("/standinginstructions") @Component @Scope("singleton") -@Api(tags = {"Standing Instructions"}) +@Api(tags = { "Standing Instructions" }) @SwaggerDefinition(tags = { - @Tag(name = "Standing Instructions", description = "Standing instructions (or standing orders) refer to instructions a bank account holder (\"the payer\") gives to his or her bank to pay a set amount at regular intervals to another's (\"the payee's\") account.\n" + "\n" + "Note: At present only savings account to savings account and savings account to Loan account transfers are permitted.") -}) + @Tag(name = "Standing Instructions", description = "Standing instructions (or standing orders) refer to instructions a bank account holder (\"the payer\") gives to his or her bank to pay a set amount at regular intervals to another's (\"the payee's\") account.\n" + + "\n" + + "Note: At present only savings account to savings account and savings account to Loan account transfers are permitted.") }) public class StandingInstructionApiResource { private final PlatformSecurityContext context; @@ -81,11 +82,11 @@ public class StandingInstructionApiResource { @Autowired public StandingInstructionApiResource(final PlatformSecurityContext context, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final ApiRequestParameterHelper apiRequestParameterHelper, - final StandingInstructionReadPlatformService standingInstructionReadPlatformService, - final AccountTransfersReadPlatformService accountTransfersReadPlatformService) { + final DefaultToApiJsonSerializer toApiJsonSerializer, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final ApiRequestParameterHelper apiRequestParameterHelper, + final StandingInstructionReadPlatformService standingInstructionReadPlatformService, + final AccountTransfersReadPlatformService accountTransfersReadPlatformService) { this.context = context; this.toApiJsonSerializer = toApiJsonSerializer; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; @@ -96,15 +97,24 @@ public class StandingInstructionApiResource { @GET @Path("template") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @ApiOperation(value = "Retrieve Standing Instruction Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Requests:\n" + "\n" + "standinginstructions/template?fromAccountType=2&fromOfficeId=1\n" + "\n" + "standinginstructions/template?fromAccountType=2&fromOfficeId=1&fromClientId=1&transferType=1\n" + "\n" + "standinginstructions/template?fromClientId=1&fromAccountType=2&fromAccountId=1&transferType=1") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Retrieve Standing Instruction Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + + "Example Requests:\n" + "\n" + "standinginstructions/template?fromAccountType=2&fromOfficeId=1\n" + "\n" + + "standinginstructions/template?fromAccountType=2&fromOfficeId=1&fromClientId=1&transferType=1\n" + "\n" + + "standinginstructions/template?fromClientId=1&fromAccountType=2&fromAccountId=1&transferType=1") @ApiResponses(@ApiResponse(code = 200, message = "OK", response = StandingInstructionApiResourceSwagger.GetStandingInstructionsTemplateResponse.class)) - public String template(@QueryParam("fromOfficeId") @ApiParam(value = "fromOfficeId") final Long fromOfficeId, @QueryParam("fromClientId") @ApiParam(value = "fromClientId") final Long fromClientId, - @QueryParam("fromAccountId") @ApiParam(value = "fromAccountId") final Long fromAccountId, @QueryParam("fromAccountType") @ApiParam(value = "fromAccountType") final Integer fromAccountType, - @QueryParam("toOfficeId") @ApiParam(value = "toOfficeId") final Long toOfficeId, @QueryParam("toClientId") @ApiParam(value = "toClientId") final Long toClientId, - @QueryParam("toAccountId") @ApiParam(value = "toAccountId") final Long toAccountId, @QueryParam("toAccountType") @ApiParam(value = "toAccountType") final Integer toAccountType, - @QueryParam("transferType") @ApiParam(value = "transferType") final Integer transferType, @Context final UriInfo uriInfo) { + public String template(@QueryParam("fromOfficeId") @ApiParam(value = "fromOfficeId") final Long fromOfficeId, + @QueryParam("fromClientId") @ApiParam(value = "fromClientId") final Long fromClientId, + @QueryParam("fromAccountId") @ApiParam(value = "fromAccountId") final Long fromAccountId, + @QueryParam("fromAccountType") @ApiParam(value = "fromAccountType") final Integer fromAccountType, + @QueryParam("toOfficeId") @ApiParam(value = "toOfficeId") final Long toOfficeId, + @QueryParam("toClientId") @ApiParam(value = "toClientId") final Long toClientId, + @QueryParam("toAccountId") @ApiParam(value = "toAccountId") final Long toAccountId, + @QueryParam("toAccountType") @ApiParam(value = "toAccountType") final Integer toAccountType, + @QueryParam("transferType") @ApiParam(value = "transferType") final Integer transferType, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(StandingInstructionApiConstants.STANDING_INSTRUCTION_RESOURCE_NAME); @@ -117,11 +127,13 @@ public class StandingInstructionApiResource { } @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create new Standing Instruction", httpMethod = "POST", notes = "Ability to create new instruction for transfer of monetary funds from one account to another") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = StandingInstructionApiResourceSwagger.PostStandingInstructionsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = StandingInstructionApiResourceSwagger.PostStandingInstructionsResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = StandingInstructionApiResourceSwagger.PostStandingInstructionsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = StandingInstructionApiResourceSwagger.PostStandingInstructionsResponse.class) }) public String create(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createStandingInstruction().withJson(apiRequestBodyAsJson) @@ -134,13 +146,19 @@ public class StandingInstructionApiResource { @PUT @Path("{standingInstructionId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @ApiOperation(value = "Update Standing Instruction | Delete Standing Instruction", httpMethod = "PUT", notes = "Ability to modify existing instruction for transfer of monetary funds from one account to another.\n" + "\n" + "PUT https://DomainName/api/v1/standinginstructions/1?command=update\n" + "\n\n" + "Ability to modify existing instruction for transfer of monetary funds from one account to another.\n" + "\n" + "PUT https://DomainName/api/v1/standinginstructions/1?command=delete") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = false, paramType = "body", dataType = "body", format = "body", dataTypeClass = StandingInstructionApiResourceSwagger.PutStandingInstructionsStandingInstructionIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = StandingInstructionApiResourceSwagger.PutStandingInstructionsStandingInstructionIdResponse.class)}) - public String update(@PathParam("standingInstructionId") @ApiParam(value = "standingInstructionId") final Long standingInstructionId, @ApiParam(hidden = true) final String apiRequestBodyAsJson, - @QueryParam("command") @ApiParam(value = "command") final String commandParam) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Update Standing Instruction | Delete Standing Instruction", httpMethod = "PUT", notes = "Ability to modify existing instruction for transfer of monetary funds from one account to another.\n" + + "\n" + "PUT https://DomainName/api/v1/standinginstructions/1?command=update\n" + "\n\n" + + "Ability to modify existing instruction for transfer of monetary funds from one account to another.\n" + "\n" + + "PUT https://DomainName/api/v1/standinginstructions/1?command=delete") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = false, paramType = "body", dataType = "body", format = "body", dataTypeClass = StandingInstructionApiResourceSwagger.PutStandingInstructionsStandingInstructionIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = StandingInstructionApiResourceSwagger.PutStandingInstructionsStandingInstructionIdResponse.class) }) + public String update(@PathParam("standingInstructionId") @ApiParam(value = "standingInstructionId") final Long standingInstructionId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson, + @QueryParam("command") @ApiParam(value = "command") final String commandParam) { CommandWrapper commandRequest = null; if (is(commandParam, "update")) { @@ -151,9 +169,7 @@ public class StandingInstructionApiResource { .build(); } - if (commandRequest == null) { - throw new UnrecognizedQueryParamException("command", commandParam); - } + if (commandRequest == null) { throw new UnrecognizedQueryParamException("command", commandParam); } final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); @@ -165,16 +181,23 @@ public class StandingInstructionApiResource { } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "List Standing Instructions", httpMethod = "GET", notes = "Example Requests:\n" + "\n" + "standinginstructions") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = StandingInstructionApiResourceSwagger.GetStandingInstructionsResponse.class)}) - public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, - @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, - @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, - @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, @QueryParam("transferType") @ApiParam(value = "transferType") final Integer transferType, - @QueryParam("clientName") @ApiParam(value = "clientName") final String clientName, @QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, - @QueryParam("fromAccountId") @ApiParam(value = "fromAccountId") final Long fromAccount, @QueryParam("fromAccountType") @ApiParam(value = "fromAccountType") final Integer fromAccountType) { + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = StandingInstructionApiResourceSwagger.GetStandingInstructionsResponse.class) }) + public String retrieveAll(@Context final UriInfo uriInfo, + @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, + @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, + @QueryParam("transferType") @ApiParam(value = "transferType") final Integer transferType, + @QueryParam("clientName") @ApiParam(value = "clientName") final String clientName, + @QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @QueryParam("fromAccountId") @ApiParam(value = "fromAccountId") final Long fromAccount, + @QueryParam("fromAccountType") @ApiParam(value = "fromAccountType") final Integer fromAccountType) { this.context.authenticatedUser().validateHasReadPermission(StandingInstructionApiConstants.STANDING_INSTRUCTION_RESOURCE_NAME); @@ -194,14 +217,20 @@ public class StandingInstructionApiResource { @GET @Path("{standingInstructionId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @ApiOperation(value = "Retrieve Standing Instruction", httpMethod = "GET", notes = "Example Requests :\n" + "\n" + "standinginstructions/1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = StandingInstructionApiResourceSwagger.GetStandingInstructionsStandingInstructionIdResponse.class)}) - public String retrieveOne(@PathParam("standingInstructionId") @ApiParam(value = "standingInstructionId") final Long standingInstructionId, @Context final UriInfo uriInfo, - @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Retrieve Standing Instruction", httpMethod = "GET", notes = "Example Requests :\n" + "\n" + + "standinginstructions/1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = StandingInstructionApiResourceSwagger.GetStandingInstructionsStandingInstructionIdResponse.class) }) + public String retrieveOne( + @PathParam("standingInstructionId") @ApiParam(value = "standingInstructionId") final Long standingInstructionId, + @Context final UriInfo uriInfo, @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, + @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { this.context.authenticatedUser().validateHasReadPermission(StandingInstructionApiConstants.STANDING_INSTRUCTION_RESOURCE_NAME); @@ -220,11 +249,11 @@ public class StandingInstructionApiResource { } if (associationParameters.contains("template")) { final StandingInstructionData templateData = this.standingInstructionReadPlatformService.retrieveTemplate( - standingInstructionData.fromClient().officeId(), standingInstructionData.fromClient().id(), standingInstructionData - .fromAccount().accountId(), standingInstructionData.fromAccountType().getValue(), standingInstructionData - .toClient().officeId(), standingInstructionData.toClient().id(), standingInstructionData.toAccount() - .accountId(), standingInstructionData.toAccountType().getValue(), standingInstructionData.transferType() - .getValue()); + standingInstructionData.fromClient().officeId(), standingInstructionData.fromClient().id(), + standingInstructionData.fromAccount().accountId(), standingInstructionData.fromAccountType().getValue(), + standingInstructionData.toClient().officeId(), standingInstructionData.toClient().id(), + standingInstructionData.toAccount().accountId(), standingInstructionData.toAccountType().getValue(), + standingInstructionData.transferType().getValue()); standingInstructionData = StandingInstructionData.withTemplateData(standingInstructionData, templateData); } } @@ -233,4 +262,4 @@ public class StandingInstructionApiResource { return this.toApiJsonSerializer.serialize(settings, standingInstructionData, StandingInstructionApiConstants.RESPONSE_DATA_PARAMETERS); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiResourceSwagger.java index 11c4a7e51..2f0c806da 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionApiResourceSwagger.java @@ -34,12 +34,12 @@ final class StandingInstructionApiResourceSwagger { @ApiModel(value = "GetStandingInstructionsTemplateResponse") public static final class GetStandingInstructionsTemplateResponse { - private GetStandingInstructionsTemplateResponse() { - } + + private GetStandingInstructionsTemplateResponse() {} final class GetFromOfficeResponseStandingInstructionSwagger { - private GetFromOfficeResponseStandingInstructionSwagger() { - } + + private GetFromOfficeResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Long id; @@ -56,8 +56,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetFromAccountTypeResponseStandingInstructionSwagger { - private GetFromAccountTypeResponseStandingInstructionSwagger() { - } + + private GetFromAccountTypeResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "2") public Long id; @@ -68,8 +68,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetFromOfficeOptionsResponseStandingInstructionSwagger { - private GetFromOfficeOptionsResponseStandingInstructionSwagger() { - } + + private GetFromOfficeOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Long id; @@ -80,8 +80,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetFromClientOptionsResponseStandingInstructionSwagger { - private GetFromClientOptionsResponseStandingInstructionSwagger() { - } + + private GetFromClientOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Long id; @@ -94,8 +94,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetFromAccountTypeOptionsResponseStandingInstructionSwagger { - private GetFromAccountTypeOptionsResponseStandingInstructionSwagger() { - } + + private GetFromAccountTypeOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "2") public Long id; @@ -106,8 +106,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetToOfficeOptionsResponseStandingInstructionSwagger { - private GetToOfficeOptionsResponseStandingInstructionSwagger() { - } + + private GetToOfficeOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -118,8 +118,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetToAccountTypeOptionsResponseStandingInstructionSwagger { - private GetToAccountTypeOptionsResponseStandingInstructionSwagger() { - } + + private GetToAccountTypeOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -130,8 +130,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetTransferTypeOptionsResponseStandingInstructionSwagger { - private GetTransferTypeOptionsResponseStandingInstructionSwagger() { - } + + private GetTransferTypeOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -142,8 +142,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetStatusOptionsResponseStandingInstructionSwagger { - private GetStatusOptionsResponseStandingInstructionSwagger() { - } + + private GetStatusOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -154,8 +154,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetInstructionTypeOptionsResponseStandingInstructionSwagger { - private GetInstructionTypeOptionsResponseStandingInstructionSwagger() { - } + + private GetInstructionTypeOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -166,8 +166,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetPriorityOptionsResponseStandingInstructionSwagger { - private GetPriorityOptionsResponseStandingInstructionSwagger() { - } + + private GetPriorityOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -178,8 +178,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetRecurrenceTypeOptionsResponseStandingInstructionSwagger { - private GetRecurrenceTypeOptionsResponseStandingInstructionSwagger() { - } + + private GetRecurrenceTypeOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -190,8 +190,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetRecurrenceFrequencyOptionsResponseStandingInstructionSwagger { - private GetRecurrenceFrequencyOptionsResponseStandingInstructionSwagger() { - } + + private GetRecurrenceFrequencyOptionsResponseStandingInstructionSwagger() {} @ApiModelProperty(example = "0") public Integer id; @@ -218,8 +218,8 @@ final class StandingInstructionApiResourceSwagger { @ApiModel(value = "PostStandingInstructionsResponse") public static final class PostStandingInstructionsResponse { - private PostStandingInstructionsResponse() { - } + + private PostStandingInstructionsResponse() {} @ApiModelProperty(example = "1") public Long clientId; @@ -229,13 +229,14 @@ final class StandingInstructionApiResourceSwagger { @ApiModel(value = "GetStandingInstructionsResponse") public static final class GetStandingInstructionsResponse { - private GetStandingInstructionsResponse() { - } + + private GetStandingInstructionsResponse() {} final class GetPageItemsStandingInstructionSwagger { + final class GetFromOfficeStandingInstructionSwagger { - private GetFromOfficeStandingInstructionSwagger() { - } + + private GetFromOfficeStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Long id; @@ -244,8 +245,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetFromClientStandingInstructionSwagger { - private GetFromClientStandingInstructionSwagger() { - } + + private GetFromClientStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Long id; @@ -258,8 +259,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetFromAccountTypeStandingInstructionSwagger { - private GetFromAccountTypeStandingInstructionSwagger() { - } + + private GetFromAccountTypeStandingInstructionSwagger() {} @ApiModelProperty(example = "2") public Integer id; @@ -270,8 +271,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetFromAccountStandingInstructionSwagger { - private GetFromAccountStandingInstructionSwagger() { - } + + private GetFromAccountStandingInstructionSwagger() {} @ApiModelProperty(example = "14") public Long id; @@ -284,8 +285,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetToOfficeStandingInstructionSwagger { - private GetToOfficeStandingInstructionSwagger() { - } + + private GetToOfficeStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Long id; @@ -294,8 +295,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetToClientStandingInstructionSwagger { - private GetToClientStandingInstructionSwagger() { - } + + private GetToClientStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Long id; @@ -308,8 +309,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetToAccountTypeStandingInstructionSwagger { - private GetToAccountTypeStandingInstructionSwagger() { - } + + private GetToAccountTypeStandingInstructionSwagger() {} @ApiModelProperty(example = "2") public Integer id; @@ -320,8 +321,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetToAccountStandingInstructionSwagger { - private GetToAccountStandingInstructionSwagger() { - } + + private GetToAccountStandingInstructionSwagger() {} @ApiModelProperty(example = "3") public Long id; @@ -334,8 +335,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetTransferTypeStandingInstructionSwagger { - private GetTransferTypeStandingInstructionSwagger() { - } + + private GetTransferTypeStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -346,8 +347,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetPriorityStandingInstructionSwagger { - private GetPriorityStandingInstructionSwagger() { - } + + private GetPriorityStandingInstructionSwagger() {} @ApiModelProperty(example = "3") public Integer id; @@ -358,8 +359,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetInstructionTypeStandingInstructionSwagger { - private GetInstructionTypeStandingInstructionSwagger() { - } + + private GetInstructionTypeStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -370,8 +371,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetStatusStandingInstructionSwagger { - private GetStatusStandingInstructionSwagger() { - } + + private GetStatusStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -382,8 +383,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetRecurrenceTypeStandingInstructionSwagger { - private GetRecurrenceTypeStandingInstructionSwagger() { - } + + private GetRecurrenceTypeStandingInstructionSwagger() {} @ApiModelProperty(example = "1") public Integer id; @@ -394,8 +395,8 @@ final class StandingInstructionApiResourceSwagger { } final class GetRecurrenceFrequencyStandingInstructionSwagger { - private GetRecurrenceFrequencyStandingInstructionSwagger() { - } + + private GetRecurrenceFrequencyStandingInstructionSwagger() {} @ApiModelProperty(example = "2") public Integer id; @@ -442,8 +443,8 @@ final class StandingInstructionApiResourceSwagger { @ApiModel(value = "PostStandingInstructionsRequest") public static final class PostStandingInstructionsRequest { - private PostStandingInstructionsRequest() { - } + + private PostStandingInstructionsRequest() {} @ApiModelProperty(example = "1") public Long fromOfficeId; @@ -493,8 +494,8 @@ final class StandingInstructionApiResourceSwagger { @ApiModel(value = "GetStandingInstructionsStandingInstructionIdResponse") public static final class GetStandingInstructionsStandingInstructionIdResponse { - private GetStandingInstructionsStandingInstructionIdResponse() { - } + + private GetStandingInstructionsStandingInstructionIdResponse() {} @ApiModelProperty(example = "1") public Long id; @@ -528,20 +529,25 @@ final class StandingInstructionApiResourceSwagger { @ApiModel(value = "PutStandingInstructionsStandingInstructionIdResponse") public static final class PutStandingInstructionsStandingInstructionIdResponse { - private PutStandingInstructionsStandingInstructionIdResponse() { - } - final class PutUpdateStandingInstructionChanges{ + + private PutStandingInstructionsStandingInstructionIdResponse() {} + + final class PutUpdateStandingInstructionChanges { + @ApiModelProperty(example = "2") public Integer recurrenceInterval; } + @ApiModelProperty(example = "20") public Integer resourceId; public PutUpdateStandingInstructionChanges changes; } @ApiModel(value = "PutStandingInstructionsStandingInstructionIdRequest") - public static final class PutStandingInstructionsStandingInstructionIdRequest{ - private PutStandingInstructionsStandingInstructionIdRequest(){} + public static final class PutStandingInstructionsStandingInstructionIdRequest { + + private PutStandingInstructionsStandingInstructionIdRequest() {} + @ApiModelProperty(example = "2") public Integer recurrenceInterval; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionHistoryApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionHistoryApiResource.java old mode 100755 new mode 100644 index 96a1aeac1..40bab77fb --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionHistoryApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionHistoryApiResource.java @@ -51,10 +51,9 @@ import org.springframework.stereotype.Component; @Path("/standinginstructionrunhistory") @Component @Scope("singleton") -@Api(tags = {"Standing Instructions History"}) +@Api(tags = { "Standing Instructions History" }) @SwaggerDefinition(tags = { - @Tag(name = "Standing Instructions History", description = "The list capability of history can support pagination and sorting.") -}) + @Tag(name = "Standing Instructions History", description = "The list capability of history can support pagination and sorting.") }) public class StandingInstructionHistoryApiResource { private final PlatformSecurityContext context; @@ -76,16 +75,27 @@ public class StandingInstructionHistoryApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Standing Instructions Logged History", httpMethod = "GET", notes = "The list capability of history can support pagination and sorting \n\n" +"Example Requests :\n" + "\n" + "standinginstructionrunhistory\n" + "\n" + "standinginstructionrunhistory?orderBy=name&sortOrder=DESC\n" + "\n" + "standinginstructionrunhistory?offset=10&limit=50") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = StandingInstructionHistoryApiResourceSwagger.GetStandingInstructionRunHistoryResponse.class)}) - public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, - @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, - @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, - @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, @QueryParam("transferType") @ApiParam(value = "transferType") final Integer transferType, - @QueryParam("clientName") @ApiParam(value = "clientName") final String clientName, @QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, - @QueryParam("fromAccountId") @ApiParam(value = "fromAccountId") final Long fromAccount, @QueryParam("fromAccountType") @ApiParam(value = "fromAccountType") final Integer fromAccountType, - @QueryParam("locale") @ApiParam(value = "locale") final String locale, @QueryParam("dateFormat") @ApiParam(value = "dateFormat") final String dateFormat, - @QueryParam("fromDate") @ApiParam(value = "fromDate") final DateParam fromDateParam, @QueryParam("toDate") @ApiParam(value = "toDate") final DateParam toDateParam) { + @ApiOperation(value = "Standing Instructions Logged History", httpMethod = "GET", notes = "The list capability of history can support pagination and sorting \n\n" + + "Example Requests :\n" + "\n" + "standinginstructionrunhistory\n" + "\n" + + "standinginstructionrunhistory?orderBy=name&sortOrder=DESC\n" + "\n" + "standinginstructionrunhistory?offset=10&limit=50") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = StandingInstructionHistoryApiResourceSwagger.GetStandingInstructionRunHistoryResponse.class) }) + public String retrieveAll(@Context final UriInfo uriInfo, + @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, + @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, + @QueryParam("transferType") @ApiParam(value = "transferType") final Integer transferType, + @QueryParam("clientName") @ApiParam(value = "clientName") final String clientName, + @QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @QueryParam("fromAccountId") @ApiParam(value = "fromAccountId") final Long fromAccount, + @QueryParam("fromAccountType") @ApiParam(value = "fromAccountType") final Integer fromAccountType, + @QueryParam("locale") @ApiParam(value = "locale") final String locale, + @QueryParam("dateFormat") @ApiParam(value = "dateFormat") final String dateFormat, + @QueryParam("fromDate") @ApiParam(value = "fromDate") final DateParam fromDateParam, + @QueryParam("toDate") @ApiParam(value = "toDate") final DateParam toDateParam) { this.context.authenticatedUser().validateHasReadPermission(StandingInstructionApiConstants.STANDING_INSTRUCTION_RESOURCE_NAME); @@ -109,4 +119,4 @@ public class StandingInstructionHistoryApiResource { final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, history); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionHistoryApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionHistoryApiResourceSwagger.java index ad4843c03..c174dde84 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionHistoryApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/api/StandingInstructionHistoryApiResourceSwagger.java @@ -27,19 +27,19 @@ import java.util.Set; * Created by Chirag Gupta on 12/01/17. */ final class StandingInstructionHistoryApiResourceSwagger { - private StandingInstructionHistoryApiResourceSwagger() { - } + + private StandingInstructionHistoryApiResourceSwagger() {} @ApiModel(value = "GetStandingInstructionRunHistoryResponse") public final static class GetStandingInstructionRunHistoryResponse { - private GetStandingInstructionRunHistoryResponse() { - } + + private GetStandingInstructionRunHistoryResponse() {} final class GetStandingInstructionHistoryPageItemsResponse { final class GetStandingInstructionHistoryPageItemsFromClient { - private GetStandingInstructionHistoryPageItemsFromClient() { - } + + private GetStandingInstructionHistoryPageItemsFromClient() {} @ApiModelProperty(example = "1") public Long id; @@ -52,8 +52,8 @@ final class StandingInstructionHistoryApiResourceSwagger { } final class GetStandingInstructionHistoryFromAccount { - private GetStandingInstructionHistoryFromAccount() { - } + + private GetStandingInstructionHistoryFromAccount() {} @ApiModelProperty(example = "2") public Long id; @@ -66,8 +66,8 @@ final class StandingInstructionHistoryApiResourceSwagger { } final class GetStandingInstructionHistoryToAccount { - private GetStandingInstructionHistoryToAccount() { - } + + private GetStandingInstructionHistoryToAccount() {} @ApiModelProperty(example = "1") public Long id; @@ -80,8 +80,8 @@ final class StandingInstructionHistoryApiResourceSwagger { } final class GetStandingInstructionHistoryToClient { - private GetStandingInstructionHistoryToClient() { - } + + private GetStandingInstructionHistoryToClient() {} @ApiModelProperty(example = "1") public Long id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransferDTO.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransferDTO.java old mode 100755 new mode 100644 index 7f4226338..a627e27ca --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransferDTO.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransferDTO.java @@ -60,9 +60,9 @@ public class AccountTransferDTO { final PortfolioAccountType fromAccountType, final PortfolioAccountType toAccountType, final Long fromAccountId, final Long toAccountId, final String description, final Locale locale, final DateTimeFormatter fmt, final PaymentDetail paymentDetail, final Integer fromTransferType, final Integer toTransferType, final Long chargeId, - Integer loanInstallmentNumber, Integer transferType, final AccountTransferDetails accountTransferDetails, - final String noteText, final String txnExternalId, final Loan loan, SavingsAccount toSavingsAccount, - final SavingsAccount fromSavingsAccount, final Boolean isRegularTransaction, Boolean isExceptionForBalanceCheck) { + Integer loanInstallmentNumber, Integer transferType, final AccountTransferDetails accountTransferDetails, final String noteText, + final String txnExternalId, final Loan loan, SavingsAccount toSavingsAccount, final SavingsAccount fromSavingsAccount, + final Boolean isRegularTransaction, Boolean isExceptionForBalanceCheck) { this.transactionDate = transactionDate; this.transactionAmount = transactionAmount; this.fromAccountType = fromAccountType; @@ -93,8 +93,8 @@ public class AccountTransferDTO { public AccountTransferDTO(final LocalDate transactionDate, final BigDecimal transactionAmount, final PortfolioAccountType fromAccountType, final PortfolioAccountType toAccountType, final Long fromAccountId, final Long toAccountId, final String description, final Locale locale, final DateTimeFormatter fmt, - final Integer fromTransferType, final Integer toTransferType, final String txnExternalId, - final Loan fromLoan, final Loan toLoan) { + final Integer fromTransferType, final Integer toTransferType, final String txnExternalId, final Loan fromLoan, + final Loan toLoan) { this.transactionDate = transactionDate; this.transactionAmount = transactionAmount; this.fromAccountType = fromAccountType; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransferData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransferData.java index 15af30461..06955e35d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransferData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransferData.java @@ -97,8 +97,8 @@ public class AccountTransferData implements Serializable { final EnumOptionData fromAccountType = null; final EnumOptionData toAccountType = null; - return new AccountTransferData(id, reversed, null, null, fromAccountType, null, currency, transferAmount, transferDate, - description, null, null, toAccountType, null, null, null, null, null, null, null, null, null); + return new AccountTransferData(id, reversed, null, null, fromAccountType, null, currency, transferAmount, transferDate, description, + null, null, toAccountType, null, null, null, null, null, null, null, null, null); } private AccountTransferData(final Long id, final Boolean reversed, final OfficeData fromOffice, final ClientData fromClient, @@ -134,4 +134,4 @@ public class AccountTransferData implements Serializable { this.toAccountTypeOptions = toAccountTypeOptions; this.toAccountOptions = toAccountOptions; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransfersDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransfersDataValidator.java index 93f8f4111..11076bcb4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransfersDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransfersDataValidator.java @@ -46,15 +46,13 @@ public class AccountTransfersDataValidator { private final FromJsonHelper fromApiJsonHelper; private final AccountTransfersDetailDataValidator accountTransfersDetailDataValidator; - private static final Set REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - AccountDetailConstants.localeParamName, AccountDetailConstants.dateFormatParamName, - AccountDetailConstants.fromOfficeIdParamName, AccountDetailConstants.fromClientIdParamName, - AccountDetailConstants.fromAccountTypeParamName, AccountDetailConstants.fromAccountIdParamName, - AccountDetailConstants.toOfficeIdParamName, AccountDetailConstants.toClientIdParamName, - AccountDetailConstants.toAccountTypeParamName, AccountDetailConstants.toAccountIdParamName, - AccountTransfersApiConstants.transferDateParamName, AccountTransfersApiConstants.transferAmountParamName, - AccountTransfersApiConstants.transferDescriptionParamName)); - + private static final Set REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(AccountDetailConstants.localeParamName, + AccountDetailConstants.dateFormatParamName, AccountDetailConstants.fromOfficeIdParamName, + AccountDetailConstants.fromClientIdParamName, AccountDetailConstants.fromAccountTypeParamName, + AccountDetailConstants.fromAccountIdParamName, AccountDetailConstants.toOfficeIdParamName, + AccountDetailConstants.toClientIdParamName, AccountDetailConstants.toAccountTypeParamName, + AccountDetailConstants.toAccountIdParamName, AccountTransfersApiConstants.transferDateParamName, + AccountTransfersApiConstants.transferAmountParamName, AccountTransfersApiConstants.transferDescriptionParamName)); @Autowired public AccountTransfersDataValidator(final FromJsonHelper fromApiJsonHelper, @@ -80,21 +78,19 @@ public class AccountTransfersDataValidator { this.accountTransfersDetailDataValidator.validate(command, baseDataValidator); - final LocalDate transactionDate = this.fromApiJsonHelper - .extractLocalDateNamed(AccountTransfersApiConstants.transferDateParamName, element); - baseDataValidator.reset().parameter(AccountTransfersApiConstants.transferDateParamName).value - (transactionDate).notNull(); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(AccountTransfersApiConstants.transferDateParamName, + element); + baseDataValidator.reset().parameter(AccountTransfersApiConstants.transferDateParamName).value(transactionDate).notNull(); - final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed - (AccountTransfersApiConstants.transferAmountParamName, element); - baseDataValidator.reset().parameter(AccountTransfersApiConstants.transferAmountParamName).value - (transactionAmount).notNull().positiveAmount(); + final BigDecimal transactionAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AccountTransfersApiConstants.transferAmountParamName, element); + baseDataValidator.reset().parameter(AccountTransfersApiConstants.transferAmountParamName).value(transactionAmount).notNull() + .positiveAmount(); - final String transactionDescription = this.fromApiJsonHelper.extractStringNamed(AccountTransfersApiConstants - .transferDescriptionParamName, element); - baseDataValidator.reset().parameter(AccountTransfersApiConstants.transferDescriptionParamName).value - (transactionDescription).notBlank() - .notExceedingLengthOf(200); + final String transactionDescription = this.fromApiJsonHelper + .extractStringNamed(AccountTransfersApiConstants.transferDescriptionParamName, element); + baseDataValidator.reset().parameter(AccountTransfersApiConstants.transferDescriptionParamName).value(transactionDescription) + .notBlank().notExceedingLengthOf(200); throwExceptionIfValidationWarningsExist(dataValidationErrors); } @@ -102,4 +98,4 @@ public class AccountTransfersDataValidator { private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransfersDetailDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransfersDetailDataValidator.java old mode 100755 new mode 100644 index e07d88474..8c7f876ba --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransfersDetailDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/AccountTransfersDetailDataValidator.java @@ -71,9 +71,9 @@ public class AccountTransfersDetailDataValidator { baseDataValidator.reset().parameter(toAccountIdParamName).value(toAccountId).notNull().integerGreaterThanZero(); final Integer toAccountType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(toAccountTypeParamName, element); - baseDataValidator.reset().parameter(toAccountTypeParamName).value(toAccountType).notNull() - .isOneOfTheseValues(Integer.valueOf(1), Integer.valueOf(2)); + baseDataValidator.reset().parameter(toAccountTypeParamName).value(toAccountType).notNull().isOneOfTheseValues(Integer.valueOf(1), + Integer.valueOf(2)); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionDTO.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionDTO.java old mode 100755 new mode 100644 index 15c5ad631..6e05df16c --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionDTO.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionDTO.java @@ -33,7 +33,8 @@ public class StandingInstructionDTO { final Date endDateRange; public StandingInstructionDTO(final SearchParameters searchParameters, final Integer transferType, final String clientName, - final Long clientId, final Long fromAccount, final Integer fromAccountType, final Date startDateRange, final Date endDateRange) { + final Long clientId, final Long fromAccount, final Integer fromAccountType, final Date startDateRange, + final Date endDateRange) { this.searchParameters = searchParameters; this.transferType = transferType; this.clientName = clientName; @@ -76,7 +77,6 @@ public class StandingInstructionDTO { return this.startDateRange; } - public Date endDateRange() { return this.endDateRange; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionData.java old mode 100755 new mode 100644 index 5ed6cb705..778432cbb --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionData.java @@ -261,8 +261,8 @@ public class StandingInstructionData { instructionData.toOffice, instructionData.toClient, instructionData.toAccountType, instructionData.toAccount, instructionData.transferType, instructionData.priority, instructionData.instructionType, instructionData.status, instructionData.amount, instructionData.validFrom, instructionData.validTill, instructionData.recurrenceType, - instructionData.recurrenceFrequency, instructionData.recurrenceInterval, instructionData.recurrenceOnMonthDay, - transactions, instructionData.fromOfficeOptions, instructionData.fromClientOptions, instructionData.fromAccountTypeOptions, + instructionData.recurrenceFrequency, instructionData.recurrenceInterval, instructionData.recurrenceOnMonthDay, transactions, + instructionData.fromOfficeOptions, instructionData.fromClientOptions, instructionData.fromAccountTypeOptions, instructionData.fromAccountOptions, instructionData.toOfficeOptions, instructionData.toClientOptions, instructionData.toAccountTypeOptions, instructionData.toAccountOptions, instructionData.transferTypeOptions, instructionData.statusOptions, instructionData.instructionTypeOptions, instructionData.priorityOptions, @@ -380,9 +380,8 @@ public class StandingInstructionData { return this.toClient; } - public Long getId() { return this.id; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionDataValidator.java old mode 100755 new mode 100644 index 7e5a41eba..44634aae8 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/data/StandingInstructionDataValidator.java @@ -53,36 +53,30 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component - public class StandingInstructionDataValidator { +public class StandingInstructionDataValidator { private final FromJsonHelper fromApiJsonHelper; private final AccountTransfersDetailDataValidator accountTransfersDetailDataValidator; - private static final Set CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - AccountDetailConstants.localeParamName, AccountDetailConstants.dateFormatParamName, - AccountDetailConstants.fromOfficeIdParamName, AccountDetailConstants.fromClientIdParamName, - AccountDetailConstants.fromAccountTypeParamName, AccountDetailConstants.fromAccountIdParamName, - AccountDetailConstants.toOfficeIdParamName, AccountDetailConstants.toClientIdParamName, - AccountDetailConstants.toAccountTypeParamName, AccountDetailConstants.toAccountIdParamName, - AccountDetailConstants.transferTypeParamName, StandingInstructionApiConstants.priorityParamName, - StandingInstructionApiConstants.instructionTypeParamName, StandingInstructionApiConstants.statusParamName, - StandingInstructionApiConstants.amountParamName, StandingInstructionApiConstants.validFromParamName, - StandingInstructionApiConstants.validTillParamName, StandingInstructionApiConstants.recurrenceTypeParamName, - StandingInstructionApiConstants.recurrenceFrequencyParamName, - StandingInstructionApiConstants.recurrenceIntervalParamName, - StandingInstructionApiConstants.recurrenceOnMonthDayParamName, - StandingInstructionApiConstants.nameParamName, StandingInstructionApiConstants.monthDayFormatParamName)); - - private static final Set UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - AccountDetailConstants.localeParamName, AccountDetailConstants.dateFormatParamName, + private static final Set CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(AccountDetailConstants.localeParamName, + AccountDetailConstants.dateFormatParamName, AccountDetailConstants.fromOfficeIdParamName, + AccountDetailConstants.fromClientIdParamName, AccountDetailConstants.fromAccountTypeParamName, + AccountDetailConstants.fromAccountIdParamName, AccountDetailConstants.toOfficeIdParamName, + AccountDetailConstants.toClientIdParamName, AccountDetailConstants.toAccountTypeParamName, + AccountDetailConstants.toAccountIdParamName, AccountDetailConstants.transferTypeParamName, StandingInstructionApiConstants.priorityParamName, StandingInstructionApiConstants.instructionTypeParamName, StandingInstructionApiConstants.statusParamName, StandingInstructionApiConstants.amountParamName, StandingInstructionApiConstants.validFromParamName, StandingInstructionApiConstants.validTillParamName, - StandingInstructionApiConstants.recurrenceTypeParamName, - StandingInstructionApiConstants.recurrenceFrequencyParamName, - StandingInstructionApiConstants.recurrenceIntervalParamName, - StandingInstructionApiConstants.recurrenceOnMonthDayParamName, - StandingInstructionApiConstants.monthDayFormatParamName)); + StandingInstructionApiConstants.recurrenceTypeParamName, StandingInstructionApiConstants.recurrenceFrequencyParamName, + StandingInstructionApiConstants.recurrenceIntervalParamName, StandingInstructionApiConstants.recurrenceOnMonthDayParamName, + StandingInstructionApiConstants.nameParamName, StandingInstructionApiConstants.monthDayFormatParamName)); + private static final Set UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(AccountDetailConstants.localeParamName, + AccountDetailConstants.dateFormatParamName, StandingInstructionApiConstants.priorityParamName, + StandingInstructionApiConstants.instructionTypeParamName, StandingInstructionApiConstants.statusParamName, + StandingInstructionApiConstants.amountParamName, StandingInstructionApiConstants.validFromParamName, + StandingInstructionApiConstants.validTillParamName, StandingInstructionApiConstants.recurrenceTypeParamName, + StandingInstructionApiConstants.recurrenceFrequencyParamName, StandingInstructionApiConstants.recurrenceIntervalParamName, + StandingInstructionApiConstants.recurrenceOnMonthDayParamName, StandingInstructionApiConstants.monthDayFormatParamName)); @Autowired public StandingInstructionDataValidator(final FromJsonHelper fromApiJsonHelper, @@ -106,73 +100,80 @@ import org.springframework.stereotype.Component; final JsonElement element = command.parsedJson(); - final Integer status = this.fromApiJsonHelper - .extractIntegerNamed(StandingInstructionApiConstants.statusParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.statusParamName).value(status).notNull() - .inMinMaxRange(1, 2); + final Integer status = this.fromApiJsonHelper.extractIntegerNamed(StandingInstructionApiConstants.statusParamName, element, + Locale.getDefault()); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.statusParamName).value(status).notNull().inMinMaxRange(1, 2); - final LocalDate validFrom = this.fromApiJsonHelper - .extractLocalDateNamed(StandingInstructionApiConstants.validFromParamName, element); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.validFromParamName).value(validFrom) - .notNull(); + final LocalDate validFrom = this.fromApiJsonHelper.extractLocalDateNamed(StandingInstructionApiConstants.validFromParamName, + element); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.validFromParamName).value(validFrom).notNull(); - final LocalDate validTill = this.fromApiJsonHelper - .extractLocalDateNamed(StandingInstructionApiConstants.validTillParamName, element); + final LocalDate validTill = this.fromApiJsonHelper.extractLocalDateNamed(StandingInstructionApiConstants.validTillParamName, + element); baseDataValidator.reset().parameter(StandingInstructionApiConstants.validTillParamName).value(validTill) .validateDateAfter(validFrom); - final BigDecimal transferAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(StandingInstructionApiConstants.amountParamName, element); + final BigDecimal transferAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(StandingInstructionApiConstants.amountParamName, element); baseDataValidator.reset().parameter(StandingInstructionApiConstants.amountParamName).value(transferAmount).positiveAmount(); final Integer transferType = this.fromApiJsonHelper.extractIntegerNamed(transferTypeParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(transferTypeParamName).value(transferType).notNull().inMinMaxRange(1, 3); - final Integer priority = this.fromApiJsonHelper.extractIntegerNamed(StandingInstructionApiConstants.priorityParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.priorityParamName).value(priority).notNull().inMinMaxRange(1, 4); - - final Integer standingInstructionType = this.fromApiJsonHelper.extractIntegerNamed(StandingInstructionApiConstants.instructionTypeParamName, element, + final Integer priority = this.fromApiJsonHelper.extractIntegerNamed(StandingInstructionApiConstants.priorityParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.instructionTypeParamName).value(standingInstructionType).notNull().inMinMaxRange(1, 2); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.priorityParamName).value(priority).notNull().inMinMaxRange(1, + 4); - final Integer recurrenceType = this.fromApiJsonHelper.extractIntegerNamed(StandingInstructionApiConstants.recurrenceTypeParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceTypeParamName).value(recurrenceType).notNull().inMinMaxRange(1, 2); + final Integer standingInstructionType = this.fromApiJsonHelper + .extractIntegerNamed(StandingInstructionApiConstants.instructionTypeParamName, element, Locale.getDefault()); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.instructionTypeParamName).value(standingInstructionType) + .notNull().inMinMaxRange(1, 2); + + final Integer recurrenceType = this.fromApiJsonHelper.extractIntegerNamed(StandingInstructionApiConstants.recurrenceTypeParamName, + element, Locale.getDefault()); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceTypeParamName).value(recurrenceType).notNull() + .inMinMaxRange(1, 2); boolean isPeriodic = false; if (recurrenceType != null) { isPeriodic = AccountTransferRecurrenceType.fromInt(recurrenceType).isPeriodicRecurrence(); } - final Integer recurrenceFrequency = this.fromApiJsonHelper.extractIntegerNamed( - StandingInstructionApiConstants.recurrenceFrequencyParamName, element, - Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceFrequencyParamName) - .value(recurrenceFrequency).inMinMaxRange(0, 3); + final Integer recurrenceFrequency = this.fromApiJsonHelper + .extractIntegerNamed(StandingInstructionApiConstants.recurrenceFrequencyParamName, element, Locale.getDefault()); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceFrequencyParamName).value(recurrenceFrequency) + .inMinMaxRange(0, 3); if (recurrenceFrequency != null) { PeriodFrequencyType frequencyType = PeriodFrequencyType.fromInt(recurrenceFrequency); if (frequencyType.isMonthly() || frequencyType.isYearly()) { final MonthDay monthDay = this.fromApiJsonHelper .extractMonthDayNamed(StandingInstructionApiConstants.recurrenceOnMonthDayParamName, element); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceOnMonthDayParamName) - .value(monthDay).notNull(); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceOnMonthDayParamName).value(monthDay) + .notNull(); } } - final Integer recurrenceInterval = this.fromApiJsonHelper.extractIntegerNamed( - StandingInstructionApiConstants.recurrenceIntervalParamName, element, - Locale.getDefault()); + final Integer recurrenceInterval = this.fromApiJsonHelper + .extractIntegerNamed(StandingInstructionApiConstants.recurrenceIntervalParamName, element, Locale.getDefault()); if (isPeriodic) { - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceIntervalParamName).value(recurrenceInterval).notNull(); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceFrequencyParamName).value(recurrenceFrequency).notNull(); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceIntervalParamName).value(recurrenceInterval) + .notNull(); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceFrequencyParamName).value(recurrenceFrequency) + .notNull(); } - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceIntervalParamName).value(recurrenceInterval).integerGreaterThanZero(); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceIntervalParamName).value(recurrenceInterval) + .integerGreaterThanZero(); final String name = this.fromApiJsonHelper.extractStringNamed(StandingInstructionApiConstants.nameParamName, element); baseDataValidator.reset().parameter(StandingInstructionApiConstants.nameParamName).value(name).notNull(); final Integer toAccountType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(toAccountTypeParamName, element); if (toAccountType != null && PortfolioAccountType.fromInt(toAccountType).isSavingsAccount()) { - baseDataValidator.reset().parameter(StandingInstructionApiConstants.instructionTypeParamName).value(standingInstructionType).notNull().inMinMaxRange(1, 1); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceTypeParamName).value(recurrenceType).notNull().inMinMaxRange(1, 1); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.instructionTypeParamName).value(standingInstructionType) + .notNull().inMinMaxRange(1, 1); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceTypeParamName).value(recurrenceType).notNull() + .inMinMaxRange(1, 1); } if (standingInstructionType != null && StandingInstructionType.fromInt(standingInstructionType).isFixedAmoutTransfer()) { @@ -214,73 +215,67 @@ import org.springframework.stereotype.Component; final JsonElement element = command.parsedJson(); if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.validFromParamName, element)) { - final LocalDate validFrom = this.fromApiJsonHelper - .extractLocalDateNamed(StandingInstructionApiConstants.validFromParamName, element); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.validFromParamName).value(validFrom) - .notNull(); + final LocalDate validFrom = this.fromApiJsonHelper.extractLocalDateNamed(StandingInstructionApiConstants.validFromParamName, + element); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.validFromParamName).value(validFrom).notNull(); } if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.validTillParamName, element)) { - final LocalDate validTill = this.fromApiJsonHelper - .extractLocalDateNamed(StandingInstructionApiConstants.validTillParamName, element); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.validTillParamName).value(validTill) - .notNull(); + final LocalDate validTill = this.fromApiJsonHelper.extractLocalDateNamed(StandingInstructionApiConstants.validTillParamName, + element); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.validTillParamName).value(validTill).notNull(); } if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.amountParamName, element)) { final BigDecimal transferAmount = this.fromApiJsonHelper .extractBigDecimalWithLocaleNamed(StandingInstructionApiConstants.amountParamName, element); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.amountParamName).value(transferAmount) - .positiveAmount(); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.amountParamName).value(transferAmount).positiveAmount(); } if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.statusParamName, element)) { - final Integer status = this.fromApiJsonHelper - .extractIntegerNamed(StandingInstructionApiConstants.statusParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.statusParamName).value(status).notNull() - .inMinMaxRange(1, 2); + final Integer status = this.fromApiJsonHelper.extractIntegerNamed(StandingInstructionApiConstants.statusParamName, element, + Locale.getDefault()); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.statusParamName).value(status).notNull().inMinMaxRange(1, + 2); } if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.priorityParamName, element)) { - final Integer priority = this.fromApiJsonHelper.extractIntegerNamed( - StandingInstructionApiConstants.priorityParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.priorityParamName).value(priority) - .notNull().inMinMaxRange(1, 4); + final Integer priority = this.fromApiJsonHelper.extractIntegerNamed(StandingInstructionApiConstants.priorityParamName, element, + Locale.getDefault()); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.priorityParamName).value(priority).notNull() + .inMinMaxRange(1, 4); } if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.instructionTypeParamName, element)) { - final Integer standingInstructionType = this.fromApiJsonHelper.extractIntegerNamed( - StandingInstructionApiConstants.instructionTypeParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.instructionTypeParamName) - .value(standingInstructionType).notNull().inMinMaxRange(1, 2); + final Integer standingInstructionType = this.fromApiJsonHelper + .extractIntegerNamed(StandingInstructionApiConstants.instructionTypeParamName, element, Locale.getDefault()); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.instructionTypeParamName).value(standingInstructionType) + .notNull().inMinMaxRange(1, 2); } if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.recurrenceTypeParamName, element)) { - final Integer recurrenceType = this.fromApiJsonHelper.extractIntegerNamed( - StandingInstructionApiConstants.recurrenceTypeParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceTypeParamName) - .value(recurrenceType).notNull().inMinMaxRange(1, 2); + final Integer recurrenceType = this.fromApiJsonHelper + .extractIntegerNamed(StandingInstructionApiConstants.recurrenceTypeParamName, element, Locale.getDefault()); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceTypeParamName).value(recurrenceType).notNull() + .inMinMaxRange(1, 2); } - if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.recurrenceFrequencyParamName, - element)) { - final Integer recurrenceFrequency = this.fromApiJsonHelper.extractIntegerNamed( - StandingInstructionApiConstants.recurrenceFrequencyParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceFrequencyParamName) - .value(recurrenceFrequency).inMinMaxRange(0, 3); + if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.recurrenceFrequencyParamName, element)) { + final Integer recurrenceFrequency = this.fromApiJsonHelper + .extractIntegerNamed(StandingInstructionApiConstants.recurrenceFrequencyParamName, element, Locale.getDefault()); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceFrequencyParamName).value(recurrenceFrequency) + .inMinMaxRange(0, 3); } - if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.recurrenceIntervalParamName, - element)) { - final Integer recurrenceInterval = this.fromApiJsonHelper.extractIntegerNamed( - StandingInstructionApiConstants.recurrenceIntervalParamName, element, Locale.getDefault()); - baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceIntervalParamName) - .value(recurrenceInterval).integerGreaterThanZero(); + if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.recurrenceIntervalParamName, element)) { + final Integer recurrenceInterval = this.fromApiJsonHelper + .extractIntegerNamed(StandingInstructionApiConstants.recurrenceIntervalParamName, element, Locale.getDefault()); + baseDataValidator.reset().parameter(StandingInstructionApiConstants.recurrenceIntervalParamName).value(recurrenceInterval) + .integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(StandingInstructionApiConstants.nameParamName, element)) { - final String name = this.fromApiJsonHelper.extractStringNamed(StandingInstructionApiConstants.nameParamName, - element); + final String name = this.fromApiJsonHelper.extractStringNamed(StandingInstructionApiConstants.nameParamName, element); baseDataValidator.reset().parameter(StandingInstructionApiConstants.nameParamName).value(name).notNull(); } @@ -290,4 +285,4 @@ import org.springframework.stereotype.Component; private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountAssociationType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountAssociationType.java old mode 100755 new mode 100644 index a386db45a..09ba317e1 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountAssociationType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountAssociationType.java @@ -70,4 +70,4 @@ public enum AccountAssociationType { return this.value.equals(AccountAssociationType.GUARANTOR_ACCOUNT_ASSOCIATION.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountAssociationsRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountAssociationsRepository.java old mode 100755 new mode 100644 index 00266c476..8c87a7e0c --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountAssociationsRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountAssociationsRepository.java @@ -23,12 +23,13 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface AccountAssociationsRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface AccountAssociationsRepository + extends JpaRepository, JpaSpecificationExecutor { @Query("select aa from AccountAssociations aa where aa.loanAccount.id= :loanId and aa.associationType = :associationType") AccountAssociations findByLoanIdAndType(@Param("loanId") Long loanId, @Param("associationType") Integer accountAssociationType); @Query("select aa from AccountAssociations aa where aa.savingsAccount.id= :savingsId and aa.associationType = :associationType") - AccountAssociations findBySavingsIdAndType(@Param("savingsId") Long savingsId, @Param("associationType") Integer accountAssociationType); + AccountAssociations findBySavingsIdAndType(@Param("savingsId") Long savingsId, + @Param("associationType") Integer accountAssociationType); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferAssembler.java index 72cac807d..1f936b40a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferAssembler.java @@ -159,4 +159,4 @@ public class AccountTransferAssembler { return accountTransferDetails; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetailAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetailAssembler.java old mode 100755 new mode 100644 index 4c6f50a4d..0ba93136e --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetailAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetailAssembler.java @@ -51,9 +51,9 @@ public class AccountTransferDetailAssembler { private final LoanAssembler loanAccountAssembler; @Autowired - public AccountTransferDetailAssembler(final ClientRepositoryWrapper clientRepository, final OfficeRepositoryWrapper officeRepositoryWrapper, - final SavingsAccountAssembler savingsAccountAssembler, final FromJsonHelper fromApiJsonHelper, - final LoanAssembler loanAccountAssembler) { + public AccountTransferDetailAssembler(final ClientRepositoryWrapper clientRepository, + final OfficeRepositoryWrapper officeRepositoryWrapper, final SavingsAccountAssembler savingsAccountAssembler, + final FromJsonHelper fromApiJsonHelper, final LoanAssembler loanAccountAssembler) { this.clientRepository = clientRepository; this.officeRepositoryWrapper = officeRepositoryWrapper; this.savingsAccountAssembler = savingsAccountAssembler; @@ -209,4 +209,4 @@ public class AccountTransferDetailAssembler { return AccountTransferDetails.loanToLoanTransfer(fromOffice, fromClient, fromLoanAccount, toOffice, toClient, toLoanAccount, transferType); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetailRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetailRepository.java old mode 100755 new mode 100644 index f4d881f93..b5abbb609 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetailRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetailRepository.java @@ -21,5 +21,5 @@ package org.apache.fineract.portfolio.account.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface AccountTransferDetailRepository extends JpaRepository, - JpaSpecificationExecutor {} \ No newline at end of file +public interface AccountTransferDetailRepository + extends JpaRepository, JpaSpecificationExecutor {} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetails.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetails.java old mode 100755 new mode 100644 index 02b43ca7c..ca9b91c1a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetails.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferDetails.java @@ -74,7 +74,7 @@ public class AccountTransferDetails extends AbstractPersistableCustom { @Column(name = "transfer_type") private Integer transferType; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "accountTransferDetails", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "accountTransferDetails", orphanRemoval = true, fetch = FetchType.EAGER) private List accountTransferTransactions = new ArrayList<>(); @OneToOne(mappedBy = "accountTransferDetails", cascade = CascadeType.ALL, optional = true, orphanRemoval = true, fetch = FetchType.EAGER) @@ -95,9 +95,8 @@ public class AccountTransferDetails extends AbstractPersistableCustom { transferType, null); } - public static AccountTransferDetails loanTosavingsTransfer(final Office fromOffice, final Client fromClient, - final Loan fromLoanAccount, final Office toOffice, final Client toClient, final SavingsAccount toSavingsAccount, - Integer transferType) { + public static AccountTransferDetails loanTosavingsTransfer(final Office fromOffice, final Client fromClient, final Loan fromLoanAccount, + final Office toOffice, final Client toClient, final SavingsAccount toSavingsAccount, Integer transferType) { return new AccountTransferDetails(fromOffice, fromClient, null, fromLoanAccount, toOffice, toClient, toSavingsAccount, null, transferType, null); } @@ -154,9 +153,9 @@ public class AccountTransferDetails extends AbstractPersistableCustom { return AccountTransferType.fromInt(this.transferType); } - public static AccountTransferDetails loanToLoanTransfer(Office fromOffice, Client fromClient, Loan fromLoanAccount, Office toOffice, Client toClient, - Loan toLoanAccount, Integer transferType) { + public static AccountTransferDetails loanToLoanTransfer(Office fromOffice, Client fromClient, Loan fromLoanAccount, Office toOffice, + Client toClient, Loan toLoanAccount, Integer transferType) { return new AccountTransferDetails(fromOffice, fromClient, null, fromLoanAccount, toOffice, toClient, null, toLoanAccount, transferType, null); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferRecurrenceType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferRecurrenceType.java old mode 100755 new mode 100644 index 5ac0c18b0..ad3154429 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferRecurrenceType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferRecurrenceType.java @@ -69,4 +69,4 @@ public enum AccountTransferRecurrenceType { return this.value.equals(AccountTransferRecurrenceType.AS_PER_DUES.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferRepository.java index f8f6c61dc..7e395b203 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferRepository.java @@ -25,8 +25,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface AccountTransferRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface AccountTransferRepository + extends JpaRepository, JpaSpecificationExecutor { @Query("select att from AccountTransferTransaction att where att.accountTransferDetails.fromLoanAccount.id= :accountNumber and att.reversed=false") List findByFromLoanId(@Param("accountNumber") Long accountNumber); @@ -39,4 +39,4 @@ public interface AccountTransferRepository extends JpaRepository findByFromLoanTransactions(@Param("loanTransactions") Collection loanTransactions); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferStandingInstruction.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferStandingInstruction.java old mode 100755 new mode 100644 index 5be569b91..cca712da9 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferStandingInstruction.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferStandingInstruction.java @@ -55,7 +55,8 @@ import org.joda.time.LocalDate; import org.joda.time.MonthDay; @Entity -@Table(name = "m_account_transfer_standing_instructions", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "name") }) +@Table(name = "m_account_transfer_standing_instructions", uniqueConstraints = { + @UniqueConstraint(columnNames = { "name" }, name = "name") }) public class AccountTransferStandingInstruction extends AbstractPersistableCustom { @ManyToOne @@ -109,9 +110,9 @@ public class AccountTransferStandingInstruction extends AbstractPersistableCusto } public static AccountTransferStandingInstruction create(final AccountTransferDetails accountTransferDetails, final String name, - final Integer priority, final Integer instructionType, final Integer status, final BigDecimal amount, - final LocalDate validFrom, final LocalDate validTill, final Integer recurrenceType, final Integer recurrenceFrequency, - final Integer recurrenceInterval, final MonthDay recurrenceOnMonthDay) { + final Integer priority, final Integer instructionType, final Integer status, final BigDecimal amount, final LocalDate validFrom, + final LocalDate validTill, final Integer recurrenceType, final Integer recurrenceFrequency, final Integer recurrenceInterval, + final MonthDay recurrenceOnMonthDay) { Integer recurrenceOnDay = null; Integer recurrenceOnMonth = null; if (recurrenceOnMonthDay != null) { @@ -123,9 +124,9 @@ public class AccountTransferStandingInstruction extends AbstractPersistableCusto } private AccountTransferStandingInstruction(final AccountTransferDetails accountTransferDetails, final String name, - final Integer priority, final Integer instructionType, final Integer status, final BigDecimal amount, - final LocalDate validFrom, final LocalDate validTill, final Integer recurrenceType, final Integer recurrenceFrequency, - final Integer recurrenceInterval, final Integer recurrenceOnDay, final Integer recurrenceOnMonth) { + final Integer priority, final Integer instructionType, final Integer status, final BigDecimal amount, final LocalDate validFrom, + final LocalDate validTill, final Integer recurrenceType, final Integer recurrenceFrequency, final Integer recurrenceInterval, + final Integer recurrenceOnDay, final Integer recurrenceOnMonth) { this.accountTransferDetails = accountTransferDetails; this.name = name; this.priority = priority; @@ -286,15 +287,16 @@ public class AccountTransferStandingInstruction extends AbstractPersistableCusto this.latsRunDate = latsRunDate; } - public void updateStatus(Integer status){ + public void updateStatus(Integer status) { this.status = status; } /** - * delete the standing instruction by setting the status to 3 and appending "_deleted_" and the id to the name + * delete the standing instruction by setting the status to 3 and appending + * "_deleted_" and the id to the name **/ - public void delete() { - this.status = StandingInstructionStatus.DELETED.getValue(); - this.name = this.name + "_deleted_" + this.getId(); - } + public void delete() { + this.status = StandingInstructionStatus.DELETED.getValue(); + this.name = this.name + "_deleted_" + this.getId(); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferTransaction.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferTransaction.java index 333d11afa..6a254f65b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferTransaction.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferTransaction.java @@ -144,9 +144,10 @@ public class AccountTransferTransaction extends AbstractPersistableCustom { return this.accountTransferDetails; } - public static AccountTransferTransaction loanToLoanTransfer(AccountTransferDetails accountTransferDetails, LoanTransaction disburseTransaction, - LoanTransaction repaymentTransaction, LocalDate transactionDate, Money transactionMonetaryAmount, String description) { - return new AccountTransferTransaction(accountTransferDetails, null, null, repaymentTransaction, disburseTransaction, transactionDate, - transactionMonetaryAmount, description); - } -} \ No newline at end of file + public static AccountTransferTransaction loanToLoanTransfer(AccountTransferDetails accountTransferDetails, + LoanTransaction disburseTransaction, LoanTransaction repaymentTransaction, LocalDate transactionDate, + Money transactionMonetaryAmount, String description) { + return new AccountTransferTransaction(accountTransferDetails, null, null, repaymentTransaction, disburseTransaction, + transactionDate, transactionMonetaryAmount, description); + } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferType.java old mode 100755 new mode 100644 index 4a273a04a..3d717fcb3 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/AccountTransferType.java @@ -84,4 +84,4 @@ public enum AccountTransferType { public boolean isInterestTransfer() { return this.value.equals(AccountTransferType.INTEREST_TRANSFER.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionAssembler.java old mode 100755 new mode 100644 index 6ed3bd4a6..7fcd01aa1 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionAssembler.java @@ -90,4 +90,4 @@ public class StandingInstructionAssembler { return accountTransferDetails; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionPriority.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionPriority.java old mode 100755 new mode 100644 index c55e94218..fe6e70245 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionPriority.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionPriority.java @@ -84,4 +84,4 @@ public enum StandingInstructionPriority { public boolean isMediumPriority() { return this.value.equals(StandingInstructionPriority.MEDIUM.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionRepository.java old mode 100755 new mode 100644 index a0c5fde89..45aa95458 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionRepository.java @@ -26,8 +26,9 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface StandingInstructionRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface StandingInstructionRepository + extends JpaRepository, JpaSpecificationExecutor { + public final static String FIND_BY_LOAN_AND_STATUS_QUERY = "select accountTransferStandingInstruction " + "from AccountTransferStandingInstruction accountTransferStandingInstruction " + "where accountTransferStandingInstruction.status = :status " @@ -41,8 +42,10 @@ public interface StandingInstructionRepository extends JpaRepository findByLoanAccountAndStatus(@Param("loan") Loan loan, @Param("status") Integer status); + public Collection findByLoanAccountAndStatus(@Param("loan") Loan loan, + @Param("status") Integer status); @Query(FIND_BY_SAVINGS_AND_STATUS_QUERY) - public Collection findBySavingsAccountAndStatus(@Param("savingsAccount") SavingsAccount savingsAccount, @Param("status") Integer status); + public Collection findBySavingsAccountAndStatus( + @Param("savingsAccount") SavingsAccount savingsAccount, @Param("status") Integer status); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionStatus.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionStatus.java old mode 100755 new mode 100644 index 1ff99a0e8..cd452ed46 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionStatus.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionStatus.java @@ -77,4 +77,4 @@ public enum StandingInstructionStatus { return this.value.equals(StandingInstructionStatus.ACTIVE.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionType.java old mode 100755 new mode 100644 index b212d3a2b..c266bb2ac --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/domain/StandingInstructionType.java @@ -69,4 +69,4 @@ public enum StandingInstructionType { return this.value.equals(StandingInstructionType.DUES.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/exception/AccountTransferNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/exception/AccountTransferNotFoundException.java index 14c729d23..f405fb814 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/exception/AccountTransferNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/exception/AccountTransferNotFoundException.java @@ -25,4 +25,4 @@ public class AccountTransferNotFoundException extends AbstractPlatformResourceNo public AccountTransferNotFoundException(final Long id) { super("error.msg.accounttransfer.id.invalid", "Account transfer with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/exception/StandingInstructionNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/exception/StandingInstructionNotFoundException.java old mode 100755 new mode 100644 index e18f3e334..07f2102aa --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/exception/StandingInstructionNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/exception/StandingInstructionNotFoundException.java @@ -29,4 +29,4 @@ public class StandingInstructionNotFoundException extends AbstractPlatformResour super("error.msg.standinginstruction.id.invalid", "AccountTransferStandingInstruction with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/handler/CreateAccountTransferCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/handler/CreateAccountTransferCommandHandler.java index 85bca076c..1f2041385 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/handler/CreateAccountTransferCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/handler/CreateAccountTransferCommandHandler.java @@ -44,4 +44,4 @@ public class CreateAccountTransferCommandHandler implements NewCommandSourceHand return this.writePlatformService.create(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/handler/RefundByTransferCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/handler/RefundByTransferCommandHandler.java index 5165e31bb..e8a171d5c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/handler/RefundByTransferCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/handler/RefundByTransferCommandHandler.java @@ -44,4 +44,4 @@ public class RefundByTransferCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.refundByTransfer(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 8c1f35c2e..806123fb1 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java @@ -140,15 +140,19 @@ public class AccountAssociationsReadPlatformServiceImpl implements AccountAssoci public AccountAssociationsMapper() { final StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("aa.id as id,"); - // sqlBuilder.append("savingsAccount.id as savingsAccountId, savingsAccount.account_no as savingsAccountNo,"); + // sqlBuilder.append("savingsAccount.id as savingsAccountId, + // savingsAccount.account_no as savingsAccountNo,"); sqlBuilder.append("loanAccount.id as loanAccountId, loanAccount.account_no as loanAccountNo,"); - // sqlBuilder.append("linkLoanAccount.id as linkLoanAccountId, linkLoanAccount.account_no as linkLoanAccountNo, "); + // sqlBuilder.append("linkLoanAccount.id as linkLoanAccountId, + // linkLoanAccount.account_no as linkLoanAccountNo, "); sqlBuilder.append("linkSavingsAccount.id as linkSavingsAccountId, linkSavingsAccount.account_no as linkSavingsAccountNo "); sqlBuilder.append("from m_portfolio_account_associations aa "); - // sqlBuilder.append("left join m_savings_account savingsAccount on savingsAccount.id = aa.savings_account_id "); + // sqlBuilder.append("left join m_savings_account savingsAccount on + // savingsAccount.id = aa.savings_account_id "); sqlBuilder.append("left join m_loan loanAccount on loanAccount.id = aa.loan_account_id "); sqlBuilder.append("left join m_savings_account linkSavingsAccount on linkSavingsAccount.id = aa.linked_savings_account_id "); - // sqlBuilder.append("left join m_loan linkLoanAccount on linkLoanAccount.id = aa.linked_loan_account_id "); + // sqlBuilder.append("left join m_loan linkLoanAccount on + // linkLoanAccount.id = aa.linked_loan_account_id "); this.schemaSql = sqlBuilder.toString(); } @@ -191,8 +195,9 @@ public class AccountAssociationsReadPlatformServiceImpl implements AccountAssoci } } + @Override - public PortfolioAccountData retriveSavingsAccount(final Long savingsId){ + public PortfolioAccountData retriveSavingsAccount(final Long savingsId) { String accountNo = jdbcTemplate.queryForObject("select account_no from m_savings_account where id = ?", String.class, savingsId); return PortfolioAccountData.lookup(savingsId, accountNo); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransferEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransferEnumerations.java index 6894fbbe4..8d690f481 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransferEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransferEnumerations.java @@ -190,4 +190,4 @@ public class AccountTransferEnumerations { return optionData; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersReadPlatformService.java index 0a4d99422..c1e68ee57 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersReadPlatformService.java @@ -28,8 +28,8 @@ import org.joda.time.LocalDate; public interface AccountTransfersReadPlatformService { - AccountTransferData retrieveTemplate(Long fromOfficeId, Long fromClientId, Long fromAccountId, Integer fromAccountType, - Long toOfficeId, Long toClientId, Long toAccountId, Integer toAccountType); + AccountTransferData retrieveTemplate(Long fromOfficeId, Long fromClientId, Long fromAccountId, Integer fromAccountType, Long toOfficeId, + Long toClientId, Long toAccountId, Integer toAccountType); Page retrieveAll(SearchParameters searchParameters, Long accountDetailId); @@ -44,6 +44,5 @@ public interface AccountTransfersReadPlatformService { AccountTransferData retrieveRefundByTransferTemplate(Long fromOfficeId, Long fromClientId, Long fromAccountId, Integer fromAccountType, Long toOfficeId, Long toClientId, Long toAccountId, Integer toAccountType); - BigDecimal getTotalTransactionAmount(Long accountId, Integer accountType, - LocalDate transactionDate); -} \ No newline at end of file + BigDecimal getTotalTransactionAmount(Long accountId, Integer accountType, LocalDate transactionDate); +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersReadPlatformServiceImpl.java index ff1a32d07..76f676e3d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersReadPlatformServiceImpl.java @@ -55,8 +55,7 @@ import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; @Service -public class AccountTransfersReadPlatformServiceImpl implements - AccountTransfersReadPlatformService { +public class AccountTransfersReadPlatformServiceImpl implements AccountTransfersReadPlatformService { private final JdbcTemplate jdbcTemplate; private final ClientReadPlatformService clientReadPlatformService; @@ -69,16 +68,12 @@ public class AccountTransfersReadPlatformServiceImpl implements // pagination private final PaginationHelper paginationHelper = new PaginationHelper<>(); - private final DateTimeFormatter formatter = DateTimeFormat - .forPattern("yyyy-MM-dd"); + private final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); @Autowired - public AccountTransfersReadPlatformServiceImpl( - final RoutingDataSource dataSource, - final ClientReadPlatformService clientReadPlatformService, - final OfficeReadPlatformService officeReadPlatformService, - final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService, - final ColumnValidator columnValidator) { + public AccountTransfersReadPlatformServiceImpl(final RoutingDataSource dataSource, + final ClientReadPlatformService clientReadPlatformService, final OfficeReadPlatformService officeReadPlatformService, + final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.clientReadPlatformService = clientReadPlatformService; this.officeReadPlatformService = officeReadPlatformService; @@ -89,35 +84,26 @@ public class AccountTransfersReadPlatformServiceImpl implements } @Override - public AccountTransferData retrieveTemplate(final Long fromOfficeId, - final Long fromClientId, final Long fromAccountId, - final Integer fromAccountType, final Long toOfficeId, - final Long toClientId, final Long toAccountId, + public AccountTransferData retrieveTemplate(final Long fromOfficeId, final Long fromClientId, final Long fromAccountId, + final Integer fromAccountType, final Long toOfficeId, final Long toClientId, final Long toAccountId, final Integer toAccountType) { - final EnumOptionData loanAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.LOAN); - final EnumOptionData savingsAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.SAVINGS); + final EnumOptionData loanAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN); + final EnumOptionData savingsAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS); final Integer mostRelevantFromAccountType = fromAccountType; - final Collection fromAccountTypeOptions = Arrays - .asList(savingsAccountType, loanAccountType); + final Collection fromAccountTypeOptions = Arrays.asList(savingsAccountType, loanAccountType); final Collection toAccountTypeOptions; - if (mostRelevantFromAccountType != null - && mostRelevantFromAccountType == 1) { + if (mostRelevantFromAccountType != null && mostRelevantFromAccountType == 1) { // overpaid loan amt transfer to savings account toAccountTypeOptions = Arrays.asList(savingsAccountType); } else { - toAccountTypeOptions = Arrays.asList(loanAccountType, - savingsAccountType); + toAccountTypeOptions = Arrays.asList(loanAccountType, savingsAccountType); } final Integer mostRelevantToAccountType = toAccountType; - final EnumOptionData fromAccountTypeData = AccountTransferEnumerations - .accountType(mostRelevantFromAccountType); - final EnumOptionData toAccountTypeData = AccountTransferEnumerations - .accountType(mostRelevantToAccountType); + final EnumOptionData fromAccountTypeData = AccountTransferEnumerations.accountType(mostRelevantFromAccountType); + final EnumOptionData toAccountTypeData = AccountTransferEnumerations.accountType(mostRelevantToAccountType); // from settings OfficeData fromOffice = null; @@ -145,37 +131,30 @@ public class AccountTransfersReadPlatformServiceImpl implements } else { accountType = PortfolioAccountType.SAVINGS.getValue(); } - fromAccount = this.portfolioAccountReadPlatformService.retrieveOne( - fromAccountId, accountType); + fromAccount = this.portfolioAccountReadPlatformService.retrieveOne(fromAccountId, accountType); // override provided fromClient with client of account mostRelevantFromClientId = fromAccount.clientId(); } if (mostRelevantFromClientId != null) { - fromClient = this.clientReadPlatformService - .retrieveOne(mostRelevantFromClientId); + fromClient = this.clientReadPlatformService.retrieveOne(mostRelevantFromClientId); mostRelevantFromOfficeId = fromClient.officeId(); long[] loanStatus = null; if (mostRelevantFromAccountType == 1) { loanStatus = new long[] { 300, 700 }; } - PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO( - mostRelevantFromAccountType, mostRelevantFromClientId, + PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO(mostRelevantFromAccountType, mostRelevantFromClientId, loanStatus); - fromAccountOptions = this.portfolioAccountReadPlatformService - .retrieveAllForLookup(portfolioAccountDTO); + fromAccountOptions = this.portfolioAccountReadPlatformService.retrieveAllForLookup(portfolioAccountDTO); } Collection fromOfficeOptions = null; Collection fromClientOptions = null; if (mostRelevantFromOfficeId != null) { - fromOffice = this.officeReadPlatformService - .retrieveOffice(mostRelevantFromOfficeId); - fromOfficeOptions = this.officeReadPlatformService - .retrieveAllOfficesForDropdown(); - fromClientOptions = this.clientReadPlatformService - .retrieveAllForLookupByOfficeId(mostRelevantFromOfficeId); + fromOffice = this.officeReadPlatformService.retrieveOffice(mostRelevantFromOfficeId); + fromOfficeOptions = this.officeReadPlatformService.retrieveAllOfficesForDropdown(); + fromClientOptions = this.clientReadPlatformService.retrieveAllForLookupByOfficeId(mostRelevantFromOfficeId); } // defaults @@ -184,57 +163,43 @@ public class AccountTransfersReadPlatformServiceImpl implements Collection toClientOptions = null; if (toAccountId != null && fromAccount != null) { - toAccount = this.portfolioAccountReadPlatformService.retrieveOne( - toAccountId, mostRelevantToAccountType, + toAccount = this.portfolioAccountReadPlatformService.retrieveOne(toAccountId, mostRelevantToAccountType, fromAccount.currencyCode()); mostRelevantToClientId = toAccount.clientId(); } if (mostRelevantToClientId != null) { - toClient = this.clientReadPlatformService - .retrieveOne(mostRelevantToClientId); + toClient = this.clientReadPlatformService.retrieveOne(mostRelevantToClientId); mostRelevantToOfficeId = toClient.officeId(); - toClientOptions = this.clientReadPlatformService - .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); + toClientOptions = this.clientReadPlatformService.retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); - toAccountOptions = retrieveToAccounts(fromAccount, - mostRelevantToAccountType, mostRelevantToClientId); + toAccountOptions = retrieveToAccounts(fromAccount, mostRelevantToAccountType, mostRelevantToClientId); } if (mostRelevantToOfficeId != null) { - toOffice = this.officeReadPlatformService - .retrieveOffice(mostRelevantToOfficeId); - toOfficeOptions = this.officeReadPlatformService - .retrieveAllOfficesForDropdown(); + toOffice = this.officeReadPlatformService.retrieveOffice(mostRelevantToOfficeId); + toOfficeOptions = this.officeReadPlatformService.retrieveAllOfficesForDropdown(); - toClientOptions = this.clientReadPlatformService - .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); + toClientOptions = this.clientReadPlatformService.retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); if (toClientOptions != null && toClientOptions.size() == 1) { toClient = new ArrayList<>(toClientOptions).get(0); - toAccountOptions = retrieveToAccounts(fromAccount, - mostRelevantToAccountType, mostRelevantToClientId); + toAccountOptions = retrieveToAccounts(fromAccount, mostRelevantToAccountType, mostRelevantToClientId); } } - return AccountTransferData.template(fromOffice, fromClient, - fromAccountTypeData, fromAccount, transferDate, toOffice, - toClient, toAccountTypeData, toAccount, fromOfficeOptions, - fromClientOptions, fromAccountTypeOptions, fromAccountOptions, - toOfficeOptions, toClientOptions, toAccountTypeOptions, - toAccountOptions); + return AccountTransferData.template(fromOffice, fromClient, fromAccountTypeData, fromAccount, transferDate, toOffice, toClient, + toAccountTypeData, toAccount, fromOfficeOptions, fromClientOptions, fromAccountTypeOptions, fromAccountOptions, + toOfficeOptions, toClientOptions, toAccountTypeOptions, toAccountOptions); } - private Collection retrieveToAccounts( - final PortfolioAccountData excludeThisAccountFromOptions, + private Collection retrieveToAccounts(final PortfolioAccountData excludeThisAccountFromOptions, final Integer toAccountType, final Long toClientId) { - final String currencyCode = excludeThisAccountFromOptions != null ? excludeThisAccountFromOptions - .currencyCode() : null; + final String currencyCode = excludeThisAccountFromOptions != null ? excludeThisAccountFromOptions.currencyCode() : null; - PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO( - toAccountType, toClientId, currencyCode, null, null); + PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO(toAccountType, toClientId, currencyCode, null, null); Collection accountOptions = this.portfolioAccountReadPlatformService .retrieveAllForLookup(portfolioAccountDTO); if (!CollectionUtils.isEmpty(accountOptions)) { @@ -247,8 +212,7 @@ public class AccountTransfersReadPlatformServiceImpl implements } @Override - public Page retrieveAll( - final SearchParameters searchParameters, final Long accountDetailId) { + public Page retrieveAll(final SearchParameters searchParameters, final Long accountDetailId) { final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); @@ -260,8 +224,7 @@ public class AccountTransfersReadPlatformServiceImpl implements } if (searchParameters.isOrderByRequested()) { - sqlBuilder.append(" order by ").append( - searchParameters.getOrderBy()); + sqlBuilder.append(" order by ").append(searchParameters.getOrderBy()); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy()); if (searchParameters.isSortOrderProvided()) { sqlBuilder.append(' ').append(searchParameters.getSortOrder()); @@ -272,14 +235,12 @@ public class AccountTransfersReadPlatformServiceImpl implements if (searchParameters.isLimited()) { sqlBuilder.append(" limit ").append(searchParameters.getLimit()); if (searchParameters.isOffset()) { - sqlBuilder.append(" offset ").append( - searchParameters.getOffset()); + sqlBuilder.append(" offset ").append(searchParameters.getOffset()); } } final String sqlCountRows = "SELECT FOUND_ROWS()"; - return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, - sqlBuilder.toString(), finalObjectArray, + return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), finalObjectArray, this.accountTransfersMapper); } @@ -287,11 +248,9 @@ public class AccountTransfersReadPlatformServiceImpl implements public AccountTransferData retrieveOne(final Long transferId) { try { - final String sql = "select " + this.accountTransfersMapper.schema() - + " where att.id = ?"; + final String sql = "select " + this.accountTransfersMapper.schema() + " where att.id = ?"; - return this.jdbcTemplate.queryForObject(sql, - this.accountTransfersMapper, new Object[] { transferId }); + return this.jdbcTemplate.queryForObject(sql, this.accountTransfersMapper, new Object[] { transferId }); } catch (final EmptyResultDataAccessException e) { throw new AccountTransferNotFoundException(transferId); } @@ -301,82 +260,52 @@ public class AccountTransfersReadPlatformServiceImpl implements public Collection fetchPostInterestTransactionIds(final Long accountId) { final String sql = "select att.from_savings_transaction_id from m_account_transfer_transaction att inner join m_account_transfer_details atd on atd.id = att.account_transfer_details_id where atd.from_savings_account_id=? and att.is_reversed =0 and atd.transfer_type = ?"; - final List transactionId = this.jdbcTemplate.queryForList(sql, - Long.class, accountId, + final List transactionId = this.jdbcTemplate.queryForList(sql, Long.class, accountId, AccountTransferType.INTEREST_TRANSFER.getValue()); return transactionId; } - private static final class AccountTransfersMapper implements - RowMapper { + private static final class AccountTransfersMapper implements RowMapper { private final String schemaSql; public AccountTransfersMapper() { final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("att.id as id, att.is_reversed as isReversed,"); - sqlBuilder - .append("att.transaction_date as transferDate, att.amount as transferAmount,"); + sqlBuilder.append("att.transaction_date as transferDate, att.amount as transferAmount,"); sqlBuilder.append("att.description as transferDescription,"); - sqlBuilder - .append("att.currency_code as currencyCode, att.currency_digits as currencyDigits,"); + sqlBuilder.append("att.currency_code as currencyCode, att.currency_digits as currencyDigits,"); sqlBuilder.append("att.currency_multiplesof as inMultiplesOf, "); - sqlBuilder - .append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); + sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); - sqlBuilder - .append("fromoff.id as fromOfficeId, fromoff.name as fromOfficeName,"); - sqlBuilder - .append("tooff.id as toOfficeId, tooff.name as toOfficeName,"); - sqlBuilder - .append("fromclient.id as fromClientId, fromclient.display_name as fromClientName,"); - sqlBuilder - .append("toclient.id as toClientId, toclient.display_name as toClientName,"); - sqlBuilder - .append("fromsavacc.id as fromSavingsAccountId, fromsavacc.account_no as fromSavingsAccountNo,"); - sqlBuilder - .append("fromloanacc.id as fromLoanAccountId, fromloanacc.account_no as fromLoanAccountNo,"); - sqlBuilder - .append("tosavacc.id as toSavingsAccountId, tosavacc.account_no as toSavingsAccountNo,"); - sqlBuilder - .append("toloanacc.id as toLoanAccountId, toloanacc.account_no as toLoanAccountNo,"); - sqlBuilder - .append("fromsavtran.id as fromSavingsAccountTransactionId,"); - sqlBuilder - .append("fromsavtran.transaction_type_enum as fromSavingsAccountTransactionType,"); + sqlBuilder.append("fromoff.id as fromOfficeId, fromoff.name as fromOfficeName,"); + sqlBuilder.append("tooff.id as toOfficeId, tooff.name as toOfficeName,"); + sqlBuilder.append("fromclient.id as fromClientId, fromclient.display_name as fromClientName,"); + sqlBuilder.append("toclient.id as toClientId, toclient.display_name as toClientName,"); + sqlBuilder.append("fromsavacc.id as fromSavingsAccountId, fromsavacc.account_no as fromSavingsAccountNo,"); + sqlBuilder.append("fromloanacc.id as fromLoanAccountId, fromloanacc.account_no as fromLoanAccountNo,"); + sqlBuilder.append("tosavacc.id as toSavingsAccountId, tosavacc.account_no as toSavingsAccountNo,"); + sqlBuilder.append("toloanacc.id as toLoanAccountId, toloanacc.account_no as toLoanAccountNo,"); + sqlBuilder.append("fromsavtran.id as fromSavingsAccountTransactionId,"); + sqlBuilder.append("fromsavtran.transaction_type_enum as fromSavingsAccountTransactionType,"); sqlBuilder.append("tosavtran.id as toSavingsAccountTransactionId,"); - sqlBuilder - .append("tosavtran.transaction_type_enum as toSavingsAccountTransactionType"); + sqlBuilder.append("tosavtran.transaction_type_enum as toSavingsAccountTransactionType"); sqlBuilder.append(" FROM m_account_transfer_transaction att "); - sqlBuilder - .append("left join m_account_transfer_details atd on atd.id = att.account_transfer_details_id "); - sqlBuilder - .append("join m_currency curr on curr.code = att.currency_code "); - sqlBuilder - .append("join m_office fromoff on fromoff.id = atd.from_office_id "); - sqlBuilder - .append("join m_office tooff on tooff.id = atd.to_office_id "); - sqlBuilder - .append("join m_client fromclient on fromclient.id = atd.from_client_id "); - sqlBuilder - .append("join m_client toclient on toclient.id = atd.to_client_id "); - sqlBuilder - .append("left join m_savings_account fromsavacc on fromsavacc.id = atd.from_savings_account_id "); - sqlBuilder - .append("left join m_loan fromloanacc on fromloanacc.id = atd.from_loan_account_id "); - sqlBuilder - .append("left join m_savings_account tosavacc on tosavacc.id = atd.to_savings_account_id "); - sqlBuilder - .append("left join m_loan toloanacc on toloanacc.id = atd.to_loan_account_id "); - sqlBuilder - .append("left join m_savings_account_transaction fromsavtran on fromsavtran.id = att.from_savings_transaction_id "); - sqlBuilder - .append("left join m_savings_account_transaction tosavtran on tosavtran.id = att.to_savings_transaction_id "); - sqlBuilder - .append("left join m_loan_transaction fromloantran on fromloantran.id = att.from_savings_transaction_id "); - sqlBuilder - .append("left join m_loan_transaction toloantran on toloantran.id = att.to_savings_transaction_id "); + sqlBuilder.append("left join m_account_transfer_details atd on atd.id = att.account_transfer_details_id "); + sqlBuilder.append("join m_currency curr on curr.code = att.currency_code "); + sqlBuilder.append("join m_office fromoff on fromoff.id = atd.from_office_id "); + sqlBuilder.append("join m_office tooff on tooff.id = atd.to_office_id "); + sqlBuilder.append("join m_client fromclient on fromclient.id = atd.from_client_id "); + sqlBuilder.append("join m_client toclient on toclient.id = atd.to_client_id "); + sqlBuilder.append("left join m_savings_account fromsavacc on fromsavacc.id = atd.from_savings_account_id "); + sqlBuilder.append("left join m_loan fromloanacc on fromloanacc.id = atd.from_loan_account_id "); + sqlBuilder.append("left join m_savings_account tosavacc on tosavacc.id = atd.to_savings_account_id "); + sqlBuilder.append("left join m_loan toloanacc on toloanacc.id = atd.to_loan_account_id "); + sqlBuilder.append("left join m_savings_account_transaction fromsavtran on fromsavtran.id = att.from_savings_transaction_id "); + sqlBuilder.append("left join m_savings_account_transaction tosavtran on tosavtran.id = att.to_savings_transaction_id "); + sqlBuilder.append("left join m_loan_transaction fromloantran on fromloantran.id = att.from_savings_transaction_id "); + sqlBuilder.append("left join m_loan_transaction toloantran on toloantran.id = att.to_savings_transaction_id "); this.schemaSql = sqlBuilder.toString(); } @@ -386,115 +315,81 @@ public class AccountTransfersReadPlatformServiceImpl implements } @Override - public AccountTransferData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public AccountTransferData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); final boolean reversed = rs.getBoolean("isReversed"); - final LocalDate transferDate = JdbcSupport.getLocalDate(rs, - "transferDate"); - final BigDecimal transferAmount = JdbcSupport - .getBigDecimalDefaultToZeroIfNull(rs, "transferAmount"); - final String transferDescription = rs - .getString("transferDescription"); + final LocalDate transferDate = JdbcSupport.getLocalDate(rs, "transferDate"); + final BigDecimal transferAmount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "transferAmount"); + final String transferDescription = rs.getString("transferDescription"); 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 Integer inMultiplesOf = JdbcSupport.getInteger(rs, - "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, - currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); + final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); + final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId"); final String fromOfficeName = rs.getString("fromOfficeName"); - final OfficeData fromOffice = OfficeData.dropdown(fromOfficeId, - fromOfficeName, null); + final OfficeData fromOffice = OfficeData.dropdown(fromOfficeId, fromOfficeName, null); final Long toOfficeId = JdbcSupport.getLong(rs, "toOfficeId"); final String toOfficeName = rs.getString("toOfficeName"); - final OfficeData toOffice = OfficeData.dropdown(toOfficeId, - toOfficeName, null); + final OfficeData toOffice = OfficeData.dropdown(toOfficeId, toOfficeName, null); final Long fromClientId = JdbcSupport.getLong(rs, "fromClientId"); final String fromClientName = rs.getString("fromClientName"); - final ClientData fromClient = ClientData.lookup(fromClientId, - fromClientName, fromOfficeId, fromOfficeName); + final ClientData fromClient = ClientData.lookup(fromClientId, fromClientName, fromOfficeId, fromOfficeName); final Long toClientId = JdbcSupport.getLong(rs, "toClientId"); final String toClientName = rs.getString("toClientName"); - final ClientData toClient = ClientData.lookup(toClientId, - toClientName, toOfficeId, toOfficeName); + final ClientData toClient = ClientData.lookup(toClientId, toClientName, toOfficeId, toOfficeName); - final Long fromSavingsAccountId = JdbcSupport.getLong(rs, - "fromSavingsAccountId"); - final String fromSavingsAccountNo = rs - .getString("fromSavingsAccountNo"); - final Long fromLoanAccountId = JdbcSupport.getLong(rs, - "fromLoanAccountId"); + final Long fromSavingsAccountId = JdbcSupport.getLong(rs, "fromSavingsAccountId"); + final String fromSavingsAccountNo = rs.getString("fromSavingsAccountNo"); + final Long fromLoanAccountId = JdbcSupport.getLong(rs, "fromLoanAccountId"); final String fromLoanAccountNo = rs.getString("fromLoanAccountNo"); PortfolioAccountData fromAccount = null; EnumOptionData fromAccountType = null; if (fromSavingsAccountId != null) { - fromAccount = PortfolioAccountData.lookup(fromSavingsAccountId, - fromSavingsAccountNo); - fromAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.SAVINGS); + fromAccount = PortfolioAccountData.lookup(fromSavingsAccountId, fromSavingsAccountNo); + fromAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS); } else if (fromLoanAccountId != null) { - fromAccount = PortfolioAccountData.lookup(fromLoanAccountId, - fromLoanAccountNo); - fromAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.LOAN); + fromAccount = PortfolioAccountData.lookup(fromLoanAccountId, fromLoanAccountNo); + fromAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN); } PortfolioAccountData toAccount = null; EnumOptionData toAccountType = null; - final Long toSavingsAccountId = JdbcSupport.getLong(rs, - "toSavingsAccountId"); - final String toSavingsAccountNo = rs - .getString("toSavingsAccountNo"); - final Long toLoanAccountId = JdbcSupport.getLong(rs, - "toLoanAccountId"); + final Long toSavingsAccountId = JdbcSupport.getLong(rs, "toSavingsAccountId"); + final String toSavingsAccountNo = rs.getString("toSavingsAccountNo"); + final Long toLoanAccountId = JdbcSupport.getLong(rs, "toLoanAccountId"); final String toLoanAccountNo = rs.getString("toLoanAccountNo"); if (toSavingsAccountId != null) { - toAccount = PortfolioAccountData.lookup(toSavingsAccountId, - toSavingsAccountNo); - toAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.SAVINGS); + toAccount = PortfolioAccountData.lookup(toSavingsAccountId, toSavingsAccountNo); + toAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS); } else if (toLoanAccountId != null) { - toAccount = PortfolioAccountData.lookup(toLoanAccountId, - toLoanAccountNo); - toAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.LOAN); + toAccount = PortfolioAccountData.lookup(toLoanAccountId, toLoanAccountNo); + toAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN); } - return AccountTransferData.instance(id, reversed, transferDate, - currency, transferAmount, transferDescription, fromOffice, - toOffice, fromClient, toClient, fromAccountType, - fromAccount, toAccountType, toAccount); + return AccountTransferData.instance(id, reversed, transferDate, currency, transferAmount, transferDescription, fromOffice, + toOffice, fromClient, toClient, fromAccountType, fromAccount, toAccountType, toAccount); } } @Override - public boolean isAccountTransfer(final Long transactionId, - final PortfolioAccountType accountType) { - final StringBuilder sql = new StringBuilder( - "select count(*) from m_account_transfer_transaction at where "); + public boolean isAccountTransfer(final Long transactionId, final PortfolioAccountType accountType) { + final StringBuilder sql = new StringBuilder("select count(*) from m_account_transfer_transaction at where "); if (accountType.isLoanAccount()) { - sql.append("at.from_loan_transaction_id=").append(transactionId) - .append(" or at.to_loan_transaction_id=") - .append(transactionId); + sql.append("at.from_loan_transaction_id=").append(transactionId).append(" or at.to_loan_transaction_id=").append(transactionId); } else { - sql.append("at.from_savings_transaction_id=").append(transactionId) - .append(" or at.to_savings_transaction_id=") + sql.append("at.from_savings_transaction_id=").append(transactionId).append(" or at.to_savings_transaction_id=") .append(transactionId); } @@ -503,74 +398,59 @@ public class AccountTransfersReadPlatformServiceImpl implements } @Override - public Page retrieveByStandingInstruction( - final Long id, final SearchParameters searchParameters) { + public Page retrieveByStandingInstruction(final Long id, final SearchParameters searchParameters) { final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); - sqlBuilder - .append(this.accountTransfersMapper.schema()) - .append(" join m_account_transfer_standing_instructions atsi on atsi.account_transfer_details_id = att.account_transfer_details_id "); + sqlBuilder.append(this.accountTransfersMapper.schema()).append( + " join m_account_transfer_standing_instructions atsi on atsi.account_transfer_details_id = att.account_transfer_details_id "); sqlBuilder.append(" where atsi.id = ?"); if (searchParameters != null) { if (searchParameters.isOrderByRequested()) { - sqlBuilder.append(" order by ").append( - searchParameters.getOrderBy()); + sqlBuilder.append(" order by ").append(searchParameters.getOrderBy()); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy()); if (searchParameters.isSortOrderProvided()) { - sqlBuilder.append(' ').append( - searchParameters.getSortOrder()); + sqlBuilder.append(' ').append(searchParameters.getSortOrder()); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getSortOrder()); } } if (searchParameters.isLimited()) { - sqlBuilder.append(" limit ") - .append(searchParameters.getLimit()); + sqlBuilder.append(" limit ").append(searchParameters.getLimit()); if (searchParameters.isOffset()) { - sqlBuilder.append(" offset ").append( - searchParameters.getOffset()); + sqlBuilder.append(" offset ").append(searchParameters.getOffset()); } } } final Object[] finalObjectArray = { id }; final String sqlCountRows = "SELECT FOUND_ROWS()"; - return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, - sqlBuilder.toString(), finalObjectArray, + return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), finalObjectArray, this.accountTransfersMapper); } @Override - public AccountTransferData retrieveRefundByTransferTemplate( - final Long fromOfficeId, final Long fromClientId, - final Long fromAccountId, final Integer fromAccountType, - final Long toOfficeId, final Long toClientId, - final Long toAccountId, final Integer toAccountType) { + public AccountTransferData retrieveRefundByTransferTemplate(final Long fromOfficeId, final Long fromClientId, final Long fromAccountId, + final Integer fromAccountType, final Long toOfficeId, final Long toClientId, final Long toAccountId, + final Integer toAccountType) { // TODO Auto-generated method stub - final EnumOptionData loanAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.LOAN); - final EnumOptionData savingsAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.SAVINGS); + final EnumOptionData loanAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN); + final EnumOptionData savingsAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS); final Integer mostRelevantFromAccountType = fromAccountType; - final Collection fromAccountTypeOptions = Arrays - .asList(savingsAccountType, loanAccountType); + final Collection fromAccountTypeOptions = Arrays.asList(savingsAccountType, loanAccountType); final Collection toAccountTypeOptions; if (mostRelevantFromAccountType == 1) { // overpaid loan amt transfer to savings account toAccountTypeOptions = Arrays.asList(savingsAccountType); } else { - toAccountTypeOptions = Arrays.asList(loanAccountType, - savingsAccountType); + toAccountTypeOptions = Arrays.asList(loanAccountType, savingsAccountType); } final Integer mostRelevantToAccountType = toAccountType; - final EnumOptionData fromAccountTypeData = AccountTransferEnumerations - .accountType(mostRelevantFromAccountType); - final EnumOptionData toAccountTypeData = AccountTransferEnumerations - .accountType(mostRelevantToAccountType); + final EnumOptionData fromAccountTypeData = AccountTransferEnumerations.accountType(mostRelevantFromAccountType); + final EnumOptionData toAccountTypeData = AccountTransferEnumerations.accountType(mostRelevantToAccountType); // from settings OfficeData fromOffice = null; @@ -598,37 +478,30 @@ public class AccountTransfersReadPlatformServiceImpl implements } else { accountType = PortfolioAccountType.SAVINGS.getValue(); } - fromAccount = this.portfolioAccountReadPlatformService - .retrieveOneByPaidInAdvance(fromAccountId, accountType); + fromAccount = this.portfolioAccountReadPlatformService.retrieveOneByPaidInAdvance(fromAccountId, accountType); // override provided fromClient with client of account mostRelevantFromClientId = fromAccount.clientId(); } if (mostRelevantFromClientId != null) { - fromClient = this.clientReadPlatformService - .retrieveOne(mostRelevantFromClientId); + fromClient = this.clientReadPlatformService.retrieveOne(mostRelevantFromClientId); mostRelevantFromOfficeId = fromClient.officeId(); long[] loanStatus = null; if (mostRelevantFromAccountType == 1) { loanStatus = new long[] { 300, 700 }; } - PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO( - mostRelevantFromAccountType, mostRelevantFromClientId, + PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO(mostRelevantFromAccountType, mostRelevantFromClientId, loanStatus); - fromAccountOptions = this.portfolioAccountReadPlatformService - .retrieveAllForLookup(portfolioAccountDTO); + fromAccountOptions = this.portfolioAccountReadPlatformService.retrieveAllForLookup(portfolioAccountDTO); } Collection fromOfficeOptions = null; Collection fromClientOptions = null; if (mostRelevantFromOfficeId != null) { - fromOffice = this.officeReadPlatformService - .retrieveOffice(mostRelevantFromOfficeId); - fromOfficeOptions = this.officeReadPlatformService - .retrieveAllOfficesForDropdown(); - fromClientOptions = this.clientReadPlatformService - .retrieveAllForLookupByOfficeId(mostRelevantFromOfficeId); + fromOffice = this.officeReadPlatformService.retrieveOffice(mostRelevantFromOfficeId); + fromOfficeOptions = this.officeReadPlatformService.retrieveAllOfficesForDropdown(); + fromClientOptions = this.clientReadPlatformService.retrieveAllForLookupByOfficeId(mostRelevantFromOfficeId); } // defaults @@ -637,65 +510,49 @@ public class AccountTransfersReadPlatformServiceImpl implements Collection toClientOptions = null; if (toAccountId != null && fromAccount != null) { - toAccount = this.portfolioAccountReadPlatformService.retrieveOne( - toAccountId, mostRelevantToAccountType, + toAccount = this.portfolioAccountReadPlatformService.retrieveOne(toAccountId, mostRelevantToAccountType, fromAccount.currencyCode()); mostRelevantToClientId = toAccount.clientId(); } if (mostRelevantToClientId != null) { - toClient = this.clientReadPlatformService - .retrieveOne(mostRelevantToClientId); + toClient = this.clientReadPlatformService.retrieveOne(mostRelevantToClientId); mostRelevantToOfficeId = toClient.officeId(); - toClientOptions = this.clientReadPlatformService - .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); + toClientOptions = this.clientReadPlatformService.retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); - toAccountOptions = retrieveToAccounts(fromAccount, - mostRelevantToAccountType, mostRelevantToClientId); + toAccountOptions = retrieveToAccounts(fromAccount, mostRelevantToAccountType, mostRelevantToClientId); } if (mostRelevantToOfficeId != null) { - toOffice = this.officeReadPlatformService - .retrieveOffice(mostRelevantToOfficeId); - toOfficeOptions = this.officeReadPlatformService - .retrieveAllOfficesForDropdown(); + toOffice = this.officeReadPlatformService.retrieveOffice(mostRelevantToOfficeId); + toOfficeOptions = this.officeReadPlatformService.retrieveAllOfficesForDropdown(); - toClientOptions = this.clientReadPlatformService - .retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); + toClientOptions = this.clientReadPlatformService.retrieveAllForLookupByOfficeId(mostRelevantToOfficeId); if (toClientOptions != null && toClientOptions.size() == 1) { toClient = new ArrayList<>(toClientOptions).get(0); - toAccountOptions = retrieveToAccounts(fromAccount, - mostRelevantToAccountType, mostRelevantToClientId); + toAccountOptions = retrieveToAccounts(fromAccount, mostRelevantToAccountType, mostRelevantToClientId); } } - return AccountTransferData.template(fromOffice, fromClient, - fromAccountTypeData, fromAccount, transferDate, toOffice, - toClient, toAccountTypeData, toAccount, fromOfficeOptions, - fromClientOptions, fromAccountTypeOptions, fromAccountOptions, - toOfficeOptions, toClientOptions, toAccountTypeOptions, - toAccountOptions); + return AccountTransferData.template(fromOffice, fromClient, fromAccountTypeData, fromAccount, transferDate, toOffice, toClient, + toAccountTypeData, toAccount, fromOfficeOptions, fromClientOptions, fromAccountTypeOptions, fromAccountOptions, + toOfficeOptions, toClientOptions, toAccountTypeOptions, toAccountOptions); } @Override - public BigDecimal getTotalTransactionAmount(Long accountId, - Integer accountType, LocalDate transactionDate) { - StringBuilder sqlBuilder = new StringBuilder( - " select sum(trans.amount) as totalTransactionAmount "); + public BigDecimal getTotalTransactionAmount(Long accountId, Integer accountType, LocalDate transactionDate) { + StringBuilder sqlBuilder = new StringBuilder(" select sum(trans.amount) as totalTransactionAmount "); sqlBuilder.append(" from m_account_transfer_details as det "); - sqlBuilder - .append(" inner join m_account_transfer_transaction as trans "); + sqlBuilder.append(" inner join m_account_transfer_transaction as trans "); sqlBuilder.append(" on det.id = trans.account_transfer_details_id "); sqlBuilder.append(" where trans.is_reversed = 0 "); sqlBuilder.append(" and trans.transaction_date = ? "); - sqlBuilder - .append(" and IF(1=?, det.from_loan_account_id = ?, det.from_savings_account_id = ?) "); + sqlBuilder.append(" and IF(1=?, det.from_loan_account_id = ?, det.from_savings_account_id = ?) "); return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), - new Object[] { this.formatter.print(transactionDate), - accountType, accountId, accountId }, BigDecimal.class); + new Object[] { this.formatter.print(transactionDate), accountType, accountId, accountId }, BigDecimal.class); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersWritePlatformService.java index 5d680c200..19765cd8d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersWritePlatformService.java @@ -43,4 +43,4 @@ public interface AccountTransfersWritePlatformService { void reverseTransfersWithFromAccountTransactions(Collection fromTransactionIds, PortfolioAccountType accountTypeId); AccountTransferDetails repayLoanWithTopup(AccountTransferDTO accountTransferDTO); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersWritePlatformServiceImpl.java index 61b598040..44aa8d2e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/AccountTransfersWritePlatformServiceImpl.java @@ -87,8 +87,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer final SavingsAccountAssembler savingsAccountAssembler, final SavingsAccountDomainService savingsAccountDomainService, final LoanAssembler loanAssembler, final LoanAccountDomainService loanAccountDomainService, final SavingsAccountWritePlatformService savingsAccountWritePlatformService, - final AccountTransferDetailRepository accountTransferDetailRepository, - final LoanReadPlatformService loanReadPlatformService, + final AccountTransferDetailRepository accountTransferDetailRepository, final LoanReadPlatformService loanReadPlatformService, final GSIMRepositoy gsimRepository) { this.accountTransfersDataValidator = accountTransfersDataValidator; this.accountTransferAssembler = accountTransferAssembler; @@ -100,7 +99,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer this.savingsAccountWritePlatformService = savingsAccountWritePlatformService; this.accountTransferDetailRepository = accountTransferDetailRepository; this.loanReadPlatformService = loanReadPlatformService; - this.gsimRepository=gsimRepository; + this.gsimRepository = gsimRepository; } @Transactional @@ -143,8 +142,8 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer final Long toSavingsId = command.longValueOfParameterNamed(toAccountIdParamName); final SavingsAccount toSavingsAccount = this.savingsAccountAssembler.assembleFrom(toSavingsId); - final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(toSavingsAccount, fmt, - transactionDate, transactionAmount, paymentDetail, isAccountTransfer, isRegularTransaction); + final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(toSavingsAccount, fmt, transactionDate, + transactionAmount, paymentDetail, isAccountTransfer, isRegularTransaction); final AccountTransferDetails accountTransferDetails = this.accountTransferAssembler.assembleSavingsToSavingsTransfer(command, fromSavingsAccount, toSavingsAccount, withdrawal, deposit); @@ -189,8 +188,8 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer final Long toSavingsAccountId = command.longValueOfParameterNamed(toAccountIdParamName); final SavingsAccount toSavingsAccount = this.savingsAccountAssembler.assembleFrom(toSavingsAccountId); - final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(toSavingsAccount, fmt, - transactionDate, transactionAmount, paymentDetail, isAccountTransfer, isRegularTransaction); + final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(toSavingsAccount, fmt, transactionDate, + transactionAmount, paymentDetail, isAccountTransfer, isRegularTransaction); final AccountTransferDetails accountTransferDetails = this.accountTransferAssembler.assembleLoanToSavingsTransfer(command, fromLoanAccount, toSavingsAccount, deposit, loanRefundTransaction); @@ -226,7 +225,8 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer @Override @Transactional - public void reverseTransfersWithFromAccountTransactions(final Collection fromTransactionIds, final PortfolioAccountType accountTypeId) { + public void reverseTransfersWithFromAccountTransactions(final Collection fromTransactionIds, + final PortfolioAccountType accountTypeId) { List acccountTransfers = null; if (accountTypeId.isLoanAccount()) { acccountTransfers = this.accountTransferRepository.findByFromLoanTransactions(fromTransactionIds); @@ -261,13 +261,13 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer this.loanAccountDomainService.reverseTransfer(accountTransfer.getToLoanTransaction()); } if (accountTransfer.getFromTransaction() != null) { - this.savingsAccountWritePlatformService.undoTransaction(accountTransfer.accountTransferDetails().fromSavingsAccount() - .getId(), accountTransfer.getFromTransaction().getId(), true); + this.savingsAccountWritePlatformService.undoTransaction( + accountTransfer.accountTransferDetails().fromSavingsAccount().getId(), accountTransfer.getFromTransaction().getId(), + true); } if (accountTransfer.getToSavingsTransaction() != null) { - this.savingsAccountWritePlatformService.undoTransaction( - accountTransfer.accountTransferDetails().toSavingsAccount().getId(), accountTransfer.getToSavingsTransaction() - .getId(), true); + this.savingsAccountWritePlatformService.undoTransaction(accountTransfer.accountTransferDetails().toSavingsAccount().getId(), + accountTransfer.getToSavingsTransaction().getId(), true); } accountTransfer.reverse(); this.accountTransferRepository.save(accountTransfer); @@ -307,8 +307,9 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer } final SavingsTransactionBooleanValues transactionBooleanValues = new SavingsTransactionBooleanValues(isAccountTransfer, - isRegularTransaction, fromSavingsAccount.isWithdrawalFeeApplicableForTransfer(), AccountTransferType.fromInt( - accountTransferDTO.getTransferType()).isInterestTransfer(), accountTransferDTO.isExceptionForBalanceCheck()); + isRegularTransaction, fromSavingsAccount.isWithdrawalFeeApplicableForTransfer(), + AccountTransferType.fromInt(accountTransferDTO.getTransferType()).isInterestTransfer(), + accountTransferDTO.isExceptionForBalanceCheck()); final SavingsAccountTransaction withdrawal = this.savingsAccountDomainService.handleWithdrawal(fromSavingsAccount, accountTransferDTO.getFmt(), accountTransferDTO.getTransactionDate(), accountTransferDTO.getTransactionAmount(), @@ -324,11 +325,12 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer } else { final boolean isRecoveryRepayment = false; - final Boolean isHolidayValidationDone=false; - final HolidayDetailDTO holidayDetailDto=null; + final Boolean isHolidayValidationDone = false; + final HolidayDetailDTO holidayDetailDto = null; loanTransaction = this.loanAccountDomainService.makeRepayment(toLoanAccount, new CommandProcessingResultBuilder(), accountTransferDTO.getTransactionDate(), accountTransferDTO.getTransactionAmount(), - accountTransferDTO.getPaymentDetail(), null, null, isRecoveryRepayment, isAccountTransfer,holidayDetailDto,isHolidayValidationDone); + accountTransferDTO.getPaymentDetail(), null, null, isRecoveryRepayment, isAccountTransfer, holidayDetailDto, + isHolidayValidationDone); } accountTransferDetails = this.accountTransferAssembler.assembleSavingsToLoanTransfer(accountTransferDTO, fromSavingsAccount, @@ -360,8 +362,9 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer } final SavingsTransactionBooleanValues transactionBooleanValues = new SavingsTransactionBooleanValues(isAccountTransfer, - isRegularTransaction, fromSavingsAccount.isWithdrawalFeeApplicableForTransfer(), AccountTransferType.fromInt( - accountTransferDTO.getTransferType()).isInterestTransfer(), accountTransferDTO.isExceptionForBalanceCheck()); + isRegularTransaction, fromSavingsAccount.isWithdrawalFeeApplicableForTransfer(), + AccountTransferType.fromInt(accountTransferDTO.getTransferType()).isInterestTransfer(), + accountTransferDTO.isExceptionForBalanceCheck()); final SavingsAccountTransaction withdrawal = this.savingsAccountDomainService.handleWithdrawal(fromSavingsAccount, accountTransferDTO.getFmt(), accountTransferDTO.getTransactionDate(), accountTransferDTO.getTransactionAmount(), @@ -415,11 +418,10 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer transferTransactionId = accountTransferDetails.getId(); // if the savings account is GSIM, update its parent as well - if(toSavingsAccount.getGsim()!=null) - { - GroupSavingsIndividualMonitoring gsim=gsimRepository.findById(toSavingsAccount.getGsim().getId()).get(); - BigDecimal currentBalance=gsim.getParentDeposit(); - BigDecimal newBalance=currentBalance.add(accountTransferDTO.getTransactionAmount()); + if (toSavingsAccount.getGsim() != null) { + GroupSavingsIndividualMonitoring gsim = gsimRepository.findById(toSavingsAccount.getGsim().getId()).get(); + BigDecimal currentBalance = gsim.getParentDeposit(); + BigDecimal newBalance = currentBalance.add(accountTransferDTO.getTransactionAmount()); gsim.setParentDeposit(newBalance); gsimRepository.save(gsim); } @@ -450,15 +452,15 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer } LoanTransaction disburseTransaction = this.loanAccountDomainService.makeDisburseTransaction(accountTransferDTO.getFromAccountId(), - accountTransferDTO.getTransactionDate(), accountTransferDTO.getTransactionAmount(), - accountTransferDTO.getPaymentDetail(), accountTransferDTO.getNoteText(), accountTransferDTO.getTxnExternalId(), true); + accountTransferDTO.getTransactionDate(), accountTransferDTO.getTransactionAmount(), accountTransferDTO.getPaymentDetail(), + accountTransferDTO.getNoteText(), accountTransferDTO.getTxnExternalId(), true); LoanTransaction repayTransaction = this.loanAccountDomainService.makeRepayment(toLoanAccount, new CommandProcessingResultBuilder(), - accountTransferDTO.getTransactionDate(), accountTransferDTO.getTransactionAmount(), - accountTransferDTO.getPaymentDetail(), null, null, false, isAccountTransfer,null,false, true); + accountTransferDTO.getTransactionDate(), accountTransferDTO.getTransactionAmount(), accountTransferDTO.getPaymentDetail(), + null, null, false, isAccountTransfer, null, false, true); - AccountTransferDetails accountTransferDetails = this.accountTransferAssembler.assembleLoanToLoanTransfer(accountTransferDTO, fromLoanAccount, - toLoanAccount, disburseTransaction, repayTransaction); + AccountTransferDetails accountTransferDetails = this.accountTransferAssembler.assembleLoanToLoanTransfer(accountTransferDTO, + fromLoanAccount, toLoanAccount, disburseTransaction, repayTransaction); this.accountTransferDetailRepository.saveAndFlush(accountTransferDetails); return accountTransferDetails; @@ -482,7 +484,8 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer return fromAccountType.isSavingsAccount() && toAccountType.isLoanAccount(); } - private boolean isSavingsToSavingsAccountTransfer(final PortfolioAccountType fromAccountType, final PortfolioAccountType toAccountType) { + private boolean isSavingsToSavingsAccountTransfer(final PortfolioAccountType fromAccountType, + final PortfolioAccountType toAccountType) { return fromAccountType.isSavingsAccount() && toAccountType.isSavingsAccount(); } @@ -506,8 +509,9 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer BigDecimal overpaid = this.loanReadPlatformService.retrieveTotalPaidInAdvance(fromLoanAccountId).getPaidInAdvance(); - if (overpaid == null || overpaid.compareTo(BigDecimal.ZERO) == 0 ? Boolean.TRUE:Boolean.FALSE || transactionAmount.floatValue() > overpaid.floatValue()) { - if(overpaid == null) { + if (overpaid == null || overpaid.compareTo(BigDecimal.ZERO) == 0 ? Boolean.TRUE + : Boolean.FALSE || transactionAmount.floatValue() > overpaid.floatValue()) { + if (overpaid == null) { overpaid = BigDecimal.ZERO; } throw new InvalidPaidInAdvanceAmountException(overpaid.toPlainString()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/PortfolioAccountReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/PortfolioAccountReadPlatformService.java index e4fc94d67..fdbf47486 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/PortfolioAccountReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/PortfolioAccountReadPlatformService.java @@ -31,4 +31,4 @@ public interface PortfolioAccountReadPlatformService { Collection retrieveAllForLookup(final PortfolioAccountDTO portfolioAccountDTO); PortfolioAccountData retrieveOneByPaidInAdvance(Long accountId, Integer accountTypeId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/PortfolioAccountReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/PortfolioAccountReadPlatformServiceImpl.java index 8d3a0c4ef..ac011679e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/PortfolioAccountReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/PortfolioAccountReadPlatformServiceImpl.java @@ -104,7 +104,7 @@ public class PortfolioAccountReadPlatformServiceImpl implements PortfolioAccount public Collection retrieveAllForLookup(final PortfolioAccountDTO portfolioAccountDTO) { final List sqlParams = new ArrayList<>(); - //sqlParams.add(portfolioAccountDTO.getClientId()); + // sqlParams.add(portfolioAccountDTO.getClientId()); Collection accounts = null; String sql = null; String defaultAccountStatus = "300"; @@ -151,11 +151,11 @@ public class PortfolioAccountReadPlatformServiceImpl implements PortfolioAccount sqlParams.add(portfolioAccountDTO.getDepositType()); } - if(portfolioAccountDTO.isExcludeOverDraftAccounts()){ + if (portfolioAccountDTO.isExcludeOverDraftAccounts()) { sql += " and sa.allow_overdraft = 0"; } - if(portfolioAccountDTO.getClientId() == null && portfolioAccountDTO.getGroupId() != null){ + if (portfolioAccountDTO.getClientId() == null && portfolioAccountDTO.getGroupId() != null) { sql += " and sa.group_id = ? "; sqlParams.add(portfolioAccountDTO.getGroupId()); } @@ -223,8 +223,8 @@ public class PortfolioAccountReadPlatformServiceImpl implements PortfolioAccount final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMulitplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMulitplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMulitplesOf, currencyDisplaySymbol, + currencyNameCode); return new PortfolioAccountData(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, currency); @@ -287,8 +287,8 @@ public class PortfolioAccountReadPlatformServiceImpl implements PortfolioAccount final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMulitplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); final BigDecimal amtForTransfer = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalOverpaid"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMulitplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMulitplesOf, currencyDisplaySymbol, + currencyNameCode); return new PortfolioAccountData(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, currency, amtForTransfer); @@ -304,15 +304,15 @@ public class PortfolioAccountReadPlatformServiceImpl implements PortfolioAccount final StringBuilder amountQueryString = new StringBuilder(400); amountQueryString.append("(select (SUM(ifnull(mr.principal_completed_derived, 0)) +"); amountQueryString.append("SUM(ifnull(mr.interest_completed_derived, 0)) + "); - amountQueryString.append("SUM(ifnull(mr.fee_charges_completed_derived, 0)) + "); - amountQueryString.append(" SUM(ifnull(mr.penalty_charges_completed_derived, 0))) as total_in_advance_derived"); - amountQueryString.append(" from m_loan ml INNER JOIN m_loan_repayment_schedule mr on mr.loan_id = ml.id"); - amountQueryString.append(" where ml.id=? and ml.loan_status_id = 300"); - amountQueryString.append(" and mr.duedate >= CURDATE() group by ml.id having"); - amountQueryString.append(" (SUM(ifnull(mr.principal_completed_derived, 0)) + "); - amountQueryString.append(" SUM(ifnull(mr.interest_completed_derived, 0)) + "); - amountQueryString.append("SUM(ifnull(mr.fee_charges_completed_derived, 0)) + "); - amountQueryString.append("SUM(ifnull(mr.penalty_charges_completed_derived, 0))) > 0) as totalOverpaid "); + amountQueryString.append("SUM(ifnull(mr.fee_charges_completed_derived, 0)) + "); + amountQueryString.append(" SUM(ifnull(mr.penalty_charges_completed_derived, 0))) as total_in_advance_derived"); + amountQueryString.append(" from m_loan ml INNER JOIN m_loan_repayment_schedule mr on mr.loan_id = ml.id"); + amountQueryString.append(" where ml.id=? and ml.loan_status_id = 300"); + amountQueryString.append(" and mr.duedate >= CURDATE() group by ml.id having"); + amountQueryString.append(" (SUM(ifnull(mr.principal_completed_derived, 0)) + "); + amountQueryString.append(" SUM(ifnull(mr.interest_completed_derived, 0)) + "); + amountQueryString.append("SUM(ifnull(mr.fee_charges_completed_derived, 0)) + "); + amountQueryString.append("SUM(ifnull(mr.penalty_charges_completed_derived, 0))) > 0) as totalOverpaid "); final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("la.id as id, la.account_no as accountNo, la.external_id as externalId, "); @@ -365,8 +365,8 @@ public class PortfolioAccountReadPlatformServiceImpl implements PortfolioAccount final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMulitplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); final BigDecimal amtForTransfer = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalOverpaid"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMulitplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMulitplesOf, currencyDisplaySymbol, + currencyNameCode); return new PortfolioAccountData(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, currency, amtForTransfer); @@ -376,20 +376,21 @@ public class PortfolioAccountReadPlatformServiceImpl implements PortfolioAccount @Override public PortfolioAccountData retrieveOneByPaidInAdvance(Long accountId, Integer accountTypeId) { // TODO Auto-generated method stub - Object[] sqlParams = new Object[] { accountId , accountId}; + Object[] sqlParams = new Object[] { accountId, accountId }; PortfolioAccountData accountData = null; - //String currencyCode = null; + // String currencyCode = null; try { String sql = null; - //final PortfolioAccountType accountType = PortfolioAccountType.fromInt(accountTypeId); + // final PortfolioAccountType accountType = + // PortfolioAccountType.fromInt(accountTypeId); - sql = "select " + this.accountRefundByTransferMapper.schema() + " where la.id = ?"; - /* if (currencyCode != null) { - sql += " and la.currency_code = ?"; - sqlParams = new Object[] {accountId , accountId,currencyCode }; - }*/ + sql = "select " + this.accountRefundByTransferMapper.schema() + " where la.id = ?"; + /* + * if (currencyCode != null) { sql += " and la.currency_code = ?"; + * sqlParams = new Object[] {accountId , accountId,currencyCode }; } + */ - accountData = this.jdbcTemplate.queryForObject(sql, this.accountRefundByTransferMapper, sqlParams); + accountData = this.jdbcTemplate.queryForObject(sql, this.accountRefundByTransferMapper, sqlParams); } catch (final EmptyResultDataAccessException e) { throw new AccountTransferNotFoundException(accountId); @@ -397,4 +398,4 @@ public class PortfolioAccountReadPlatformServiceImpl implements PortfolioAccount return accountData; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformService.java old mode 100755 new mode 100644 index 3fdf79652..7bedc6d77 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformService.java @@ -26,4 +26,4 @@ public interface StandingInstructionHistoryReadPlatformService { Page retrieveAll(StandingInstructionDTO standingInstructionDTO); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 37cedbaa0..dc64d4ce4 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionHistoryReadPlatformServiceImpl.java @@ -59,8 +59,7 @@ public class StandingInstructionHistoryReadPlatformServiceImpl implements Standi private final PaginationHelper paginationHelper = new PaginationHelper<>(); @Autowired - public StandingInstructionHistoryReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + public StandingInstructionHistoryReadPlatformServiceImpl(final RoutingDataSource dataSource, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.standingInstructionHistoryMapper = new StandingInstructionHistoryMapper(); this.columnValidator = columnValidator; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformService.java old mode 100755 new mode 100644 index d3d680981..ab328ce79 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformService.java @@ -37,4 +37,4 @@ public interface StandingInstructionReadPlatformService { StandingInstructionDuesData retriveLoanDuesData(Long loanId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 620ac96ff..42110322d --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformServiceImpl.java @@ -87,8 +87,7 @@ public class StandingInstructionReadPlatformServiceImpl implements StandingInstr public StandingInstructionReadPlatformServiceImpl(final RoutingDataSource dataSource, final ClientReadPlatformService clientReadPlatformService, final OfficeReadPlatformService officeReadPlatformService, final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService, - final DropdownReadPlatformService dropdownReadPlatformService, - final ColumnValidator columnValidator) { + final DropdownReadPlatformService dropdownReadPlatformService, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.clientReadPlatformService = clientReadPlatformService; this.officeReadPlatformService = officeReadPlatformService; @@ -215,14 +214,12 @@ public class StandingInstructionReadPlatformServiceImpl implements StandingInstr } final Collection transferTypeOptions = Arrays.asList(transferType(AccountTransferType.ACCOUNT_TRANSFER), - transferType(AccountTransferType.LOAN_REPAYMENT)/* - * , - * transferType( - * AccountTransferType - * . - * CHARGE_PAYMENT - * ) - */); + transferType( + AccountTransferType.LOAN_REPAYMENT)/* + * , transferType( + * AccountTransferType + * . CHARGE_PAYMENT ) + */); final Collection statusOptions = Arrays.asList(standingInstructionStatus(StandingInstructionStatus.ACTIVE), standingInstructionStatus(StandingInstructionStatus.DISABLED)); final Collection instructionTypeOptions = Arrays.asList(standingInstructionType(StandingInstructionType.FIXED), @@ -337,8 +334,8 @@ public class StandingInstructionReadPlatformServiceImpl implements StandingInstr final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select "); sqlBuilder.append(this.standingInstructionMapper.schema()); - sqlBuilder - .append(" where atsi.status=? and CURRENT_DATE() >= atsi.valid_from and (atsi.valid_till IS NULL or CURRENT_DATE() < atsi.valid_till) ") + sqlBuilder.append( + " where atsi.status=? and CURRENT_DATE() >= atsi.valid_from and (atsi.valid_till IS NULL or CURRENT_DATE() < atsi.valid_till) ") .append(" and (atsi.last_run_date <> CURRENT_DATE() or atsi.last_run_date IS NULL)") .append(" ORDER BY atsi.priority DESC"); return this.jdbcTemplate.query(sqlBuilder.toString(), this.standingInstructionMapper, status); @@ -574,8 +571,8 @@ public class StandingInstructionReadPlatformServiceImpl implements StandingInstr final BigDecimal penaltyChargesPaid = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "penalityCompleted"); final BigDecimal penaltyChargesWrittenOff = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "penaltyWrittenOff"); final BigDecimal penaltyChargesWaived = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "penaltyWaived"); - final BigDecimal penaltyChargesActualDue = penaltyChargesExpectedDue.subtract(penaltyChargesWaived).subtract( - penaltyChargesWrittenOff); + final BigDecimal penaltyChargesActualDue = penaltyChargesExpectedDue.subtract(penaltyChargesWaived) + .subtract(penaltyChargesWrittenOff); final BigDecimal penaltyChargesOutstanding = penaltyChargesActualDue.subtract(penaltyChargesPaid); final BigDecimal feeChargesExpectedDue = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "feeAmount"); @@ -592,4 +589,4 @@ public class StandingInstructionReadPlatformServiceImpl implements StandingInstr } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionWritePlatformService.java old mode 100755 new mode 100644 index 922f8b07b..0b3f60b55 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionWritePlatformService.java @@ -32,4 +32,4 @@ public interface StandingInstructionWritePlatformService { CommandProcessingResult delete(Long id); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionWritePlatformServiceImpl.java old mode 100755 new mode 100644 index eebc50717..331d5cd79 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionWritePlatformServiceImpl.java @@ -143,8 +143,8 @@ public class StandingInstructionWritePlatformServiceImpl implements StandingInst final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("name")) { final String name = command.stringValueOfParameterNamed(StandingInstructionApiConstants.nameParamName); - throw new PlatformDataIntegrityException("error.msg.standinginstruction.duplicate.name", "Standinginstruction with name `" - + name + "` already exists", "name", name); + throw new PlatformDataIntegrityException("error.msg.standinginstruction.duplicate.name", + "Standinginstruction with name `" + name + "` already exists", "name", name); } LOG.error("Error occured.", dve); throw new PlatformDataIntegrityException("error.msg.client.unknown.data.integrity.issue", @@ -159,7 +159,8 @@ public class StandingInstructionWritePlatformServiceImpl implements StandingInst return fromAccountType.isSavingsAccount() && toAccountType.isLoanAccount(); } - private boolean isSavingsToSavingsAccountTransfer(final PortfolioAccountType fromAccountType, final PortfolioAccountType toAccountType) { + private boolean isSavingsToSavingsAccountTransfer(final PortfolioAccountType fromAccountType, + final PortfolioAccountType toAccountType) { return fromAccountType.isSavingsAccount() && toAccountType.isSavingsAccount(); } @@ -169,25 +170,19 @@ public class StandingInstructionWritePlatformServiceImpl implements StandingInst AccountTransferStandingInstruction standingInstructionsForUpdate = this.standingInstructionRepository.findById(id) .orElseThrow(() -> new StandingInstructionNotFoundException(id)); final Map actualChanges = standingInstructionsForUpdate.update(command); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withEntityId(id) - .with(actualChanges) - .build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(id).with(actualChanges).build(); } @Override public CommandProcessingResult delete(final Long id) { AccountTransferStandingInstruction standingInstructionsForUpdate = this.standingInstructionRepository.findById(id).get(); - // update the "deleted" and "name" properties of the standing instruction + // update the "deleted" and "name" properties of the standing + // instruction standingInstructionsForUpdate.delete(); final Map actualChanges = new HashMap<>(); actualChanges.put(statusParamName, StandingInstructionStatus.DELETED.getValue()); - return new CommandProcessingResultBuilder() - .withEntityId(id) - .with(actualChanges) - .build(); + return new CommandProcessingResultBuilder().withEntityId(id).with(actualChanges).build(); } @Override @@ -238,13 +233,13 @@ public class StandingInstructionWritePlatformServiceImpl implements StandingInst final boolean isRegularTransaction = true; final boolean isExceptionForBalanceCheck = false; AccountTransferDTO accountTransferDTO = new AccountTransferDTO(transactionDate, transactionAmount, data.fromAccountType(), - data.toAccountType(), data.fromAccount().accountId(), data.toAccount().accountId(), data.name() - + " Standing instruction trasfer ", null, null, null, null, data.toTransferType(), null, null, data - .transferType().getValue(), null, null, null, null, null, fromSavingsAccount, - isRegularTransaction, isExceptionForBalanceCheck); + data.toAccountType(), data.fromAccount().accountId(), data.toAccount().accountId(), + data.name() + " Standing instruction trasfer ", null, null, null, null, data.toTransferType(), null, null, + data.transferType().getValue(), null, null, null, null, null, fromSavingsAccount, isRegularTransaction, + isExceptionForBalanceCheck); final boolean transferCompleted = transferAmount(errors, accountTransferDTO, data.getId()); - if(transferCompleted){ + if (transferCompleted) { final String updateQuery = "UPDATE m_account_transfer_standing_instructions SET last_run_date = ? where id = ?"; this.jdbcTemplate.update(updateQuery, transactionDate.toDate(), data.getId()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/AccountSummaryCollectionData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/AccountSummaryCollectionData.java index b6c0fc46c..f7fd9f899 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/AccountSummaryCollectionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/AccountSummaryCollectionData.java @@ -29,40 +29,44 @@ public class AccountSummaryCollectionData { private final Collection loanAccounts; private final Collection groupLoanIndividualMonitoringAccounts; private final Collection savingsAccounts; - private final Collection shareAccounts ; + private final Collection shareAccounts; private final Collection guarantorAccounts; private final Collection memberLoanAccounts; private final Collection memberSavingsAccounts; private final Collection memberGuarantorAccounts; - - /* METHOD SIGNATURE CHANGE NOTICE: Method's signature - was changed for GLIM & GSIM implementation*/ - public AccountSummaryCollectionData(final Collection loanAccounts,final Collection groupLoanIndividualMonitoringAccounts, - final Collection savingsAccounts, final Collection shareAccounts,final Collection guarantorAccounts) - { + /* + * METHOD SIGNATURE CHANGE NOTICE: Method's signature was changed for GLIM & + * GSIM implementation + */ + public AccountSummaryCollectionData(final Collection loanAccounts, + final Collection groupLoanIndividualMonitoringAccounts, + final Collection savingsAccounts, final Collection shareAccounts, + final Collection guarantorAccounts) { this.loanAccounts = defaultLoanAccountsIfEmpty(loanAccounts); - this.groupLoanIndividualMonitoringAccounts=groupLoanIndividualMonitoringAccounts; + this.groupLoanIndividualMonitoringAccounts = groupLoanIndividualMonitoringAccounts; this.savingsAccounts = defaultSavingsAccountsIfEmpty(savingsAccounts); - this.shareAccounts = defaultShareAccountsIfEmpty(shareAccounts) ; + this.shareAccounts = defaultShareAccountsIfEmpty(shareAccounts); this.guarantorAccounts = guarantorAccounts; this.memberLoanAccounts = null; this.memberSavingsAccounts = null; this.memberGuarantorAccounts = null; } - public AccountSummaryCollectionData(final Collection loanAccounts,final Collection groupLoanIndividualMonitoringAccounts, - final Collection savingsAccounts, final Collection guarantorAccounts, final Collection memberLoanAccounts, - final Collection memberSavingsAccounts, final Collection memberGuarantorAccounts) { - /* Note to Self: GSIM not passed in*/ + public AccountSummaryCollectionData(final Collection loanAccounts, + final Collection groupLoanIndividualMonitoringAccounts, + final Collection savingsAccounts, final Collection guarantorAccounts, + final Collection memberLoanAccounts, final Collection memberSavingsAccounts, + final Collection memberGuarantorAccounts) { + /* Note to Self: GSIM not passed in */ this.loanAccounts = defaultLoanAccountsIfEmpty(loanAccounts); - this.groupLoanIndividualMonitoringAccounts=groupLoanIndividualMonitoringAccounts; + this.groupLoanIndividualMonitoringAccounts = groupLoanIndividualMonitoringAccounts; this.savingsAccounts = defaultSavingsAccountsIfEmpty(savingsAccounts); this.guarantorAccounts = guarantorAccounts; - this.shareAccounts = null ; + this.shareAccounts = null; this.memberLoanAccounts = defaultLoanAccountsIfEmpty(memberLoanAccounts); this.memberSavingsAccounts = defaultSavingsAccountsIfEmpty(memberSavingsAccounts); this.memberGuarantorAccounts = defaultGuarantorAccountsIfEmpty(memberGuarantorAccounts); @@ -92,11 +96,12 @@ public class AccountSummaryCollectionData { return returnCollection; } - private Collection defaultGuarantorAccountsIfEmpty(final Collection collection) { + private Collection defaultGuarantorAccountsIfEmpty( + final Collection collection) { Collection returnCollection = null; if (collection != null && !collection.isEmpty()) { returnCollection = collection; } return returnCollection; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/GuarantorAccountSummaryData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/GuarantorAccountSummaryData.java index 5ac6ce18f..914b9b263 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/GuarantorAccountSummaryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/GuarantorAccountSummaryData.java @@ -44,10 +44,12 @@ public class GuarantorAccountSummaryData { private final Boolean isActive; private final String relationship; private final BigDecimal onHoldAmount; + public GuarantorAccountSummaryData(final Long id, final String accountNo, final String externalId, final Long productId, - final String loanProductName, final String shortLoanProductName, final LoanStatusEnumData loanStatus, final EnumOptionData loanType, final Integer loanCycle, - final Boolean inArrears,final BigDecimal originalLoan,final BigDecimal loanBalance,final BigDecimal amountPaid, - final Boolean isActive, final String relationship, final BigDecimal onHoldAmount) { + final String loanProductName, final String shortLoanProductName, final LoanStatusEnumData loanStatus, + final EnumOptionData loanType, final Integer loanCycle, final Boolean inArrears, final BigDecimal originalLoan, + final BigDecimal loanBalance, final BigDecimal amountPaid, final Boolean isActive, final String relationship, + final BigDecimal onHoldAmount) { this.id = id; this.accountNo = accountNo; this.externalId = externalId; @@ -65,4 +67,4 @@ public class GuarantorAccountSummaryData { this.relationship = relationship; this.onHoldAmount = onHoldAmount; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/LoanAccountSummaryData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/LoanAccountSummaryData.java index 29edf5aa1..3d24ef513 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/LoanAccountSummaryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/LoanAccountSummaryData.java @@ -46,11 +46,12 @@ public class LoanAccountSummaryData { private final BigDecimal amountPaid; public LoanAccountSummaryData(final Long id, final String accountNo, final String externalId, final Long productId, - final String loanProductName, final String shortLoanProductName, final LoanStatusEnumData loanStatus, final EnumOptionData loanType, final Integer loanCycle, - final LoanApplicationTimelineData timeline, final Boolean inArrears,final BigDecimal originalLoan,final BigDecimal loanBalance,final BigDecimal amountPaid) { + final String loanProductName, final String shortLoanProductName, final LoanStatusEnumData loanStatus, + final EnumOptionData loanType, final Integer loanCycle, final LoanApplicationTimelineData timeline, final Boolean inArrears, + final BigDecimal originalLoan, final BigDecimal loanBalance, final BigDecimal amountPaid) { this.id = id; this.accountNo = accountNo; - this.parentAccountNumber=null; + this.parentAccountNumber = null; this.externalId = externalId; this.productId = productId; this.productName = loanProductName; @@ -65,13 +66,13 @@ public class LoanAccountSummaryData { this.amountPaid = amountPaid; } - - public LoanAccountSummaryData(final Long id, final String accountNo,final String parentAccountNumber, final String externalId, final Long productId, - final String loanProductName, final String shortLoanProductName, final LoanStatusEnumData loanStatus, final EnumOptionData loanType, final Integer loanCycle, - final LoanApplicationTimelineData timeline, final Boolean inArrears,final BigDecimal originalLoan,final BigDecimal loanBalance,final BigDecimal amountPaid) { + public LoanAccountSummaryData(final Long id, final String accountNo, final String parentAccountNumber, final String externalId, + final Long productId, final String loanProductName, final String shortLoanProductName, final LoanStatusEnumData loanStatus, + final EnumOptionData loanType, final Integer loanCycle, final LoanApplicationTimelineData timeline, final Boolean inArrears, + final BigDecimal originalLoan, final BigDecimal loanBalance, final BigDecimal amountPaid) { this.id = id; this.accountNo = accountNo; - this.parentAccountNumber=parentAccountNumber; + this.parentAccountNumber = parentAccountNumber; this.externalId = externalId; this.productId = productId; this.productName = loanProductName; @@ -85,4 +86,4 @@ public class LoanAccountSummaryData { this.originalLoan = originalLoan; this.amountPaid = amountPaid; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/SavingsAccountSummaryData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/SavingsAccountSummaryData.java index 73e3793b4..c3a2faf23 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/SavingsAccountSummaryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/SavingsAccountSummaryData.java @@ -41,19 +41,19 @@ public class SavingsAccountSummaryData { private final SavingsAccountStatusEnumData status; private final CurrencyData currency; private final BigDecimal accountBalance; - //differentiate Individual, JLG or Group account + // differentiate Individual, JLG or Group account private final EnumOptionData accountType; private final SavingsAccountApplicationTimelineData timeline; private final SavingsAccountSubStatusEnumData subStatus; private final LocalDate lastActiveTransactionDate; - //differentiate deposit accounts Savings, FD and RD accounts + // differentiate deposit accounts Savings, FD and RD accounts private final EnumOptionData depositType; public SavingsAccountSummaryData(final Long id, final String accountNo, final String externalId, final Long productId, final String productName, final String shortProductName, final SavingsAccountStatusEnumData status, final CurrencyData currency, - final BigDecimal accountBalance, final EnumOptionData accountType, final SavingsAccountApplicationTimelineData timeline, final EnumOptionData depositType, - final SavingsAccountSubStatusEnumData subStatus, final LocalDate lastActiveTransactionDate) { + final BigDecimal accountBalance, final EnumOptionData accountType, final SavingsAccountApplicationTimelineData timeline, + final EnumOptionData depositType, final SavingsAccountSubStatusEnumData subStatus, final LocalDate lastActiveTransactionDate) { this.id = id; this.accountNo = accountNo; this.externalId = externalId; @@ -77,4 +77,4 @@ public class SavingsAccountSummaryData { public Long getId() { return id; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/SavingsSummaryCustom.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/SavingsSummaryCustom.java index 5805508b9..4f114111c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/SavingsSummaryCustom.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/SavingsSummaryCustom.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.fineract.portfolio.accountdetails.data; import java.math.BigDecimal; @@ -28,10 +27,9 @@ import org.apache.fineract.portfolio.savings.data.SavingsAccountStatusEnumData; import org.apache.fineract.portfolio.savings.data.SavingsAccountSubStatusEnumData; import org.joda.time.LocalDate; - @SuppressWarnings("unused") -public class SavingsSummaryCustom - { +public class SavingsSummaryCustom { + private final Long id; private final String displayName; private final String accountNo; @@ -42,21 +40,22 @@ public class SavingsSummaryCustom private final SavingsAccountStatusEnumData status; private final CurrencyData currency; private final BigDecimal accountBalance; - //differentiate Individual, JLG or Group account + // differentiate Individual, JLG or Group account private final EnumOptionData accountType; private final SavingsAccountApplicationTimelineData timeline; private final SavingsAccountSubStatusEnumData subStatus; private final LocalDate lastActiveTransactionDate; - //differentiate deposit accounts Savings, FD and RD accounts + // differentiate deposit accounts Savings, FD and RD accounts private final EnumOptionData depositType; - public SavingsSummaryCustom(final Long id,final String displayName, final String accountNo, final String externalId, final Long productId, - final String productName, final String shortProductName, final SavingsAccountStatusEnumData status, final CurrencyData currency, - final BigDecimal accountBalance, final EnumOptionData accountType, final SavingsAccountApplicationTimelineData timeline, final EnumOptionData depositType, + public SavingsSummaryCustom(final Long id, final String displayName, final String accountNo, final String externalId, + final Long productId, final String productName, final String shortProductName, final SavingsAccountStatusEnumData status, + final CurrencyData currency, final BigDecimal accountBalance, final EnumOptionData accountType, + final SavingsAccountApplicationTimelineData timeline, final EnumOptionData depositType, final SavingsAccountSubStatusEnumData subStatus, final LocalDate lastActiveTransactionDate) { this.id = id; - this.displayName=displayName; + this.displayName = displayName; this.accountNo = accountNo; this.externalId = externalId; this.productId = productId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/ShareAccountSummaryData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/ShareAccountSummaryData.java index fab68f5cc..b85dc97fa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/ShareAccountSummaryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/data/ShareAccountSummaryData.java @@ -38,24 +38,20 @@ public class ShareAccountSummaryData implements Serializable { private final CurrencyData currency; private final ShareAccountApplicationTimelineData timeline; - public ShareAccountSummaryData(final Long id, final String accountNo, - final String externalId, final Long productId, - final String productName, final String shortProductName, - final ShareAccountStatusEnumData status, - final CurrencyData currency, final Long approvedShares, - final Long pendingForApprovalShares, - final ShareAccountApplicationTimelineData timeline) { + public ShareAccountSummaryData(final Long id, final String accountNo, final String externalId, final Long productId, + final String productName, final String shortProductName, final ShareAccountStatusEnumData status, final CurrencyData currency, + final Long approvedShares, final Long pendingForApprovalShares, final ShareAccountApplicationTimelineData timeline) { this.id = id; this.accountNo = accountNo; this.externalId = externalId; - if(approvedShares == null) { - this.totalApprovedShares = Long.valueOf(0) ; - }else { + if (approvedShares == null) { + this.totalApprovedShares = Long.valueOf(0); + } else { this.totalApprovedShares = approvedShares; } - if(pendingForApprovalShares == null) { - this.totalPendingForApprovalShares = Long.valueOf(0) ; - }else { + if (pendingForApprovalShares == null) { + this.totalPendingForApprovalShares = Long.valueOf(0); + } else { this.totalPendingForApprovalShares = pendingForApprovalShares; } this.productId = productId; @@ -66,7 +62,6 @@ public class ShareAccountSummaryData implements Serializable { this.timeline = timeline; } - public String getAccountNo() { return this.accountNo; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/domain/AccountType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/domain/AccountType.java index 450282fe5..387a53e44 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/domain/AccountType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/domain/AccountType.java @@ -26,9 +26,8 @@ public enum AccountType { INVALID(0, "accountType.invalid"), // INDIVIDUAL(1, "accountType.individual"), // GROUP(2, "accountType.group"), // - JLG(3, "accountType.jlg"),// JLG account given in group context - GLIM(4, "accountType.glim"), - GSIM(5, "accountType.gsim"); + JLG(3, "accountType.jlg"), // JLG account given in group context + GLIM(4, "accountType.glim"), GSIM(5, "accountType.gsim"); private final Integer value; private final String code; @@ -107,4 +106,4 @@ public enum AccountType { public boolean isGSIMAccount() { return this.value.equals(AccountType.GSIM.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountDetailsReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountDetailsReadPlatformService.java old mode 100755 new mode 100644 index 6e99ff417..5cdb0c33e --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountDetailsReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountDetailsReadPlatformService.java @@ -35,7 +35,7 @@ public interface AccountDetailsReadPlatformService { public Collection retrieveClientActiveLoanAccountSummary(final Long clientId); - public List retrieveLoanAccountDetailsByGroupIdAndGlimAccountNumber(Long groupId,final String glimAccount); + public List retrieveLoanAccountDetailsByGroupIdAndGlimAccountNumber(Long groupId, final String glimAccount); public Collection retrieveGroupActiveLoanAccountSummary(final Long groupId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountDetailsReadPlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountDetailsReadPlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index ff00b1711..a7f2117f1 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountDetailsReadPlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountDetailsReadPlatformServiceJpaRepositoryImpl.java @@ -74,9 +74,11 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou // Check if client exists this.clientReadPlatformService.retrieveOne(clientId); final String loanwhereClause = " where l.client_id = ?"; - final String glimLoanClause=" where l.client_id = ? and l.loan_type_enum=4"; + final String glimLoanClause = " where l.client_id = ? and l.loan_type_enum=4"; - //note to self: investigate the effect of have loans stored as another type especially given that we want to maintain how the system currently handles loans of exisiting types. + // note to self: investigate the effect of have loans stored as another + // type especially given that we want to maintain how the system + // currently handles loans of exisiting types. final String savingswhereClause = " where sa.client_id = ? order by sa.status_enum ASC, sa.account_no ASC"; final String guarantorWhereClause = " where g.entity_id = ? and g.is_active = 1 order by l.account_no ASC"; @@ -84,10 +86,10 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final List glimAccounts = retrieveLoanAccountDetails(glimLoanClause, new Object[] { clientId }); final List loanAccounts = retrieveLoanAccountDetails(loanwhereClause, new Object[] { clientId }); final List savingsAccounts = retrieveAccountDetails(savingswhereClause, new Object[] { clientId }); - final List shareAccounts = retrieveShareAccountDetails(clientId) ; - final List guarantorloanAccounts = retrieveGuarantorLoanAccountDetails( - guarantorWhereClause, new Object[] { clientId }); - return new AccountSummaryCollectionData(loanAccounts,glimAccounts, savingsAccounts, shareAccounts,guarantorloanAccounts); + final List shareAccounts = retrieveShareAccountDetails(clientId); + final List guarantorloanAccounts = retrieveGuarantorLoanAccountDetails(guarantorWhereClause, + new Object[] { clientId }); + return new AccountSummaryCollectionData(loanAccounts, glimAccounts, savingsAccounts, shareAccounts, guarantorloanAccounts); } @Override @@ -102,9 +104,11 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final String guarantorWhereClauseForGroup = " where l.group_id = ? and l.client_id is null and g.is_active = 1 order by l.account_no ASC"; final String guarantorWhereClauseForMembers = " where l.group_id = ? and l.client_id is not null and g.is_active = 1 order by l.account_no ASC"; - final List glimAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new Object[] { groupId }); + final List glimAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, + new Object[] { groupId }); - final List groupLoanAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroup, new Object[] { groupId }); + final List groupLoanAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroup, + new Object[] { groupId }); final List groupSavingsAccounts = retrieveAccountDetails(savingswhereClauseForGroup, new Object[] { groupId }); final List groupGuarantorloanAccounts = retrieveGuarantorLoanAccountDetails( @@ -115,13 +119,14 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou new Object[] { groupId }); final List memberGuarantorloanAccounts = retrieveGuarantorLoanAccountDetails( - guarantorWhereClauseForMembers, new Object[] { groupId }); - return new AccountSummaryCollectionData(groupLoanAccounts,glimAccounts, groupSavingsAccounts, groupGuarantorloanAccounts, memberLoanAccounts, memberSavingsAccounts, memberGuarantorloanAccounts); + guarantorWhereClauseForMembers, new Object[] { groupId }); + return new AccountSummaryCollectionData(groupLoanAccounts, glimAccounts, groupSavingsAccounts, groupGuarantorloanAccounts, + memberLoanAccounts, memberSavingsAccounts, memberGuarantorloanAccounts); } @Override - public AccountSummaryCollectionData retrieveGroupAccountDetails(final Long groupId,final Long gsimId) { + public AccountSummaryCollectionData retrieveGroupAccountDetails(final Long groupId, final Long gsimId) { // Check if group exists this.groupReadPlatformService.retrieveOne(groupId); final String loanWhereClauseForGroup = " where l.group_id = ? and l.client_id is null"; @@ -130,15 +135,18 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final String savingswhereClauseForGroup = " where sa.group_id = ? and sa.gsim_id = ? sa.client_id is null order by sa.status_enum ASC, sa.account_no ASC"; final String savingswhereClauseForMembers = " where sa.group_id = ? and sa.client_id is not null order by sa.status_enum ASC, sa.account_no ASC"; - final List glimAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new Object[] { groupId }); - final List groupLoanAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroup, new Object[] { groupId }); + final List glimAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, + new Object[] { groupId }); + final List groupLoanAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroup, + new Object[] { groupId }); final List gsimSavingsAccounts = retrieveAccountDetails(savingswhereClauseForGroup, - new Object[] { groupId,gsimId }); + new Object[] { groupId, gsimId }); final List memberLoanAccounts = retrieveLoanAccountDetails(loanWhereClauseForMembers, new Object[] { groupId }); final List memberSavingsAccounts = retrieveAccountDetails(savingswhereClauseForMembers, new Object[] { groupId }); - return new AccountSummaryCollectionData(groupLoanAccounts, glimAccounts,gsimSavingsAccounts, null,memberLoanAccounts, memberSavingsAccounts,null); + return new AccountSummaryCollectionData(groupLoanAccounts, glimAccounts, gsimSavingsAccounts, null, memberLoanAccounts, + memberSavingsAccounts, null); } @Override @@ -164,12 +172,14 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou } @Override - public List retrieveLoanAccountDetailsByGroupIdAndGlimAccountNumber(final Long groupId,final String glimAccount) { + public List retrieveLoanAccountDetailsByGroupIdAndGlimAccountNumber(final Long groupId, + final String glimAccount) { final LoanAccountSummaryDataMapper rm = new LoanAccountSummaryDataMapper(); final String loanWhereClauseForGroupAndLoanType = " where l.group_id =? and glim.account_number=? and l.loan_type_enum=4"; final String sql = "select " + rm.loanAccountSummarySchema() + loanWhereClauseForGroupAndLoanType; - // this.columnValidator.validateSqlInjection(rm.loanAccountSummarySchema(), loanWhereClauseForGroupAndLoanType); - return this.jdbcTemplate.query(sql, rm, new Object[]{groupId , glimAccount}); + // this.columnValidator.validateSqlInjection(rm.loanAccountSummarySchema(), + // loanWhereClauseForGroupAndLoanType); + return this.jdbcTemplate.query(sql, rm, new Object[] { groupId, glimAccount }); } @Override @@ -178,7 +188,6 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou return retrieveLoanAccountDetails(loanWhereClause, new Object[] { groupId }); } - private List retrieveLoanAccountDetails(final String loanwhereClause, final Object[] inputs) { final LoanAccountSummaryDataMapper rm = new LoanAccountSummaryDataMapper(); final String sql = "select " + rm.loanAccountSummarySchema() + loanwhereClause; @@ -193,61 +202,58 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou private List retrieveAccountDetails(final String savingswhereClause, final Object[] inputs) { final SavingsAccountSummaryDataMapper savingsAccountSummaryDataMapper = new SavingsAccountSummaryDataMapper(); final String savingsSql = "select " + savingsAccountSummaryDataMapper.schema() + savingswhereClause; - this.columnValidator.validateSqlInjection(savingsAccountSummaryDataMapper.schema() , savingswhereClause); + this.columnValidator.validateSqlInjection(savingsAccountSummaryDataMapper.schema(), savingswhereClause); return this.jdbcTemplate.query(savingsSql, savingsAccountSummaryDataMapper, inputs); } private List retrieveShareAccountDetails(final Long clientId) { - final ShareAccountSummaryDataMapper mapper = new ShareAccountSummaryDataMapper() ; - final String query = "select " + mapper.schema() + " where sa.client_id = ?" ; - return this.jdbcTemplate.query(query, mapper, new Object [] {clientId}); + final ShareAccountSummaryDataMapper mapper = new ShareAccountSummaryDataMapper(); + final String query = "select " + mapper.schema() + " where sa.client_id = ?"; + return this.jdbcTemplate.query(query, mapper, new Object[] { clientId }); } - private List retrieveGuarantorLoanAccountDetails( - final String loanwhereClause, final Object[] inputs) { + private List retrieveGuarantorLoanAccountDetails(final String loanwhereClause, final Object[] inputs) { final GuarantorLoanAccountSummaryDataMapper rm = new GuarantorLoanAccountSummaryDataMapper(); - final String sql = "select " + rm.guarantorLoanAccountSummarySchema() - + loanwhereClause; + final String sql = "select " + rm.guarantorLoanAccountSummarySchema() + loanwhereClause; return this.jdbcTemplate.query(sql, rm, inputs); } private final static class ShareAccountSummaryDataMapper implements RowMapper { - private final String schema ; + private final String schema; ShareAccountSummaryDataMapper() { final StringBuilder buff = new StringBuilder() - .append("sa.id as id, sa.external_id as externalId, sa.status_enum as statusEnum, ") - .append("sa.account_no as accountNo, sa.total_approved_shares as approvedShares, sa.total_pending_shares as pendingShares, ") - .append("sa.savings_account_id as savingsAccountNo, sa.minimum_active_period_frequency as minimumactivePeriod,") - .append("sa.minimum_active_period_frequency_enum as minimumactivePeriodEnum,") - .append("sa.lockin_period_frequency as lockinPeriod, sa.lockin_period_frequency_enum as lockinPeriodEnum, ") - .append("sa.submitted_date as submittedDate, sbu.username as submittedByUsername, ") - .append("sbu.firstname as submittedByFirstname, sbu.lastname as submittedByLastname, ") - .append("sa.rejected_date as rejectedDate, rbu.username as rejectedByUsername, ") - .append("rbu.firstname as rejectedByFirstname, rbu.lastname as rejectedByLastname, ") - .append("sa.approved_date as approvedDate, abu.username as approvedByUsername, ") - .append("abu.firstname as approvedByFirstname, abu.lastname as approvedByLastname, ") - .append("sa.activated_date as activatedDate, avbu.username as activatedByUsername, ") - .append("avbu.firstname as activatedByFirstname, avbu.lastname as activatedByLastname, ") - .append("sa.closed_date as closedDate, cbu.username as closedByUsername, ") - .append("cbu.firstname as closedByFirstname, cbu.lastname as closedByLastname, ") - .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, ") - .append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ") - .append("curr.display_symbol as currencyDisplaySymbol, sa.product_id as productId, p.name as productName, p.short_name as shortProductName ") - .append("from m_share_account sa ") - .append("join m_share_product as p on p.id = sa.product_id ") - .append("join m_currency curr on curr.code = sa.currency_code ") - .append("left join m_appuser sbu on sbu.id = sa.submitted_userid ") - .append("left join m_appuser rbu on rbu.id = sa.rejected_userid ") - .append("left join m_appuser abu on abu.id = sa.approved_userid ") - .append("left join m_appuser avbu on avbu.id = sa.activated_userid ") - .append("left join m_appuser cbu on cbu.id = sa.closed_userid ") ; - schema = buff.toString() ; + .append("sa.id as id, sa.external_id as externalId, sa.status_enum as statusEnum, ") + .append("sa.account_no as accountNo, sa.total_approved_shares as approvedShares, sa.total_pending_shares as pendingShares, ") + .append("sa.savings_account_id as savingsAccountNo, sa.minimum_active_period_frequency as minimumactivePeriod,") + .append("sa.minimum_active_period_frequency_enum as minimumactivePeriodEnum,") + .append("sa.lockin_period_frequency as lockinPeriod, sa.lockin_period_frequency_enum as lockinPeriodEnum, ") + .append("sa.submitted_date as submittedDate, sbu.username as submittedByUsername, ") + .append("sbu.firstname as submittedByFirstname, sbu.lastname as submittedByLastname, ") + .append("sa.rejected_date as rejectedDate, rbu.username as rejectedByUsername, ") + .append("rbu.firstname as rejectedByFirstname, rbu.lastname as rejectedByLastname, ") + .append("sa.approved_date as approvedDate, abu.username as approvedByUsername, ") + .append("abu.firstname as approvedByFirstname, abu.lastname as approvedByLastname, ") + .append("sa.activated_date as activatedDate, avbu.username as activatedByUsername, ") + .append("avbu.firstname as activatedByFirstname, avbu.lastname as activatedByLastname, ") + .append("sa.closed_date as closedDate, cbu.username as closedByUsername, ") + .append("cbu.firstname as closedByFirstname, cbu.lastname as closedByLastname, ") + .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, ") + .append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ") + .append("curr.display_symbol as currencyDisplaySymbol, sa.product_id as productId, p.name as productName, p.short_name as shortProductName ") + .append("from m_share_account sa ").append("join m_share_product as p on p.id = sa.product_id ") + .append("join m_currency curr on curr.code = sa.currency_code ") + .append("left join m_appuser sbu on sbu.id = sa.submitted_userid ") + .append("left join m_appuser rbu on rbu.id = sa.rejected_userid ") + .append("left join m_appuser abu on abu.id = sa.approved_userid ") + .append("left join m_appuser avbu on avbu.id = sa.activated_userid ") + .append("left join m_appuser cbu on cbu.id = sa.closed_userid "); + schema = buff.toString(); } + @Override - public ShareAccountSummaryData mapRow(ResultSet rs, int rowNum) - throws SQLException { + public ShareAccountSummaryData mapRow(ResultSet rs, int rowNum) throws SQLException { final Long id = JdbcSupport.getLong(rs, "id"); final String accountNo = rs.getString("accountNo"); @@ -258,15 +264,15 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final String productName = rs.getString("productName"); final String shortProductName = rs.getString("shortProductName"); final Integer statusId = JdbcSupport.getInteger(rs, "statusEnum"); - final ShareAccountStatusEnumData status = SharesEnumerations.status(statusId) ; + final ShareAccountStatusEnumData status = SharesEnumerations.status(statusId); 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 Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final LocalDate submittedOnDate = JdbcSupport.getLocalDate(rs, "submittedDate"); final String submittedByUsername = rs.getString("submittedByUsername"); @@ -294,8 +300,8 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final String closedByLastname = rs.getString("closedByLastname"); final ShareAccountApplicationTimelineData timeline = new ShareAccountApplicationTimelineData(submittedOnDate, - submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, - rejectedByFirstname, rejectedByLastname, approvedOnDate, approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, + submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, rejectedByFirstname, + rejectedByLastname, approvedOnDate, approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, closedByLastname); @@ -304,9 +310,10 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou } public String schema() { - return this.schema ; + return this.schema; } } + private static final class SavingsAccountSummaryDataMapper implements RowMapper { final String schemaSql; @@ -348,8 +355,8 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou accountsSummary.append("cbu.username as closedByUsername,"); accountsSummary.append("cbu.firstname as closedByFirstname, cbu.lastname as closedByLastname,"); - accountsSummary - .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); + accountsSummary.append( + "sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); accountsSummary.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); accountsSummary.append("curr.display_symbol as currencyDisplaySymbol, "); accountsSummary.append("sa.product_id as productId, p.name as productName, p.short_name as shortProductName, "); @@ -394,8 +401,8 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final LocalDate submittedOnDate = JdbcSupport.getLocalDate(rs, "submittedOnDate"); final String submittedByUsername = rs.getString("submittedByUsername"); @@ -432,14 +439,13 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final LocalDate lastActiveTransactionDate = JdbcSupport.getLocalDate(rs, "lastActiveTransactionDate"); final SavingsAccountApplicationTimelineData timeline = new SavingsAccountApplicationTimelineData(submittedOnDate, - submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, - rejectedByFirstname, rejectedByLastname, withdrawnOnDate, withdrawnByUsername, withdrawnByFirstname, - withdrawnByLastname, approvedOnDate, approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, - activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, - closedByLastname); + submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, rejectedByFirstname, + rejectedByLastname, withdrawnOnDate, withdrawnByUsername, withdrawnByFirstname, withdrawnByLastname, approvedOnDate, + approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, activatedByUsername, activatedByFirstname, + activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, closedByLastname); - return new SavingsAccountSummaryData(id, accountNo, externalId, productId, productName, shortProductName, status, currency, accountBalance, - accountTypeData, timeline, depositTypeData, subStatus, lastActiveTransactionDate); + return new SavingsAccountSummaryData(id, accountNo, externalId, productId, productName, shortProductName, status, currency, + accountBalance, accountTypeData, timeline, depositTypeData, subStatus, lastActiveTransactionDate); } } @@ -448,14 +454,12 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou public String loanAccountSummarySchema() { final StringBuilder accountsSummary = new StringBuilder("l.id as id, l.account_no as accountNo, l.external_id as externalId,"); - accountsSummary - .append(" l.product_id as productId, lp.name as productName, lp.short_name as shortProductName,") + accountsSummary.append(" l.product_id as productId, lp.name as productName, lp.short_name as shortProductName,") .append(" l.loan_status_id as statusId, l.loan_type_enum as loanType,") .append(" glim.account_number as parentAccountNumber,") - .append("l.principal_disbursed_derived as originalLoan,") - .append("l.total_outstanding_derived as loanBalance,") + .append("l.principal_disbursed_derived as originalLoan,").append("l.total_outstanding_derived as loanBalance,") .append("l.total_repayment_derived as amountPaid,") .append(" l.loan_product_counter as loanCycle,") @@ -498,7 +502,7 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final Long id = JdbcSupport.getLong(rs, "id"); final String accountNo = rs.getString("accountNo"); - final String parentAccountNumber=rs.getString("parentAccountNumber"); + final String parentAccountNumber = rs.getString("parentAccountNumber"); final String externalId = rs.getString("externalId"); final Long productId = JdbcSupport.getLong(rs, "productId"); final String loanProductName = rs.getString("productName"); @@ -540,9 +544,9 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final String closedByFirstname = rs.getString("closedByFirstname"); final String closedByLastname = rs.getString("closedByLastname"); - final BigDecimal originalLoan = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs,"originalLoan"); - final BigDecimal loanBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs,"loanBalance"); - final BigDecimal amountPaid = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs,"amountPaid"); + final BigDecimal originalLoan = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "originalLoan"); + final BigDecimal loanBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "loanBalance"); + final BigDecimal amountPaid = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "amountPaid"); final LocalDate writtenOffOnDate = JdbcSupport.getLocalDate(rs, "writtenOffOnDate"); @@ -561,99 +565,76 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou disbursedByFirstname, disbursedByLastname, closedOnDate, closedByUsername, closedByFirstname, closedByLastname, expectedMaturityDate, writtenOffOnDate, closedByUsername, closedByFirstname, closedByLastname); - return new LoanAccountSummaryData(id, accountNo,parentAccountNumber, externalId, productId, loanProductName, shortLoanProductName, loanStatus, loanType, loanCycle, - timeline, inArrears,originalLoan,loanBalance,amountPaid); + return new LoanAccountSummaryData(id, accountNo, parentAccountNumber, externalId, productId, loanProductName, + shortLoanProductName, loanStatus, loanType, loanCycle, timeline, inArrears, originalLoan, loanBalance, amountPaid); } } - private static final class GuarantorLoanAccountSummaryDataMapper implements - RowMapper { - public String guarantorLoanAccountSummarySchema() { + private static final class GuarantorLoanAccountSummaryDataMapper implements RowMapper { - final StringBuilder accountsSummary = new StringBuilder( - "l.id as id, l.account_no as accountNo, l.external_id as externalId,"); - accountsSummary - .append(" l.product_id as productId, lp.name as productName, lp.short_name as shortProductName,") - .append(" l.loan_status_id as statusId, l.loan_type_enum as loanType,") + public String guarantorLoanAccountSummarySchema() { - .append("l.principal_disbursed_derived as originalLoan,") - .append("l.total_outstanding_derived as loanBalance,") - .append("l.total_repayment_derived as amountPaid,") + final StringBuilder accountsSummary = new StringBuilder("l.id as id, l.account_no as accountNo, l.external_id as externalId,"); + accountsSummary.append(" l.product_id as productId, lp.name as productName, lp.short_name as shortProductName,") + .append(" l.loan_status_id as statusId, l.loan_type_enum as loanType,") - .append(" l.loan_product_counter as loanCycle,") + .append("l.principal_disbursed_derived as originalLoan,").append("l.total_outstanding_derived as loanBalance,") + .append("l.total_repayment_derived as amountPaid,") - .append(" l.submittedon_date as submittedOnDate,") + .append(" l.loan_product_counter as loanCycle,") - .append(" l.rejectedon_date as rejectedOnDate,") - .append(" l.withdrawnon_date as withdrawnOnDate,") - .append(" l.approvedon_date as approvedOnDate,") - .append(" l.expected_disbursedon_date as expectedDisbursementDate, l.disbursedon_date as actualDisbursementDate,") - .append(" l.closedon_date as closedOnDate,") - .append(" la.overdue_since_date_derived as overdueSinceDate,") - .append(" l.writtenoffon_date as writtenOffOnDate, l.expected_maturedon_date as expectedMaturityDate,") - .append(" g.is_active as isActive,") - .append(" cv.code_value as relationship,") - .append(" sa.on_hold_funds_derived") - .append(" from m_loan l ") - .append(" join m_guarantor as g on g.loan_id = l.id ") - .append(" join m_client as c on c.id = g.entity_id ") - .append(" LEFT JOIN m_product_loan AS lp ON lp.id = l.product_id") - .append(" left join m_loan_arrears_aging la on la.loan_id = l.id") - .append(" left join m_code_value cv ON cv.id = g.client_reln_cv_id") - .append(" left join m_savings_account sa on sa.client_id = c.id") + .append(" l.submittedon_date as submittedOnDate,") - ; + .append(" l.rejectedon_date as rejectedOnDate,").append(" l.withdrawnon_date as withdrawnOnDate,") + .append(" l.approvedon_date as approvedOnDate,") + .append(" l.expected_disbursedon_date as expectedDisbursementDate, l.disbursedon_date as actualDisbursementDate,") + .append(" l.closedon_date as closedOnDate,").append(" la.overdue_since_date_derived as overdueSinceDate,") + .append(" l.writtenoffon_date as writtenOffOnDate, l.expected_maturedon_date as expectedMaturityDate,") + .append(" g.is_active as isActive,").append(" cv.code_value as relationship,").append(" sa.on_hold_funds_derived") + .append(" from m_loan l ").append(" join m_guarantor as g on g.loan_id = l.id ") + .append(" join m_client as c on c.id = g.entity_id ").append(" LEFT JOIN m_product_loan AS lp ON lp.id = l.product_id") + .append(" left join m_loan_arrears_aging la on la.loan_id = l.id") + .append(" left join m_code_value cv ON cv.id = g.client_reln_cv_id") + .append(" left join m_savings_account sa on sa.client_id = c.id") - return accountsSummary.toString(); - } + ; - @Override - public GuarantorAccountSummaryData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { - - final Long id = JdbcSupport.getLong(rs, "id"); - final String accountNo = rs.getString("accountNo"); - final String externalId = rs.getString("externalId"); - final Long productId = JdbcSupport.getLong(rs, "productId"); - final String loanProductName = rs.getString("productName"); - final String shortLoanProductName = rs - .getString("shortProductName"); - final Integer loanStatusId = JdbcSupport.getInteger(rs, "statusId"); - final LoanStatusEnumData loanStatus = LoanEnumerations - .status(loanStatusId); - final Integer loanTypeId = JdbcSupport.getInteger(rs, "loanType"); - final EnumOptionData loanType = AccountEnumerations - .loanType(loanTypeId); - final Integer loanCycle = JdbcSupport.getInteger(rs, "loanCycle"); - - final BigDecimal originalLoan = JdbcSupport - .getBigDecimalDefaultToNullIfZero(rs, "originalLoan"); - final BigDecimal loanBalance = JdbcSupport - .getBigDecimalDefaultToNullIfZero(rs, "loanBalance"); - final BigDecimal amountPaid = JdbcSupport - .getBigDecimalDefaultToNullIfZero(rs, "amountPaid"); - final BigDecimal onHoldAmount = JdbcSupport - .getBigDecimalDefaultToNullIfZero(rs, - "on_hold_funds_derived"); - - final LocalDate overdueSinceDate = JdbcSupport.getLocalDate(rs, - "overdueSinceDate"); - Boolean inArrears = true; - if (overdueSinceDate == null) { - inArrears = false; + return accountsSummary.toString(); } - final Boolean isActive = rs.getBoolean("isActive"); + @Override + public GuarantorAccountSummaryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - final String relationship = rs.getString("relationship"); - return new GuarantorAccountSummaryData(id, accountNo, externalId, - productId, loanProductName, shortLoanProductName, - loanStatus, loanType, loanCycle, inArrears, originalLoan, - loanBalance, amountPaid, isActive, relationship, - onHoldAmount); - } + final Long id = JdbcSupport.getLong(rs, "id"); + final String accountNo = rs.getString("accountNo"); + final String externalId = rs.getString("externalId"); + final Long productId = JdbcSupport.getLong(rs, "productId"); + final String loanProductName = rs.getString("productName"); + final String shortLoanProductName = rs.getString("shortProductName"); + final Integer loanStatusId = JdbcSupport.getInteger(rs, "statusId"); + final LoanStatusEnumData loanStatus = LoanEnumerations.status(loanStatusId); + final Integer loanTypeId = JdbcSupport.getInteger(rs, "loanType"); + final EnumOptionData loanType = AccountEnumerations.loanType(loanTypeId); + final Integer loanCycle = JdbcSupport.getInteger(rs, "loanCycle"); + + final BigDecimal originalLoan = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "originalLoan"); + final BigDecimal loanBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "loanBalance"); + final BigDecimal amountPaid = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "amountPaid"); + final BigDecimal onHoldAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "on_hold_funds_derived"); + + final LocalDate overdueSinceDate = JdbcSupport.getLocalDate(rs, "overdueSinceDate"); + Boolean inArrears = true; + if (overdueSinceDate == null) { + inArrears = false; + } + + final Boolean isActive = rs.getBoolean("isActive"); + + final String relationship = rs.getString("relationship"); + return new GuarantorAccountSummaryData(id, accountNo, externalId, productId, loanProductName, shortLoanProductName, loanStatus, + loanType, loanCycle, inArrears, originalLoan, loanBalance, amountPaid, isActive, relationship, onHoldAmount); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountEnumerations.java old mode 100755 new mode 100644 index f2cb800ed..1f59da32b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accountdetails/service/AccountEnumerations.java @@ -32,7 +32,8 @@ public class AccountEnumerations { } public static EnumOptionData loanType(final AccountType type) { - EnumOptionData optionData = new EnumOptionData(AccountType.INVALID.getValue().longValue(), AccountType.INVALID.getCode(), "Invalid"); + EnumOptionData optionData = new EnumOptionData(AccountType.INVALID.getValue().longValue(), AccountType.INVALID.getCode(), + "Invalid"); switch (type) { case INVALID: optionData = new EnumOptionData(AccountType.INVALID.getValue().longValue(), AccountType.INVALID.getCode(), "Invalid"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/api/AccountsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/api/AccountsApiResource.java index be3de3fa4..fbc68f55d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/api/AccountsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/api/AccountsApiResource.java @@ -64,17 +64,15 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; - @Path("/accounts/{type}") @Component @Scope("singleton") -@Api(tags = {"Share Account"}) +@Api(tags = { "Share Account" }) @SwaggerDefinition(tags = { - @Tag(name = "Share Account", description = "Share accounts are instances of a praticular share product created for an individual. An application process around the creation of accounts is also supported.") -}) + @Tag(name = "Share Account", description = "Share accounts are instances of a praticular share product created for an individual. An application process around the creation of accounts is also supported.") }) public class AccountsApiResource { - private final ApplicationContext applicationContext ; + private final ApplicationContext applicationContext; private final ApiRequestParameterHelper apiRequestParameterHelper; private final DefaultToApiJsonSerializer toApiJsonSerializer; private final PlatformSecurityContext platformSecurityContext; @@ -83,39 +81,39 @@ public class AccountsApiResource { private final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService; @Autowired - public AccountsApiResource(final ApplicationContext applicationContext, - final ApiRequestParameterHelper apiRequestParameterHelper, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final PlatformSecurityContext platformSecurityContext, + public AccountsApiResource(final ApplicationContext applicationContext, final ApiRequestParameterHelper apiRequestParameterHelper, + final DefaultToApiJsonSerializer toApiJsonSerializer, final PlatformSecurityContext platformSecurityContext, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final BulkImportWorkbookService bulkImportWorkbookService, final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService) { - this.applicationContext = applicationContext ; - this.apiRequestParameterHelper = apiRequestParameterHelper ; - this.toApiJsonSerializer = toApiJsonSerializer ; - this.platformSecurityContext = platformSecurityContext ; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService ; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; + this.applicationContext = applicationContext; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.toApiJsonSerializer = toApiJsonSerializer; + this.platformSecurityContext = platformSecurityContext; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Share Account Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Requests:\n" + "\n" + "accounts/share/template?clientId=1\n" + "\n" + "\n" + "accounts/share/template?clientId=1&productId=1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.GetAccountsTypeTemplateResponse.class)}) - public String template(@PathParam("type") @ApiParam(value = "type") final String accountType, @QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, - @QueryParam("productId") @ApiParam(value = "productId") final Long productId, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve Share Account Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Requests:\n" + "\n" + "accounts/share/template?clientId=1\n" + + "\n" + "\n" + "accounts/share/template?clientId=1&productId=1") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.GetAccountsTypeTemplateResponse.class) }) + public String template(@PathParam("type") @ApiParam(value = "type") final String accountType, + @QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @QueryParam("productId") @ApiParam(value = "productId") final Long productId, @Context final UriInfo uriInfo) { try { - this.platformSecurityContext.authenticatedUser() ; - String serviceName = accountType+AccountsApiConstants.READPLATFORM_NAME ; - AccountReadPlatformService service = (AccountReadPlatformService) this.applicationContext.getBean(serviceName) ; + this.platformSecurityContext.authenticatedUser(); + String serviceName = accountType + AccountsApiConstants.READPLATFORM_NAME; + AccountReadPlatformService service = (AccountReadPlatformService) this.applicationContext.getBean(serviceName); final AccountData accountData = service.retrieveTemplate(clientId, productId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, accountData, service.getResponseDataParams()); - }catch(BeansException e) { + } catch (BeansException e) { throw new ResourceNotFoundException(); } } @@ -124,17 +122,19 @@ public class AccountsApiResource { @Path("{accountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a share application/account", httpMethod = "GET", notes = "Retrieves a share application/account\n\n" + "Example Requests :\n" + "\n" + "shareaccount/1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.GetAccountsTypeAccountIdResponse.class)}) - public String retrieveAccount(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @PathParam("type") @ApiParam(value = "type") final String accountType, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a share application/account", httpMethod = "GET", notes = "Retrieves a share application/account\n\n" + + "Example Requests :\n" + "\n" + "shareaccount/1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.GetAccountsTypeAccountIdResponse.class) }) + public String retrieveAccount(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @PathParam("type") @ApiParam(value = "type") final String accountType, @Context final UriInfo uriInfo) { try { - String serviceName = accountType+AccountsApiConstants.READPLATFORM_NAME ; + String serviceName = accountType + AccountsApiConstants.READPLATFORM_NAME; final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - AccountReadPlatformService service = (AccountReadPlatformService) this.applicationContext.getBean(serviceName) ; - AccountData data = service.retrieveOne(accountId, settings.isTemplate()) ; + AccountReadPlatformService service = (AccountReadPlatformService) this.applicationContext.getBean(serviceName); + AccountData data = service.retrieveOne(accountId, settings.isTemplate()); return this.toApiJsonSerializer.serialize(settings, data, service.getResponseDataParams()); - }catch(BeansException e) { + } catch (BeansException e) { throw new ResourceNotFoundException(); } } @@ -142,16 +142,19 @@ public class AccountsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List share applications/accounts", httpMethod = "GET", notes = "Lists share applications/accounts\n\n" + "Example Requests:\n" + "\n" + "shareaccount") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.GetAccountsTypeResponse.class)}) - public String retrieveAllAccounts(@PathParam("type") @ApiParam(value = "type") final String accountType, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, @Context final UriInfo uriInfo) { + @ApiOperation(value = "List share applications/accounts", httpMethod = "GET", notes = "Lists share applications/accounts\n\n" + + "Example Requests:\n" + "\n" + "shareaccount") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.GetAccountsTypeResponse.class) }) + public String retrieveAllAccounts(@PathParam("type") @ApiParam(value = "type") final String accountType, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, @Context final UriInfo uriInfo) { try { - String serviceName = accountType+AccountsApiConstants.READPLATFORM_NAME ; - AccountReadPlatformService service = (AccountReadPlatformService) this.applicationContext.getBean(serviceName) ; - Page data = service.retrieveAll(offset, limit) ; + String serviceName = accountType + AccountsApiConstants.READPLATFORM_NAME; + AccountReadPlatformService service = (AccountReadPlatformService) this.applicationContext.getBean(serviceName); + Page data = service.retrieveAll(offset, limit); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, data, service.getResponseDataParams()); - }catch(BeansException e) { + } catch (BeansException e) { throw new ResourceNotFoundException(); } } @@ -159,10 +162,15 @@ public class AccountsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Submit new share application", httpMethod = "POST", notes = "Submits new share application\n\n" + "Mandatory Fields: clientId, productId, submittedDate, savingsAccountId, requestedShares, applicationDate\n\n" + "Optional Fields: accountNo, externalId\n\n" + "Inherited from Product (if not provided): minimumActivePeriod, minimumActivePeriodFrequencyType, lockinPeriodFrequency, lockinPeriodFrequencyType") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountsApiResourceSwagger.PostAccountsTypeRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.PostAccountsTypeResponse.class)}) - public String createAccount(@PathParam("type") @ApiParam(value = "type") final String accountType, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Submit new share application", httpMethod = "POST", notes = "Submits new share application\n\n" + + "Mandatory Fields: clientId, productId, submittedDate, savingsAccountId, requestedShares, applicationDate\n\n" + + "Optional Fields: accountNo, externalId\n\n" + + "Inherited from Product (if not provided): minimumActivePeriod, minimumActivePeriodFrequencyType, lockinPeriodFrequency, lockinPeriodFrequencyType") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountsApiResourceSwagger.PostAccountsTypeRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.PostAccountsTypeResponse.class) }) + public String createAccount(@PathParam("type") @ApiParam(value = "type") final String accountType, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { CommandWrapper commandWrapper = null; this.platformSecurityContext.authenticatedUser(); commandWrapper = new CommandWrapperBuilder().createAccount(accountType).withJson(apiRequestBodyAsJson).build(); @@ -174,14 +182,37 @@ public class AccountsApiResource { @Path("{accountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Approve share application | Undo approval share application | Reject share application | Activate a share account | Close a share account | Apply additional shares on a share account | Approve additional shares request on a share account | Reject additional shares request on a share account | Redeem shares on a share account", httpMethod = "POST", notes = "Approve share application:\n\n" + "Approves share application so long as its in 'Submitted and pending approval' state.\n\n" + "Undo approval share application:\n\n" + "Will move 'approved' share application back to 'Submitted and pending approval' state.\n\n" + "Reject share application:\n\n" + "Rejects share application so long as its in 'Submitted and pending approval' state.\n\n" + "Activate a share account:\n\n" + "Results in an approved share application being converted into an 'active' share account.\n\n" + "Close a share account:\n\n" + "Results in an Activated share application being converted into an 'closed' share account.\n" + "\n" + "closedDate is closure date of share account\n\n" + "Mandatory Fields: dateFormat,locale,closedDate\n\n" + "Apply additional shares on a share account:\n\n" + "requestedDate is requsted date of share purchase\n" + "\n" + "requestedShares is number of shares to be purchase\n\n" + "Mandatory Fields: dateFormat,locale,requestedDate, requestedShares\n\n" + "Approve additional shares request on a share account\n\n" + "requestedShares is Share purchase transaction ids\n\n" + "Mandatory Fields: requestedShares\n\n" + "Reject additional shares request on a share account:\n\n" + "requestedShares is Share purchase transaction ids\n\n" + "Mandatory Fields: requestedShares\n\n" + "Redeem shares on a share account:\n\n" + "Results redeem some/all shares from share account.\n" + "\n" + "requestedDate is requsted date of shares redeem\n" + "\n" + "requestedShares is number of shares to be redeemed\n\n" + "Mandatory Fields: dateFormat,locale,requestedDate,requestedShares\n\n" + "Showing request/response for 'Reject additional shares request on a share account'\n\n" + "For more info visit this link - https://demo.fineract.dev/fineract-provider/api-docs/apiLive.htm#shareaccounts") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountsApiResourceSwagger.PostAccountsTypeAccountIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.PostAccountsTypeAccountIdResponse.class)}) - public String handleCommands(@PathParam("type") @ApiParam(value = "type") final String accountType, @PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiOperation(value = "Approve share application | Undo approval share application | Reject share application | Activate a share account | Close a share account | Apply additional shares on a share account | Approve additional shares request on a share account | Reject additional shares request on a share account | Redeem shares on a share account", httpMethod = "POST", notes = "Approve share application:\n\n" + + "Approves share application so long as its in 'Submitted and pending approval' state.\n\n" + + "Undo approval share application:\n\n" + + "Will move 'approved' share application back to 'Submitted and pending approval' state.\n\n" + "Reject share application:\n\n" + + "Rejects share application so long as its in 'Submitted and pending approval' state.\n\n" + "Activate a share account:\n\n" + + "Results in an approved share application being converted into an 'active' share account.\n\n" + "Close a share account:\n\n" + + "Results in an Activated share application being converted into an 'closed' share account.\n" + "\n" + + "closedDate is closure date of share account\n\n" + "Mandatory Fields: dateFormat,locale,closedDate\n\n" + + "Apply additional shares on a share account:\n\n" + "requestedDate is requsted date of share purchase\n" + "\n" + + "requestedShares is number of shares to be purchase\n\n" + + "Mandatory Fields: dateFormat,locale,requestedDate, requestedShares\n\n" + + "Approve additional shares request on a share account\n\n" + "requestedShares is Share purchase transaction ids\n\n" + + "Mandatory Fields: requestedShares\n\n" + "Reject additional shares request on a share account:\n\n" + + "requestedShares is Share purchase transaction ids\n\n" + "Mandatory Fields: requestedShares\n\n" + + "Redeem shares on a share account:\n\n" + "Results redeem some/all shares from share account.\n" + "\n" + + "requestedDate is requsted date of shares redeem\n" + "\n" + "requestedShares is number of shares to be redeemed\n\n" + + "Mandatory Fields: dateFormat,locale,requestedDate,requestedShares\n\n" + + "Showing request/response for 'Reject additional shares request on a share account'\n\n" + + "For more info visit this link - https://demo.fineract.dev/fineract-provider/api-docs/apiLive.htm#shareaccounts") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountsApiResourceSwagger.PostAccountsTypeAccountIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.PostAccountsTypeAccountIdResponse.class) }) + public String handleCommands(@PathParam("type") @ApiParam(value = "type") final String accountType, + @PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { CommandWrapper commandWrapper = null; this.platformSecurityContext.authenticatedUser(); - commandWrapper = new CommandWrapperBuilder().createAccountCommand(accountType, accountId, commandParam).withJson(apiRequestBodyAsJson).build(); + commandWrapper = new CommandWrapperBuilder().createAccountCommand(accountType, accountId, commandParam) + .withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandWrapper); return this.toApiJsonSerializer.serialize(commandProcessingResult); } @@ -191,9 +222,13 @@ public class AccountsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Modify a share application", httpMethod = "PUT", notes = "Share application can only be modified when in 'Submitted and pending approval' state. Once the application is approved, the details cannot be changed using this method. Specific api endpoints will be created to allow change of interest detail such as rate, compounding period, posting period etc") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountsApiResourceSwagger.PutAccountsTypeAccountIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.PutAccountsTypeAccountIdResponse.class)}) - public String updateAccount(@PathParam("type") @ApiParam(value = "type") final String accountType, @PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = AccountsApiResourceSwagger.PutAccountsTypeAccountIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = AccountsApiResourceSwagger.PutAccountsTypeAccountIdResponse.class) }) + public String updateAccount(@PathParam("type") @ApiParam(value = "type") final String accountType, + @PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { this.platformSecurityContext.authenticatedUser(); final CommandWrapper commandRequest = new CommandWrapperBuilder().updateAccount(accountType, accountId) .withJson(apiRequestBodyAsJson).build(); @@ -206,16 +241,17 @@ public class AccountsApiResource { @Produces("application/vnd.ms-excel") public Response getSharedAccountsTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.SHARE_ACCOUNTS.toString(),officeId, null,dateFormat); + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.SHARE_ACCOUNTS.toString(), officeId, null, dateFormat); } + @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postSharedAccountsTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId = this. bulkImportWorkbookService.importWorkbook(GlobalEntityType.SHARE_ACCOUNTS.toString(), uploadedInputStream, - fileDetail,locale,dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.SHARE_ACCOUNTS.toString(), + uploadedInputStream, fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/api/AccountsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/api/AccountsApiResourceSwagger.java index 9f5b2e6df..a341efc04 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/api/AccountsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/api/AccountsApiResourceSwagger.java @@ -28,17 +28,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/20/17. */ final class AccountsApiResourceSwagger { - private AccountsApiResourceSwagger() { - } + + private AccountsApiResourceSwagger() {} @ApiModel(value = "GetAccountsTypeTemplateResponse") public final static class GetAccountsTypeTemplateResponse { - private GetAccountsTypeTemplateResponse() { - } + + private GetAccountsTypeTemplateResponse() {} final class GetAccountsTypeProductOptions { - private GetAccountsTypeProductOptions() { - } + + private GetAccountsTypeProductOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -59,12 +59,12 @@ final class AccountsApiResourceSwagger { @ApiModel(value = "GetAccountsTypeAccountIdResponse") public final static class GetAccountsTypeAccountIdResponse { - private GetAccountsTypeAccountIdResponse() { - } + + private GetAccountsTypeAccountIdResponse() {} final class GetAccountsStatus { - private GetAccountsStatus() { - } + + private GetAccountsStatus() {} @ApiModelProperty(example = "300") public Integer id; @@ -85,8 +85,8 @@ final class AccountsApiResourceSwagger { } final class GetAccountsTimeline { - private GetAccountsTimeline() { - } + + private GetAccountsTimeline() {} @ApiModelProperty(example = "[2016, 4, 1]") public LocalDate submittedOnDate; @@ -109,8 +109,8 @@ final class AccountsApiResourceSwagger { } final class GetAccountsCurrency { - private GetAccountsCurrency() { - } + + private GetAccountsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -129,8 +129,8 @@ final class AccountsApiResourceSwagger { } final class GetAccountsSummary { - private GetAccountsSummary() { - } + + private GetAccountsSummary() {} @ApiModelProperty(example = "2") public Integer id; @@ -150,12 +150,12 @@ final class AccountsApiResourceSwagger { } final class GetAccountsPurchasedShares { - private GetAccountsPurchasedShares() { - } + + private GetAccountsPurchasedShares() {} final class GetAccountsPurchasedSharesStatus { - private GetAccountsPurchasedSharesStatus() { - } + + private GetAccountsPurchasedSharesStatus() {} @ApiModelProperty(example = "300") public Integer id; @@ -166,8 +166,8 @@ final class AccountsApiResourceSwagger { } final class GetAccountsPurchasedSharesType { - private GetAccountsPurchasedSharesType() { - } + + private GetAccountsPurchasedSharesType() {} @ApiModelProperty(example = "500") public Integer id; @@ -198,8 +198,8 @@ final class AccountsApiResourceSwagger { } final class GetAccountsLockPeriodTypeEnum { - private GetAccountsLockPeriodTypeEnum() { - } + + private GetAccountsLockPeriodTypeEnum() {} @ApiModelProperty(example = "0") public Integer id; @@ -210,12 +210,12 @@ final class AccountsApiResourceSwagger { } final class GetAccountsCharges { - private GetAccountsCharges() { - } + + private GetAccountsCharges() {} final class GetAccountsChargeTimeType { - private GetAccountsChargeTimeType() { - } + + private GetAccountsChargeTimeType() {} @ApiModelProperty(example = "13") public Integer id; @@ -226,8 +226,8 @@ final class AccountsApiResourceSwagger { } final class GetAccountsChargeCalculationType { - private GetAccountsChargeCalculationType() { - } + + private GetAccountsChargeCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -238,8 +238,8 @@ final class AccountsApiResourceSwagger { } final class GetAccountsChargesCurrency { - private GetAccountsChargesCurrency() { - } + + private GetAccountsChargesCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -286,7 +286,6 @@ final class AccountsApiResourceSwagger { public Boolean isActive; } - @ApiModelProperty(example = "2") public Integer id; @ApiModelProperty(example = "000000002") @@ -325,16 +324,16 @@ final class AccountsApiResourceSwagger { @ApiModel(value = "GetAccountsTypeResponse") public final static class GetAccountsTypeResponse { - private GetAccountsTypeResponse() { - } + + private GetAccountsTypeResponse() {} final class GetAccountsPageItems { - private GetAccountsPageItems() { - } + + private GetAccountsPageItems() {} final class GetAccountsTypeStatus { - private GetAccountsTypeStatus() { - } + + private GetAccountsTypeStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -355,16 +354,16 @@ final class AccountsApiResourceSwagger { } final class GetAccountsTypeTimeline { - private GetAccountsTypeTimeline() { - } + + private GetAccountsTypeTimeline() {} @ApiModelProperty(example = "[2013, 3, 1]") public LocalDate submittedOnDate; } final class GetAccountsTypePurchasedShares { - private GetAccountsTypePurchasedShares() { - } + + private GetAccountsTypePurchasedShares() {} @ApiModelProperty(example = "1") public Integer id; @@ -377,8 +376,8 @@ final class AccountsApiResourceSwagger { } final class GetAccountsTypeSummary { - private GetAccountsTypeSummary() { - } + + private GetAccountsTypeSummary() {} public GetAccountsTypeAccountIdResponse.GetAccountsCharges.GetAccountsChargesCurrency currency; } @@ -409,12 +408,12 @@ final class AccountsApiResourceSwagger { @ApiModel(value = "PostAccountsTypeRequest") public final static class PostAccountsTypeRequest { - private PostAccountsTypeRequest() { - } + + private PostAccountsTypeRequest() {} final class PostAccountsCharges { - private PostAccountsCharges() { - } + + private PostAccountsCharges() {} @ApiModelProperty(example = "20") public Integer chargeId; @@ -455,8 +454,8 @@ final class AccountsApiResourceSwagger { @ApiModel(value = "PostAccountsTypeResponse") public final static class PostAccountsTypeResponse { - private PostAccountsTypeResponse() { - } + + private PostAccountsTypeResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -464,12 +463,12 @@ final class AccountsApiResourceSwagger { @ApiModel(value = "PostAccountsTypeAccountIdRequest") public final static class PostAccountsTypeAccountIdRequest { - private PostAccountsTypeAccountIdRequest() { - } + + private PostAccountsTypeAccountIdRequest() {} final class PostAccountsRequestedShares { - private PostAccountsRequestedShares() { - } + + private PostAccountsRequestedShares() {} @ApiModelProperty(example = "35") public Integer id; @@ -480,8 +479,8 @@ final class AccountsApiResourceSwagger { @ApiModel(value = "PostAccountsTypeAccountIdResponse") public final static class PostAccountsTypeAccountIdResponse { - private PostAccountsTypeAccountIdResponse() { - } + + private PostAccountsTypeAccountIdResponse() {} @ApiModelProperty(example = "5") public Integer resourceId; @@ -489,8 +488,8 @@ final class AccountsApiResourceSwagger { @ApiModel(value = "PutAccountsTypeAccountIdRequest") public final static class PutAccountsTypeAccountIdRequest { - private PutAccountsTypeAccountIdRequest() { - } + + private PutAccountsTypeAccountIdRequest() {} @ApiModelProperty(example = "en") public String locale; @@ -504,12 +503,12 @@ final class AccountsApiResourceSwagger { @ApiModel(value = "PutAccountsTypeAccountIdResponse") public final static class PutAccountsTypeAccountIdResponse { - private PutAccountsTypeAccountIdResponse() { - } + + private PutAccountsTypeAccountIdResponse() {} final class PutAccountsChanges { - private PutAccountsChanges() { - } + + private PutAccountsChanges() {} @ApiModelProperty(example = "dd MMMM yyyy") public String dateFormat; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/constants/AccountsApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/constants/AccountsApiConstants.java index 6cf6adc67..1f3260e8c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/constants/AccountsApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/constants/AccountsApiConstants.java @@ -18,10 +18,9 @@ */ package org.apache.fineract.portfolio.accounts.constants; - public interface AccountsApiConstants { - public final String READPLATFORM_NAME = "AccountReadPlatformService" ; + public final String READPLATFORM_NAME = "AccountReadPlatformService"; - public final String ACCOUNT_COMMANDSERVICE = "ACCOUNT_COMMANDSERVICE" ; + public final String ACCOUNT_COMMANDSERVICE = "ACCOUNT_COMMANDSERVICE"; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/constants/ShareAccountApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/constants/ShareAccountApiConstants.java index cdbf4b191..6abef1d29 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/constants/ShareAccountApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/constants/ShareAccountApiConstants.java @@ -40,9 +40,9 @@ public interface ShareAccountApiConstants { String REJECT_ADDITIONSHARES_COMMAND = "rejectadditionalshares"; // - String locale_paramname = "locale" ; + String locale_paramname = "locale"; - String dateformat_paramname = "dateFormat" ; + String dateformat_paramname = "dateFormat"; String id_paramname = "id"; @@ -54,7 +54,7 @@ public interface ShareAccountApiConstants { String approveddate_paramname = "approvedDate"; - String activatedate_paramname = "activatedDate" ; + String activatedate_paramname = "activatedDate"; String fieldofferid_paramname = "fieldOfficerId"; @@ -90,23 +90,21 @@ public interface ShareAccountApiConstants { String purchasedprice_paramname = "unitPrice"; - String note_paramname = "note" ; + String note_paramname = "note"; - String requesteddate_paramname = "requestedDate" ; + String requesteddate_paramname = "requestedDate"; - String additionalshares_paramname = "additionalshares" ; + String additionalshares_paramname = "additionalshares"; String closeddate_paramname = "closedDate"; String shareEntityType = "share"; - Set supportedParameters = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(locale_paramname, - dateformat_paramname, id_paramname,clientid_paramname, productid_paramname, - submitteddate_paramname,approveddate_paramname, externalid_paramname, currency_paramname, - digitsafterdecimal_paramname, inmultiplesof_paramname, requestedshares_paramname, - savingsaccountid_paramname,lockinperiod_paramname, lockperiodfrequencytype_paramname, - minimumactiveperiod_paramname, minimumactiveperiodfrequencytype_paramname, - allowdividendcalculationforinactiveclients_paramname, charges_paramname, applicationdate_param, - purchaseddate_paramname,numberofshares_paramname,purchasedprice_paramname))); + Set supportedParameters = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(locale_paramname, dateformat_paramname, + id_paramname, clientid_paramname, productid_paramname, submitteddate_paramname, approveddate_paramname, externalid_paramname, + currency_paramname, digitsafterdecimal_paramname, inmultiplesof_paramname, requestedshares_paramname, + savingsaccountid_paramname, lockinperiod_paramname, lockperiodfrequencytype_paramname, minimumactiveperiod_paramname, + minimumactiveperiodfrequencytype_paramname, allowdividendcalculationforinactiveclients_paramname, charges_paramname, + applicationdate_param, purchaseddate_paramname, numberofshares_paramname, purchasedprice_paramname))); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/data/AccountData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/data/AccountData.java index 1513d7333..18e0c8b2e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/data/AccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/data/AccountData.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.portfolio.accounts.data; - public interface AccountData { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/exceptions/ShareAccountNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/exceptions/ShareAccountNotFoundException.java index 61c35e18c..a35418498 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/exceptions/ShareAccountNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/exceptions/ShareAccountNotFoundException.java @@ -20,10 +20,9 @@ package org.apache.fineract.portfolio.accounts.exceptions; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - -public class ShareAccountNotFoundException extends AbstractPlatformResourceNotFoundException{ +public class ShareAccountNotFoundException extends AbstractPlatformResourceNotFoundException { public ShareAccountNotFoundException(final Long id) { - super("error.msg.shareaccount.id.invalid", " Account with identifier " + id + " does not exist" , id); + super("error.msg.shareaccount.id.invalid", " Account with identifier " + id + " does not exist", id); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/service/AccountsCommandsService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/service/AccountsCommandsService.java index a88c02dd1..ff3595966 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/service/AccountsCommandsService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/accounts/service/AccountsCommandsService.java @@ -18,8 +18,7 @@ */ package org.apache.fineract.portfolio.accounts.service; - public interface AccountsCommandsService { - public Object handleCommand(final Long accountId, final String command, final String jsonBody) ; + public Object handleCommand(final Long accountId, final String command, final String jsonBody); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/api/EntityFieldConfigurationApiResources.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/api/EntityFieldConfigurationApiResources.java index 4f52d8f3e..42f9f9393 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/api/EntityFieldConfigurationApiResources.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/api/EntityFieldConfigurationApiResources.java @@ -52,15 +52,16 @@ import org.springframework.stereotype.Component; @Path("/fieldconfiguration/{entity}") @Component @Scope("singleton") -@Api(tags = {"Entity Field Configuration"}) +@Api(tags = { "Entity Field Configuration" }) @SwaggerDefinition(tags = { - @Tag(name = "Entity Field Configuration", description = "Entity Field configuration API is a generic and extensible \n" + "wherein various entities and subentities can be related.\n" + "Also it gives the user an ability to enable/disable fields,\n" + "add regular expression for validation") -}) + @Tag(name = "Entity Field Configuration", description = "Entity Field configuration API is a generic and extensible \n" + + "wherein various entities and subentities can be related.\n" + + "Also it gives the user an ability to enable/disable fields,\n" + "add regular expression for validation") }) public class EntityFieldConfigurationApiResources { - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("clientAddressId", "client_id", - "address_id", "address_type_id", "isActive", "fieldConfigurationId", "entity", "table", "field", - "is_enabled", "is_mandatory", "validation_regex")); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("clientAddressId", "client_id", "address_id", "address_type_id", "isActive", "fieldConfigurationId", "entity", + "table", "field", "is_enabled", "is_mandatory", "validation_regex")); private final String resourceNameForPermissions = "Address"; private final PlatformSecurityContext context; private final DefaultToApiJsonSerializer toApiJsonSerializer; @@ -88,18 +89,16 @@ public class EntityFieldConfigurationApiResources { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(httpMethod = "GET", value = "Retrieves the Entity Field Configuration", notes = "It retrieves all the Entity Field Configuration") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = EntityFieldConfigurationApiResourcesSwagger.GetFieldConfigurationEntityResponse.class, responseContainer = "List")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = EntityFieldConfigurationApiResourcesSwagger.GetFieldConfigurationEntityResponse.class, responseContainer = "List") }) public String getAddresses(@PathParam("entity") @ApiParam(value = "entity") final String entityname, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final Collection fldconfig = this.readPlatformServicefld - .retrieveFieldConfiguration(entityname); + final Collection fldconfig = this.readPlatformServicefld.retrieveFieldConfiguration(entityname); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializerfld.serialize(settings, fldconfig, this.RESPONSE_DATA_PARAMETERS); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/api/EntityFieldConfigurationApiResourcesSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/api/EntityFieldConfigurationApiResourcesSwagger.java index a221a3ded..9a1e3bd7c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/api/EntityFieldConfigurationApiResourcesSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/api/EntityFieldConfigurationApiResourcesSwagger.java @@ -25,13 +25,13 @@ import io.swagger.annotations.ApiModelProperty; * Created by Chirag Gupta on 12/01/17. */ final class EntityFieldConfigurationApiResourcesSwagger { - private EntityFieldConfigurationApiResourcesSwagger() { - } + + private EntityFieldConfigurationApiResourcesSwagger() {} @ApiModel(value = "GetFieldConfigurationEntityResponse") public static final class GetFieldConfigurationEntityResponse { - private GetFieldConfigurationEntityResponse() { - } + + private GetFieldConfigurationEntityResponse() {} @ApiModelProperty(example = "1") public Integer fieldConfigurationId; @@ -49,4 +49,3 @@ final class EntityFieldConfigurationApiResourcesSwagger { public String validation_regex; } } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/AddressData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/AddressData.java index a791ba94e..0c6eaa84c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/AddressData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/AddressData.java @@ -78,8 +78,8 @@ public class AddressData implements Serializable { private final Collection stateProvinceIdOptions; private final Collection addressTypeIdOptions; - public AddressData(Long addressTypeId,String street, String addressLine1, String addressLine2, String addressLine3, - String city,String postalCode, Boolean isActive,Long stateProvinceId,Long countryId) { + public AddressData(Long addressTypeId, String street, String addressLine1, String addressLine2, String addressLine3, String city, + String postalCode, Boolean isActive, Long stateProvinceId, Long countryId) { this.addressTypeId = addressTypeId; this.isActive = isActive; @@ -109,13 +109,11 @@ public class AddressData implements Serializable { this.addressTypeIdOptions = null; } - private AddressData(final String addressType, final Long client_id, final Long addressId, final Long addressTypeId, - final Boolean is_active, final String street, final String addressLine1, final String addressLine2, - final String addressLine3, final String townVillage, final String city, final String countyDistrict, - final Long stateProvinceId, final Long countryId, final String stateName, final String countryName, - final String postalCode, final BigDecimal latitude, final BigDecimal longitude, final String createdBy, - final Date createdOn, final String updatedBy, final Date updatedOn, + final Boolean is_active, final String street, final String addressLine1, final String addressLine2, final String addressLine3, + final String townVillage, final String city, final String countyDistrict, final Long stateProvinceId, final Long countryId, + final String stateName, final String countryName, final String postalCode, final BigDecimal latitude, + final BigDecimal longitude, final String createdBy, final Date createdOn, final String updatedBy, final Date updatedOn, final Collection countryIdOptions, final Collection stateProvinceIdOptions, final Collection addressTypeIdOptions) { this.addressType = addressType; @@ -146,32 +144,28 @@ public class AddressData implements Serializable { this.addressTypeIdOptions = addressTypeIdOptions; } - public static AddressData instance(final String addressType, final Long client_id, final Long addressId, - final Long addressTypeId, final Boolean is_active, final String street, final String addressLine1, - final String addressLine2, final String addressLine3, final String townVillage, final String city, - final String countyDistrict, final Long stateProvinceId, final Long countryId, final String stateName, - final String countryName, final String postalCode, final BigDecimal latitude, final BigDecimal longitude, - final String createdBy, final Date createdOn, final String updatedBy, final Date updatedOn) { + public static AddressData instance(final String addressType, final Long client_id, final Long addressId, final Long addressTypeId, + final Boolean is_active, final String street, final String addressLine1, final String addressLine2, final String addressLine3, + final String townVillage, final String city, final String countyDistrict, final Long stateProvinceId, final Long countryId, + final String stateName, final String countryName, final String postalCode, final BigDecimal latitude, + final BigDecimal longitude, final String createdBy, final Date createdOn, final String updatedBy, final Date updatedOn) { - return new AddressData(addressType, client_id, addressId, addressTypeId, is_active, street, addressLine1, - addressLine2, addressLine3, townVillage, city, countyDistrict, stateProvinceId, countryId, - stateName, countryName, postalCode, latitude, longitude, createdBy, createdOn, updatedBy, + return new AddressData(addressType, client_id, addressId, addressTypeId, is_active, street, addressLine1, addressLine2, + addressLine3, townVillage, city, countyDistrict, stateProvinceId, countryId, stateName, countryName, postalCode, latitude, + longitude, createdBy, createdOn, updatedBy, updatedOn, null, null, null); + } + + public static AddressData instance1(final Long addressId, final String street, final String addressLine1, final String addressLine2, + final String addressLine3, final String townVillage, final String city, final String countyDistrict, final Long stateProvinceId, + final Long countryId, final String postalCode, final BigDecimal latitude, final BigDecimal longitude, final String createdBy, + final Date createdOn, final String updatedBy, final Date updatedOn) { + return new AddressData(null, null, addressId, null, false, street, addressLine1, addressLine2, addressLine3, townVillage, city, + countyDistrict, stateProvinceId, countryId, null, null, postalCode, latitude, longitude, createdBy, createdOn, updatedBy, updatedOn, null, null, null); } - public static AddressData instance1(final Long addressId, final String street, final String addressLine1, - final String addressLine2, final String addressLine3, final String townVillage, final String city, - final String countyDistrict, final Long stateProvinceId, final Long countryId, final String postalCode, - final BigDecimal latitude, final BigDecimal longitude, final String createdBy, final Date createdOn, - final String updatedBy, final Date updatedOn) { - return new AddressData(null, null, addressId, null, false, street, addressLine1, addressLine2, - addressLine3, townVillage, city, countyDistrict, stateProvinceId, countryId, null, null, - postalCode, latitude, longitude, createdBy, createdOn, updatedBy, updatedOn, null, null, null); - } - public static AddressData template(final Collection countryIdOptions, - final Collection stateProvinceIdOptions, - final Collection addressTypeIdOptions) { + final Collection stateProvinceIdOptions, final Collection addressTypeIdOptions) { final Long client_idtemp = null; final Long addressIdtemp = null; @@ -212,11 +206,10 @@ public class AddressData implements Serializable { final Date updatedOntemp = null; - return new AddressData(null, client_idtemp, addressIdtemp, addressTypeIdtemp, is_activetemp, streettemp, - addressLine1temp, addressLine2temp, addressLine3temp, townVillagetemp, citytemp, - countyDistricttemp, stateProvinceIdtemp, countryIdtemp, null, null, postalCodetemp, latitudetemp, - longitudetemp, createdBytemp, createdOntemp, updatedBytemp, updatedOntemp, countryIdOptions, - stateProvinceIdOptions, addressTypeIdOptions); + return new AddressData(null, client_idtemp, addressIdtemp, addressTypeIdtemp, is_activetemp, streettemp, addressLine1temp, + addressLine2temp, addressLine3temp, townVillagetemp, citytemp, countyDistricttemp, stateProvinceIdtemp, countryIdtemp, null, + null, postalCodetemp, latitudetemp, longitudetemp, createdBytemp, createdOntemp, updatedBytemp, updatedOntemp, + countryIdOptions, stateProvinceIdOptions, addressTypeIdOptions); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/ClientAddressData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/ClientAddressData.java index b776ae869..2e32169e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/ClientAddressData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/ClientAddressData.java @@ -30,8 +30,8 @@ public class ClientAddressData { private final boolean isActive; - private ClientAddressData(final long clientAddressId, final long client_id, final long address_id, - final long address_type_id, final boolean isActive) { + private ClientAddressData(final long clientAddressId, final long client_id, final long address_id, final long address_type_id, + final boolean isActive) { this.clientAddressId = clientAddressId; this.client_id = client_id; this.address_id = address_id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/FieldConfigurationData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/FieldConfigurationData.java index 1a1bd5d5d..9f60a4bf1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/FieldConfigurationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/data/FieldConfigurationData.java @@ -19,6 +19,7 @@ package org.apache.fineract.portfolio.address.data; public class FieldConfigurationData { + private final long fieldConfigurationId; private final String entity; @@ -33,8 +34,8 @@ public class FieldConfigurationData { private final String validation_regex; - private FieldConfigurationData(final long fieldConfigurationId, final String entity, final String subentity, - final String field, final boolean is_enabled, final boolean is_mandatory, final String validation_regex) { + private FieldConfigurationData(final long fieldConfigurationId, final String entity, final String subentity, final String field, + final boolean is_enabled, final boolean is_mandatory, final String validation_regex) { this.fieldConfigurationId = fieldConfigurationId; this.entity = entity; this.subentity = subentity; @@ -44,11 +45,9 @@ public class FieldConfigurationData { this.validation_regex = validation_regex; } - public static FieldConfigurationData instance(final long fieldConfigurationId, final String entity, - final String subentity, final String field, final boolean is_enabled, final boolean is_mandatory, - final String validation_regex) { - return new FieldConfigurationData(fieldConfigurationId, entity, subentity, field, is_enabled, is_mandatory, - validation_regex); + public static FieldConfigurationData instance(final long fieldConfigurationId, final String entity, final String subentity, + final String field, final boolean is_enabled, final boolean is_mandatory, final String validation_regex) { + return new FieldConfigurationData(fieldConfigurationId, entity, subentity, field, is_enabled, is_mandatory, validation_regex); } public long getFieldConfigurationId() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/Address.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/Address.java index 0d6131e57..651da01a4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/Address.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/domain/Address.java @@ -100,11 +100,10 @@ public class Address extends AbstractPersistableCustom { @Column(name = "updated_on") private Date updatedOn; - private Address(final String street, final String addressLine1, final String addressLine2, - final String addressLine3, final String townVillage, final String city, final String countyDistrict, - final CodeValue stateProvince, final CodeValue country, final String postalCode, final BigDecimal latitude, - final BigDecimal longitude, final String createdBy, final LocalDate createdOn, final String updatedBy, - final LocalDate updatedOn) { + private Address(final String street, final String addressLine1, final String addressLine2, final String addressLine3, + final String townVillage, final String city, final String countyDistrict, final CodeValue stateProvince, + final CodeValue country, final String postalCode, final BigDecimal latitude, final BigDecimal longitude, final String createdBy, + final LocalDate createdOn, final String updatedBy, final LocalDate updatedOn) { this.street = street; this.addressLine1 = addressLine1; this.addressLine2 = addressLine2; @@ -167,12 +166,11 @@ public class Address extends AbstractPersistableCustom { final LocalDate updatedOn = command.localDateValueOfParameterNamed("updatedOn"); - return new Address(street, addressLine1, addressLine2, addressLine3, townVillage, city, countyDistrict, - stateProvince, country, postalCode, latitude, longitude, createdBy, createdOn, updatedBy, updatedOn); + return new Address(street, addressLine1, addressLine2, addressLine3, townVillage, city, countyDistrict, stateProvince, country, + postalCode, latitude, longitude, createdBy, createdOn, updatedBy, updatedOn); } - public static Address fromJsonObject(final JsonObject jsonObject, final CodeValue state_province, - final CodeValue country) { + public static Address fromJsonObject(final JsonObject jsonObject, final CodeValue state_province, final CodeValue country) { String street = ""; String addressLine1 = ""; String addressLine2 = ""; @@ -244,9 +242,8 @@ public class Address extends AbstractPersistableCustom { updatedOnDate = LocalDate.parse(updatedOn, formatter); } - return new Address(street, addressLine1, addressLine2, addressLine3, townVillage, city, countyDistrict, - state_province, country, postalCode, latitude, longitude, createdBy, createdOnDate, updatedBy, - updatedOnDate); + return new Address(street, addressLine1, addressLine2, addressLine3, townVillage, city, countyDistrict, state_province, country, + postalCode, latitude, longitude, createdBy, createdOnDate, updatedBy, updatedOnDate); } public Set getClientaddress() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/exception/AddressNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/exception/AddressNotFoundException.java index d565fd0a9..88484feef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/exception/AddressNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/exception/AddressNotFoundException.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class AddressNotFoundException extends AbstractPlatformResourceNotFoundException { public AddressNotFoundException(final long clientId) { - super("error.msg.address.client.Identifier.not.found", - "Client with client ID `" + clientId + "` is not mapped with any address", clientId); + super("error.msg.address.client.Identifier.not.found", "Client with client ID `" + clientId + "` is not mapped with any address", + clientId); } public AddressNotFoundException(final long clientId, final long addressTypeId) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/serialization/AddressCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/serialization/AddressCommandFromApiJsonDeserializer.java index 2dc4e7434..ccead5e79 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/serialization/AddressCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/serialization/AddressCommandFromApiJsonDeserializer.java @@ -41,6 +41,7 @@ import org.springframework.stereotype.Component; @Component public class AddressCommandFromApiJsonDeserializer { + private final FromJsonHelper fromApiJsonHelper; private final FieldConfigurationReadPlatformService readservice; @@ -60,22 +61,17 @@ public class AddressCommandFromApiJsonDeserializer { } public void validate(final String json, final boolean fromNewClient) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource("Address"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("Address"); final JsonElement element = this.fromApiJsonHelper.parse(json); Set supportedParameters = new HashSet<>(); - final List configurationData = new ArrayList<>( - this.readservice.retrieveFieldConfigurationList("ADDRESS")); + final List configurationData = new ArrayList<>(this.readservice.retrieveFieldConfigurationList("ADDRESS")); final List enabledFieldList = new ArrayList<>(); final Map madatoryFieldsMap = new HashMap(); @@ -123,8 +119,7 @@ public class AddressCommandFromApiJsonDeserializer { } if (!regexFieldsMap.get("street").isEmpty()) { - baseDataValidator.reset().parameter("street").value(street) - .matchesRegularExpression(regexFieldsMap.get("street")); + baseDataValidator.reset().parameter("street").value(street).matchesRegularExpression(regexFieldsMap.get("street")); } } @@ -176,8 +171,7 @@ public class AddressCommandFromApiJsonDeserializer { baseDataValidator.reset().parameter("city").value(city).notBlank(); } if (!regexFieldsMap.get("city").isEmpty()) { - baseDataValidator.reset().parameter("city").value(city) - .matchesRegularExpression(regexFieldsMap.get("city")); + baseDataValidator.reset().parameter("city").value(city).matchesRegularExpression(regexFieldsMap.get("city")); } } final String countyDistrict = this.fromApiJsonHelper.extractStringNamed("countyDistrict", element); @@ -261,8 +255,8 @@ public class AddressCommandFromApiJsonDeserializer { private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressReadPlatformService.java index eb7f94a2a..82168f43d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressReadPlatformService.java @@ -22,6 +22,7 @@ import java.util.Collection; import org.apache.fineract.portfolio.address.data.AddressData; public interface AddressReadPlatformService { + public Collection retrieveAddressFields(long clientid); public Collection retrieveAllClientAddress(long clientid); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressReadPlatformServiceImpl.java index 362b84875..5448867a6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressReadPlatformServiceImpl.java @@ -51,6 +51,7 @@ public class AddressReadPlatformServiceImpl implements AddressReadPlatformServic } private static final class AddFieldsMapper implements RowMapper { + public String schema() { return "addr.id as id,client.id as client_id,addr.street as street,addr.address_line_1 as address_line_1,addr.address_line_2 as address_line_2," + "addr.address_line_3 as address_line_3,addr.town_village as town_village, addr.city as city,addr.county_district as county_district," @@ -60,8 +61,7 @@ public class AddressReadPlatformServiceImpl implements AddressReadPlatformServic } @Override - public AddressData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public AddressData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final long addressId = rs.getLong("id"); @@ -99,30 +99,28 @@ public class AddressReadPlatformServiceImpl implements AddressReadPlatformServic final Date updated_on = rs.getDate("updated_on"); - return AddressData.instance1(addressId, street, address_line_1, address_line_2, address_line_3, - town_village, city, county_district, state_province_id, country_id, postal_code, latitude, - longitude, created_by, created_on, updated_by, updated_on); + return AddressData.instance1(addressId, street, address_line_1, address_line_2, address_line_3, town_village, city, + county_district, state_province_id, country_id, postal_code, latitude, longitude, created_by, created_on, updated_by, + updated_on); } } private static final class AddMapper implements RowMapper { + public String schema() { return "cv2.code_value as addressType,ca.client_id as client_id,addr.id as id,ca.address_type_id as addresstyp,ca.is_active as is_active,addr.street as street,addr.address_line_1 as address_line_1,addr.address_line_2 as address_line_2," + "addr.address_line_3 as address_line_3,addr.town_village as town_village, addr.city as city,addr.county_district as county_district," + "addr.state_province_id as state_province_id,cv.code_value as state_name, addr.country_id as country_id,c.code_value as country_name,addr.postal_code as postal_code,addr.latitude as latitude," + "addr.longitude as longitude,addr.created_by as created_by,addr.created_on as created_on,addr.updated_by as updated_by," - + "addr.updated_on as updated_on" - + " from m_address addr left join m_code_value cv on addr.state_province_id=cv.id" - + " left join m_code_value c on addr.country_id=c.id" - + " join m_client_address ca on addr.id= ca.address_id" + + "addr.updated_on as updated_on" + " from m_address addr left join m_code_value cv on addr.state_province_id=cv.id" + + " left join m_code_value c on addr.country_id=c.id" + " join m_client_address ca on addr.id= ca.address_id" + " join m_code_value cv2 on ca.address_type_id=cv2.id"; } @Override - public AddressData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public AddressData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final String addressType = rs.getString("addressType"); final long addressId = rs.getLong("id"); @@ -169,10 +167,9 @@ public class AddressReadPlatformServiceImpl implements AddressReadPlatformServic final Date updated_on = rs.getDate("updated_on"); - return AddressData.instance(addressType, client_id, addressId, address_type_id, is_active, street, - address_line_1, address_line_2, address_line_3, town_village, city, county_district, - state_province_id, country_id, state_name, country_name, postal_code, latitude, longitude, - created_by, created_on, updated_by, updated_on); + return AddressData.instance(addressType, client_id, addressId, address_type_id, is_active, street, address_line_1, + address_line_2, address_line_3, town_village, city, county_district, state_province_id, country_id, state_name, + country_name, postal_code, latitude, longitude, created_by, created_on, updated_by, updated_on); } } @@ -206,8 +203,7 @@ public class AddressReadPlatformServiceImpl implements AddressReadPlatformServic } @Override - public Collection retrieveAddressbyTypeAndStatus(final long clientid, final long typeid, - final String status) { + public Collection retrieveAddressbyTypeAndStatus(final long clientid, final long typeid, final String status) { this.context.authenticatedUser(); Boolean temp = false; temp = Boolean.parseBoolean(status); @@ -232,13 +228,11 @@ public class AddressReadPlatformServiceImpl implements AddressReadPlatformServic @Override public AddressData retrieveTemplate() { - final List countryoptions = new ArrayList<>( - this.readService.retrieveCodeValuesByCode("COUNTRY")); + final List countryoptions = new ArrayList<>(this.readService.retrieveCodeValuesByCode("COUNTRY")); final List StateOptions = new ArrayList<>(this.readService.retrieveCodeValuesByCode("STATE")); - final List addressTypeOptions = new ArrayList<>( - this.readService.retrieveCodeValuesByCode("ADDRESS_TYPE")); + final List addressTypeOptions = new ArrayList<>(this.readService.retrieveCodeValuesByCode("ADDRESS_TYPE")); return AddressData.template(countryoptions, StateOptions, addressTypeOptions); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressWritePlatformService.java index c60e6c0f4..9c5f4d4a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressWritePlatformService.java @@ -23,6 +23,7 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; import org.apache.fineract.portfolio.client.domain.Client; public interface AddressWritePlatformService { + CommandProcessingResult addClientAddress(Long clientId, Long addressTypeId, JsonCommand command); CommandProcessingResult addNewClientAddress(Client client, JsonCommand command); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressWritePlatformServiceImpl.java index e79f8cadc..ff609630d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/AddressWritePlatformServiceImpl.java @@ -42,6 +42,7 @@ import org.springframework.stereotype.Service; @Service public class AddressWritePlatformServiceImpl implements AddressWritePlatformService { + private final PlatformSecurityContext context; private final CodeValueRepository codeValueRepository; private final ClientAddressRepository clientAddressRepository; @@ -51,10 +52,9 @@ public class AddressWritePlatformServiceImpl implements AddressWritePlatformServ private final AddressCommandFromApiJsonDeserializer fromApiJsonDeserializer; @Autowired - public AddressWritePlatformServiceImpl(final PlatformSecurityContext context, - final CodeValueRepository codeValueRepository, final ClientAddressRepository clientAddressRepository, - final ClientRepositoryWrapper clientRepositoryWrapper, final AddressRepository addressRepository, - final ClientAddressRepositoryWrapper clientAddressRepositoryWrapper, + public AddressWritePlatformServiceImpl(final PlatformSecurityContext context, final CodeValueRepository codeValueRepository, + final ClientAddressRepository clientAddressRepository, final ClientRepositoryWrapper clientRepositoryWrapper, + final AddressRepository addressRepository, final ClientAddressRepositoryWrapper clientAddressRepositoryWrapper, final AddressCommandFromApiJsonDeserializer fromApiJsonDeserializer) { this.context = context; this.codeValueRepository = codeValueRepository; @@ -67,8 +67,7 @@ public class AddressWritePlatformServiceImpl implements AddressWritePlatformServ } @Override - public CommandProcessingResult addClientAddress(final Long clientId, final Long addressTypeId, - final JsonCommand command) { + public CommandProcessingResult addClientAddress(final Long clientId, final Long addressTypeId, final JsonCommand command) { CodeValue stateIdobj = null; CodeValue countryIdObj = null; long stateId; @@ -102,8 +101,7 @@ public class AddressWritePlatformServiceImpl implements AddressWritePlatformServ final ClientAddress clientAddressobj = ClientAddress.fromJson(isActive, client, addobj, addressTypeIdObj); this.clientAddressRepository.save(clientAddressobj); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()) - .withEntityId(clientAddressobj.getId()).build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(clientAddressobj.getId()).build(); } // following method is used for adding multiple addresses while creating new @@ -118,7 +116,7 @@ public class AddressWritePlatformServiceImpl implements AddressWritePlatformServ ClientAddress clientAddressobj = new ClientAddress(); final JsonArray addressArray = command.arrayOfParameterNamed("address"); - if(addressArray != null){ + if (addressArray != null) { for (int i = 0; i < addressArray.size(); i++) { final JsonObject jsonObject = addressArray.get(i).getAsJsonObject(); @@ -145,22 +143,20 @@ public class AddressWritePlatformServiceImpl implements AddressWritePlatformServ final Long addressid = add.getId(); final Address addobj = this.addressRepository.getOne(addressid); - //final boolean isActive = jsonObject.get("isActive").getAsBoolean(); - boolean isActive=false; - if(jsonObject.get("isActive")!= null) - { - isActive= jsonObject.get("isActive").getAsBoolean(); + // final boolean isActive = + // jsonObject.get("isActive").getAsBoolean(); + boolean isActive = false; + if (jsonObject.get("isActive") != null) { + isActive = jsonObject.get("isActive").getAsBoolean(); } - clientAddressobj = ClientAddress.fromJson(isActive, client, addobj, addressTypeIdObj); this.clientAddressRepository.save(clientAddressobj); } } - return new CommandProcessingResultBuilder().withCommandId(command.commandId()) - .withEntityId(clientAddressobj.getId()).build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(clientAddressobj.getId()).build(); } @Override @@ -181,12 +177,9 @@ public class AddressWritePlatformServiceImpl implements AddressWritePlatformServ final long addressId = command.longValueOfParameterNamed("addressId"); - final ClientAddress clientAddressObj = this.clientAddressRepositoryWrapper - .findOneByClientIdAndAddressId(clientId, addressId); + final ClientAddress clientAddressObj = this.clientAddressRepositoryWrapper.findOneByClientIdAndAddressId(clientId, addressId); - if (clientAddressObj == null) { - throw new AddressNotFoundException(clientId); - } + if (clientAddressObj == null) { throw new AddressNotFoundException(clientId); } final Address addobj = this.addressRepository.getOne(addressId); @@ -290,7 +283,6 @@ public class AddressWritePlatformServiceImpl implements AddressWritePlatformServ clientAddressObj.setIs_active(active); } - return new CommandProcessingResultBuilder().withCommandId(command.commandId()) - .withEntityId(clientAddressObj.getId()).build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(clientAddressObj.getId()).build(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/FieldConfigurationReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/FieldConfigurationReadPlatformService.java index 25718bbff..dc69eaf57 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/FieldConfigurationReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/FieldConfigurationReadPlatformService.java @@ -23,6 +23,7 @@ import java.util.List; import org.apache.fineract.portfolio.address.data.FieldConfigurationData; public interface FieldConfigurationReadPlatformService { + public Collection retrieveFieldConfiguration(String entity); List retrieveFieldConfigurationList(String entity); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/FieldConfigurationReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/FieldConfigurationReadPlatformServiceImpl.java index 9f9f6f785..f8c05dc78 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/FieldConfigurationReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/address/service/FieldConfigurationReadPlatformServiceImpl.java @@ -32,25 +32,25 @@ import org.springframework.stereotype.Service; @Service public class FieldConfigurationReadPlatformServiceImpl implements FieldConfigurationReadPlatformService { + private final JdbcTemplate jdbcTemplate; private final PlatformSecurityContext context; @Autowired - public FieldConfigurationReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { + public FieldConfigurationReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); } private static final class FieldMapper implements RowMapper { + public String schema() { return "fld.id as fieldConfigurationId,fld.entity as entity,fld.subentity as subentity,fld.field as field,fld.is_enabled as is_enabled," + "fld.is_mandatory as is_mandatory,fld.validation_regex as validation_regex from m_field_configuration fld"; } @Override - public FieldConfigurationData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public FieldConfigurationData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final long fieldConfigurationId = rs.getLong("fieldConfigurationId"); final String entity = rs.getString("entity"); final String subentity = rs.getString("subentity"); @@ -59,8 +59,8 @@ public class FieldConfigurationReadPlatformServiceImpl implements FieldConfigura final boolean is_mandatory = rs.getBoolean("is_mandatory"); final String validation_regex = rs.getString("validation_regex"); - return FieldConfigurationData.instance(fieldConfigurationId, entity, subentity, field, is_enabled, - is_mandatory, validation_regex); + return FieldConfigurationData.instance(fieldConfigurationId, entity, subentity, field, is_enabled, is_mandatory, + validation_regex); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/CalendarConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/CalendarConstants.java index c380b4ba7..cccbf8dee 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/CalendarConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/CalendarConstants.java @@ -26,13 +26,18 @@ public class CalendarConstants { public static final String CALENDAR_RESOURCE_NAME = "calendar"; public static enum CalendarSupportedParameters { + CALENDAR_ID("id"), ENTITY_TYPE("entityType"), ENTITY_ID("entityId"), TITLE("title"), DESCRIPTION("description"), LOCATION( "location"), START_DATE("startDate"), END_DATE("endDate"), CREATED_DATE("createdDate"), DURATION("duration"), TYPE_ID( - "typeId"), REPEATING("repeating"), REMIND_BY_ID("remindById"), FIRST_REMINDER("firstReminder"), SECOND_REMINDER( - "secondReminder"), LOCALE("locale"), DATE_FORMAT("dateFormat"), FREQUENCY("frequency"), INTERVAL("interval"), REPEATS_ON_DAY( - "repeatsOnDay"), RESCHEDULE_BASED_ON_MEETING_DATES("reschedulebasedOnMeetingDates"), PRESENT_MEETING_DATE( - "presentMeetingDate"), NEW_MEETING_DATE("newMeetingDate"),MEETING_TIME("meetingtime"),Time_Format("timeFormat"), REPEATS_ON_NTH_DAY_OF_MONTH("repeatsOnNthDayOfMonth"), - REPEATS_ON_LAST_WEEKDAY_OF_MONTH("repeatsOnLastWeekdayOfMonth"), REPEATS_ON_DAY_OF_MONTH("repeatsOnDayOfMonth"); + "typeId"), REPEATING("repeating"), REMIND_BY_ID("remindById"), FIRST_REMINDER("firstReminder"), SECOND_REMINDER( + "secondReminder"), LOCALE("locale"), DATE_FORMAT("dateFormat"), FREQUENCY("frequency"), INTERVAL( + "interval"), REPEATS_ON_DAY("repeatsOnDay"), RESCHEDULE_BASED_ON_MEETING_DATES( + "reschedulebasedOnMeetingDates"), PRESENT_MEETING_DATE( + "presentMeetingDate"), NEW_MEETING_DATE("newMeetingDate"), MEETING_TIME( + "meetingtime"), Time_Format("timeFormat"), REPEATS_ON_NTH_DAY_OF_MONTH( + "repeatsOnNthDayOfMonth"), REPEATS_ON_LAST_WEEKDAY_OF_MONTH( + "repeatsOnLastWeekdayOfMonth"), REPEATS_ON_DAY_OF_MONTH( + "repeatsOnDayOfMonth"); private final String value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/api/CalendarsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/api/CalendarsApiResource.java index 2f1a149a3..c9fee5a1c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/api/CalendarsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/api/CalendarsApiResource.java @@ -67,12 +67,11 @@ public class CalendarsApiResource { /** * The set of parameters that are supported in response for {@link Calendar} */ - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "entityId", "entityType", "title", - "description", "location", "startDate", "endDate", "duration", "type", "repeating", "recurrence", "frequency", "interval", - "repeatsOnDay", "remindBy", "firstReminder", "secondReminder", "humanReadable", "createdDate", "lastUpdatedDate", - "createdByUserId", "createdByUsername", "lastUpdatedByUserId", "lastUpdatedByUsername", "recurringDates", - "nextTenRecurringDates", "entityTypeOptions", "calendarTypeOptions", "remindByOptions", "frequencyOptions", - "repeatsOnDayOptions")); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "entityId", "entityType", "title", "description", + "location", "startDate", "endDate", "duration", "type", "repeating", "recurrence", "frequency", "interval", "repeatsOnDay", + "remindBy", "firstReminder", "secondReminder", "humanReadable", "createdDate", "lastUpdatedDate", "createdByUserId", + "createdByUsername", "lastUpdatedByUserId", "lastUpdatedByUsername", "recurringDates", "nextTenRecurringDates", + "entityTypeOptions", "calendarTypeOptions", "remindByOptions", "frequencyOptions", "repeatsOnDayOptions")); private final String resourceNameForPermissions = "CALENDAR"; private final PlatformSecurityContext context; @@ -228,7 +227,8 @@ public class CalendarsApiResource { final List remindByOptions = this.dropdownReadPlatformService.retrieveCalendarRemindByOptions(); final List frequencyOptions = this.dropdownReadPlatformService.retrieveCalendarFrequencyTypeOptions(); final List repeatsOnDayOptions = this.dropdownReadPlatformService.retrieveCalendarWeekDaysTypeOptions(); - final List frequencyNthDayTypeOptions = this.dropdownReadPlatformService.retrieveCalendarFrequencyNthDayTypeOptions(); + final List frequencyNthDayTypeOptions = this.dropdownReadPlatformService + .retrieveCalendarFrequencyNthDayTypeOptions(); return CalendarData.withTemplateOptions(calendarData, entityTypeOptions, calendarTypeOptions, remindByOptions, frequencyOptions, repeatsOnDayOptions, frequencyNthDayTypeOptions); } @@ -261,4 +261,4 @@ public class CalendarsApiResource { return resourceDetails.build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/data/CalendarData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/data/CalendarData.java index 48eb05f68..38dddc5da 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/data/CalendarData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/data/CalendarData.java @@ -80,32 +80,33 @@ public class CalendarData implements Serializable { final List repeatsOnDayOptions; final List frequencyNthDayTypeOptions; - //import fields + // import fields private transient Integer rowIndex; - private String dateFormat; - private String locale; - private String centerId; + private String dateFormat; + private String locale; + private String centerId; private String typeId; - public static CalendarData importInstanceNoRepeatsOnDay(LocalDate startDate, boolean repeating, - EnumOptionData frequency, Integer interval,Integer rowIndex,String locale,String dateFormat){ - return new CalendarData(startDate, repeating, frequency, interval, rowIndex,locale,dateFormat); + public static CalendarData importInstanceNoRepeatsOnDay(LocalDate startDate, boolean repeating, EnumOptionData frequency, + Integer interval, Integer rowIndex, String locale, String dateFormat) { + return new CalendarData(startDate, repeating, frequency, interval, rowIndex, locale, dateFormat); } - public static CalendarData importInstanceWithRepeatsOnDay(LocalDate startDate, boolean repeating, - EnumOptionData frequency,Integer interval,EnumOptionData repeatsOnDay,Integer rowIndex, - String locale,String dateFormat){ - return new CalendarData(startDate, repeating, frequency, interval, repeatsOnDay, rowIndex,locale,dateFormat); + + public static CalendarData importInstanceWithRepeatsOnDay(LocalDate startDate, boolean repeating, EnumOptionData frequency, + Integer interval, EnumOptionData repeatsOnDay, Integer rowIndex, String locale, String dateFormat) { + return new CalendarData(startDate, repeating, frequency, interval, repeatsOnDay, rowIndex, locale, dateFormat); } - private CalendarData(LocalDate startDate, boolean repeating,EnumOptionData frequency,Integer interval, - Integer rowIndex,String locale,String dateFormat) { + + private CalendarData(LocalDate startDate, boolean repeating, EnumOptionData frequency, Integer interval, Integer rowIndex, + String locale, String dateFormat) { this.startDate = startDate; this.repeating = repeating; this.frequency = frequency; this.interval = interval; - this.rowIndex=rowIndex; - this.dateFormat= dateFormat; - this.locale= locale; + this.rowIndex = rowIndex; + this.dateFormat = dateFormat; + this.locale = locale; this.description = ""; this.typeId = "1"; this.id = null; @@ -126,7 +127,7 @@ public class CalendarData implements Serializable { this.recurringDates = null; this.nextTenRecurringDates = null; this.humanReadable = null; - this.recentEligibleMeetingDate =null; + this.recentEligibleMeetingDate = null; this.createdDate = null; this.lastUpdatedDate = null; this.createdByUserId = null; @@ -140,19 +141,19 @@ public class CalendarData implements Serializable { this.frequencyOptions = null; this.repeatsOnDayOptions = null; this.frequencyNthDayTypeOptions = null; - this.duration=null; + this.duration = null; } - private CalendarData(LocalDate startDate, boolean repeating,EnumOptionData frequency,Integer interval, - EnumOptionData repeatsOnDay,Integer rowIndex,String locale,String dateFormat) { + private CalendarData(LocalDate startDate, boolean repeating, EnumOptionData frequency, Integer interval, EnumOptionData repeatsOnDay, + Integer rowIndex, String locale, String dateFormat) { this.startDate = startDate; this.repeating = repeating; this.frequency = frequency; this.interval = interval; this.repeatsOnDay = repeatsOnDay; - this.rowIndex=rowIndex; - this.dateFormat= dateFormat; - this.locale= locale; + this.rowIndex = rowIndex; + this.dateFormat = dateFormat; + this.locale = locale; this.description = ""; this.typeId = "1"; this.id = null; @@ -172,7 +173,7 @@ public class CalendarData implements Serializable { this.recurringDates = null; this.nextTenRecurringDates = null; this.humanReadable = null; - this.recentEligibleMeetingDate =null; + this.recentEligibleMeetingDate = null; this.createdDate = null; this.lastUpdatedDate = null; this.createdByUserId = null; @@ -186,14 +187,15 @@ public class CalendarData implements Serializable { this.frequencyOptions = null; this.repeatsOnDayOptions = null; this.frequencyNthDayTypeOptions = null; - this.duration=null; + this.duration = null; } + public void setCenterId(String centerId) { this.centerId = centerId; } - public void setTitle(String title){ - this.title=title; + public void setTitle(String title) { + this.title = title; } public static CalendarData instance(final Long id, final Long calendarInstanceId, final Long entityId, final EnumOptionData entityType, @@ -229,24 +231,26 @@ public class CalendarData implements Serializable { return new CalendarData(calendarData.id, calendarData.calendarInstanceId, calendarData.entityId, calendarData.entityType, calendarData.title, calendarData.description, calendarData.location, calendarData.startDate, calendarData.endDate, calendarData.duration, calendarData.type, calendarData.repeating, calendarData.recurrence, calendarData.frequency, - calendarData.interval, calendarData.repeatsOnDay, calendarData.repeatsOnNthDayOfMonth, calendarData.remindBy, calendarData.firstReminder, - calendarData.secondReminder, recurringDates, nextTenRecurringDates, calendarData.humanReadable, recentEligibleMeetingDate, - calendarData.createdDate, calendarData.lastUpdatedDate, calendarData.createdByUserId, calendarData.createdByUsername, - calendarData.lastUpdatedByUserId, calendarData.lastUpdatedByUsername, calendarData.repeatsOnDayOfMonth, calendarData.entityTypeOptions, - calendarData.calendarTypeOptions, calendarData.remindByOptions, calendarData.frequencyOptions, - calendarData.repeatsOnDayOptions, calendarData.meetingTime, calendarData.frequencyNthDayTypeOptions); + calendarData.interval, calendarData.repeatsOnDay, calendarData.repeatsOnNthDayOfMonth, calendarData.remindBy, + calendarData.firstReminder, calendarData.secondReminder, recurringDates, nextTenRecurringDates, calendarData.humanReadable, + recentEligibleMeetingDate, calendarData.createdDate, calendarData.lastUpdatedDate, calendarData.createdByUserId, + calendarData.createdByUsername, calendarData.lastUpdatedByUserId, calendarData.lastUpdatedByUsername, + calendarData.repeatsOnDayOfMonth, calendarData.entityTypeOptions, calendarData.calendarTypeOptions, + calendarData.remindByOptions, calendarData.frequencyOptions, calendarData.repeatsOnDayOptions, calendarData.meetingTime, + calendarData.frequencyNthDayTypeOptions); } public static CalendarData withRecentEligibleMeetingDate(final CalendarData calendarData, final LocalDate recentEligibleMeetingDate) { return new CalendarData(calendarData.id, calendarData.calendarInstanceId, calendarData.entityId, calendarData.entityType, calendarData.title, calendarData.description, calendarData.location, calendarData.startDate, calendarData.endDate, calendarData.duration, calendarData.type, calendarData.repeating, calendarData.recurrence, calendarData.frequency, - calendarData.interval, calendarData.repeatsOnDay, calendarData.repeatsOnNthDayOfMonth, calendarData.remindBy, calendarData.firstReminder, - calendarData.secondReminder, calendarData.recurringDates, calendarData.nextTenRecurringDates, calendarData.humanReadable, - recentEligibleMeetingDate, calendarData.createdDate, calendarData.lastUpdatedDate, calendarData.createdByUserId, - calendarData.createdByUsername, calendarData.lastUpdatedByUserId, calendarData.lastUpdatedByUsername, - calendarData.repeatsOnDayOfMonth, calendarData.entityTypeOptions, calendarData.calendarTypeOptions, calendarData.remindByOptions, - calendarData.frequencyOptions, calendarData.repeatsOnDayOptions,calendarData.meetingTime, calendarData.frequencyNthDayTypeOptions); + calendarData.interval, calendarData.repeatsOnDay, calendarData.repeatsOnNthDayOfMonth, calendarData.remindBy, + calendarData.firstReminder, calendarData.secondReminder, calendarData.recurringDates, calendarData.nextTenRecurringDates, + calendarData.humanReadable, recentEligibleMeetingDate, calendarData.createdDate, calendarData.lastUpdatedDate, + calendarData.createdByUserId, calendarData.createdByUsername, calendarData.lastUpdatedByUserId, + calendarData.lastUpdatedByUsername, calendarData.repeatsOnDayOfMonth, calendarData.entityTypeOptions, + calendarData.calendarTypeOptions, calendarData.remindByOptions, calendarData.frequencyOptions, + calendarData.repeatsOnDayOptions, calendarData.meetingTime, calendarData.frequencyNthDayTypeOptions); } public static CalendarData sensibleDefaultsForNewCalendarCreation() { @@ -325,7 +329,7 @@ public class CalendarData implements Serializable { final LocalDate lastUpdatedDate, final Long createdByUserId, final String createdByUsername, final Long lastUpdatedByUserId, final String lastUpdatedByUsername, final Integer repeatsOnDayOfMonth, final List entityTypeOptions, final List calendarTypeOptions, final List remindByOptions, - final List repeatsOptions, final List repeatsOnDayOptions,final LocalTime meetingTime, + final List repeatsOptions, final List repeatsOnDayOptions, final LocalTime meetingTime, final List frequencyNthDayTypeOptions) { this.id = id; this.calendarInstanceId = calendarInstanceId; @@ -473,79 +477,67 @@ public class CalendarData implements Serializable { } public boolean isValidRecurringDate(final LocalDate compareDate, final Boolean isSkipMeetingOnFirstDay, final Integer numberOfDays) { - if (isBetweenStartAndEndDate(compareDate)) { return CalendarUtils.isValidRedurringDate(this.getRecurrence(), this.getStartDate(), - compareDate, isSkipMeetingOnFirstDay, numberOfDays); } + if (isBetweenStartAndEndDate(compareDate)) { + return CalendarUtils.isValidRedurringDate(this.getRecurrence(), this.getStartDate(), compareDate, isSkipMeetingOnFirstDay, + numberOfDays); + } return false; } - public Integer interval(){ + public Integer interval() { return this.interval; } - public EnumOptionData frequencyType(){ + public EnumOptionData frequencyType() { return this.frequency; } + public EnumOptionData getRepeatsOnDay() { return this.repeatsOnDay; } + public EnumOptionData getRepeatsOnNthDayOfMonth() { return this.repeatsOnNthDayOfMonth; } @Override public boolean equals(Object o) { - if (this == o){ return true;} - if (!(o instanceof CalendarData)) { - return false; - } + if (this == o) { return true; } + if (!(o instanceof CalendarData)) { return false; } CalendarData that = (CalendarData) o; - return Objects.equals(repeating, that.repeating) && - Objects.equals(id, that.id) && - Objects.equals(calendarInstanceId, that.calendarInstanceId) && - Objects.equals(entityId, that.entityId) && - Objects.equals(entityType, that.entityType) && - Objects.equals(title, that.title) && - Objects.equals(description, that.description) && - Objects.equals(location, that.location) && - Objects.equals(startDate, that.startDate) && - Objects.equals(endDate, that.endDate) && - Objects.equals(meetingTime, that.meetingTime) && - Objects.equals(duration, that.duration) && - Objects.equals(type, that.type) && - Objects.equals(recurrence, that.recurrence) && - Objects.equals(frequency, that.frequency) && - Objects.equals(interval, that.interval) && - Objects.equals(repeatsOnDay, that.repeatsOnDay) && - Objects.equals(repeatsOnNthDayOfMonth, that.repeatsOnNthDayOfMonth) && - Objects.equals(remindBy, that.remindBy) && - Objects.equals(firstReminder, that.firstReminder) && - Objects.equals(secondReminder, that.secondReminder) && - Objects.equals(recurringDates, that.recurringDates) && - Objects.equals(nextTenRecurringDates, that.nextTenRecurringDates) && - Objects.equals(humanReadable, that.humanReadable) && - Objects.equals(recentEligibleMeetingDate, that.recentEligibleMeetingDate) && - Objects.equals(createdDate, that.createdDate) && - Objects.equals(lastUpdatedDate, that.lastUpdatedDate) && - Objects.equals(createdByUserId, that.createdByUserId) && - Objects.equals(createdByUsername, that.createdByUsername) && - Objects.equals(lastUpdatedByUserId, that.lastUpdatedByUserId) && - Objects.equals(lastUpdatedByUsername, that.lastUpdatedByUsername) && - Objects.equals(repeatsOnDayOfMonth, that.repeatsOnDayOfMonth) && - Objects.equals(entityTypeOptions, that.entityTypeOptions) && - Objects.equals(calendarTypeOptions, that.calendarTypeOptions) && - Objects.equals(remindByOptions, that.remindByOptions) && - Objects.equals(frequencyOptions, that.frequencyOptions) && - Objects.equals(repeatsOnDayOptions, that.repeatsOnDayOptions) && - Objects.equals(frequencyNthDayTypeOptions, that.frequencyNthDayTypeOptions) && - Objects.equals(rowIndex, that.rowIndex) && - Objects.equals(dateFormat, that.dateFormat) && - Objects.equals(locale, that.locale) && - Objects.equals(centerId, that.centerId) && - Objects.equals(typeId, that.typeId); + return Objects.equals(repeating, that.repeating) && Objects.equals(id, that.id) + && Objects.equals(calendarInstanceId, that.calendarInstanceId) && Objects.equals(entityId, that.entityId) + && Objects.equals(entityType, that.entityType) && Objects.equals(title, that.title) + && Objects.equals(description, that.description) && Objects.equals(location, that.location) + && Objects.equals(startDate, that.startDate) && Objects.equals(endDate, that.endDate) + && Objects.equals(meetingTime, that.meetingTime) && Objects.equals(duration, that.duration) + && Objects.equals(type, that.type) && Objects.equals(recurrence, that.recurrence) + && Objects.equals(frequency, that.frequency) && Objects.equals(interval, that.interval) + && Objects.equals(repeatsOnDay, that.repeatsOnDay) && Objects.equals(repeatsOnNthDayOfMonth, that.repeatsOnNthDayOfMonth) + && Objects.equals(remindBy, that.remindBy) && Objects.equals(firstReminder, that.firstReminder) + && Objects.equals(secondReminder, that.secondReminder) && Objects.equals(recurringDates, that.recurringDates) + && Objects.equals(nextTenRecurringDates, that.nextTenRecurringDates) && Objects.equals(humanReadable, that.humanReadable) + && Objects.equals(recentEligibleMeetingDate, that.recentEligibleMeetingDate) + && Objects.equals(createdDate, that.createdDate) && Objects.equals(lastUpdatedDate, that.lastUpdatedDate) + && Objects.equals(createdByUserId, that.createdByUserId) && Objects.equals(createdByUsername, that.createdByUsername) + && Objects.equals(lastUpdatedByUserId, that.lastUpdatedByUserId) + && Objects.equals(lastUpdatedByUsername, that.lastUpdatedByUsername) + && Objects.equals(repeatsOnDayOfMonth, that.repeatsOnDayOfMonth) + && Objects.equals(entityTypeOptions, that.entityTypeOptions) + && Objects.equals(calendarTypeOptions, that.calendarTypeOptions) && Objects.equals(remindByOptions, that.remindByOptions) + && Objects.equals(frequencyOptions, that.frequencyOptions) && Objects.equals(repeatsOnDayOptions, that.repeatsOnDayOptions) + && Objects.equals(frequencyNthDayTypeOptions, that.frequencyNthDayTypeOptions) && Objects.equals(rowIndex, that.rowIndex) + && Objects.equals(dateFormat, that.dateFormat) && Objects.equals(locale, that.locale) + && Objects.equals(centerId, that.centerId) && Objects.equals(typeId, that.typeId); } @Override public int hashCode() { - return Objects.hash(id, calendarInstanceId, entityId, entityType, title, description, location, startDate, endDate, meetingTime, duration, type, repeating, recurrence, frequency, interval, repeatsOnDay, repeatsOnNthDayOfMonth, remindBy, firstReminder, secondReminder, recurringDates, nextTenRecurringDates, humanReadable, recentEligibleMeetingDate, createdDate, lastUpdatedDate, createdByUserId, createdByUsername, lastUpdatedByUserId, lastUpdatedByUsername, repeatsOnDayOfMonth, entityTypeOptions, calendarTypeOptions, remindByOptions, frequencyOptions, repeatsOnDayOptions, frequencyNthDayTypeOptions, rowIndex, dateFormat, locale, centerId, typeId); + return Objects.hash(id, calendarInstanceId, entityId, entityType, title, description, location, startDate, endDate, meetingTime, + duration, type, repeating, recurrence, frequency, interval, repeatsOnDay, repeatsOnNthDayOfMonth, remindBy, firstReminder, + secondReminder, recurringDates, nextTenRecurringDates, humanReadable, recentEligibleMeetingDate, createdDate, + lastUpdatedDate, createdByUserId, createdByUsername, lastUpdatedByUserId, lastUpdatedByUsername, repeatsOnDayOfMonth, + entityTypeOptions, calendarTypeOptions, remindByOptions, frequencyOptions, repeatsOnDayOptions, frequencyNthDayTypeOptions, + rowIndex, dateFormat, locale, centerId, typeId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/data/CalendarHistoryDataWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/data/CalendarHistoryDataWrapper.java index bfae0c0f0..05ee726a3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/data/CalendarHistoryDataWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/data/CalendarHistoryDataWrapper.java @@ -26,15 +26,15 @@ import java.util.Set; import org.apache.fineract.portfolio.calendar.domain.CalendarHistory; import org.joda.time.LocalDate; - public class CalendarHistoryDataWrapper { private final List calendarHistoryList; - public CalendarHistoryDataWrapper(final Set calendarHistoryList){ + public CalendarHistoryDataWrapper(final Set calendarHistoryList) { this.calendarHistoryList = new ArrayList<>(); this.calendarHistoryList.addAll(calendarHistoryList); final Comparator orderByDate = new Comparator() { + @Override public int compare(CalendarHistory calendarHistory1, CalendarHistory calendarHistory2) { return calendarHistory1.getEndDateLocalDate().compareTo(calendarHistory2.getEndDateLocalDate()); @@ -48,13 +48,13 @@ public class CalendarHistoryDataWrapper { for (CalendarHistory history : this.calendarHistoryList) { if (history.getEndDateLocalDate().isAfter(dueRepaymentPeriodDate)) { calendarHistory = history; - break; + break; } } return calendarHistory; } - public List getCalendarHistoryList(){ + public List getCalendarHistoryList() { return this.calendarHistoryList; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/Calendar.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/Calendar.java index c166a7317..c44b483aa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/Calendar.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/Calendar.java @@ -92,7 +92,7 @@ public class Calendar extends AbstractAuditableCustom { @Column(name = "second_reminder", nullable = true) private Integer secondReminder; - @Column(name="meeting_time",nullable=true) + @Column(name = "meeting_time", nullable = true) @Temporal(TemporalType.TIME) private Date meetingtime; @@ -104,9 +104,9 @@ public class Calendar extends AbstractAuditableCustom { } - public Calendar(final String title, final String description, final String location, final LocalDate startDate, - final LocalDate endDate, final Integer duration, final Integer typeId, final boolean repeating, final String recurrence, - final Integer remindById, final Integer firstReminder, final Integer secondReminder,final Date meetingtime) { + public Calendar(final String title, final String description, final String location, final LocalDate startDate, final LocalDate endDate, + final Integer duration, final Integer typeId, final boolean repeating, final String recurrence, final Integer remindById, + final Integer firstReminder, final Integer secondReminder, final Date meetingtime) { final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CALENDAR_RESOURCE_NAME); @@ -141,7 +141,7 @@ public class Calendar extends AbstractAuditableCustom { this.remindById = remindById; this.firstReminder = firstReminder; this.secondReminder = secondReminder; - this.meetingtime=meetingtime; + this.meetingtime = meetingtime; } public static Calendar createRepeatingCalendar(final String title, final LocalDate startDate, final Integer typeId, @@ -161,9 +161,9 @@ public class Calendar extends AbstractAuditableCustom { final Integer remindById = null; final Integer firstReminder = null; final Integer secondReminder = null; - final Date meetingtime=null; + final Date meetingtime = null; return new Calendar(title, description, location, startDate, endDate, duration, typeId, repeating, recurrence, remindById, - firstReminder, secondReminder,meetingtime); + firstReminder, secondReminder, meetingtime); } public static Calendar fromJson(final JsonCommand command) { @@ -171,7 +171,7 @@ public class Calendar extends AbstractAuditableCustom { // final Long entityId = command.getSupportedEntityId(); // final Integer entityTypeId = // CalendarEntityType.valueOf(command.getSupportedEntityType().toUpperCase()).getValue(); - Date meetingtime=null; + Date meetingtime = null; final String title = command.stringValueOfParameterNamed(CalendarSupportedParameters.TITLE.getValue()); final String description = command.stringValueOfParameterNamed(CalendarSupportedParameters.DESCRIPTION.getValue()); final String location = command.stringValueOfParameterNamed(CalendarSupportedParameters.LOCATION.getValue()); @@ -181,18 +181,17 @@ public class Calendar extends AbstractAuditableCustom { final Integer typeId = command.integerValueSansLocaleOfParameterNamed(CalendarSupportedParameters.TYPE_ID.getValue()); final boolean repeating = command.booleanPrimitiveValueOfParameterNamed(CalendarSupportedParameters.REPEATING.getValue()); final Integer remindById = command.integerValueSansLocaleOfParameterNamed(CalendarSupportedParameters.REMIND_BY_ID.getValue()); - final Integer firstReminder = command.integerValueSansLocaleOfParameterNamed(CalendarSupportedParameters.FIRST_REMINDER - .getValue()); - final Integer secondReminder = command.integerValueSansLocaleOfParameterNamed(CalendarSupportedParameters.SECOND_REMINDER - .getValue()); - final LocalDateTime time= command.localTimeValueOfParameterNamed(CalendarSupportedParameters.MEETING_TIME.getValue()); - if(time!=null){ - meetingtime=time.toDate(); - } + final Integer firstReminder = command.integerValueSansLocaleOfParameterNamed(CalendarSupportedParameters.FIRST_REMINDER.getValue()); + final Integer secondReminder = command + .integerValueSansLocaleOfParameterNamed(CalendarSupportedParameters.SECOND_REMINDER.getValue()); + final LocalDateTime time = command.localTimeValueOfParameterNamed(CalendarSupportedParameters.MEETING_TIME.getValue()); + if (time != null) { + meetingtime = time.toDate(); + } final String recurrence = Calendar.constructRecurrence(command, null); return new Calendar(title, description, location, startDate, endDate, duration, typeId, repeating, recurrence, remindById, - firstReminder, secondReminder,meetingtime); + firstReminder, secondReminder, meetingtime); } public Map updateStartDateAndDerivedFeilds(final LocalDate newMeetingStartDate) { @@ -403,12 +402,12 @@ public class Calendar extends AbstractAuditableCustom { final String timeFormat = command.stringValueOfParameterNamed(CalendarSupportedParameters.Time_Format.getValue()); final String time = CalendarSupportedParameters.MEETING_TIME.getValue(); - if (command.isChangeInTimeParameterNamed(CalendarSupportedParameters.MEETING_TIME.getValue(), this.meetingtime,timeFormat)) { + if (command.isChangeInTimeParameterNamed(CalendarSupportedParameters.MEETING_TIME.getValue(), this.meetingtime, timeFormat)) { final String newValue = command.stringValueOfParameterNamed(CalendarSupportedParameters.MEETING_TIME.getValue()); actualChanges.put(CalendarSupportedParameters.MEETING_TIME.getValue(), newValue); - LocalDateTime timeInLocalDateTimeFormat=command.localTimeValueOfParameterNamed(time); - if(timeInLocalDateTimeFormat!=null){ - this.meetingtime= timeInLocalDateTimeFormat.toDate(); + LocalDateTime timeInLocalDateTimeFormat = command.localTimeValueOfParameterNamed(time); + if (timeInLocalDateTimeFormat != null) { + this.meetingtime = timeInLocalDateTimeFormat.toDate(); } } @@ -484,7 +483,7 @@ public class Calendar extends AbstractAuditableCustom { return this.secondReminder; } - public Date getMeetingTime(){ + public Date getMeetingTime() { return this.meetingtime; } @@ -566,14 +565,14 @@ public class Calendar extends AbstractAuditableCustom { } Integer repeatsOnNthDayOfMonth = null; if (frequencyType.isMonthly()) { - repeatsOnNthDayOfMonth = command.integerValueOfParameterNamed(CalendarSupportedParameters.REPEATS_ON_NTH_DAY_OF_MONTH - .getValue()); + repeatsOnNthDayOfMonth = command + .integerValueOfParameterNamed(CalendarSupportedParameters.REPEATS_ON_NTH_DAY_OF_MONTH.getValue()); final NthDayType nthDay = NthDayType.fromInt(repeatsOnNthDayOfMonth); - repeatsOnDay = command.integerValueOfParameterNamed(CalendarSupportedParameters.REPEATS_ON_LAST_WEEKDAY_OF_MONTH - .getValue()); + repeatsOnDay = command + .integerValueOfParameterNamed(CalendarSupportedParameters.REPEATS_ON_LAST_WEEKDAY_OF_MONTH.getValue()); if (nthDay.isOnDay()) { - repeatsOnNthDayOfMonth = command.integerValueOfParameterNamed(CalendarSupportedParameters.REPEATS_ON_DAY_OF_MONTH - .getValue()); + repeatsOnNthDayOfMonth = command + .integerValueOfParameterNamed(CalendarSupportedParameters.REPEATS_ON_DAY_OF_MONTH.getValue()); repeatsOnDay = null; } } @@ -583,8 +582,8 @@ public class Calendar extends AbstractAuditableCustom { return ""; } - private static String constructRecurrence(final CalendarFrequencyType frequencyType, final Integer interval, - final Integer repeatsOnDay, final Integer repeatsOnNthDayOfMonth) { + private static String constructRecurrence(final CalendarFrequencyType frequencyType, final Integer interval, final Integer repeatsOnDay, + final Integer repeatsOnNthDayOfMonth) { final StringBuilder recurrenceBuilder = new StringBuilder(200); recurrenceBuilder.append("FREQ="); @@ -608,7 +607,8 @@ public class Calendar extends AbstractAuditableCustom { recurrenceBuilder.append(";BYMONTHDAY="); recurrenceBuilder.append(repeatsOnNthDayOfMonth); } - } else if (repeatsOnNthDayOfMonth != null && repeatsOnDay != null && !repeatsOnDay.equals(CalendarWeekDaysType.INVALID.getValue())) { + } else if (repeatsOnNthDayOfMonth != null && repeatsOnDay != null + && !repeatsOnDay.equals(CalendarWeekDaysType.INVALID.getValue())) { final NthDayType nthDay = NthDayType.fromInt(repeatsOnNthDayOfMonth); if (!nthDay.isInvalid()) { recurrenceBuilder.append(";BYSETPOS="); @@ -626,13 +626,17 @@ public class Calendar extends AbstractAuditableCustom { public boolean isValidRecurringDate(final LocalDate compareDate, Boolean isSkipRepaymentOnFirstMonth, Integer numberOfDays) { - if (isBetweenStartAndEndDate(compareDate)) { return CalendarUtils.isValidRedurringDate(getRecurrence(), getStartDateLocalDate(), - compareDate, isSkipRepaymentOnFirstMonth, numberOfDays); } + if (isBetweenStartAndEndDate(compareDate)) { + return CalendarUtils.isValidRedurringDate(getRecurrence(), getStartDateLocalDate(), compareDate, isSkipRepaymentOnFirstMonth, + numberOfDays); + } // validate with history details. for (CalendarHistory history : history()) { - if (history.isBetweenStartAndEndDate(compareDate)) { return CalendarUtils.isValidRedurringDate(history.getRecurrence(), - history.getStartDateLocalDate(), compareDate, isSkipRepaymentOnFirstMonth, numberOfDays); } + if (history.isBetweenStartAndEndDate(compareDate)) { + return CalendarUtils.isValidRedurringDate(history.getRecurrence(), history.getStartDateLocalDate(), compareDate, + isSkipRepaymentOnFirstMonth, numberOfDays); + } } return false; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarFrequencyType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarFrequencyType.java index 79da79363..060011fd5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarFrequencyType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarFrequencyType.java @@ -25,8 +25,8 @@ import org.springframework.util.StringUtils; public enum CalendarFrequencyType { - INVALID(0, "calendarFrequencyType.invalid"), DAILY(1, "calendarFrequencyType.daily"), WEEKLY(2, "calendarFrequencyType.weekly"), MONTHLY( - 3, "calendarFrequencyType.monthly"), YEARLY(4, "calendarFrequencyType.yearly"); + INVALID(0, "calendarFrequencyType.invalid"), DAILY(1, "calendarFrequencyType.daily"), WEEKLY(2, + "calendarFrequencyType.weekly"), MONTHLY(3, "calendarFrequencyType.monthly"), YEARLY(4, "calendarFrequencyType.yearly"); private final Integer value; private final String code; @@ -62,9 +62,7 @@ public enum CalendarFrequencyType { public static CalendarFrequencyType fromString(final String frequencyString) { CalendarFrequencyType frequency = CalendarFrequencyType.INVALID; - if (StringUtils.isEmpty(frequencyString)) { - return frequency; - } + if (StringUtils.isEmpty(frequencyString)) { return frequency; } if (frequencyString.equalsIgnoreCase(CalendarFrequencyType.DAILY.toString())) { frequency = CalendarFrequencyType.DAILY; @@ -108,7 +106,8 @@ public enum CalendarFrequencyType { * To convert from period frequency type tp calendar frequency type. This * method requires code refactoring. * - * @param periodFrequencyType periodFrequencyType + * @param periodFrequencyType + * periodFrequencyType * @return CalendarFrequencyType */ public static CalendarFrequencyType from(final PeriodFrequencyType periodFrequencyType) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarInstanceRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarInstanceRepository.java index 8200d7a88..4ecb09bf5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarInstanceRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarInstanceRepository.java @@ -36,9 +36,13 @@ public interface CalendarInstanceRepository extends JpaRepository findByEntityIdAndEntityTypeId(Long entityId, Integer entityTypeId); /** - * @param entityId : Id of {@link Client}, {@link Group}, {@link Loan} or {@link SavingsAccount}. - * @param entityTypeId: {@link CalendarEntityType} - * @param calendarTypeId: {@link CalendarType} + * @param entityId + * : Id of {@link Client}, {@link Group}, {@link Loan} or + * {@link SavingsAccount}. + * @param entityTypeId: + * {@link CalendarEntityType} + * @param calendarTypeId: + * {@link CalendarType} * @return */ CalendarInstance findByEntityIdAndEntityTypeIdAndCalendarTypeId(Long entityId, Integer entityTypeId, Integer calendarTypeId); @@ -54,10 +58,10 @@ public interface CalendarInstanceRepository extends JpaRepository loanStatuses ); + Integer countOfLoansSyncedWithCalendar(@Param("calendarId") Long calendarId, @Param("loanStatuses") Collection loanStatuses); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarInstanceRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarInstanceRepositoryWrapper.java index 35d666a93..0952f755e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarInstanceRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarInstanceRepositoryWrapper.java @@ -46,8 +46,7 @@ public class CalendarInstanceRepositoryWrapper { } public CalendarInstance findOneWithNotFoundDetection(final Long CalendarInstanceId) { - return this.repository.findById(CalendarInstanceId) - .orElseThrow(() -> new CalendarInstanceNotFoundException(CalendarInstanceId)); + return this.repository.findById(CalendarInstanceId).orElseThrow(() -> new CalendarInstanceNotFoundException(CalendarInstanceId)); } public void save(final CalendarInstance calendatInstance) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarRepositoryWrapper.java index 66444c0f1..f86e4bc9c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarRepositoryWrapper.java @@ -45,8 +45,7 @@ public class CalendarRepositoryWrapper { } public Calendar findOneWithNotFoundDetection(final Long calendarId) { - return this.repository.findById(calendarId) - .orElseThrow(() -> new CalendarNotFoundException(calendarId)); + return this.repository.findById(calendarId).orElseThrow(() -> new CalendarNotFoundException(calendarId)); } public void save(final Calendar calendar) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarWeekDaysType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarWeekDaysType.java index 362400d87..2c0fcbff0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarWeekDaysType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/domain/CalendarWeekDaysType.java @@ -25,8 +25,8 @@ import org.springframework.util.StringUtils; public enum CalendarWeekDaysType { INVALID(0, "calendarWeekDaysType.invalid"), MO(1, "calendarWeekDaysType.monday"), TU(2, "calendarWeekDaysType.tuesday"), WE(3, - "calendarWeekDaysType.wednesday"), TH(4, "calendarWeekDaysType.thursday"), FR(5, "calendarWeekDaysType.friday"), SA(6, - "calendarWeekDaysType.saturday"), SU(7, "calendarWeekDaysType.sunday"); + "calendarWeekDaysType.wednesday"), TH(4, "calendarWeekDaysType.thursday"), FR(5, + "calendarWeekDaysType.friday"), SA(6, "calendarWeekDaysType.saturday"), SU(7, "calendarWeekDaysType.sunday"); private final Integer value; private final String code; @@ -79,9 +79,7 @@ public enum CalendarWeekDaysType { public static CalendarWeekDaysType fromString(final String weekDayString) { CalendarWeekDaysType weekDay = CalendarWeekDaysType.INVALID; - if (StringUtils.isEmpty(weekDayString)) { - return weekDay; - } + if (StringUtils.isEmpty(weekDayString)) { return weekDay; } if (weekDayString.equalsIgnoreCase(CalendarWeekDaysType.MO.toString())) { weekDay = CalendarWeekDaysType.MO; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarDateException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarDateException.java index b2e2d1f4d..f62050a76 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarDateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarDateException.java @@ -28,4 +28,4 @@ public class CalendarDateException extends AbstractPlatformDomainRuleException { public CalendarDateException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.calendar." + postFix, defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarEntityTypeNotSupportedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarEntityTypeNotSupportedException.java index 1ce29c7e7..884e609ab 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarEntityTypeNotSupportedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarEntityTypeNotSupportedException.java @@ -23,7 +23,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class CalendarEntityTypeNotSupportedException extends AbstractPlatformResourceNotFoundException { public CalendarEntityTypeNotSupportedException(final String resource) { - super("calendar.entitytype.not.supported", "Calendar does not support resource "+ resource); + super("calendar.entitytype.not.supported", "Calendar does not support resource " + resource); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarInstanceNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarInstanceNotFoundException.java index 4c97aca42..072e99b0c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarInstanceNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarInstanceNotFoundException.java @@ -30,7 +30,8 @@ public class CalendarInstanceNotFoundException extends AbstractPlatformResourceN super("error.msg.calendar.instance.id.invalid", "Calendar Instance with identifier " + id + " does not exist", id); } - public CalendarInstanceNotFoundException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { + public CalendarInstanceNotFoundException(final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg.calendar.instance." + postFix, defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarNotFoundException.java index 7bf03714a..f0fd3bb12 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarNotFoundException.java @@ -28,4 +28,4 @@ public class CalendarNotFoundException extends AbstractPlatformResourceNotFoundE public CalendarNotFoundException(final Long id) { super("error.msg.calendar.id.invalid", "Calendar with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarParameterUpdateNotSupportedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarParameterUpdateNotSupportedException.java index 34396cf33..b7541ed5a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarParameterUpdateNotSupportedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/CalendarParameterUpdateNotSupportedException.java @@ -29,4 +29,4 @@ public class CalendarParameterUpdateNotSupportedException extends AbstractPlatfo final Object... defaultUserMessageArgs) { super("error.msg.calendar.update.of." + postFix + ".is.not.supported", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/MeetingFrequencyMismatchException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/MeetingFrequencyMismatchException.java index 7c5d4636a..11f57781b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/MeetingFrequencyMismatchException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/MeetingFrequencyMismatchException.java @@ -25,7 +25,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR */ public class MeetingFrequencyMismatchException extends AbstractPlatformDomainRuleException { - public MeetingFrequencyMismatchException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { + public MeetingFrequencyMismatchException(final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg.calendar." + postFix + ".not.the.same.as.meeting.frequency", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/NotValidRecurringDateException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/NotValidRecurringDateException.java index 2adee969f..627396848 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/NotValidRecurringDateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/exception/NotValidRecurringDateException.java @@ -28,4 +28,4 @@ public class NotValidRecurringDateException extends AbstractPlatformDomainRuleEx public NotValidRecurringDateException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.calendar." + postFix + ".not.valid.recurring.date", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/handler/DeleteCalendarCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/handler/DeleteCalendarCommandHandler.java index a415104b6..079ed6c12 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/handler/DeleteCalendarCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/handler/DeleteCalendarCommandHandler.java @@ -43,4 +43,4 @@ public class DeleteCalendarCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.deleteCalendar(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/serialization/CalendarCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/serialization/CalendarCommandFromApiJsonDeserializer.java index 81e11db4d..810c9dd49 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/serialization/CalendarCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/serialization/CalendarCommandFromApiJsonDeserializer.java @@ -80,12 +80,12 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD final Integer typeId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CalendarSupportedParameters.TYPE_ID.getValue(), element); final boolean repeating = this.fromApiJsonHelper.extractBooleanNamed(CalendarSupportedParameters.REPEATING.getValue(), element); - final Integer remindById = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.REMIND_BY_ID.getValue(), element); - final Integer firstReminder = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.FIRST_REMINDER.getValue(), element); - final Integer secondReminder = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.SECOND_REMINDER.getValue(), element); + final Integer remindById = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CalendarSupportedParameters.REMIND_BY_ID.getValue(), + element); + final Integer firstReminder = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.FIRST_REMINDER.getValue(), element); + final Integer secondReminder = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.SECOND_REMINDER.getValue(), element); return new CalendarCommand(title, description, location, startDate, endDate, createdDate, duration, typeId, repeating, remindById, firstReminder, secondReminder); @@ -104,8 +104,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("calendar"); final String title = this.fromApiJsonHelper.extractStringNamed(CalendarSupportedParameters.TITLE.getValue(), element); - baseDataValidator.reset().parameter(CalendarSupportedParameters.TITLE.getValue()).value(title).notBlank() - .notExceedingLengthOf(50); + baseDataValidator.reset().parameter(CalendarSupportedParameters.TITLE.getValue()).value(title).notBlank().notExceedingLengthOf(50); if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.DESCRIPTION.getValue(), element)) { final String description = this.fromApiJsonHelper.extractStringNamed(CalendarSupportedParameters.DESCRIPTION.getValue(), @@ -139,8 +138,8 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.DURATION.getValue(), element)) { - final Integer duration = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.DURATION.getValue(), element); + final Integer duration = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CalendarSupportedParameters.DURATION.getValue(), + element); baseDataValidator.reset().parameter(CalendarSupportedParameters.DURATION.getValue()).value(duration).ignoreIfNull(); } @@ -151,25 +150,24 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.REPEATING.getValue(), element)) { // FIXME - Throws NullPointerException when boolean value is null - final boolean repeating = this.fromApiJsonHelper.extractBooleanNamed(CalendarSupportedParameters.REPEATING.getValue(), - element); + final boolean repeating = this.fromApiJsonHelper.extractBooleanNamed(CalendarSupportedParameters.REPEATING.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.REPEATING.getValue()).value(repeating).notNull(); if (repeating) { - final Integer frequency = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.FREQUENCY.getValue(), element); + final Integer frequency = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.FREQUENCY.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.FREQUENCY.getValue()).value(frequency).notBlank() .inMinMaxRange(CalendarFrequencyType.getMinValue(), CalendarFrequencyType.getMaxValue()); if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.INTERVAL.getValue(), element)) { - final Integer interval = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.INTERVAL.getValue(), element); + final Integer interval = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.INTERVAL.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.INTERVAL.getValue()).value(interval).notNull() .integerGreaterThanZero(); } if (CalendarFrequencyType.fromInt(frequency).isWeekly()) { - final Integer repeatsOnDay = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.REPEATS_ON_DAY.getValue(), element); + final Integer repeatsOnDay = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.REPEATS_ON_DAY.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.REPEATS_ON_DAY.getValue()).value(repeatsOnDay) .notBlank().inMinMaxRange(CalendarWeekDaysType.getMinValue(), CalendarWeekDaysType.getMaxValue()); } else if (CalendarFrequencyType.fromInt(frequency).isMonthly()) { @@ -181,34 +179,35 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.REMIND_BY_ID.getValue(), element)) { - final Integer remindById = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.REMIND_BY_ID.getValue(), element); + final Integer remindById = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.REMIND_BY_ID.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.REMIND_BY_ID.getValue()).value(remindById).ignoreIfNull() .inMinMaxRange(CalendarRemindBy.getMinValue(), CalendarRemindBy.getMaxValue()); } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.FIRST_REMINDER.getValue(), element)) { - final Integer firstReminder = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.FIRST_REMINDER.getValue(), element); - baseDataValidator.reset().parameter(CalendarSupportedParameters.FIRST_REMINDER.getValue()).value(firstReminder) - .ignoreIfNull().integerGreaterThanZero(); + final Integer firstReminder = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.FIRST_REMINDER.getValue(), element); + baseDataValidator.reset().parameter(CalendarSupportedParameters.FIRST_REMINDER.getValue()).value(firstReminder).ignoreIfNull() + .integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.SECOND_REMINDER.getValue(), element)) { - final Integer secondReminder = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.SECOND_REMINDER.getValue(), element); - baseDataValidator.reset().parameter(CalendarSupportedParameters.SECOND_REMINDER.getValue()).value(secondReminder) - .ignoreIfNull().integerGreaterThanZero(); + final Integer secondReminder = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.SECOND_REMINDER.getValue(), element); + baseDataValidator.reset().parameter(CalendarSupportedParameters.SECOND_REMINDER.getValue()).value(secondReminder).ignoreIfNull() + .integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.MEETING_TIME.getValue(), element)) { - final LocalDateTime meetingTime = this.fromApiJsonHelper.extractLocalTimeNamed(CalendarSupportedParameters.MEETING_TIME.getValue(), - element); + final LocalDateTime meetingTime = this.fromApiJsonHelper + .extractLocalTimeNamed(CalendarSupportedParameters.MEETING_TIME.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.MEETING_TIME.getValue()).value(meetingTime).ignoreIfNull(); } - - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForUpdate(final String json) { @@ -224,22 +223,22 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("calendar"); if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.RESCHEDULE_BASED_ON_MEETING_DATES.getValue(), element)) { - final Boolean rescheduleBasedOnMeetingDates = this.fromApiJsonHelper.extractBooleanNamed( - CalendarSupportedParameters.RESCHEDULE_BASED_ON_MEETING_DATES.getValue(), element); + final Boolean rescheduleBasedOnMeetingDates = this.fromApiJsonHelper + .extractBooleanNamed(CalendarSupportedParameters.RESCHEDULE_BASED_ON_MEETING_DATES.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.RESCHEDULE_BASED_ON_MEETING_DATES.getValue()) .value(rescheduleBasedOnMeetingDates).validateForBooleanValue(); } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.PRESENT_MEETING_DATE.getValue(), element)) { - final String presentMeetingDate = this.fromApiJsonHelper.extractStringNamed( - CalendarSupportedParameters.PRESENT_MEETING_DATE.getValue(), element); + final String presentMeetingDate = this.fromApiJsonHelper + .extractStringNamed(CalendarSupportedParameters.PRESENT_MEETING_DATE.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.PRESENT_MEETING_DATE.getValue()).value(presentMeetingDate) .notNull(); } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.NEW_MEETING_DATE.getValue(), element)) { - final String newMeetingDate = this.fromApiJsonHelper.extractStringNamed( - CalendarSupportedParameters.NEW_MEETING_DATE.getValue(), element); + final String newMeetingDate = this.fromApiJsonHelper.extractStringNamed(CalendarSupportedParameters.NEW_MEETING_DATE.getValue(), + element); baseDataValidator.reset().parameter(CalendarSupportedParameters.NEW_MEETING_DATE.getValue()).value(newMeetingDate).notNull(); } @@ -278,8 +277,8 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.DURATION.getValue(), element)) { - final Integer duration = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.DURATION.getValue(), element); + final Integer duration = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CalendarSupportedParameters.DURATION.getValue(), + element); baseDataValidator.reset().parameter(CalendarSupportedParameters.DURATION.getValue()).value(duration).ignoreIfNull(); } // TODO: AA do not allow to change calendar type. @@ -291,29 +290,28 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.REPEATING.getValue(), element)) { // FIXME - Throws NullPointerException when boolean value is null - final boolean repeating = this.fromApiJsonHelper.extractBooleanNamed(CalendarSupportedParameters.REPEATING.getValue(), - element); + final boolean repeating = this.fromApiJsonHelper.extractBooleanNamed(CalendarSupportedParameters.REPEATING.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.REPEATING.getValue()).value(repeating).notNull(); if (repeating) { - final Integer frequency = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.FREQUENCY.getValue(), element); + final Integer frequency = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.FREQUENCY.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.FREQUENCY.getValue()).value(frequency).notBlank() .inMinMaxRange(CalendarFrequencyType.getMinValue(), CalendarFrequencyType.getMaxValue()); if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.INTERVAL.getValue(), element)) { - final Integer interval = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.INTERVAL.getValue(), element); + final Integer interval = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.INTERVAL.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.INTERVAL.getValue()).value(interval).notNull() .integerGreaterThanZero(); } if (CalendarFrequencyType.fromInt(frequency).isWeekly()) { - if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.REPEATS_ON_DAY.getValue(), element)) { - final Integer repeatsOnDay = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.REPEATS_ON_DAY.getValue(), element); - baseDataValidator.reset().parameter(CalendarSupportedParameters.REPEATS_ON_DAY.getValue()).value(repeatsOnDay) - .notBlank().inMinMaxRange(CalendarWeekDaysType.getMinValue(), CalendarWeekDaysType.getMaxValue()); + if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.REPEATS_ON_DAY.getValue(), element)) { + final Integer repeatsOnDay = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.REPEATS_ON_DAY.getValue(), element); + baseDataValidator.reset().parameter(CalendarSupportedParameters.REPEATS_ON_DAY.getValue()).value(repeatsOnDay) + .notBlank().inMinMaxRange(CalendarWeekDaysType.getMinValue(), CalendarWeekDaysType.getMaxValue()); } } else if (CalendarFrequencyType.fromInt(frequency).isMonthly()) { CalendarUtils.validateNthDayOfMonthFrequency(baseDataValidator, @@ -324,33 +322,34 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.REMIND_BY_ID.getValue(), element)) { - final Integer remindById = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.REMIND_BY_ID.getValue(), element); + final Integer remindById = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.REMIND_BY_ID.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.REMIND_BY_ID.getValue()).value(remindById).ignoreIfNull() .inMinMaxRange(CalendarRemindBy.getMinValue(), CalendarRemindBy.getMaxValue()); } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.FIRST_REMINDER.getValue(), element)) { - final Integer firstReminder = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.FIRST_REMINDER.getValue(), element); - baseDataValidator.reset().parameter(CalendarSupportedParameters.FIRST_REMINDER.getValue()).value(firstReminder) - .ignoreIfNull(); + final Integer firstReminder = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.FIRST_REMINDER.getValue(), element); + baseDataValidator.reset().parameter(CalendarSupportedParameters.FIRST_REMINDER.getValue()).value(firstReminder).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.SECOND_REMINDER.getValue(), element)) { - final Integer secondReminder = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - CalendarSupportedParameters.SECOND_REMINDER.getValue(), element); + final Integer secondReminder = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(CalendarSupportedParameters.SECOND_REMINDER.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.SECOND_REMINDER.getValue()).value(secondReminder) .ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(CalendarSupportedParameters.MEETING_TIME.getValue(), element)) { - final LocalDateTime startDate = this.fromApiJsonHelper.extractLocalTimeNamed(CalendarSupportedParameters.MEETING_TIME.getValue(), - element); + final LocalDateTime startDate = this.fromApiJsonHelper + .extractLocalTimeNamed(CalendarSupportedParameters.MEETING_TIME.getValue(), element); baseDataValidator.reset().parameter(CalendarSupportedParameters.MEETING_TIME.getValue()).value(startDate).ignoreIfNull(); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarDropdownReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarDropdownReadPlatformService.java index 6afa9ef7a..78570b3b7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarDropdownReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarDropdownReadPlatformService.java @@ -32,6 +32,7 @@ public interface CalendarDropdownReadPlatformService { List retrieveCalendarFrequencyTypeOptions(); List retrieveCalendarWeekDaysTypeOptions(); + List retrieveCalendarFrequencyNthDayTypeOptions(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarDropdownReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarDropdownReadPlatformServiceImpl.java index 99d0e3495..68af8b425 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarDropdownReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarDropdownReadPlatformServiceImpl.java @@ -54,6 +54,7 @@ public class CalendarDropdownReadPlatformServiceImpl implements CalendarDropdown public List retrieveCalendarWeekDaysTypeOptions() { return CalendarEnumerations.calendarWeekDaysType(CalendarWeekDaysType.values()); } + @Override public List retrieveCalendarFrequencyNthDayTypeOptions() { return CalendarEnumerations.calendarFrequencyNthDayType(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarEnumerations.java index 500e3eca3..c3ee39aa4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarEnumerations.java @@ -36,7 +36,8 @@ public class CalendarEnumerations { } public static EnumOptionData calendarEntityType(final CalendarEntityType entityType) { - final EnumOptionData optionData = new EnumOptionData(entityType.getValue().longValue(), entityType.getCode(), entityType.toString()); + final EnumOptionData optionData = new EnumOptionData(entityType.getValue().longValue(), entityType.getCode(), + entityType.toString()); return optionData; } @@ -90,7 +91,7 @@ public class CalendarEnumerations { EnumOptionData optionData = null; if (!calendarFrequencyType.isInvalid()) { optionData = new EnumOptionData(calendarFrequencyType.getValue().longValue(), calendarFrequencyType.getCode(), - calendarFrequencyType.toString()); + calendarFrequencyType.toString()); } return optionData; } @@ -113,7 +114,7 @@ public class CalendarEnumerations { EnumOptionData optionData = null; if (!calendarWeekDaysType.isInvalid()) { optionData = new EnumOptionData(calendarWeekDaysType.getValue().longValue(), calendarWeekDaysType.getCode(), - calendarWeekDaysType.toString()); + calendarWeekDaysType.toString()); } return optionData; } @@ -127,14 +128,17 @@ public class CalendarEnumerations { } return optionDatas; } + public static EnumOptionData calendarFrequencyNthDayType(final int id) { return calendarFrequencyNthDayType(NthDayType.fromInt(id)); } + public static EnumOptionData calendarFrequencyNthDayType(final NthDayType calendarFrequencyNthDayType) { - final EnumOptionData optionData = new EnumOptionData(calendarFrequencyNthDayType.getValue().longValue(), calendarFrequencyNthDayType.getCode(), - calendarFrequencyNthDayType.toString()); + final EnumOptionData optionData = new EnumOptionData(calendarFrequencyNthDayType.getValue().longValue(), + calendarFrequencyNthDayType.getCode(), calendarFrequencyNthDayType.toString()); return optionData; } + public static List calendarFrequencyNthDayType() { final List optionDatas = Arrays.asList(calendarFrequencyNthDayType(NthDayType.ONE), calendarFrequencyNthDayType(NthDayType.TWO), calendarFrequencyNthDayType(NthDayType.THREE), diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarReadPlatformService.java index 3b77146cc..d84e4a897 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarReadPlatformService.java @@ -51,6 +51,4 @@ public interface CalendarReadPlatformService { Boolean isCalendarAssociatedWithEntity(final Long entityId, final Long calendarId, Long entityTypeId); - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarReadPlatformServiceImpl.java index b3ae7cce4..d80900cfc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarReadPlatformServiceImpl.java @@ -49,7 +49,8 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ private final ConfigurationDomainService configurationDomainService; @Autowired - public CalendarReadPlatformServiceImpl(final RoutingDataSource dataSource, final ConfigurationDomainService configurationDomainService) { + public CalendarReadPlatformServiceImpl(final RoutingDataSource dataSource, + final ConfigurationDomainService configurationDomainService) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.configurationDomainService = configurationDomainService; } @@ -88,7 +89,8 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ final EnumOptionData frequency = CalendarEnumerations.calendarFrequencyType(CalendarUtils.getFrequency(recurrence)); final Integer interval = Integer.valueOf(CalendarUtils.getInterval(recurrence)); final EnumOptionData repeatsOnDay = CalendarEnumerations.calendarWeekDaysType(CalendarUtils.getRepeatsOnDay(recurrence)); - final EnumOptionData repeatsOnNthDayOfMonth = CalendarEnumerations.calendarFrequencyNthDayType(CalendarUtils.getRepeatsOnNthDayOfMonth(recurrence)); + final EnumOptionData repeatsOnNthDayOfMonth = CalendarEnumerations + .calendarFrequencyNthDayType(CalendarUtils.getRepeatsOnNthDayOfMonth(recurrence)); final Integer remindById = rs.getInt("remindById"); EnumOptionData remindBy = null; if (remindById != null && remindById != 0) { @@ -107,12 +109,12 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ final String createdByUserName = rs.getString("creatingUserName"); final Long lastUpdatedByUserId = rs.getLong("updatingUserId"); final String lastUpdatedByUserName = rs.getString("updatingUserName"); - final LocalTime meetingTime = JdbcSupport.getLocalTime(rs,"meetingTime"); + final LocalTime meetingTime = JdbcSupport.getLocalTime(rs, "meetingTime"); return CalendarData.instance(id, calendarInstanceId, entityId, entityType, title, description, location, startDate, endDate, - duration, type, repeating, recurrence, frequency, interval, repeatsOnDay, repeatsOnNthDayOfMonth, remindBy, firstReminder, secondReminder, - humanReadable, createdDate, lastUpdatedDate, createdByUserId, createdByUserName, lastUpdatedByUserId, - lastUpdatedByUserName,meetingTime, monthOnDay); + duration, type, repeating, recurrence, frequency, interval, repeatsOnDay, repeatsOnNthDayOfMonth, remindBy, + firstReminder, secondReminder, humanReadable, createdDate, lastUpdatedDate, createdByUserId, createdByUserName, + lastUpdatedByUserId, lastUpdatedByUserName, meetingTime, monthOnDay); } } @@ -205,7 +207,8 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ } @Override - public Collection generateRecurringDates(final CalendarData calendarData, final boolean withHistory, final LocalDate tillDate) { + public Collection generateRecurringDates(final CalendarData calendarData, final boolean withHistory, + final LocalDate tillDate) { final LocalDate fromDate = null; Collection recurringDates = generateRecurringDate(calendarData, fromDate, tillDate, -1); @@ -225,8 +228,8 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ return generateRecurringDate(calendarData, DateUtils.getLocalDateOfTenant(), tillDate, 10); } - private Collection generateRecurringDate(final CalendarData calendarData, final LocalDate fromDate, - final LocalDate tillDate, final int maxCount) { + private Collection generateRecurringDate(final CalendarData calendarData, final LocalDate fromDate, final LocalDate tillDate, + final int maxCount) { if (!calendarData.isRepeating()) { return null; } final String rrule = calendarData.getRecurrence(); @@ -244,14 +247,13 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ final LocalDate periodEndDate = this.getPeriodEndDate(calendarData.getEndDate(), tillDate); Integer numberOfDays = 0; - boolean isSkipRepaymentOnFirstMonthEnabled = this.configurationDomainService - .isSkippingMeetingOnFirstDayOfMonthEnabled(); + boolean isSkipRepaymentOnFirstMonthEnabled = this.configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); if (isSkipRepaymentOnFirstMonthEnabled) { numberOfDays = this.configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } - final Collection recurringDates = CalendarUtils.getRecurringDates(rrule, seedDate, periodStartDate, - periodEndDate, maxCount, isSkipRepaymentOnFirstMonthEnabled, numberOfDays); + final Collection recurringDates = CalendarUtils.getRecurringDates(rrule, seedDate, periodStartDate, periodEndDate, + maxCount, isSkipRepaymentOnFirstMonthEnabled, numberOfDays); return recurringDates; } @@ -260,11 +262,9 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ String query = "Select COUNT(*) from m_calendar_instance ci where ci.entity_id = ? and ci.calendar_id = ? and " + " ci.entity_type_enum = ?"; try { - int calendarInstaneId = this.jdbcTemplate.queryForObject(query, - new Object[] { entityId, calendarId, entityTypeId }, Integer.class); - if (calendarInstaneId > 0) { - return true; - } + int calendarInstaneId = this.jdbcTemplate.queryForObject(query, new Object[] { entityId, calendarId, entityTypeId }, + Integer.class); + if (calendarInstaneId > 0) { return true; } return false; } catch (final EmptyResultDataAccessException e) { return false; @@ -330,10 +330,8 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ * 18th of Oct as per current calendar */ - Integer numberOfDays = 0; - boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService - .isSkippingMeetingOnFirstDayOfMonthEnabled(); + boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); if (isSkipRepaymentOnFirstMonthEnabled) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } @@ -341,8 +339,8 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ if (lastMeetingDate != null && !calendarData.isBetweenStartAndEndDate(lastMeetingDate) && !calendarData.isBetweenStartAndEndDate(DateUtils.getLocalDateOfTenant())) { applicableCalendarData = this.retrieveApplicableCalendarFromHistory(calendarData.getId(), lastMeetingDate); - nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), - lastMeetingDate, isSkipRepaymentOnFirstMonthEnabled, numberOfDays); + nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), lastMeetingDate, + isSkipRepaymentOnFirstMonthEnabled, numberOfDays); } /** @@ -351,8 +349,8 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ */ if (nextEligibleMeetingDate == null) { final LocalDate seedDate = (lastMeetingDate != null) ? lastMeetingDate : calendarData.getStartDate(); - nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), - seedDate, isSkipRepaymentOnFirstMonthEnabled, numberOfDays); + nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), seedDate, + isSkipRepaymentOnFirstMonthEnabled, numberOfDays); } else if (calendarData.isBetweenStartAndEndDate(nextEligibleMeetingDate)) { nextEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(applicableCalendarData.getRecurrence(), calendarData.getStartDate(), isSkipRepaymentOnFirstMonthEnabled, numberOfDays); @@ -479,8 +477,8 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ final EnumOptionData frequency = CalendarEnumerations.calendarFrequencyType(CalendarUtils.getFrequency(recurrence)); final Integer interval = Integer.valueOf(CalendarUtils.getInterval(recurrence)); final EnumOptionData repeatsOnDay = CalendarEnumerations.calendarWeekDaysType(CalendarUtils.getRepeatsOnDay(recurrence)); - final EnumOptionData repeatsOnNthDayOfMonth = CalendarEnumerations.calendarFrequencyNthDayType(CalendarUtils - .getRepeatsOnNthDayOfMonth(recurrence)); + final EnumOptionData repeatsOnNthDayOfMonth = CalendarEnumerations + .calendarFrequencyNthDayType(CalendarUtils.getRepeatsOnNthDayOfMonth(recurrence)); final Integer remindById = rs.getInt("remindById"); EnumOptionData remindBy = null; if (remindById != null && remindById != 0) { @@ -509,5 +507,4 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ } } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarUtils.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarUtils.java index b9a1c4fb3..42820e587 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarUtils.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/calendar/service/CalendarUtils.java @@ -55,6 +55,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CalendarUtils { + private final static Logger LOG = LoggerFactory.getLogger(CalendarUtils.class); static { System.setProperty("net.fortuna.ical4j.timezone.date.floating", "true"); @@ -116,7 +117,7 @@ public class CalendarUtils { try { formattedDate = new Date(seedDateStr, "yyyy-MM-dd"); } catch (final ParseException e) { - LOG.error("Invalid date: {}" , seedDateStr, e); + LOG.error("Invalid date: {}", seedDateStr, e); } return formattedDate; } @@ -182,7 +183,8 @@ public class CalendarUtils { return recurringDates; } - private static Collection skipMeetingOnFirstdayOfMonth(final Collection recurringDates, final Integer numberOfDays) { + private static Collection skipMeetingOnFirstdayOfMonth(final Collection recurringDates, + final Integer numberOfDays) { final Collection adjustedRecurringDates = new ArrayList<>(); for (@SuppressWarnings("rawtypes") @@ -213,10 +215,10 @@ public class CalendarUtils { return recur; } catch (final ParseException e) { // TODO Auto-generated catch block - LOG.error("Problem occurred in getICalRecur function",e); + LOG.error("Problem occurred in getICalRecur function", e); } catch (final ValidationException e) { // TODO Auto-generated catch block - LOG.error("Problem occurred in getICalRecur function",e); + LOG.error("Problem occurred in getICalRecur function", e); } return null; @@ -233,8 +235,8 @@ public class CalendarUtils { rrule.validate(); recur = rrule.getRecur(); } catch (final ValidationException e) { - throw new PlatformDataIntegrityException("error.msg.invalid.recurring.rule", "The Recurring Rule value: " + recurringRule - + " is not valid.", "recurrence", recurringRule); + throw new PlatformDataIntegrityException("error.msg.invalid.recurring.rule", + "The Recurring Rule value: " + recurringRule + " is not valid.", "recurrence", recurringRule); } catch (final ParseException e) { throw new PlatformDataIntegrityException("error.msg.recurring.rule.parsing.error", "Error in pasring the Recurring Rule value: " + recurringRule, "recurrence", recurringRule); @@ -306,9 +308,9 @@ public class CalendarUtils { } } else { if (recur.getInterval() == 1 || recur.getInterval() == -1) { - humanReadable = "Monthly on day " + startDate.getDayOfMonth(); - } else { - humanReadable = "Every " + recur.getInterval() + " months on day " + startDate.getDayOfMonth(); + humanReadable = "Monthly on day " + startDate.getDayOfMonth(); + } else { + humanReadable = "Every " + recur.getInterval() + " months on day " + startDate.getDayOfMonth(); } } } else if (recur.getFrequency().equals(Recur.Frequency.YEARLY)) { @@ -368,6 +370,7 @@ public class CalendarUtils { } public static enum DayNameEnum { + MO(1, "Monday"), TU(2, "Tuesday"), WE(3, "Wednesday"), TH(4, "Thursday"), FR(5, "Friday"), SA(6, "Saturday"), SU(7, "Sunday"); private final String code; @@ -393,8 +396,11 @@ public class CalendarUtils { return DayNameEnum.MO;// Default it to Monday } } + public static enum NthDayNameEnum { + ONE(1, "First"), TWO(2, "Second"), THREE(3, "Third"), FOUR(4, "Fourth"), FIVE(5, "Fifth"), LAST(-1, "Last"), INVALID(0, "Invalid"); + private final String code; private final Integer value; @@ -402,12 +408,15 @@ public class CalendarUtils { this.value = value; this.code = code; } + public String getCode() { return this.code; } + public int getValue() { return this.value; } + public static NthDayNameEnum from(final String name) { for (final NthDayNameEnum nthDayName : NthDayNameEnum.values()) { if (nthDayName.toString().equals(name)) { return nthDayName; } @@ -462,27 +471,22 @@ public class CalendarUtils { public static CalendarWeekDaysType getRepeatsOnDay(final String recurringRule) { final Recur recur = CalendarUtils.getICalRecur(recurringRule); final WeekDayList weekDays = recur.getDayList(); - if (weekDays.isEmpty()) { - return CalendarWeekDaysType.INVALID; - } + if (weekDays.isEmpty()) { return CalendarWeekDaysType.INVALID; } // supports only one day - WeekDay weekDay = weekDays.get(0); + WeekDay weekDay = weekDays.get(0); return CalendarWeekDaysType.fromString(weekDay.getDay().name()); } + public static NthDayType getRepeatsOnNthDayOfMonth(final String recurringRule) { final Recur recur = CalendarUtils.getICalRecur(recurringRule); NumberList monthDays = null; - if(recur.getDayList().isEmpty()) { + if (recur.getDayList().isEmpty()) { monthDays = recur.getMonthDayList(); } else { monthDays = recur.getSetPosList(); } - if (monthDays.isEmpty()) { - return NthDayType.INVALID; - } - if (!recur.getMonthDayList().isEmpty() && recur.getSetPosList().isEmpty()) { - return NthDayType.ONDAY; - } + if (monthDays.isEmpty()) { return NthDayType.INVALID; } + if (!recur.getMonthDayList().isEmpty() && recur.getSetPosList().isEmpty()) { return NthDayType.ONDAY; } Integer monthDay = monthDays.get(0); return NthDayType.fromInt(monthDay); } @@ -494,7 +498,8 @@ public class CalendarUtils { if (recur == null) { return null; } LocalDate startDate = disbursementDate; final LocalDate seedDate = calendar.getStartDateLocalDate(); - if (isValidRedurringDate(calendar.getRecurrence(), seedDate, startDate, isSkipRepaymentOnFirstDayOfMonth, numberOfDays) && !frequency.equals(Recur.Frequency.DAILY.name())) { + if (isValidRedurringDate(calendar.getRecurrence(), seedDate, startDate, isSkipRepaymentOnFirstDayOfMonth, numberOfDays) + && !frequency.equals(Recur.Frequency.DAILY.name())) { startDate = startDate.plusDays(1); } // Recurring dates should follow loanRepaymentInterval. @@ -520,8 +525,9 @@ public class CalendarUtils { Recur modifiedRecur = recurBuilder.build(); final LocalDate firstRepaymentDate = getNextRecurringDate(modifiedRecur, seedDate, startDate); - if (isSkipRepaymentOnFirstDayOfMonth && firstRepaymentDate.getDayOfMonth() == 1) { return adjustRecurringDate(firstRepaymentDate, - numberOfDays); } + if (isSkipRepaymentOnFirstDayOfMonth && firstRepaymentDate.getDayOfMonth() == 1) { + return adjustRecurringDate(firstRepaymentDate, numberOfDays); + } return firstRepaymentDate; } @@ -531,15 +537,17 @@ public class CalendarUtils { final boolean isSkipRepaymentOnFirstDayOfMonth, final Integer numberOfDays) { final Recur recur = CalendarUtils.getICalRecur(recurringRule); if (recur == null) { return null; } - if (isValidRecurringDate(recur, seedDate, oldRepaymentDate, isSkipRepaymentOnFirstDayOfMonth, numberOfDays)) { return oldRepaymentDate; } + if (isValidRecurringDate(recur, seedDate, oldRepaymentDate, isSkipRepaymentOnFirstDayOfMonth, numberOfDays)) { + return oldRepaymentDate; + } LocalDate nextRepaymentDate = getNextRepaymentMeetingDate(recurringRule, seedDate, oldRepaymentDate, loanRepaymentInterval, frequency, workingDays, isSkipRepaymentOnFirstDayOfMonth, numberOfDays); return nextRepaymentDate; } - public static LocalDate getNextRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, - final LocalDate repaymentDate, final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays, + public static LocalDate getNextRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, final LocalDate repaymentDate, + final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays, boolean isSkipRepaymentOnFirstDayOfMonth, final Integer numberOfDays) { final Recur recur = CalendarUtils.getICalRecur(recurringRule); @@ -560,7 +568,6 @@ public class CalendarUtils { recurBuilder = recurBuilder.interval(loanRepaymentInterval); - /* * Recurring dates should follow loanRepayment frequency. //e.g. daily * meeting frequency should support all loan products with any type of @@ -568,7 +575,6 @@ public class CalendarUtils { * same as loan repayment frequency. */ - if (recur.getFrequency().equals(Recur.Frequency.DAILY)) { recurBuilder = recurBuilder.frequency(Recur.Frequency.valueOf(frequency)); } @@ -688,6 +694,7 @@ public class CalendarUtils { return scheduleDate; } + public static void validateNthDayOfMonthFrequency(DataValidatorBuilder baseDataValidator, final String repeatsOnNthDayOfMonthParamName, final String repeatsOnDayParamName, final JsonElement element, final FromJsonHelper fromApiJsonHelper) { final Integer repeatsOnNthDayOfMonth = fromApiJsonHelper.extractIntegerSansLocaleNamed(repeatsOnNthDayOfMonthParamName, element); @@ -709,6 +716,7 @@ public class CalendarUtils { } } } + public static Integer getMonthOnDay(String recurringRule) { final Recur recur = CalendarUtils.getICalRecur(recurringRule); NumberList monthDayList = null; @@ -716,32 +724,32 @@ public class CalendarUtils { if (getMeetingPeriodFrequencyType(recur).isMonthly()) { monthDayList = recur.getMonthDayList(); if (!monthDayList.isEmpty()) { - monthOnDay = monthDayList.get(0); + monthOnDay = monthDayList.get(0); } } return monthOnDay; } - public static LocalDate getNextRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, - final LocalDate repaymentDate, final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays, + public static LocalDate getNextRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, final LocalDate repaymentDate, + final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays, boolean isSkipRepaymentOnFirstDayOfMonth, final Integer numberOfDays, boolean applyWorkingDays) { boolean isCalledFirstTime = true; - return getNextRepaymentMeetingDate(recurringRule, seedDate, repaymentDate, loanRepaymentInterval, frequency, - workingDays, isSkipRepaymentOnFirstDayOfMonth, numberOfDays, isCalledFirstTime, applyWorkingDays); + return getNextRepaymentMeetingDate(recurringRule, seedDate, repaymentDate, loanRepaymentInterval, frequency, workingDays, + isSkipRepaymentOnFirstDayOfMonth, numberOfDays, isCalledFirstTime, applyWorkingDays); } - public static LocalDate getNextRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, - final LocalDate repaymentDate, final Integer loanRepaymentInterval, final String frequency, - boolean isSkipRepaymentOnFirstDayOfMonth, final Integer numberOfDays) { + public static LocalDate getNextRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, final LocalDate repaymentDate, + final Integer loanRepaymentInterval, final String frequency, boolean isSkipRepaymentOnFirstDayOfMonth, + final Integer numberOfDays) { boolean isCalledFirstTime = true; final WorkingDays workingDays = null; boolean applyWorkingDays = false; - return getNextRepaymentMeetingDate(recurringRule, seedDate, repaymentDate, loanRepaymentInterval, frequency, - workingDays, isSkipRepaymentOnFirstDayOfMonth, numberOfDays, isCalledFirstTime, applyWorkingDays); + return getNextRepaymentMeetingDate(recurringRule, seedDate, repaymentDate, loanRepaymentInterval, frequency, workingDays, + isSkipRepaymentOnFirstDayOfMonth, numberOfDays, isCalledFirstTime, applyWorkingDays); } - public static LocalDate getNextRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, - final LocalDate repaymentDate, final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays, + public static LocalDate getNextRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, final LocalDate repaymentDate, + final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays, boolean isSkipRepaymentOnFirstDayOfMonth, final Integer numberOfDays, boolean isCalledFirstTime, boolean applyWorkingDays) { final Recur recur = CalendarUtils.getICalRecur(recurringRule); @@ -757,10 +765,10 @@ public class CalendarUtils { * set of meeting dates reset interval same as loan repayment interval. */ int meetingInterval = recur.getInterval(); - if(meetingInterval < 1){ - meetingInterval = 1; + if (meetingInterval < 1) { + meetingInterval = 1; } - int rep = repaymentInterval dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( - dataValidationErrors).resource("calendar"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("calendar"); Group centerOrGroup = null; if (groupId != null) { - centerOrGroup = this.groupRepository - .findOneWithNotFoundDetection(groupId); + centerOrGroup = this.groupRepository.findOneWithNotFoundDetection(groupId); final Group parent = centerOrGroup.getParent(); /* Check if it is a Group and belongs to a center */ if (centerOrGroup.isGroup() && parent != null) { - Integer centerEntityTypeId = CalendarEntityType.CENTERS - .getValue(); + Integer centerEntityTypeId = CalendarEntityType.CENTERS.getValue(); /* Check if calendar is created at center */ final CalendarInstance collectionCalendarInstance = this.calendarInstanceRepository - .findByEntityIdAndEntityTypeIdAndCalendarTypeId( - parent.getId(), centerEntityTypeId, + .findByEntityIdAndEntityTypeIdAndCalendarTypeId(parent.getId(), centerEntityTypeId, CalendarType.COLLECTION.getValue()); - /* If calendar is created by parent group, then it cannot be edited by the child group */ + /* + * If calendar is created by parent group, then it cannot be + * edited by the child group + */ if (collectionCalendarInstance != null) { final String errorMessage = "meeting.created.at.center.cannot.be.edited.at.group.level"; - baseDataValidator.reset() - .failWithCodeNoParameterAddedToErrorCode( - errorMessage); + baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(errorMessage); } } } if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); } } @@ -223,19 +217,18 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr final Collection loanStatuses = new ArrayList<>(Arrays.asList(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue(), LoanStatus.APPROVED.getValue(), LoanStatus.ACTIVE.getValue())); - final Integer numberOfActiveLoansSyncedWithThisCalendar = this.calendarInstanceRepository.countOfLoansSyncedWithCalendar( - calendarId, loanStatuses); + final Integer numberOfActiveLoansSyncedWithThisCalendar = this.calendarInstanceRepository.countOfLoansSyncedWithCalendar(calendarId, + loanStatuses); /* * areActiveEntitiesSynced is set to true, if there are any active loans * synced to this calendar. */ - if(numberOfActiveLoansSyncedWithThisCalendar > 0){ + if (numberOfActiveLoansSyncedWithThisCalendar > 0) { areActiveEntitiesSynced = true; } - final Calendar calendarForUpdate = this.calendarRepository.findById(calendarId) .orElseThrow(() -> new CalendarNotFoundException(calendarId)); @@ -251,18 +244,19 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr /* * System allows to change the meeting date by two means, * - * Option 1: reschedulebasedOnMeetingDates = false or reschedulebasedOnMeetingDates is not passed - * By directly editing the recurring day with effective from - * date and system decides the next meeting date based on some sensible - * logic (i.e., number of minimum days between two repayments) + * Option 1: reschedulebasedOnMeetingDates = false or + * reschedulebasedOnMeetingDates is not passed By directly editing the + * recurring day with effective from date and system decides the next + * meeting date based on some sensible logic (i.e., number of minimum + * days between two repayments) * * - * Option 2: reschedulebasedOnMeetingDates = true - * By providing alternative meeting date for one of future - * meeting date and derive the day of recurrence from the new meeting - * date. Ex: User proposes new meeting date say "14/Nov/2014" for - * present meeting date "12/Nov/2014", based on this input other values - * re derived and loans are rescheduled + * Option 2: reschedulebasedOnMeetingDates = true By providing + * alternative meeting date for one of future meeting date and derive + * the day of recurrence from the new meeting date. Ex: User proposes + * new meeting date say "14/Nov/2014" for present meeting date + * "12/Nov/2014", based on this input other values re derived and loans + * are rescheduled * */ @@ -288,8 +282,8 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr if (!changes.isEmpty()) { // update calendar history table only if there is a change in // calendar start date. - if (reschedulebasedOnMeetingDates == null){ - presentMeetingDate = command.localDateValueOfParameterNamed(CalendarSupportedParameters.START_DATE.getValue()); + if (reschedulebasedOnMeetingDates == null) { + presentMeetingDate = command.localDateValueOfParameterNamed(CalendarSupportedParameters.START_DATE.getValue()); } if (null != newMeetingDate) { final Date endDate = presentMeetingDate.minusDays(1).toDate(); @@ -304,8 +298,8 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr if (this.configurationDomainService.isRescheduleFutureRepaymentsEnabled() && calendarForUpdate.isRepeating()) { // fetch all loan calendar instances associated with modifying // calendar. - final Collection loanCalendarInstances = this.calendarInstanceRepository.findByCalendarIdAndEntityTypeId( - calendarId, CalendarEntityType.LOANS.getValue()); + final Collection loanCalendarInstances = this.calendarInstanceRepository + .findByCalendarIdAndEntityTypeId(calendarId, CalendarEntityType.LOANS.getValue()); if (!CollectionUtils.isEmpty(loanCalendarInstances)) { // update all loans associated with modifying calendar @@ -316,10 +310,7 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr } } - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withEntityId(calendarForUpdate.getId()) - .with(changes) + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(calendarForUpdate.getId()).with(changes) .build(); } @@ -329,10 +320,7 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr .orElseThrow(() -> new CalendarNotFoundException(calendarId)); this.calendarRepository.delete(calendarForDelete); - return new CommandProcessingResultBuilder() - .withCommandId(null) - .withEntityId(calendarId) - .build(); + return new CommandProcessingResultBuilder().withCommandId(null).withEntityId(calendarId).build(); } @Override @@ -343,10 +331,7 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr final CalendarInstance newCalendarInstance = new CalendarInstance(calendarForUpdate, entityId, entityTypeId); this.calendarInstanceRepository.save(newCalendarInstance); - return new CommandProcessingResultBuilder() - .withCommandId(null) - .withEntityId(calendarForUpdate.getId()) - .build(); + return new CommandProcessingResultBuilder().withCommandId(null).withEntityId(calendarForUpdate.getId()).build(); } @Override @@ -354,12 +339,9 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr final Calendar calendarForUpdate = this.calendarRepository.findById(calendarId) .orElseThrow(() -> new CalendarNotFoundException(calendarId)); - final CalendarInstance calendarInstanceForUpdate = this.calendarInstanceRepository.findByCalendarIdAndEntityIdAndEntityTypeId( - calendarId, entityId, entityTypeId); + final CalendarInstance calendarInstanceForUpdate = this.calendarInstanceRepository + .findByCalendarIdAndEntityIdAndEntityTypeId(calendarId, entityId, entityTypeId); this.calendarInstanceRepository.saveAndFlush(calendarInstanceForUpdate); - return new CommandProcessingResultBuilder() - .withCommandId(null) - .withEntityId(calendarForUpdate.getId()) - .build(); + return new CommandProcessingResultBuilder().withCommandId(null).withEntityId(calendarForUpdate.getId()).build(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/api/ChargesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/api/ChargesApiResource.java index 42c814e6c..ee33f9313 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/api/ChargesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/api/ChargesApiResource.java @@ -59,10 +59,11 @@ import org.springframework.stereotype.Component; @Path("/charges") @Component @Scope("singleton") -@Api(tags = {"Charges"}) +@Api(tags = { "Charges" }) @SwaggerDefinition(tags = { - @Tag(name = "Charges", description = "Its typical for MFIs to add extra costs for their financial products. These are typically Fees or Penalties.\n" + "\n" + "A Charge on fineract platform is what we use to model both Fees and Penalties.\n" + "\n" + "At present we support defining charges for use with Client accounts and both loan and saving products.") -}) + @Tag(name = "Charges", description = "Its typical for MFIs to add extra costs for their financial products. These are typically Fees or Penalties.\n" + + "\n" + "A Charge on fineract platform is what we use to model both Fees and Penalties.\n" + "\n" + + "At present we support defining charges for use with Client accounts and both loan and saving products.") }) public class ChargesApiResource { private final Set CHARGES_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "amount", "currency", "penalty", "active", @@ -93,8 +94,10 @@ public class ChargesApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Charges", httpMethod = "GET", notes = "Returns the list of defined charges.\n" + "\n" + "Example Requests:\n" + "\n" + "charges") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.GetChargesResponse.class, responseContainer = "List")}) + @ApiOperation(value = "Retrieve Charges", httpMethod = "GET", notes = "Returns the list of defined charges.\n" + "\n" + + "Example Requests:\n" + "\n" + "charges") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.GetChargesResponse.class, responseContainer = "List") }) public String retrieveAllCharges(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -109,8 +112,9 @@ public class ChargesApiResource { @Path("{chargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Charge", httpMethod = "GET", notes = "Returns the details of a defined Charge.\n" + "\n" + "Example Requests:\n" + "\n" + "charges/1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.GetChargesResponse.class)}) + @ApiOperation(value = "Retrieve a Charge", httpMethod = "GET", notes = "Returns the details of a defined Charge.\n" + "\n" + + "Example Requests:\n" + "\n" + "charges/1") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.GetChargesResponse.class) }) public String retrieveCharge(@PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -130,8 +134,9 @@ public class ChargesApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Charge Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "charges/template\n") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.GetChargesTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Charge Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "charges/template\n") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.GetChargesTemplateResponse.class) }) public String retrieveNewChargeDetails(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -146,8 +151,9 @@ public class ChargesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create/Define a Charge", httpMethod = "POST", notes = "Define a new charge that can later be associated with loans and savings through their respective product definitions or directly on each account instance.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ChargesApiResourceSwagger.PostChargesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.PostChargesResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ChargesApiResourceSwagger.PostChargesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.PostChargesResponse.class) }) public String createCharge(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createCharge().withJson(apiRequestBodyAsJson).build(); @@ -162,9 +168,11 @@ public class ChargesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Charge", httpMethod = "PUT", notes = "Updates the details of a Charge.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ChargesApiResourceSwagger.PutChargesChargeIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.PutChargesChargeIdResponse.class)}) - public String updateCharge(@PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ChargesApiResourceSwagger.PutChargesChargeIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.PutChargesChargeIdResponse.class) }) + public String updateCharge(@PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCharge(chargeId).withJson(apiRequestBodyAsJson).build(); @@ -178,7 +186,7 @@ public class ChargesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Charge", httpMethod = "DELETE", notes = "Deletes a Charge.") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.DeleteChargesChargeIdResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ChargesApiResourceSwagger.DeleteChargesChargeIdResponse.class) }) public String deleteCharge(@PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteCharge(chargeId).build(); @@ -187,4 +195,4 @@ public class ChargesApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/api/ChargesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/api/ChargesApiResourceSwagger.java index 01c7a1039..5dc58cd10 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/api/ChargesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/api/ChargesApiResourceSwagger.java @@ -29,10 +29,11 @@ final class ChargesApiResourceSwagger { @ApiModel(value = "GetChargesResponse") public static final class GetChargesResponse { - private GetChargesResponse() { - } + + private GetChargesResponse() {} final class GetChargesCurrencyResponse { + @ApiModelProperty(example = "USD") public String code; @ApiModelProperty(example = "US Dollar") @@ -48,8 +49,8 @@ final class ChargesApiResourceSwagger { } final class GetChargesTimeTypeResponse { - private GetChargesTimeTypeResponse() { - } + + private GetChargesTimeTypeResponse() {} @ApiModelProperty(example = "1") public Integer id; @@ -60,8 +61,8 @@ final class ChargesApiResourceSwagger { } final class GetChargesAppliesToResponse { - private GetChargesAppliesToResponse() { - } + + private GetChargesAppliesToResponse() {} @ApiModelProperty(example = "1") public Integer id; @@ -72,8 +73,8 @@ final class ChargesApiResourceSwagger { } final class GetChargesCalculationTypeResponse { - private GetChargesCalculationTypeResponse() { - } + + private GetChargesCalculationTypeResponse() {} @ApiModelProperty(example = "1") public Integer id; @@ -84,8 +85,8 @@ final class ChargesApiResourceSwagger { } final class GetChargesPaymentModeResponse { - private GetChargesPaymentModeResponse() { - } + + private GetChargesPaymentModeResponse() {} @ApiModelProperty(example = "1") public Integer id; @@ -114,8 +115,8 @@ final class ChargesApiResourceSwagger { @ApiModel(value = "PostChargesRequest") public static final class PostChargesRequest { - private PostChargesRequest() { - } + + private PostChargesRequest() {} @ApiModelProperty(example = "Loan Service fee") public String name; @@ -139,8 +140,8 @@ final class ChargesApiResourceSwagger { @ApiModel(value = "PostChargesResponse") public static final class PostChargesResponse { - private PostChargesResponse() { - } + + private PostChargesResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -148,8 +149,8 @@ final class ChargesApiResourceSwagger { @ApiModel(value = "PutChargesChargeIdRequest") public static final class PutChargesChargeIdRequest { - private PutChargesChargeIdRequest() { - } + + private PutChargesChargeIdRequest() {} @ApiModelProperty(example = "Loan service fee(changed)") public String name; @@ -157,8 +158,8 @@ final class ChargesApiResourceSwagger { @ApiModel(value = "PutChargesChargeIdResponse") public static final class PutChargesChargeIdResponse { - private PutChargesChargeIdResponse() { - } + + private PutChargesChargeIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -167,8 +168,8 @@ final class ChargesApiResourceSwagger { @ApiModel(value = "DeleteChargesChargeIdResponse") public static final class DeleteChargesChargeIdResponse { - private DeleteChargesChargeIdResponse() { - } + + private DeleteChargesChargeIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -176,12 +177,12 @@ final class ChargesApiResourceSwagger { @ApiModel(value = "GetChargesTemplateResponse") public static final class GetChargesTemplateResponse { - private GetChargesTemplateResponse() { - } + + private GetChargesTemplateResponse() {} final class GetChargesTemplateLoanChargeCalculationTypeOptions { - private GetChargesTemplateLoanChargeCalculationTypeOptions() { - } + + private GetChargesTemplateLoanChargeCalculationTypeOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -192,8 +193,8 @@ final class ChargesApiResourceSwagger { } final class GetChargesTemplateLoanChargeTimeTypeOptions { - private GetChargesTemplateLoanChargeTimeTypeOptions() { - } + + private GetChargesTemplateLoanChargeTimeTypeOptions() {} @ApiModelProperty(example = "2") public Integer id; @@ -202,8 +203,11 @@ final class ChargesApiResourceSwagger { @ApiModelProperty(example = "Specified due date") public String value; } - final class GetChargesTemplateFeeFrequencyOptions{ - private GetChargesTemplateFeeFrequencyOptions(){} + + final class GetChargesTemplateFeeFrequencyOptions { + + private GetChargesTemplateFeeFrequencyOptions() {} + @ApiModelProperty(example = "0") public Integer id; @ApiModelProperty(example = "loanTermFrequency.periodFrequencyType.days") @@ -211,6 +215,7 @@ final class ChargesApiResourceSwagger { @ApiModelProperty(example = "Days") public String value; } + @ApiModelProperty(example = "false") public String active; @ApiModelProperty(example = "false") diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/data/ChargeData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/data/ChargeData.java old mode 100755 new mode 100644 index 738e8dfce..e73dc6b83 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/data/ChargeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/data/ChargeData.java @@ -92,8 +92,8 @@ public class ChargeData implements Comparable, Serializable { return new ChargeData(null, null, null, null, null, null, null, null, false, false, taxGroupData, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions, chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions, savingsChargeCalculationTypeOptions, - savingsChargeTimeTypeOptions, clientChargeCalculationTypeOptions, clientChargeTimeTypeOptions, null, null, null, null, - null, feeFrequencyOptions, account, incomeOrLiabilityAccountOptions, taxGroupOptions, shareChargeCalculationTypeOptions, + savingsChargeTimeTypeOptions, clientChargeCalculationTypeOptions, clientChargeTimeTypeOptions, null, null, null, null, null, + feeFrequencyOptions, account, incomeOrLiabilityAccountOptions, taxGroupOptions, shareChargeCalculationTypeOptions, shareChargeTimeTypeOptions); } @@ -103,10 +103,10 @@ public class ChargeData implements Comparable, Serializable { template.currencyOptions, template.chargeCalculationTypeOptions, template.chargeAppliesToOptions, template.chargeTimeTypeOptions, template.chargePaymetModeOptions, template.loanChargeCalculationTypeOptions, template.loanChargeTimeTypeOptions, template.savingsChargeCalculationTypeOptions, template.savingsChargeTimeTypeOptions, - template.clientChargeCalculationTypeOptions, template.clientChargeTimeTypeOptions, charge.feeOnMonthDay, - charge.feeInterval, charge.minCap, charge.maxCap, charge.feeFrequency, template.feeFrequencyOptions, - charge.incomeOrLiabilityAccount, template.incomeOrLiabilityAccountOptions, template.taxGroupOptions, - template.shareChargeCalculationTypeOptions, template.shareChargeTimeTypeOptions); + template.clientChargeCalculationTypeOptions, template.clientChargeTimeTypeOptions, charge.feeOnMonthDay, charge.feeInterval, + charge.minCap, charge.maxCap, charge.feeFrequency, template.feeFrequencyOptions, charge.incomeOrLiabilityAccount, + template.incomeOrLiabilityAccountOptions, template.taxGroupOptions, template.shareChargeCalculationTypeOptions, + template.shareChargeTimeTypeOptions); } public static ChargeData instance(final Long id, final String name, final BigDecimal amount, final CurrencyData currency, @@ -132,8 +132,8 @@ public class ChargeData implements Comparable, Serializable { final List shareChargeTimeTypeOptions = null; final Collection taxGroupOptions = null; return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode, - penalty, active, taxGroupData, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, - chargeTimeTypeOptions, chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions, + penalty, active, taxGroupData, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions, + chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions, savingsChargeCalculationTypeOptions, savingsChargeTimeTypeOptions, clientChargeCalculationTypeOptions, clientChargeTimeTypeOptions, feeOnMonthDay, feeInterval, minCap, maxCap, feeFrequency, feeFrequencyOptions, accountData, incomeOrLiabilityAccountOptions, taxGroupOptions, shareChargeCalculationTypeOptions, shareChargeTimeTypeOptions); @@ -172,8 +172,8 @@ public class ChargeData implements Comparable, Serializable { final TaxGroupData taxGroupData = null; final Collection taxGroupOptions = null; return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode, - penalty, active, taxGroupData, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, - chargeTimeTypeOptions, chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions, + penalty, active, taxGroupData, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions, + chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions, savingsChargeCalculationTypeOptions, savingsChargeTimeTypeOptions, clientChargeCalculationTypeOptions, clientChargeTimeTypeOptions, feeOnMonthDay, feeInterval, minCap, maxCap, feeFrequency, feeFrequencyOptions, account, incomeOrLiabilityAccountOptions, taxGroupOptions, shareChargeCalculationTypeOptions, shareChargeTimeTypeOptions); @@ -229,9 +229,7 @@ public class ChargeData implements Comparable, Serializable { @Override public boolean equals(final Object obj) { - if (!(obj instanceof ChargeData)) { - return false; - } + if (!(obj instanceof ChargeData)) { return false; } final ChargeData chargeData = (ChargeData) obj; return this.id.equals(chargeData.id); } @@ -275,9 +273,9 @@ public class ChargeData implements Comparable, Serializable { final LocalDate inactivationDate = null; return SavingsAccountChargeData.instance(savingsChargeId, this.id, savingsAccountId, this.name, this.currency, this.amount, - amountPaid, amountWaived, amountWrittenOff, amountOutstanding, this.chargeTimeType, dueAsOfDate, - this.chargeCalculationType, percentage, amountPercentageAppliedTo, chargeOptions, this.penalty, this.feeOnMonthDay, - this.feeInterval, isActive, inactivationDate); + amountPaid, amountWaived, amountWrittenOff, amountOutstanding, this.chargeTimeType, dueAsOfDate, this.chargeCalculationType, + percentage, amountPercentageAppliedTo, chargeOptions, this.penalty, this.feeOnMonthDay, this.feeInterval, isActive, + inactivationDate); } public ShareAccountChargeData toShareAccountChargeData() { @@ -292,7 +290,7 @@ public class ChargeData implements Comparable, Serializable { final BigDecimal amountPercentageAppliedTo = BigDecimal.ZERO; final Collection chargeOptions = null; final Boolean isActive = null; - final BigDecimal chargeAmountOrPercentage = BigDecimal.ZERO ; + final BigDecimal chargeAmountOrPercentage = BigDecimal.ZERO; return new ShareAccountChargeData(shareChargeId, this.id, shareAccountId, this.name, this.currency, this.amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, this.chargeTimeType, this.chargeCalculationType, percentage, diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/Charge.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/Charge.java old mode 100755 new mode 100644 index dadd149c6..871b2f7f0 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/Charge.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/Charge.java @@ -117,8 +117,8 @@ public class Charge extends AbstractPersistableCustom { final ChargeAppliesTo chargeAppliesTo = ChargeAppliesTo.fromInt(command.integerValueOfParameterNamed("chargeAppliesTo")); final ChargeTimeType chargeTimeType = ChargeTimeType.fromInt(command.integerValueOfParameterNamed("chargeTimeType")); - final ChargeCalculationType chargeCalculationType = ChargeCalculationType.fromInt(command - .integerValueOfParameterNamed("chargeCalculationType")); + final ChargeCalculationType chargeCalculationType = ChargeCalculationType + .fromInt(command.integerValueOfParameterNamed("chargeCalculationType")); final Integer chargePaymentMode = command.integerValueOfParameterNamed("chargePaymentMode"); final ChargePaymentMode paymentMode = chargePaymentMode == null ? null : ChargePaymentMode.fromInt(chargePaymentMode); @@ -135,13 +135,12 @@ public class Charge extends AbstractPersistableCustom { feeOnMonthDay, feeInterval, minCap, maxCap, feeFrequency, account, taxGroup); } - protected Charge() { - } + protected Charge() {} private Charge(final String name, final BigDecimal amount, final String currencyCode, final ChargeAppliesTo chargeAppliesTo, - final ChargeTimeType chargeTime, final ChargeCalculationType chargeCalculationType, final boolean penalty, - final boolean active, final ChargePaymentMode paymentMode, final MonthDay feeOnMonthDay, final Integer feeInterval, - final BigDecimal minCap, final BigDecimal maxCap, final Integer feeFrequency, final GLAccount account, final TaxGroup taxGroup) { + final ChargeTimeType chargeTime, final ChargeCalculationType chargeCalculationType, final boolean penalty, final boolean active, + final ChargePaymentMode paymentMode, final MonthDay feeOnMonthDay, final Integer feeInterval, final BigDecimal minCap, + final BigDecimal maxCap, final Integer feeFrequency, final GLAccount account, final TaxGroup taxGroup) { this.name = name; this.amount = amount; this.currencyCode = currencyCode; @@ -178,16 +177,19 @@ public class Charge extends AbstractPersistableCustom { .failWithCodeNoParameterAddedToErrorCode("not.allowed.charge.calculation.type.for.savings"); } - if (!(ChargeTimeType.fromInt(getChargeTimeType()).isWithdrawalFee() || ChargeTimeType.fromInt(getChargeTimeType()).isSavingsNoActivityFee()) + if (!(ChargeTimeType.fromInt(getChargeTimeType()).isWithdrawalFee() + || ChargeTimeType.fromInt(getChargeTimeType()).isSavingsNoActivityFee()) && ChargeCalculationType.fromInt(getChargeCalculation()).isPercentageOfAmount()) { baseDataValidator.reset().parameter("chargeCalculationType").value(this.chargeCalculation) - .failWithCodeNoParameterAddedToErrorCode("savings.charge.calculation.type.percentage.allowed.only.for.withdrawal.or.NoActivity"); + .failWithCodeNoParameterAddedToErrorCode( + "savings.charge.calculation.type.percentage.allowed.only.for.withdrawal.or.NoActivity"); } } else if (isLoanCharge()) { - if (penalty && (chargeTime.isTimeOfDisbursement() || chargeTime.isTrancheDisbursement())) { throw new ChargeDueAtDisbursementCannotBePenaltyException( - name); } + if (penalty && (chargeTime.isTimeOfDisbursement() || chargeTime.isTrancheDisbursement())) { + throw new ChargeDueAtDisbursementCannotBePenaltyException(name); + } if (!penalty && chargeTime.isOverdueInstallment()) { throw new ChargeMustBePenaltyException(name); } // TODO vishwas, this validation seems unnecessary as identical // validation is performed in the write service @@ -376,10 +378,12 @@ public class Charge extends AbstractPersistableCustom { .failWithCodeNoParameterAddedToErrorCode("not.allowed.charge.calculation.type.for.savings"); } - if (!(ChargeTimeType.fromInt(getChargeTimeType()).isWithdrawalFee() || ChargeTimeType.fromInt(getChargeTimeType()).isSavingsNoActivityFee()) + if (!(ChargeTimeType.fromInt(getChargeTimeType()).isWithdrawalFee() + || ChargeTimeType.fromInt(getChargeTimeType()).isSavingsNoActivityFee()) && ChargeCalculationType.fromInt(getChargeCalculation()).isPercentageOfAmount()) { baseDataValidator.reset().parameter("chargeCalculationType").value(this.chargeCalculation) - .failWithCodeNoParameterAddedToErrorCode("charge.calculation.type.percentage.allowed.only.for.withdrawal.or.noactivity"); + .failWithCodeNoParameterAddedToErrorCode( + "charge.calculation.type.percentage.allowed.only.for.withdrawal.or.noactivity"); } } else if (isClientCharge()) { if (!isAllowedClientChargeCalculationType()) { @@ -469,9 +473,12 @@ public class Charge extends AbstractPersistableCustom { } - if (this.penalty && ChargeTimeType.fromInt(this.chargeTimeType).isTimeOfDisbursement()) { throw new ChargeDueAtDisbursementCannotBePenaltyException( - this.name); } - if (!penalty && ChargeTimeType.fromInt(this.chargeTimeType).isOverdueInstallment()) { throw new ChargeMustBePenaltyException(name); } + if (this.penalty && ChargeTimeType.fromInt(this.chargeTimeType).isTimeOfDisbursement()) { + throw new ChargeDueAtDisbursementCannotBePenaltyException(this.name); + } + if (!penalty && ChargeTimeType.fromInt(this.chargeTimeType).isOverdueInstallment()) { + throw new ChargeMustBePenaltyException(name); + } if (command.isChangeInLongParameterNamed(ChargesApiConstants.glAccountIdParamName, getIncomeAccountId())) { final Long newValue = command.longValueOfParameterNamed(ChargesApiConstants.glAccountIdParamName); @@ -481,7 +488,7 @@ public class Charge extends AbstractPersistableCustom { if (command.isChangeInLongParameterNamed(ChargesApiConstants.taxGroupIdParamName, getTaxGroupId())) { final Long newValue = command.longValueOfParameterNamed(ChargesApiConstants.taxGroupIdParamName); actualChanges.put(ChargesApiConstants.taxGroupIdParamName, newValue); - if(taxGroup != null){ + if (taxGroup != null) { baseDataValidator.reset().parameter(ChargesApiConstants.taxGroupIdParamName).failWithCode("modification.not.supported"); } } @@ -598,36 +605,22 @@ public class Charge extends AbstractPersistableCustom { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Charge)) { - return false; - } - Charge other= (Charge) o; - return Objects.equals(name, other.name) && - Objects.equals(amount, other.amount) && - Objects.equals(currencyCode, other.currencyCode) && - Objects.equals(chargeAppliesTo, other.chargeAppliesTo) && - Objects.equals(chargeTimeType, other.chargeTimeType) && - Objects.equals(chargeCalculation, other.chargeCalculation) && - Objects.equals(chargePaymentMode, other.chargePaymentMode) && - Objects.equals(feeOnDay, other.feeOnDay) && - Objects.equals(feeInterval, other.feeInterval) && - Objects.equals(feeOnMonth, other.feeOnMonth) && - penalty == other.penalty && - active == other.active && - deleted == other.deleted && - Objects.equals(minCap, other.minCap) && - Objects.equals(maxCap, other.maxCap) && - Objects.equals(feeFrequency, other.feeFrequency) && - Objects.equals(account, other.account) && - Objects.equals(taxGroup, other.taxGroup); + if (this == o) { return true; } + if (!(o instanceof Charge)) { return false; } + Charge other = (Charge) o; + return Objects.equals(name, other.name) && Objects.equals(amount, other.amount) && Objects.equals(currencyCode, other.currencyCode) + && Objects.equals(chargeAppliesTo, other.chargeAppliesTo) && Objects.equals(chargeTimeType, other.chargeTimeType) + && Objects.equals(chargeCalculation, other.chargeCalculation) && Objects.equals(chargePaymentMode, other.chargePaymentMode) + && Objects.equals(feeOnDay, other.feeOnDay) && Objects.equals(feeInterval, other.feeInterval) + && Objects.equals(feeOnMonth, other.feeOnMonth) && penalty == other.penalty && active == other.active + && deleted == other.deleted && Objects.equals(minCap, other.minCap) && Objects.equals(maxCap, other.maxCap) + && Objects.equals(feeFrequency, other.feeFrequency) && Objects.equals(account, other.account) + && Objects.equals(taxGroup, other.taxGroup); } @Override public int hashCode() { - return Objects.hash(name, amount, currencyCode, chargeAppliesTo, chargeTimeType, chargeCalculation, - chargePaymentMode, feeOnDay, feeInterval, feeOnMonth, penalty, active, deleted, minCap, maxCap, feeFrequency, account, taxGroup); + return Objects.hash(name, amount, currencyCode, chargeAppliesTo, chargeTimeType, chargeCalculation, chargePaymentMode, feeOnDay, + feeInterval, feeOnMonth, penalty, active, deleted, minCap, maxCap, feeFrequency, account, taxGroup); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeAppliesTo.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeAppliesTo.java index eecf46348..cb97dae64 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeAppliesTo.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeAppliesTo.java @@ -23,8 +23,7 @@ public enum ChargeAppliesTo { INVALID(0, "chargeAppliesTo.invalid"), // LOAN(1, "chargeAppliesTo.loan"), // SAVINGS(2, "chargeAppliesTo.savings"), // - CLIENT(3, "chargeAppliesTo.client"), - SHARES(4, "chargeAppliesTo.shares"); + CLIENT(3, "chargeAppliesTo.client"), SHARES(4, "chargeAppliesTo.shares"); private final Integer value; private final String code; @@ -57,8 +56,8 @@ public enum ChargeAppliesTo { chargeAppliesToType = CLIENT; break; case 4: - chargeAppliesToType = SHARES ; - break ; + chargeAppliesToType = SHARES; + break; default: chargeAppliesToType = INVALID; break; @@ -81,9 +80,11 @@ public enum ChargeAppliesTo { } public boolean isSharesCharge() { - return this.value.equals(SHARES.getValue()) ; + return this.value.equals(SHARES.getValue()); } + public static Object[] validValues() { - return new Object[] { ChargeAppliesTo.LOAN.getValue(), ChargeAppliesTo.SAVINGS.getValue(), ChargeAppliesTo.CLIENT.getValue(), ChargeAppliesTo.SHARES.getValue() }; + return new Object[] { ChargeAppliesTo.LOAN.getValue(), ChargeAppliesTo.SAVINGS.getValue(), ChargeAppliesTo.CLIENT.getValue(), + ChargeAppliesTo.SHARES.getValue() }; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeCalculationType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeCalculationType.java index 38648e243..554145adb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeCalculationType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeCalculationType.java @@ -24,8 +24,8 @@ public enum ChargeCalculationType { FLAT(1, "chargeCalculationType.flat"), // PERCENT_OF_AMOUNT(2, "chargeCalculationType.percent.of.amount"), // PERCENT_OF_AMOUNT_AND_INTEREST(3, "chargeCalculationType.percent.of.amount.and.interest"), // - PERCENT_OF_INTEREST(4, "chargeCalculationType.percent.of.interest"), - PERCENT_OF_DISBURSEMENT_AMOUNT(5,"chargeCalculationType.percent.of.disbursement.amount"); + PERCENT_OF_INTEREST(4, "chargeCalculationType.percent.of.interest"), PERCENT_OF_DISBURSEMENT_AMOUNT(5, + "chargeCalculationType.percent.of.disbursement.amount"); private final Integer value; private final String code; @@ -46,7 +46,7 @@ public enum ChargeCalculationType { public static Object[] validValuesForLoan() { return new Integer[] { ChargeCalculationType.FLAT.getValue(), ChargeCalculationType.PERCENT_OF_AMOUNT.getValue(), ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST.getValue(), ChargeCalculationType.PERCENT_OF_INTEREST.getValue(), - ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue()}; + ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue() }; } public static Object[] validValuesForSavings() { @@ -65,8 +65,8 @@ public enum ChargeCalculationType { return new Integer[] { ChargeCalculationType.FLAT.getValue() }; } - public static Object[] validValuesForTrancheDisbursement(){ - return new Integer[] { ChargeCalculationType.FLAT.getValue(), ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue()}; + public static Object[] validValuesForTrancheDisbursement() { + return new Integer[] { ChargeCalculationType.FLAT.getValue(), ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue() }; } public static ChargeCalculationType fromInt(final Integer chargeCalculation) { @@ -116,10 +116,11 @@ public enum ChargeCalculationType { } public boolean isPercentageBased() { - return isPercentageOfAmount() || isPercentageOfAmountAndInterest() || isPercentageOfInterest() || isPercentageOfDisbursementAmount(); + return isPercentageOfAmount() || isPercentageOfAmountAndInterest() || isPercentageOfInterest() + || isPercentageOfDisbursementAmount(); } - public boolean isPercentageOfDisbursementAmount(){ + public boolean isPercentageOfDisbursementAmount() { return this.value.equals(ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargePaymentMode.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargePaymentMode.java old mode 100755 new mode 100644 index ddafebeb1..5e0940f3a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargePaymentMode.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargePaymentMode.java @@ -59,4 +59,4 @@ public enum ChargePaymentMode { public boolean isPaymentModeAccountTransfer() { return this.value.equals(ChargePaymentMode.ACCOUNT_TRANSFER.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeTimeType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeTimeType.java old mode 100755 new mode 100644 index ea6f84791..fdcf3e0cd --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeTimeType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/domain/ChargeTimeType.java @@ -19,6 +19,7 @@ package org.apache.fineract.portfolio.charge.domain; public enum ChargeTimeType { + INVALID(0, "chargeTimeType.invalid"), // DISBURSEMENT(1, "chargeTimeType.disbursement"), // only for loan charges SPECIFIED_DUE_DATE(2, "chargeTimeType.specifiedDueDate"), // for loan and @@ -34,10 +35,9 @@ public enum ChargeTimeType { TRANCHE_DISBURSEMENT(12, "chargeTimeType.tranchedisbursement"), // only for // loan SHAREACCOUNT_ACTIVATION(13, "chargeTimeType.activation"), // only for loan - SHARE_PURCHASE(14, "chargeTimeType.sharespurchase"), - SHARE_REDEEM(15, "chargeTimeType.sharesredeem"), + SHARE_PURCHASE(14, "chargeTimeType.sharespurchase"), SHARE_REDEEM(15, "chargeTimeType.sharesredeem"), - SAVINGS_NOACTIVITY_FEE(16,"chargeTimeType.savingsNoActivityFee"); + SAVINGS_NOACTIVITY_FEE(16, "chargeTimeType.savingsNoActivityFee"); private final Integer value; private final String code; @@ -70,7 +70,7 @@ public enum ChargeTimeType { return new Integer[] { ChargeTimeType.SPECIFIED_DUE_DATE.getValue(), ChargeTimeType.SAVINGS_ACTIVATION.getValue(), ChargeTimeType.SAVINGS_CLOSURE.getValue(), ChargeTimeType.WITHDRAWAL_FEE.getValue(), ChargeTimeType.ANNUAL_FEE.getValue(), ChargeTimeType.MONTHLY_FEE.getValue(), ChargeTimeType.OVERDRAFT_FEE.getValue(), ChargeTimeType.WEEKLY_FEE.getValue(), - ChargeTimeType.SAVINGS_NOACTIVITY_FEE.getValue()}; + ChargeTimeType.SAVINGS_NOACTIVITY_FEE.getValue() }; } public static Object[] validClientValues() { @@ -78,7 +78,8 @@ public enum ChargeTimeType { } public static Object[] validShareValues() { - return new Integer[] { ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue(), ChargeTimeType.SHARE_PURCHASE.getValue(), ChargeTimeType.SHARE_REDEEM.getValue() }; + return new Integer[] { ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue(), ChargeTimeType.SHARE_PURCHASE.getValue(), + ChargeTimeType.SHARE_REDEEM.getValue() }; } public static ChargeTimeType fromInt(final Integer chargeTime) { @@ -194,8 +195,8 @@ public enum ChargeTimeType { } public boolean isAllowedSavingsChargeTime() { - return isOnSpecifiedDueDate() || isSavingsActivation() || isSavingsClosure() || isWithdrawalFee() || isAnnualFee() - || isMonthlyFee() || isWeeklyFee() || isOverdraftFee() || isSavingsNoActivityFee(); + return isOnSpecifiedDueDate() || isSavingsActivation() || isSavingsClosure() || isWithdrawalFee() || isAnnualFee() || isMonthlyFee() + || isWeeklyFee() || isOverdraftFee() || isSavingsNoActivityFee(); } public boolean isOverdraftFee() { @@ -217,4 +218,4 @@ public enum ChargeTimeType { public boolean isSharesRedeem() { return this.value.equals(ChargeTimeType.SHARE_REDEEM.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeDueAtDisbursementCannotBePenaltyException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeDueAtDisbursementCannotBePenaltyException.java index ecea08c6c..eeeb19675 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeDueAtDisbursementCannotBePenaltyException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeDueAtDisbursementCannotBePenaltyException.java @@ -29,4 +29,4 @@ public class ChargeDueAtDisbursementCannotBePenaltyException extends AbstractPla public ChargeDueAtDisbursementCannotBePenaltyException(final String name) { super("error.msg.charge.due.at.disbursement.cannot.be.penalty", "Charge '" + name + "' is invalid.", name, name); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeIsNotActiveException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeIsNotActiveException.java index 70d33e8fa..f52db1041 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeIsNotActiveException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeIsNotActiveException.java @@ -28,4 +28,4 @@ public class ChargeIsNotActiveException extends AbstractPlatformDomainRuleExcept public ChargeIsNotActiveException(final Long id, final String name) { super("error.msg.charge.is.not.active", "Charge '" + name + "' with identifier " + id + " is not active", name, id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeMustBePenaltyException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeMustBePenaltyException.java old mode 100755 new mode 100644 index 135cac7a7..efaebd58c --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeMustBePenaltyException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeMustBePenaltyException.java @@ -29,4 +29,4 @@ public class ChargeMustBePenaltyException extends AbstractPlatformDomainRuleExce public ChargeMustBePenaltyException(final String name) { super("error.msg.charge.must.be.penalty", "Charge '" + name + "' is invalid.", name, name); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeParameterUpdateNotSupportedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeParameterUpdateNotSupportedException.java index c762ef4d7..7a7a61f4f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeParameterUpdateNotSupportedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ChargeParameterUpdateNotSupportedException.java @@ -29,4 +29,4 @@ public class ChargeParameterUpdateNotSupportedException extends AbstractPlatform final Object... defaultUserMessageArgs) { super("error.msg.charge.update.of." + postFix + ".is.not.supported", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeAddedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeAddedException.java index 302942d0b..842dfd5be 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeAddedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeAddedException.java @@ -31,4 +31,4 @@ public class LoanChargeCannotBeAddedException extends AbstractPlatformDomainRule super("error.msg." + entity + ".cannot.be.added.as." + postFix, defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeDeletedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeDeletedException.java old mode 100755 new mode 100644 index 25ef2e30c..4bba0bd1c --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeDeletedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeDeletedException.java @@ -24,6 +24,7 @@ public class LoanChargeCannotBeDeletedException extends AbstractPlatformDomainRu /*** enum of reasons of why Loan Charge cannot be waived **/ public static enum LoanChargeCannotBeDeletedReason { + ALREADY_PAID, ALREADY_WAIVED, LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE; public String errorMessage() { @@ -31,7 +32,9 @@ public class LoanChargeCannotBeDeletedException extends AbstractPlatformDomainRu return "This loan charge has been partially/completely paid"; } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) { return "This loan charge has already been waived"; - } else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "This charge cannot be deleted as the loan it is associated with is not in submitted and pending approval stage"; } + } else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { + return "This charge cannot be deleted as the loan it is associated with is not in submitted and pending approval stage"; + } return name().toString(); } @@ -40,7 +43,9 @@ public class LoanChargeCannotBeDeletedException extends AbstractPlatformDomainRu return "error.msg.loan.charge.already.paid"; } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) { return "error.msg.loan.charge.already.waived"; - } else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "error.msg.loan.charge.associated.loan.not.in.submitted.and.pending.approval.stage"; } + } else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { + return "error.msg.loan.charge.associated.loan.not.in.submitted.and.pending.approval.stage"; + } return name().toString(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBePayedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBePayedException.java old mode 100755 new mode 100644 index c391ae75a..44a81f52f --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBePayedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBePayedException.java @@ -24,6 +24,7 @@ public class LoanChargeCannotBePayedException extends AbstractPlatformDomainRule /*** enum of reasons of why Loan Charge cannot be waived **/ public static enum LoanChargeCannotBePayedReason { + ALREADY_PAID, ALREADY_WAIVED, LOAN_INACTIVE, CHARGE_NOT_ACCOUNT_TRANSFER, CHARGE_NOT_PAYABLE; public String errorMessage() { @@ -35,7 +36,9 @@ public class LoanChargeCannotBePayedException extends AbstractPlatformDomainRule return "This loan charge can be payed as the loan associated with it is currently inactive"; } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) { return "This loan charge can be payed as the charge payment mode is not account transfer"; - } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_PAYABLE")) { return "This loan charge is not Payable through account transfer"; } + } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_PAYABLE")) { + return "This loan charge is not Payable through account transfer"; + } return name().toString(); } @@ -49,7 +52,9 @@ public class LoanChargeCannotBePayedException extends AbstractPlatformDomainRule return "error.msg.loan.charge.associated.loan.inactive"; } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) { return "error.msg.loan.charge.payment.mode.not.account.transfer"; - } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_PAYABLE")) { return "error.msg.loan.charge.payment.not.allowed.account.transfer"; } + } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_PAYABLE")) { + return "error.msg.loan.charge.payment.not.allowed.account.transfer"; + } return name().toString(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeUpdatedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeUpdatedException.java old mode 100755 new mode 100644 index 220dea060..68ccbef6d --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeUpdatedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeUpdatedException.java @@ -24,6 +24,7 @@ public class LoanChargeCannotBeUpdatedException extends AbstractPlatformDomainRu /*** enum of reasons of why Loan Charge cannot be waived **/ public static enum LoanChargeCannotBeUpdatedReason { + ALREADY_PAID, ALREADY_WAIVED, LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE; public String errorMessage() { @@ -31,7 +32,9 @@ public class LoanChargeCannotBeUpdatedException extends AbstractPlatformDomainRu return "This loan charge has been partially/completely paid"; } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) { return "This loan charge has already been waived"; - } else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "This charge cannot be updated as the loan it is associated with is not in submitted and pending approval stage"; } + } else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { + return "This charge cannot be updated as the loan it is associated with is not in submitted and pending approval stage"; + } return name().toString(); } @@ -40,7 +43,9 @@ public class LoanChargeCannotBeUpdatedException extends AbstractPlatformDomainRu return "error.msg.loan.charge.already.paid"; } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) { return "error.msg.loan.charge.already.waived"; - } else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "error.msg.loan.charge.associated.loan.not.in.submitted.and.pending.approval.stage"; } + } else if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { + return "error.msg.loan.charge.associated.loan.not.in.submitted.and.pending.approval.stage"; + } return name().toString(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeWaivedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeWaivedException.java old mode 100755 new mode 100644 index 154b7ddec..78e70aa9b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeWaivedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeCannotBeWaivedException.java @@ -24,6 +24,7 @@ public class LoanChargeCannotBeWaivedException extends AbstractPlatformDomainRul /*** enum of reasons of why Loan Charge cannot be waived **/ public static enum LoanChargeCannotBeWaivedReason { + ALREADY_PAID, ALREADY_WAIVED, LOAN_INACTIVE, WAIVE_NOT_ALLOWED_FOR_CHARGE; public String errorMessage() { @@ -45,7 +46,9 @@ public class LoanChargeCannotBeWaivedException extends AbstractPlatformDomainRul return "error.msg.loan.charge.already.waived"; } else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) { return "error.msg.loan.charge.associated.loan.inactive"; - } else if (name().toString().equalsIgnoreCase("WAIVE_NOT_ALLOWED_FOR_CHARGE")) { return "error.msg.loan.charge.waive.not.allowed"; } + } else if (name().toString().equalsIgnoreCase("WAIVE_NOT_ALLOWED_FOR_CHARGE")) { + return "error.msg.loan.charge.waive.not.allowed"; + } return name().toString(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeNotFoundException.java index 3f62f17ee..9971d87cf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeNotFoundException.java @@ -35,4 +35,4 @@ public class LoanChargeNotFoundException extends AbstractPlatformResourceNotFoun super("error.msg.loanCharge.id.invalid.for.given.loan", "Loan charge with identifier " + id + " does not exist for loan " + loanId, id, loanId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeWithoutMandatoryFieldException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeWithoutMandatoryFieldException.java index b8969860b..6833b2b6f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeWithoutMandatoryFieldException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/LoanChargeWithoutMandatoryFieldException.java @@ -31,4 +31,4 @@ public class LoanChargeWithoutMandatoryFieldException extends AbstractPlatformDo super("error.msg." + entity + "." + postFix + ".cannot.be.blank", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeCannotBeWaivedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeCannotBeWaivedException.java index a9c7f4d8d..f9cd9db0e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeCannotBeWaivedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeCannotBeWaivedException.java @@ -24,6 +24,7 @@ public class SavingsAccountChargeCannotBeWaivedException extends AbstractPlatfor /*** enum of reasons of why Savings Account Charge cannot be waived **/ public static enum SavingsAccountChargeCannotBeWaivedReason { + ALREADY_PAID, ALREADY_WAIVED, SAVINGS_ACCOUNT_NOT_ACTIVE, SAVINGS_ACCOUNT_CLOSED; public String errorMessage() { @@ -33,7 +34,9 @@ public class SavingsAccountChargeCannotBeWaivedException extends AbstractPlatfor return "This savings account charge has already been waived"; } else if (name().toString().equalsIgnoreCase("SAVINGS_ACCOUNT_NOT_ACTIVE")) { return "This savings account charge cannot be waived as the Savings account associated with it is not active"; - } else if (name().toString().equalsIgnoreCase("SAVINGS_ACCOUNT_CLOSED")) { return "This savings account charge cannot be waived as the Savings account associated with it is closed"; } + } else if (name().toString().equalsIgnoreCase("SAVINGS_ACCOUNT_CLOSED")) { + return "This savings account charge cannot be waived as the Savings account associated with it is closed"; + } return name().toString(); } @@ -44,7 +47,9 @@ public class SavingsAccountChargeCannotBeWaivedException extends AbstractPlatfor return "error.msg.savings.account.charge.already.waived"; } else if (name().toString().equalsIgnoreCase("SAVINGS_ACCOUNT_NOT_ACTIVE")) { return "error.msg.savings.account.charge.associated.savings.account.not.active"; - } else if (name().toString().equalsIgnoreCase("SAVINGS_ACCOUNT_CLOSED")) { return "error.msg.savings.account.charge.associated.savings.account.closed"; } + } else if (name().toString().equalsIgnoreCase("SAVINGS_ACCOUNT_CLOSED")) { + return "error.msg.savings.account.charge.associated.savings.account.closed"; + } return name().toString(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeNotFoundException.java index b487ee3dc..4484bd554 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeNotFoundException.java @@ -32,7 +32,8 @@ public class SavingsAccountChargeNotFoundException extends AbstractPlatformResou } public SavingsAccountChargeNotFoundException(final Long id, final Long savingsAccountId) { - super("error.msg.savings.account.charge.id.invalid.for.given.savings.account", "Savings Account charge with identifier " + id - + " does not exist for Savings Account " + savingsAccountId, id, savingsAccountId); + super("error.msg.savings.account.charge.id.invalid.for.given.savings.account", + "Savings Account charge with identifier " + id + " does not exist for Savings Account " + savingsAccountId, id, + savingsAccountId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeWithoutMandatoryFieldException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeWithoutMandatoryFieldException.java index 8ce64b4c7..1fdd39544 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeWithoutMandatoryFieldException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/SavingsAccountChargeWithoutMandatoryFieldException.java @@ -31,4 +31,4 @@ public class SavingsAccountChargeWithoutMandatoryFieldException extends Abstract super("error.msg." + entity + "." + postFix + ".cannot.be.blank", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ShareAccountChargeWithoutMandatoryFieldException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ShareAccountChargeWithoutMandatoryFieldException.java index 199e776e7..1c08ae603 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ShareAccountChargeWithoutMandatoryFieldException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/exception/ShareAccountChargeWithoutMandatoryFieldException.java @@ -31,4 +31,4 @@ public class ShareAccountChargeWithoutMandatoryFieldException extends AbstractPl super("error.msg." + entity + "." + postFix + ".cannot.be.blank", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/CreateChargeDefinitionCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/CreateChargeDefinitionCommandHandler.java index d77f37beb..9114ada65 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/CreateChargeDefinitionCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/CreateChargeDefinitionCommandHandler.java @@ -44,4 +44,4 @@ public class CreateChargeDefinitionCommandHandler implements NewCommandSourceHan return this.clientWritePlatformService.createCharge(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/DeleteChargeDefinitionCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/DeleteChargeDefinitionCommandHandler.java index d780776e1..448194757 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/DeleteChargeDefinitionCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/DeleteChargeDefinitionCommandHandler.java @@ -44,4 +44,4 @@ public class DeleteChargeDefinitionCommandHandler implements NewCommandSourceHan return this.clientWritePlatformService.deleteCharge(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/UpdateChargeDefinitionCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/UpdateChargeDefinitionCommandHandler.java index c5ba56978..a9d650fce 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/UpdateChargeDefinitionCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/handler/UpdateChargeDefinitionCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateChargeDefinitionCommandHandler implements NewCommandSourceHan return this.clientWritePlatformService.updateCharge(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/serialization/ChargeDefinitionCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/serialization/ChargeDefinitionCommandFromApiJsonDeserializer.java old mode 100755 new mode 100644 index fbaf6b795..eeaa40508 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/serialization/ChargeDefinitionCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/serialization/ChargeDefinitionCommandFromApiJsonDeserializer.java @@ -133,8 +133,8 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer { if (ctt.isWeeklyFee()) { final String monthDay = this.fromApiJsonHelper.extractStringNamed("feeOnMonthDay", element); - baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay) - .mustBeBlankWhenParameterProvidedIs("chargeTimeType", chargeTimeType); + baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).mustBeBlankWhenParameterProvidedIs("chargeTimeType", + chargeTimeType); } if (ctt.isMonthlyFee()) { @@ -174,7 +174,7 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer { .longGreaterThanZero(); } - }else if(appliesTo.isSharesCharge()) { + } else if (appliesTo.isSharesCharge()) { final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element); baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull(); if (chargeTimeType != null) { @@ -187,10 +187,10 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer { .isOneOfTheseValues(ChargeCalculationType.validValuesForShares()); } - if(chargeTimeType != null && chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())) { - if(chargeCalculationType != null) { + if (chargeTimeType != null && chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())) { + if (chargeCalculationType != null) { baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType) - .isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation()); + .isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation()); } } } @@ -280,11 +280,11 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer { final Collection validLoanValues = Arrays.asList(ChargeTimeType.validLoanValues()); final Collection validSavingsValues = Arrays.asList(ChargeTimeType.validSavingsValues()); final Collection validClientValues = Arrays.asList(ChargeTimeType.validClientValues()); - final Collection validShareValues = Arrays.asList(ChargeTimeType.validShareValues()) ; + final Collection validShareValues = Arrays.asList(ChargeTimeType.validShareValues()); final Collection allValidValues = new ArrayList<>(validLoanValues); allValidValues.addAll(validSavingsValues); allValidValues.addAll(validClientValues); - allValidValues.addAll(validShareValues) ; + allValidValues.addAll(validShareValues); baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull() .isOneOfTheseValues(allValidValues.toArray(new Object[allValidValues.size()])); } @@ -355,9 +355,9 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer { private void performChargeTimeNCalculationTypeValidation(DataValidatorBuilder baseDataValidator, final Integer chargeTimeType, final Integer chargeCalculationType) { - if(chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())){ + if (chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())) { baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType) - .isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation()); + .isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation()); } if (chargeTimeType.equals(ChargeTimeType.TRANCHE_DISBURSEMENT.getValue())) { @@ -372,4 +372,4 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer { private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeDropdownReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeDropdownReadPlatformService.java index 9d57bea68..abd3b7400 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeDropdownReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeDropdownReadPlatformService.java @@ -38,11 +38,13 @@ public interface ChargeDropdownReadPlatformService { List retrieveSavingsCalculationTypes(); List retrieveSavingsCollectionTimeTypes(); + List retrieveClientCalculationTypes(); List retrieveClientCollectionTimeTypes(); - List retrieveSharesCalculationTypes() ; - List retrieveSharesCollectionTimeTypes() ; + List retrieveSharesCalculationTypes(); + + List retrieveSharesCollectionTimeTypes(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 8ced16d06..d694fb68b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java @@ -123,7 +123,7 @@ public class ChargeDropdownReadPlatformServiceImpl implements ChargeDropdownRead @Override public List retrieveSharesCollectionTimeTypes() { - return Arrays.asList(chargeTimeType(ChargeTimeType.SHAREACCOUNT_ACTIVATION), - chargeTimeType(ChargeTimeType.SHARE_PURCHASE), chargeTimeType(ChargeTimeType.SHARE_REDEEM)); + return Arrays.asList(chargeTimeType(ChargeTimeType.SHAREACCOUNT_ACTIVATION), chargeTimeType(ChargeTimeType.SHARE_PURCHASE), + chargeTimeType(ChargeTimeType.SHARE_REDEEM)); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeEnumerations.java old mode 100755 new mode 100644 index d4120aeaf..901771b74 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeEnumerations.java @@ -82,18 +82,21 @@ public class ChargeEnumerations { ChargeTimeType.TRANCHE_DISBURSEMENT.getCode(), "Tranche Disbursement"); break; case SHAREACCOUNT_ACTIVATION: - optionData = new EnumOptionData(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue().longValue(), ChargeTimeType.SHAREACCOUNT_ACTIVATION.getCode(), "Share Account Activate") ; - break ; + optionData = new EnumOptionData(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue().longValue(), + ChargeTimeType.SHAREACCOUNT_ACTIVATION.getCode(), "Share Account Activate"); + break; case SHARE_PURCHASE: - optionData = new EnumOptionData(ChargeTimeType.SHARE_PURCHASE.getValue().longValue(), ChargeTimeType.SHARE_PURCHASE.getCode(), "Share Purchase") ; - break ; + optionData = new EnumOptionData(ChargeTimeType.SHARE_PURCHASE.getValue().longValue(), + ChargeTimeType.SHARE_PURCHASE.getCode(), "Share Purchase"); + break; case SHARE_REDEEM: - optionData = new EnumOptionData(ChargeTimeType.SHARE_REDEEM.getValue().longValue(), ChargeTimeType.SHARE_REDEEM.getCode(), "Share Redeem") ; - break ; + optionData = new EnumOptionData(ChargeTimeType.SHARE_REDEEM.getValue().longValue(), ChargeTimeType.SHARE_REDEEM.getCode(), + "Share Redeem"); + break; case SAVINGS_NOACTIVITY_FEE: - optionData = new EnumOptionData(ChargeTimeType.SAVINGS_NOACTIVITY_FEE.getValue().longValue(), ChargeTimeType.SAVINGS_NOACTIVITY_FEE.getCode(), - "Saving No Activity Fee"); + optionData = new EnumOptionData(ChargeTimeType.SAVINGS_NOACTIVITY_FEE.getValue().longValue(), + ChargeTimeType.SAVINGS_NOACTIVITY_FEE.getCode(), "Saving No Activity Fee"); break; default: optionData = new EnumOptionData(ChargeTimeType.INVALID.getValue().longValue(), ChargeTimeType.INVALID.getCode(), "Invalid"); @@ -120,8 +123,8 @@ public class ChargeEnumerations { optionData = new EnumOptionData(ChargeAppliesTo.CLIENT.getValue().longValue(), ChargeAppliesTo.CLIENT.getCode(), "Client"); break; case SHARES: - optionData = new EnumOptionData(ChargeAppliesTo.SHARES.getValue().longValue(), ChargeAppliesTo.SHARES.getCode(), "Shares") ; - break ; + optionData = new EnumOptionData(ChargeAppliesTo.SHARES.getValue().longValue(), ChargeAppliesTo.SHARES.getCode(), "Shares"); + break; default: optionData = new EnumOptionData(ChargeAppliesTo.INVALID.getValue().longValue(), ChargeAppliesTo.INVALID.getCode(), "Invalid"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeReadPlatformService.java index e560dd686..0e818789c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeReadPlatformService.java @@ -121,5 +121,5 @@ public interface ChargeReadPlatformService { */ Collection retrieveSharesApplicableCharges(); - public Collection retrieveShareProductCharges(final Long shareProductId) ; + public Collection retrieveShareProductCharges(final Long shareProductId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 63f4b38e6..1d5de63d9 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeReadPlatformServiceImpl.java @@ -107,7 +107,7 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService sql += " order by c.name "; - return this.jdbcTemplate.query(sql, rm, new Object[] {currencyCode}); + return this.jdbcTemplate.query(sql, rm, new Object[] { currencyCode }); } @Override @@ -119,7 +119,7 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService sql += addInClauseToSQL_toLimitChargesMappedToOffice_ifOfficeSpecificProductsEnabled(); - sql = sql + " ;" ; + sql = sql + " ;"; return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { chargeId }); } catch (final EmptyResultDataAccessException e) { throw new ChargeNotFoundException(chargeId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java index c17e5d5c5..c5f1485a9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java @@ -116,11 +116,11 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP FineractEntityAccessType.OFFICE_ACCESS_TO_CHARGES, charge.getId()); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(charge.getId()).build(); - }catch (final DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -152,14 +152,17 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP final Boolean isChargeExistWithLoans = isAnyLoanProductsAssociateWithThisCharge(chargeId); final Boolean isChargeExistWithSavings = isAnySavingsProductsAssociateWithThisCharge(chargeId); - if (isChargeExistWithLoans || isChargeExistWithSavings) { throw new ChargeCannotBeUpdatedException( - "error.msg.charge.cannot.be.updated.it.is.used.in.loan", "This charge cannot be updated, it is used in loan"); } + if (isChargeExistWithLoans || isChargeExistWithSavings) { + throw new ChargeCannotBeUpdatedException("error.msg.charge.cannot.be.updated.it.is.used.in.loan", + "This charge cannot be updated, it is used in loan"); + } } } else if ((changes.containsKey("feeFrequency") || changes.containsKey("feeInterval")) && chargeForUpdate.isLoanCharge()) { final Boolean isChargeExistWithLoans = isAnyLoanProductsAssociateWithThisCharge(chargeId); - if (isChargeExistWithLoans) { throw new ChargeCannotBeUpdatedException( - "error.msg.charge.frequency.cannot.be.updated.it.is.used.in.loan", - "This charge frequency cannot be updated, it is used in loan"); } + if (isChargeExistWithLoans) { + throw new ChargeCannotBeUpdatedException("error.msg.charge.frequency.cannot.be.updated.it.is.used.in.loan", + "This charge frequency cannot be updated, it is used in loan"); + } } // Has account Id been changed ? @@ -189,10 +192,10 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -201,8 +204,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP @CacheEvict(value = "charges", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('ch')") public CommandProcessingResult deleteCharge(final Long chargeId) { - final Charge chargeForDelete = this.chargeRepository.findById(chargeId) - .orElseThrow(() -> new ChargeNotFoundException(chargeId)); + final Charge chargeForDelete = this.chargeRepository.findById(chargeId).orElseThrow(() -> new ChargeNotFoundException(chargeId)); if (chargeForDelete.isDeleted()) { throw new ChargeNotFoundException(chargeId); } final Collection loanProducts = this.loanProductRepository.retrieveLoanProductsByChargeId(chargeId); @@ -210,9 +212,10 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP final Boolean isChargeExistWithSavings = isAnySavingsAssociateWithThisCharge(chargeId); // TODO: Change error messages around: - if (!loanProducts.isEmpty() || isChargeExistWithLoans || isChargeExistWithSavings) { throw new ChargeCannotBeDeletedException( - "error.msg.charge.cannot.be.deleted.it.is.already.used.in.loan", - "This charge cannot be deleted, it is already used in loan"); } + if (!loanProducts.isEmpty() || isChargeExistWithLoans || isChargeExistWithSavings) { + throw new ChargeCannotBeDeletedException("error.msg.charge.cannot.be.deleted.it.is.already.used.in.loan", + "This charge cannot be deleted, it is already used in loan"); + } chargeForDelete.delete(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientAddressApiResources.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientAddressApiResources.java index 5a9f241c9..a88655064 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientAddressApiResources.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientAddressApiResources.java @@ -59,16 +59,15 @@ import org.springframework.stereotype.Component; @Path("/client") @Component @Scope("singleton") -@Api(tags = {"Clients Address"}) +@Api(tags = { "Clients Address" }) @SwaggerDefinition(tags = { - @Tag(name = "Clients Address", description = "Address module is an optional module and can be configured into the system by using GlobalConfiguration setting: enable-address. In order to activate Address module, we need to enable the configuration, enable-address by setting its value to true.") -}) + @Tag(name = "Clients Address", description = "Address module is an optional module and can be configured into the system by using GlobalConfiguration setting: enable-address. In order to activate Address module, we need to enable the configuration, enable-address by setting its value to true.") }) public class ClientAddressApiResources { - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("addressId", "street", - "addressLine1", "addressLine2", "addressLine3", "townVillage", "city", "countyDistrict", "stateProvinceId", - "countryId", "postalCode", "latitude", "longitude", "createdBy", "createdOn", "updatedBy", "updatedOn", - "clientAddressId", "client_id", "address_id", "address_type_id", "isActive", "fieldConfigurationId", - "entity", "table", "field", "is_enabled", "is_mandatory", "validation_regex")); + + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("addressId", "street", "addressLine1", "addressLine2", + "addressLine3", "townVillage", "city", "countyDistrict", "stateProvinceId", "countryId", "postalCode", "latitude", "longitude", + "createdBy", "createdOn", "updatedBy", "updatedOn", "clientAddressId", "client_id", "address_id", "address_type_id", "isActive", + "fieldConfigurationId", "entity", "table", "field", "is_enabled", "is_mandatory", "validation_regex")); private final String resourceNameForPermissions = "Address"; private final PlatformSecurityContext context; private final AddressReadPlatformServiceImpl readPlatformService; @@ -77,10 +76,8 @@ public class ClientAddressApiResources { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public ClientAddressApiResources(final PlatformSecurityContext context, - final AddressReadPlatformServiceImpl readPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, + public ClientAddressApiResources(final PlatformSecurityContext context, final AddressReadPlatformServiceImpl readPlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.context = context; this.readPlatformService = readPlatformService; @@ -98,8 +95,7 @@ public class ClientAddressApiResources { final AddressData template = this.readPlatformService.retrieveTemplate(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, template, this.RESPONSE_DATA_PARAMETERS); } @@ -109,10 +105,13 @@ public class ClientAddressApiResources { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create an address for a Client", notes = "Mandatory Fields : \n" + "type and clientId") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientAddressApiResourcesSwagger.PostClientClientIdAddressesRequest.class)}) - @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ClientAddressApiResourcesSwagger.PostClientClientIdAddressesResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientAddressApiResourcesSwagger.PostClientClientIdAddressesRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientAddressApiResourcesSwagger.PostClientClientIdAddressesResponse.class) }) public String addClientAddress(@QueryParam("type") @ApiParam(value = "type") final long addressTypeId, - @PathParam("clientid") @ApiParam(value = "clientId") final long clientid, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @PathParam("clientid") @ApiParam(value = "clientId") final long clientid, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().addClientAddress(clientid, addressTypeId) .withJson(apiRequestBodyAsJson).build(); @@ -126,10 +125,13 @@ public class ClientAddressApiResources { @Path("/{clientid}/addresses") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List all addresses for a Client", notes = "Example Requests:\n" + "\n" +"client/1/addresses\n" + "\n" + "\n" +"clients/1/addresses?status=false,true&&type=1,2,3" ) - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = ClientAddressApiResourcesSwagger.GetClientClientIdAddressesResponse.class)}) - public String getAddresses(@QueryParam("status") @ApiParam(value = "status") final String status, @QueryParam("type") @ApiParam(value = "type") final long addressTypeId, - @PathParam("clientid") @ApiParam(value = "clientId") final long clientid, @Context final UriInfo uriInfo) { + @ApiOperation(value = "List all addresses for a Client", notes = "Example Requests:\n" + "\n" + "client/1/addresses\n" + "\n" + "\n" + + "clients/1/addresses?status=false,true&&type=1,2,3") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = ClientAddressApiResourcesSwagger.GetClientClientIdAddressesResponse.class) }) + public String getAddresses(@QueryParam("status") @ApiParam(value = "status") final String status, + @QueryParam("type") @ApiParam(value = "type") final long addressTypeId, + @PathParam("clientid") @ApiParam(value = "clientId") final long clientid, @Context final UriInfo uriInfo) { Collection address; this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -144,8 +146,7 @@ public class ClientAddressApiResources { address = this.readPlatformService.retrieveAddressbyStatus(clientid, status); } - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, address, this.RESPONSE_DATA_PARAMETERS); } @@ -154,13 +155,17 @@ public class ClientAddressApiResources { @Path("/{clientid}/addresses") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Update an address for a Client", notes = "All the address fields can be updated by using update client address API\n" + "\n" + "Mandatory Fields\n" + "type and addressId") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientAddressApiResourcesSwagger.PutClientClientIdAddressesRequest.class)}) - @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = ClientAddressApiResourcesSwagger.PutClientClientIdAddressesResponse.class)}) - public String updateClientAddress(@PathParam("clientid") @ApiParam(value = "clientId") final long clientid, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Update an address for a Client", notes = "All the address fields can be updated by using update client address API\n" + + "\n" + "Mandatory Fields\n" + "type and addressId") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientAddressApiResourcesSwagger.PutClientClientIdAddressesRequest.class) }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK", response = ClientAddressApiResourcesSwagger.PutClientClientIdAddressesResponse.class) }) + public String updateClientAddress(@PathParam("clientid") @ApiParam(value = "clientId") final long clientid, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateClientAddress(clientid) - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateClientAddress(clientid).withJson(apiRequestBodyAsJson) + .build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientAddressApiResourcesSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientAddressApiResourcesSwagger.java index c6ce675c9..65ef724b7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientAddressApiResourcesSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientAddressApiResourcesSwagger.java @@ -25,13 +25,13 @@ import io.swagger.annotations.ApiModelProperty; * Created by Chirag Gupta on 01/12/18. */ final class ClientAddressApiResourcesSwagger { - private ClientAddressApiResourcesSwagger() { - } + + private ClientAddressApiResourcesSwagger() {} @ApiModel(value = "PostClientClientIdAddressesRequest") public final static class PostClientClientIdAddressesRequest { - private PostClientClientIdAddressesRequest() { - } + + private PostClientClientIdAddressesRequest() {} @ApiModelProperty(example = "Ipca") public String street; @@ -53,8 +53,8 @@ final class ClientAddressApiResourcesSwagger { @ApiModel(value = "PostClientClientIdAddressesResponse") public final static class PostClientClientIdAddressesResponse { - private PostClientClientIdAddressesResponse() { - } + + private PostClientClientIdAddressesResponse() {} @ApiModelProperty(example = "15") public Integer resourceId; @@ -62,8 +62,8 @@ final class ClientAddressApiResourcesSwagger { @ApiModel(value = "GetClientClientIdAddressesResponse") public final static class GetClientClientIdAddressesResponse { - private GetClientClientIdAddressesResponse() { - } + + private GetClientClientIdAddressesResponse() {} @ApiModelProperty(example = "111755") public Long client_id; @@ -107,8 +107,8 @@ final class ClientAddressApiResourcesSwagger { @ApiModel(value = "PutClientClientIdAddressesRequest") public final static class PutClientClientIdAddressesRequest { - private PutClientClientIdAddressesRequest() { - } + + private PutClientClientIdAddressesRequest() {} @ApiModelProperty(example = "67") public Integer addressId; @@ -118,8 +118,8 @@ final class ClientAddressApiResourcesSwagger { @ApiModel(value = "PutClientClientIdAddressesResponse") public final static class PutClientClientIdAddressesResponse { - private PutClientClientIdAddressesResponse() { - } + + private PutClientClientIdAddressesResponse() {} @ApiModelProperty(example = "67") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientApiConstants.java index c82ca20da..5e031753a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientApiConstants.java @@ -28,7 +28,6 @@ public class ClientApiConstants { public static final String CLIENT_RESOURCE_NAME = "client"; public static final String CLIENT_CHARGES_RESOURCE_NAME = "CLIENTCHARGE"; - // Client Charge Action Names public static final String CLIENT_CHARGE_ACTION_CREATE = "CREATE"; public static final String CLIENT_CHARGE_ACTION_DELETE = "DELETE"; @@ -70,10 +69,8 @@ public class ClientApiConstants { public static final String dateFormatParamName = "dateFormat"; public static final String address = "address"; public static final String familyMembers = "familyMembers"; - public static final String MARITALSTATUS="MARITALSTATUS"; - public static final String maritalStatusIdParamName="maritalStatusId"; - - + public static final String MARITALSTATUS = "MARITALSTATUS"; + public static final String maritalStatusIdParamName = "maritalStatusId"; public static final String CLIENT_TYPE_INDIVIDUAL = "Individual"; @@ -100,7 +97,6 @@ public class ClientApiConstants { public static final String closureReasonIdParamName = "closureReasonId"; public static final String reopenedDateParamName = "reopenedDate"; - public static final String rejectionDateParamName = "rejectionDate"; public static final String rejectionReasonIdParamName = "rejectionReasonId"; public static final String withdrawalDateParamName = "withdrawalDate"; @@ -126,7 +122,7 @@ public class ClientApiConstants { public static final String receiptNumberParamName = "receiptNumber"; public static final String bankNumberParamName = "bankNumber"; - //request parameters for client non person + // request parameters for client non person public static final String clientNonPersonDetailsParamName = "clientNonPersonDetails"; public static final String incorpNumberParamName = "incorpNumber"; public static final String remarksParamName = "remarks"; @@ -134,7 +130,6 @@ public class ClientApiConstants { public static final String constitutionIdParamName = "constitutionId"; public static final String mainBusinessLineIdParamName = "mainBusinessLineId"; - // response parameters public static final String statusParamName = "status"; public static final String hierarchyParamName = "hierarchy"; @@ -194,24 +189,21 @@ public class ClientApiConstants { * {@link ClientData}. Where possible, we try to get response parameters to * match those of request parameters. */ - protected static final Set CLIENT_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, - accountNoParamName, + protected static final Set CLIENT_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, accountNoParamName, externalIdParamName, statusParamName, activeParamName, activationDateParamName, firstnameParamName, middlenameParamName, - lastnameParamName, fullnameParamName, displayNameParamName, mobileNoParamName, emailAddressParamName, officeIdParamName, officeNameParamName, - transferToOfficeIdParamName, transferToOfficeNameParamName, hierarchyParamName, imageIdParamName, imagePresentParamName, - staffIdParamName, staffNameParamName, timelineParamName, groupsParamName, officeOptionsParamName, staffOptionsParamName, - dateOfBirthParamName, genderParamName, clientTypeParamName, clientClassificationParamName, legalFormParamName, - clientNonPersonDetailsParamName, isStaffParamName)); + lastnameParamName, fullnameParamName, displayNameParamName, mobileNoParamName, emailAddressParamName, officeIdParamName, + officeNameParamName, transferToOfficeIdParamName, transferToOfficeNameParamName, hierarchyParamName, imageIdParamName, + imagePresentParamName, staffIdParamName, staffNameParamName, timelineParamName, groupsParamName, officeOptionsParamName, + staffOptionsParamName, dateOfBirthParamName, genderParamName, clientTypeParamName, clientClassificationParamName, + legalFormParamName, clientNonPersonDetailsParamName, isStaffParamName)); - protected static final Set CLIENT_CHARGES_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList - (chargeIdParamName, + protected static final Set CLIENT_CHARGES_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(chargeIdParamName, clientIdParamName, chargeNameParamName, penaltyParamName, chargeTimeTypeParamName, dueAsOfDateParamName, chargeCalculationTypeParamName, currencyParamName, amountWaivedParamName, amountWrittenOffParamName, amountOutstandingParamName, amountOrPercentageParamName, amountParamName, amountPaidParamName, chargeOptionsParamName, transactionsParamName)); - protected static final Set CLIENT_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList - (idParamName, + protected static final Set CLIENT_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, transactionAmountParamName, paymentDetailDataParamName, reversedParamName, dateParamName, officeIdParamName, officeNameParamName, transactionTypeParamName, transactionCurrencyParamName, externalIdParamName, submittedOnDateParamName)); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientChargesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientChargesApiResource.java index 577b48b5c..495f947ea 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientChargesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientChargesApiResource.java @@ -67,10 +67,11 @@ import org.springframework.util.CollectionUtils; @Path("/clients/{clientId}/charges") @Component -@Api(tags = {"Client Charges"}) +@Api(tags = { "Client Charges" }) @SwaggerDefinition(tags = { - @Tag(name = "Client Charges", description = "It is typical for MFI's to directly associate charges with an implicit Client account. These can be either fees or penalties\n" + "\n" + "Client Charges are client specific instances of Charges. Refer Charges for documentation of the various properties of a charge, Only additional properties ( specific to the context of a Charge being associated with a Client account) are described here") -}) + @Tag(name = "Client Charges", description = "It is typical for MFI's to directly associate charges with an implicit Client account. These can be either fees or penalties\n" + + "\n" + + "Client Charges are client specific instances of Charges. Refer Charges for documentation of the various properties of a charge, Only additional properties ( specific to the context of a Charge being associated with a Client account) are described here") }) public class ClientChargesApiResource { private final PlatformSecurityContext context; @@ -100,22 +101,25 @@ public class ClientChargesApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Client Charges", notes = "The list capability of client charges supports pagination." + "Example Requests:\n" + "clients/1/charges\n" + "\nclients/1/charges?offset=0&limit=5" ) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientChargesApiResourceSwagger.GetClientsClientIdChargesResponse.class) }) + @ApiOperation(value = "List Client Charges", notes = "The list capability of client charges supports pagination." + + "Example Requests:\n" + "clients/1/charges\n" + "\nclients/1/charges?offset=0&limit=5") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientChargesApiResourceSwagger.GetClientsClientIdChargesResponse.class) }) public String retrieveAllClientCharges(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @DefaultValue(ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ALL) @QueryParam(ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS) @ApiParam(value = "chargeStatus") final String chargeStatus, @QueryParam("pendingPayment") @ApiParam(value = "pendingPayment") final Boolean pendingPayment, @Context final UriInfo uriInfo, - @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset) { + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset) { this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (!(is(chargeStatus, ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ALL) || is(chargeStatus, ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ACTIVE) - || is(chargeStatus, - ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_INACTIVE))) { throw new UnrecognizedQueryParamException( - ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS, chargeStatus, - new Object[] { ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ALL, - ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ACTIVE, - ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_INACTIVE }); } + || is(chargeStatus, ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_INACTIVE))) { + throw new UnrecognizedQueryParamException(ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS, chargeStatus, + new Object[] { ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ALL, + ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ACTIVE, + ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_INACTIVE }); + } final SearchParameters searchParameters = SearchParameters.forPagination(offset, limit); final Page clientCharges = this.clientChargeReadPlatformService.retrieveClientCharges(clientId, chargeStatus, @@ -147,10 +151,12 @@ public class ClientChargesApiResource { @Path("{chargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Client Charge", notes = "Example Requests:\n" + "clients/1/charges/1\n" + "\n" + "\n" + "clients/1/charges/1?fields=name,id" ) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ClientChargesApiResourceSwagger.GetClientsClientIdChargesResponse.GetClientsChargesPageItems.class) }) - public String retrieveClientCharge(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Client Charge", notes = "Example Requests:\n" + "clients/1/charges/1\n" + "\n" + "\n" + + "clients/1/charges/1?fields=name,id") + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ClientChargesApiResourceSwagger.GetClientsClientIdChargesResponse.GetClientsChargesPageItems.class) }) + public String retrieveClientCharge(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME); ClientChargeData clientCharge = this.clientChargeReadPlatformService.retrieveClientCharge(clientId, chargeId); @@ -176,10 +182,14 @@ public class ClientChargesApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Add Client Charge", notes = " This API associates a Client charge with an implicit Client account\n" + "Mandatory Fields : \n" + "chargeId and dueDate \n" + "Optional Fields : \n" + "amount" ) - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientChargesApiResourceSwagger.PostClientsClientIdChargesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = ClientChargesApiResourceSwagger.PostClientsClientIdChargesResponse.class) }) - public String applyClientCharge(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Add Client Charge", notes = " This API associates a Client charge with an implicit Client account\n" + + "Mandatory Fields : \n" + "chargeId and dueDate \n" + "Optional Fields : \n" + "amount") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientChargesApiResourceSwagger.PostClientsClientIdChargesRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = ClientChargesApiResourceSwagger.PostClientsClientIdChargesResponse.class) }) + public String applyClientCharge(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createClientCharge(clientId).withJson(apiRequestBodyAsJson) .build(); @@ -193,11 +203,19 @@ public class ClientChargesApiResource { @Path("{chargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Pay a Client Charge | Waive a Client Charge", notes = "Pay a Client Charge:\n\n" + "Mandatory Fields:" + "transactionDate and amount " + "" + "\"Pay either a part of or the entire due amount for a charge.(command=paycharge)\n" + "\n" + "Waive a Client Charge:\n" + "\n" + "\n" + "This API provides the facility of waiving off the remaining amount on a client charge (command=waive)\n\n" + "Showing request/response for 'Pay a Client Charge'" ) - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientChargesApiResourceSwagger.PostClientsClientIdChargesChargeIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientChargesApiResourceSwagger.PostClientsClientIdChargesChargeIdResponse.class)}) - public String payOrWaiveClientCharge(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId, - @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Pay a Client Charge | Waive a Client Charge", notes = "Pay a Client Charge:\n\n" + "Mandatory Fields:" + + "transactionDate and amount " + "" + "\"Pay either a part of or the entire due amount for a charge.(command=paycharge)\n" + + "\n" + "Waive a Client Charge:\n" + "\n" + "\n" + + "This API provides the facility of waiving off the remaining amount on a client charge (command=waive)\n\n" + + "Showing request/response for 'Pay a Client Charge'") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientChargesApiResourceSwagger.PostClientsClientIdChargesChargeIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientChargesApiResourceSwagger.PostClientsClientIdChargesChargeIdResponse.class) }) + public String payOrWaiveClientCharge(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { String json = ""; if (is(commandParam, ClientApiConstants.CLIENT_CHARGE_COMMAND_WAIVE_CHARGE)) { @@ -233,8 +251,10 @@ public class ClientChargesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Client Charge", notes = "Deletes a Client Charge on which no transactions have taken place (either payments or waivers). ") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientChargesApiResourceSwagger.DeleteClientsClientIdChargesChargeIdResponse.class)}) - public String deleteClientCharge(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId) { + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientChargesApiResourceSwagger.DeleteClientsClientIdChargesChargeIdResponse.class) }) + public String deleteClientCharge(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteClientCharge(clientId, chargeId).build(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientChargesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientChargesApiResourceSwagger.java index 69dc62d7e..14b3a3aaf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientChargesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientChargesApiResourceSwagger.java @@ -28,21 +28,21 @@ import java.util.Set; * Created by Chirag Gupta on 01/12/18. */ final class ClientChargesApiResourceSwagger { - private ClientChargesApiResourceSwagger() { - } + + private ClientChargesApiResourceSwagger() {} @ApiModel(value = "GetClientsClientIdChargesResponse") public final static class GetClientsClientIdChargesResponse { - private GetClientsClientIdChargesResponse() { - } + + private GetClientsClientIdChargesResponse() {} final class GetClientsChargesPageItems { - private GetClientsChargesPageItems() { - } + + private GetClientsChargesPageItems() {} final class GetClientChargeTimeType { - private GetClientChargeTimeType() { - } + + private GetClientChargeTimeType() {} @ApiModelProperty(example = "2") public Integer id; @@ -53,8 +53,8 @@ final class ClientChargesApiResourceSwagger { } final class GetClientChargeCalculationType { - private GetClientChargeCalculationType() { - } + + private GetClientChargeCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -65,8 +65,8 @@ final class ClientChargesApiResourceSwagger { } final class GetClientChargeCurrency { - private GetClientChargeCurrency() { - } + + private GetClientChargeCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -122,8 +122,8 @@ final class ClientChargesApiResourceSwagger { @ApiModel(value = "PostClientsClientIdChargesRequest") public final static class PostClientsClientIdChargesRequest { - private PostClientsClientIdChargesRequest() { - } + + private PostClientsClientIdChargesRequest() {} @ApiModelProperty(example = "100") public Integer amount; @@ -139,8 +139,8 @@ final class ClientChargesApiResourceSwagger { @ApiModel(value = "PostClientsClientIdChargesResponse") public final static class PostClientsClientIdChargesResponse { - private PostClientsClientIdChargesResponse() { - } + + private PostClientsClientIdChargesResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -152,8 +152,8 @@ final class ClientChargesApiResourceSwagger { @ApiModel(value = "PostClientsClientIdChargesChargeIdRequest") public final static class PostClientsClientIdChargesChargeIdRequest { - private PostClientsClientIdChargesChargeIdRequest() { - } + + private PostClientsClientIdChargesChargeIdRequest() {} @ApiModelProperty(example = "200") public Integer amount; @@ -167,8 +167,8 @@ final class ClientChargesApiResourceSwagger { @ApiModel(value = "PostClientsClientIdChargesChargeIdResponse") public final static class PostClientsClientIdChargesChargeIdResponse { - private PostClientsClientIdChargesChargeIdResponse() { - } + + private PostClientsClientIdChargesChargeIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -182,8 +182,8 @@ final class ClientChargesApiResourceSwagger { @ApiModel(value = "DeleteClientsClientIdChargesChargeIdResponse") public final static class DeleteClientsClientIdChargesChargeIdResponse { - private DeleteClientsClientIdChargesChargeIdResponse() { - } + + private DeleteClientsClientIdChargesChargeIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientFamilyMembersApiResources.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientFamilyMembersApiResources.java index 1466819af..387c2ea01 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientFamilyMembersApiResources.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientFamilyMembersApiResources.java @@ -51,10 +51,10 @@ import org.springframework.stereotype.Component; @Path("/clients/{clientId}/familymembers") @Component @Scope("singleton") -public class ClientFamilyMembersApiResources -{ - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id","clientId","firstName","middleName","lastName","qualification", - "relationship","maritalStatus","gender","dateOfBirth","profession","clientFamilyMemberId")); +public class ClientFamilyMembersApiResources { + + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "clientId", "firstName", "middleName", + "lastName", "qualification", "relationship", "maritalStatus", "gender", "dateOfBirth", "profession", "clientFamilyMemberId")); private final String resourceNameForPermissions = "FamilyMembers"; private final PlatformSecurityContext context; private final ClientFamilyMembersReadPlatformService readPlatformService; @@ -63,15 +63,16 @@ public class ClientFamilyMembersApiResources private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public ClientFamilyMembersApiResources(final PlatformSecurityContext context,final ClientFamilyMembersReadPlatformService readPlatformService, - final ToApiJsonSerializer toApiJsonSerializer,final ApiRequestParameterHelper apiRequestParameterHelper, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) - { - this.context=context; - this.readPlatformService=readPlatformService; - this.toApiJsonSerializer=toApiJsonSerializer; - this.apiRequestParameterHelper=apiRequestParameterHelper; - this.commandsSourceWritePlatformService=commandsSourceWritePlatformService; + public ClientFamilyMembersApiResources(final PlatformSecurityContext context, + final ClientFamilyMembersReadPlatformService readPlatformService, + final ToApiJsonSerializer toApiJsonSerializer, + final ApiRequestParameterHelper apiRequestParameterHelper, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + this.context = context; + this.readPlatformService = readPlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @@ -79,23 +80,21 @@ public class ClientFamilyMembersApiResources @Path("/{familyMemberId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String getFamilyMember(@Context final UriInfo uriInfo,@PathParam("familyMemberId") final Long familyMemberId) { + public String getFamilyMember(@Context final UriInfo uriInfo, @PathParam("familyMemberId") final Long familyMemberId) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final ClientFamilyMembersData familyMembers =this.readPlatformService.getClientFamilyMember(familyMemberId); + final ClientFamilyMembersData familyMembers = this.readPlatformService.getClientFamilyMember(familyMemberId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, familyMembers, this.RESPONSE_DATA_PARAMETERS); } - - @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String getFamilyMembers(@Context final UriInfo uriInfo,@PathParam("clientId") final long clientId) { + public String getFamilyMembers(@Context final UriInfo uriInfo, @PathParam("clientId") final long clientId) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -110,7 +109,7 @@ public class ClientFamilyMembersApiResources @Path("/template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String getTemplate(@Context final UriInfo uriInfo,@PathParam("clientId") final long clientId) { + public String getTemplate(@Context final UriInfo uriInfo, @PathParam("clientId") final long clientId) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -121,50 +120,44 @@ public class ClientFamilyMembersApiResources } - @PUT @Path("/{familyMemberId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String updateClientFamilyMembers(@PathParam("familyMemberId") final long familyMemberId, final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateFamilyMembers(familyMemberId) - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateFamilyMembers(familyMemberId).withJson(apiRequestBodyAsJson) + .build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } - @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String addClientFamilyMembers(@PathParam("clientId") final long clientid, final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().addFamilyMembers(clientid) - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().addFamilyMembers(clientid).withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } - @DELETE @Path("/{familyMemberId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String deleteClientFamilyMembers(@PathParam("familyMemberId") final long familyMemberId, final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteFamilyMembers(familyMemberId) - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteFamilyMembers(familyMemberId).withJson(apiRequestBodyAsJson) + .build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientIdentifiersApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientIdentifiersApiResource.java index 67f58ffde..72d7fb3a0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientIdentifiersApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientIdentifiersApiResource.java @@ -64,14 +64,14 @@ import org.springframework.stereotype.Component; @Path("/clients/{clientId}/identifiers") @Component @Scope("singleton") -@Api(tags = {"Client Identifier"}) +@Api(tags = { "Client Identifier" }) @SwaggerDefinition(tags = { - @Tag(name = "Client Identifier", description = "Client Identifiers refer to documents that are used to uniquely identify a customer\n" + "Ex: Drivers License, Passport, Ration card etc ") -}) + @Tag(name = "Client Identifier", description = "Client Identifiers refer to documents that are used to uniquely identify a customer\n" + + "Ex: Drivers License, Passport, Ration card etc ") }) public class ClientIdentifiersApiResource { - private static final Set CLIENT_IDENTIFIER_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "clientId", - "documentType", "documentKey", "description", "allowedDocumentTypes")); + private static final Set CLIENT_IDENTIFIER_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "clientId", "documentType", "documentKey", "description", "allowedDocumentTypes")); private final String resourceNameForPermissions = "CLIENTIDENTIFIER"; @@ -102,9 +102,12 @@ public class ClientIdentifiersApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List all Identifiers for a Client", notes = "Example Requests:\n" + "clients/1/identifiers\n" + "\n" + "\n" + "clients/1/identifiers?fields=documentKey,documentType,description") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = ClientIdentifiersApiResourceSwagger.GetClientsClientIdIdentifiersResponse.class)}) - public String retrieveAllClientIdentifiers(@Context final UriInfo uriInfo, @PathParam("clientId") @ApiParam(value = "clientId") final Long clientId) { + @ApiOperation(value = "List all Identifiers for a Client", notes = "Example Requests:\n" + "clients/1/identifiers\n" + "\n" + "\n" + + "clients/1/identifiers?fields=documentKey,documentType,description") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = ClientIdentifiersApiResourceSwagger.GetClientsClientIdIdentifiersResponse.class) }) + public String retrieveAllClientIdentifiers(@Context final UriInfo uriInfo, + @PathParam("clientId") @ApiParam(value = "clientId") final Long clientId) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -119,8 +122,10 @@ public class ClientIdentifiersApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Client Identifier Details Template", notes = "This is a convenience resource useful for building maintenance user interface screens for client applications. The template data returned consists of any or all of:\n" + "\n" + " Field Defaults\n" + " Allowed Value Lists\n" + "\n\nExample Request:\n" + "clients/1/identifiers/template" ) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientIdentifiersApiResourceSwagger.GetClientsClientIdIdentifiersTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Client Identifier Details Template", notes = "This is a convenience resource useful for building maintenance user interface screens for client applications. The template data returned consists of any or all of:\n" + + "\n" + " Field Defaults\n" + " Allowed Value Lists\n" + "\n\nExample Request:\n" + "clients/1/identifiers/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientIdentifiersApiResourceSwagger.GetClientsClientIdIdentifiersTemplateResponse.class) }) public String newClientIdentifierDetails(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -135,10 +140,13 @@ public class ClientIdentifiersApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create an Identifier for a Client", notes = "Mandatory Fields\n" + "documentKey, documentTypeId " ) - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientIdentifiersApiResourceSwagger.PostClientsClientIdIdentifiersRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientIdentifiersApiResourceSwagger.PostClientsClientIdIdentifiersResponse.class)}) - public String createClientIdentifier(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Create an Identifier for a Client", notes = "Mandatory Fields\n" + "documentKey, documentTypeId ") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientIdentifiersApiResourceSwagger.PostClientsClientIdIdentifiersRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientIdentifiersApiResourceSwagger.PostClientsClientIdIdentifiersResponse.class) }) + public String createClientIdentifier(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { try { final CommandWrapper commandRequest = new CommandWrapperBuilder().createClientIdentifier(clientId) @@ -153,8 +161,8 @@ public class ClientIdentifiersApiResource { // need to fetch client info final ClientData clientInfo = this.clientReadPlatformService.retrieveClientByIdentifier(e.getDocumentTypeId(), e.getIdentifierKey()); - rethrowas = new DuplicateClientIdentifierException(clientInfo.displayName(), clientInfo.officeName(), - e.getIdentifierType(), e.getIdentifierKey()); + rethrowas = new DuplicateClientIdentifierException(clientInfo.displayName(), clientInfo.officeName(), e.getIdentifierType(), + e.getIdentifierKey()); } throw rethrowas; } @@ -164,8 +172,10 @@ public class ClientIdentifiersApiResource { @Path("{identifierId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Client Identifier", notes = "Example Requests:\n" + "clients/1/identifier/2\n" + "\n" + "\n" + "clients/1/identifier/2?template=true\n" + "\n" + "clients/1/identifiers/2?fields=documentKey,documentType,description" ) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientIdentifiersApiResourceSwagger.GetClientsClientIdIdentifiersResponse.class)}) + @ApiOperation(value = "Retrieve a Client Identifier", notes = "Example Requests:\n" + "clients/1/identifier/2\n" + "\n" + "\n" + + "clients/1/identifier/2?template=true\n" + "\n" + "clients/1/identifiers/2?fields=documentKey,documentType,description") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientIdentifiersApiResourceSwagger.GetClientsClientIdIdentifiersResponse.class) }) public String retrieveClientIdentifiers(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @PathParam("identifierId") @ApiParam(value = "identifierId") final Long clientIdentifierId, @Context final UriInfo uriInfo) { @@ -188,10 +198,13 @@ public class ClientIdentifiersApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Client Identifier", notes = "Updates a Client Identifier") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientIdentifiersApiResourceSwagger.PutClientsClientIdIdentifiersIdentifierIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientIdentifiersApiResourceSwagger.PutClientsClientIdIdentifiersIdentifierIdResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientIdentifiersApiResourceSwagger.PutClientsClientIdIdentifiersIdentifierIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientIdentifiersApiResourceSwagger.PutClientsClientIdIdentifiersIdentifierIdResponse.class) }) public String updateClientIdentifer(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, - @PathParam("identifierId") @ApiParam(value = "identifierId") final Long clientIdentifierId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @PathParam("identifierId") @ApiParam(value = "identifierId") final Long clientIdentifierId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { try { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateClientIdentifier(clientId, clientIdentifierId) @@ -205,8 +218,8 @@ public class ClientIdentifiersApiResource { if (e.getDocumentTypeId() != null) { final ClientData clientInfo = this.clientReadPlatformService.retrieveClientByIdentifier(e.getDocumentTypeId(), e.getIdentifierKey()); - reThrowAs = new DuplicateClientIdentifierException(clientInfo.displayName(), clientInfo.officeName(), - e.getIdentifierType(), e.getIdentifierKey()); + reThrowAs = new DuplicateClientIdentifierException(clientInfo.displayName(), clientInfo.officeName(), e.getIdentifierType(), + e.getIdentifierKey()); } throw reThrowAs; } @@ -217,7 +230,8 @@ public class ClientIdentifiersApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Client Identifier", notes = "Deletes a Client Identifier") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientIdentifiersApiResourceSwagger.DeleteClientsClientIdIdentifiersIdentifierIdResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientIdentifiersApiResourceSwagger.DeleteClientsClientIdIdentifiersIdentifierIdResponse.class) }) public String deleteClientIdentifier(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @PathParam("identifierId") @ApiParam(value = "identifierId") final Long clientIdentifierId) { @@ -227,4 +241,4 @@ public class ClientIdentifiersApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientIdentifiersApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientIdentifiersApiResourceSwagger.java index 5d1271ff2..228e581c0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientIdentifiersApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientIdentifiersApiResourceSwagger.java @@ -26,17 +26,17 @@ import java.util.Set; * Created by Chirag Gupta on 01/13/18. */ final class ClientIdentifiersApiResourceSwagger { - private ClientIdentifiersApiResourceSwagger() { - } + + private ClientIdentifiersApiResourceSwagger() {} @ApiModel(value = "GetClientsClientIdIdentifiersResponse") public final static class GetClientsClientIdIdentifiersResponse { - private GetClientsClientIdIdentifiersResponse() { - } + + private GetClientsClientIdIdentifiersResponse() {} final class GetClientsDocumentType { - private GetClientsDocumentType() { - } + + private GetClientsDocumentType() {} @ApiModelProperty(example = "3") public Integer id; @@ -57,12 +57,12 @@ final class ClientIdentifiersApiResourceSwagger { @ApiModel(value = "GetClientsClientIdIdentifiersTemplateResponse") public final static class GetClientsClientIdIdentifiersTemplateResponse { - private GetClientsClientIdIdentifiersTemplateResponse() { - } + + private GetClientsClientIdIdentifiersTemplateResponse() {} final class GetClientsAllowedDocumentTypes { - private GetClientsAllowedDocumentTypes() { - } + + private GetClientsAllowedDocumentTypes() {} @ApiModelProperty(example = "1") public Integer id; @@ -77,8 +77,8 @@ final class ClientIdentifiersApiResourceSwagger { @ApiModel(value = "PostClientsClientIdIdentifiersRequest") public final static class PostClientsClientIdIdentifiersRequest { - private PostClientsClientIdIdentifiersRequest() { - } + + private PostClientsClientIdIdentifiersRequest() {} @ApiModelProperty(example = "1") public Integer documentTypeId; @@ -90,8 +90,8 @@ final class ClientIdentifiersApiResourceSwagger { @ApiModel(value = "PutClientsClientIdIdentifiersIdentifierIdRequest") public final static class PutClientsClientIdIdentifiersIdentifierIdRequest { - private PutClientsClientIdIdentifiersIdentifierIdRequest() { - } + + private PutClientsClientIdIdentifiersIdentifierIdRequest() {} @ApiModelProperty(example = "4") public Integer documentTypeId; @@ -103,8 +103,8 @@ final class ClientIdentifiersApiResourceSwagger { @ApiModel(value = "PutClientsClientIdIdentifiersIdentifierIdResponse") public final static class PutClientsClientIdIdentifiersIdentifierIdResponse { - private PutClientsClientIdIdentifiersIdentifierIdResponse() { - } + + private PutClientsClientIdIdentifiersIdentifierIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -117,8 +117,8 @@ final class ClientIdentifiersApiResourceSwagger { @ApiModel(value = "PostClientsClientIdIdentifiersResponse") public final static class PostClientsClientIdIdentifiersResponse { - private PostClientsClientIdIdentifiersResponse() { - } + + private PostClientsClientIdIdentifiersResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -130,8 +130,8 @@ final class ClientIdentifiersApiResourceSwagger { @ApiModel(value = "DeleteClientsClientIdIdentifiersIdentifierIdResponse") public final static class DeleteClientsClientIdIdentifiersIdentifierIdResponse { - private DeleteClientsClientIdIdentifiersIdentifierIdResponse() { - } + + private DeleteClientsClientIdIdentifiersIdentifierIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientTransactionsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientTransactionsApiResource.java index 628150c9a..eb9c1e175 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientTransactionsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientTransactionsApiResource.java @@ -54,10 +54,9 @@ import org.springframework.stereotype.Component; @Path("/clients/{clientId}/transactions") @Component -@Api(tags = {"Client Transaction"}) +@Api(tags = { "Client Transaction" }) @SwaggerDefinition(tags = { - @Tag(name = "Client Transaction", description = "Client Transactions refer to transactions made directly againt a Client's internal account. Currently, these transactions are only created as a result of charge payments/waivers. You are allowed to undo a transaction, however you cannot explicitly create one. ") -}) + @Tag(name = "Client Transaction", description = "Client Transactions refer to transactions made directly againt a Client's internal account. Currently, these transactions are only created as a result of charge payments/waivers. You are allowed to undo a transaction, however you cannot explicitly create one. ") }) public class ClientTransactionsApiResource { private final PlatformSecurityContext context; @@ -82,10 +81,13 @@ public class ClientTransactionsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Client Transactions", notes = "The list capability of client transaction can support pagination." + "\n\n" + "Example Requests:\n\n" + "clients/189/transactions\n\n" + "clients/189/transactions?offset=10&limit=50" ) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientTransactionsApiResourceSwagger.GetClientsClientIdTransactionsResponse.class)}) - public String retrieveAllClientTransactions(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @Context final UriInfo uriInfo, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit) { + @ApiOperation(value = "List Client Transactions", notes = "The list capability of client transaction can support pagination." + "\n\n" + + "Example Requests:\n\n" + "clients/189/transactions\n\n" + "clients/189/transactions?offset=10&limit=50") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientTransactionsApiResourceSwagger.GetClientsClientIdTransactionsResponse.class) }) + public String retrieveAllClientTransactions(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @Context final UriInfo uriInfo, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit) { this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME); SearchParameters searchParameters = SearchParameters.forPagination(offset, limit); @@ -101,8 +103,10 @@ public class ClientTransactionsApiResource { @Path("{transactionId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Client Transaction", notes = "Example Requests:\n" + "clients/1/transactions/1\n" + "\n" + "\n" + "clients/1/transactions/1?fields=id,officeName" ) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientTransactionsApiResourceSwagger.GetClientsClientIdTransactionsTransactionIdResponse.class)}) + @ApiOperation(value = "Retrieve a Client Transaction", notes = "Example Requests:\n" + "clients/1/transactions/1\n" + "\n" + "\n" + + "clients/1/transactions/1?fields=id,officeName") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientTransactionsApiResourceSwagger.GetClientsClientIdTransactionsTransactionIdResponse.class) }) public String retrieveClientTransaction(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, @Context final UriInfo uriInfo) { @@ -121,9 +125,12 @@ public class ClientTransactionsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Undo a Client Transaction", notes = "Undoes a Client Transaction") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientTransactionsApiResourceSwagger.PostClientsClientIdTransactionsTransactionIdResponse.class)}) - public String undoClientTransaction(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, - @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ClientTransactionsApiResourceSwagger.PostClientsClientIdTransactionsTransactionIdResponse.class) }) + public String undoClientTransaction(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { String json = ""; if (is(commandParam, ClientApiConstants.CLIENT_TRANSACTION_COMMAND_UNDO)) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientTransactionsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientTransactionsApiResourceSwagger.java index 3c7674c84..7ea9ca942 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientTransactionsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientTransactionsApiResourceSwagger.java @@ -28,21 +28,21 @@ import java.util.Set; * Created by Chirag Gupta on 01/13/18. */ final class ClientTransactionsApiResourceSwagger { - private ClientTransactionsApiResourceSwagger() { - } + + private ClientTransactionsApiResourceSwagger() {} @ApiModel(value = "GetClientsClientIdTransactionsResponse") public final static class GetClientsClientIdTransactionsResponse { - private GetClientsClientIdTransactionsResponse() { - } + + private GetClientsClientIdTransactionsResponse() {} final class GetClientsPageItems { - private GetClientsPageItems() { - } + + private GetClientsPageItems() {} final class GetClientsClientIdTransactionsType { - private GetClientsClientIdTransactionsType() { - } + + private GetClientsClientIdTransactionsType() {} @ApiModelProperty(example = "1") public Integer id; @@ -53,8 +53,8 @@ final class ClientTransactionsApiResourceSwagger { } final class GetClientTransactionsCurrency { - private GetClientTransactionsCurrency() { - } + + private GetClientTransactionsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -95,8 +95,8 @@ final class ClientTransactionsApiResourceSwagger { @ApiModel(value = "GetClientsClientIdTransactionsTransactionIdResponse") public final static class GetClientsClientIdTransactionsTransactionIdResponse { - private GetClientsClientIdTransactionsTransactionIdResponse() { - } + + private GetClientsClientIdTransactionsTransactionIdResponse() {} @ApiModelProperty(example = "1") public Integer id; @@ -116,11 +116,10 @@ final class ClientTransactionsApiResourceSwagger { public Boolean reversed; } - @ApiModel(value = "PostClientsClientIdTransactionsTransactionIdResponse") public final static class PostClientsClientIdTransactionsTransactionIdResponse { - private PostClientsClientIdTransactionsTransactionIdResponse() { - } + + private PostClientsClientIdTransactionsTransactionIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientsApiResource.java index 5b4b49bf3..2cd79067a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientsApiResource.java @@ -80,10 +80,10 @@ import org.springframework.stereotype.Component; @Path("/clients") @Component @Scope("singleton") -@Api(tags = {"Client"}) +@Api(tags = { "Client" }) @SwaggerDefinition(tags = { - @Tag(name = "Client", description = "Clients are people and businesses that have applied (or may apply) to an MFI for loans.\n" + "\n" + "Clients can be created in Pending or straight into Active state.") -}) + @Tag(name = "Client", description = "Clients are people and businesses that have applied (or may apply) to an MFI for loans.\n" + + "\n" + "Clients can be created in Pending or straight into Active state.") }) public class ClientsApiResource { private final PlatformSecurityContext context; @@ -107,8 +107,7 @@ public class ClientsApiResource { final AccountDetailsReadPlatformService accountDetailsReadPlatformService, final SavingsAccountReadPlatformService savingsAccountReadPlatformService, final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService, - final BulkImportWorkbookService bulkImportWorkbookService, - final GuarantorReadPlatformService guarantorReadPlatformService) { + final BulkImportWorkbookService bulkImportWorkbookService, final GuarantorReadPlatformService guarantorReadPlatformService) { this.context = context; this.clientReadPlatformService = readPlatformService; this.toApiJsonSerializer = toApiJsonSerializer; @@ -117,8 +116,8 @@ public class ClientsApiResource { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; this.accountDetailsReadPlatformService = accountDetailsReadPlatformService; this.savingsAccountReadPlatformService = savingsAccountReadPlatformService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; - this.bulkImportWorkbookService=bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; this.guarantorReadPlatformService = guarantorReadPlatformService; } @@ -126,10 +125,13 @@ public class ClientsApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Client Details Template", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Request:\n" + "\n" + "clients/template") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.GetClientsTemplateResponse.class)}) - public String retrieveTemplate(@Context final UriInfo uriInfo, @ApiParam(value = "officeId") @QueryParam("officeId") final Long officeId, @QueryParam("commandParam") @ApiParam(value = "commandParam") final String commandParam, - @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly")final boolean staffInSelectedOfficeOnly) { + @ApiOperation(value = "Retrieve Client Details Template", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Request:\n" + "\n" + "clients/template") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.GetClientsTemplateResponse.class) }) + public String retrieveTemplate(@Context final UriInfo uriInfo, + @ApiParam(value = "officeId") @QueryParam("officeId") final Long officeId, + @QueryParam("commandParam") @ApiParam(value = "commandParam") final String commandParam, + @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly) { this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); @@ -154,27 +156,31 @@ public class ClientsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Clients", notes = "The list capability of clients can support pagination and sorting.\n\n" + "Example Requests:\n" + "\n" + "clients\n" + "\n" + "clients?fields=displayName,officeName,timeline\n" + "\n" + "clients?offset=10&limit=50\n" + "\n" + "clients?orderBy=displayName&sortOrder=DESC" ) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.GetClientsResponse.class)}) - public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, - @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, - @QueryParam("displayName") @ApiParam(value = "displayName") final String displayName, @QueryParam("firstName") @ApiParam(value = "firstName") final String firstname, - @QueryParam("lastName") @ApiParam(value = "lastName") final String lastname, @QueryParam("underHierarchy") @ApiParam(value = "underHierarchy") final String hierarchy, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, + @ApiOperation(value = "List Clients", notes = "The list capability of clients can support pagination and sorting.\n\n" + + "Example Requests:\n" + "\n" + "clients\n" + "\n" + "clients?fields=displayName,officeName,timeline\n" + "\n" + + "clients?offset=10&limit=50\n" + "\n" + "clients?orderBy=displayName&sortOrder=DESC") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.GetClientsResponse.class) }) + public String retrieveAll(@Context final UriInfo uriInfo, + @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, + @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, + @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, + @QueryParam("displayName") @ApiParam(value = "displayName") final String displayName, + @QueryParam("firstName") @ApiParam(value = "firstName") final String firstname, + @QueryParam("lastName") @ApiParam(value = "lastName") final String lastname, + @QueryParam("underHierarchy") @ApiParam(value = "underHierarchy") final String hierarchy, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, @QueryParam("orphansOnly") @ApiParam(value = "orphansOnly") final Boolean orphansOnly) { - return this.retrieveAll(uriInfo, sqlSearch, officeId, externalId, displayName, firstname, - lastname, hierarchy, offset, limit, orderBy, sortOrder, orphansOnly, false); + return this.retrieveAll(uriInfo, sqlSearch, officeId, externalId, displayName, firstname, lastname, hierarchy, offset, limit, + orderBy, sortOrder, orphansOnly, false); } - public String retrieveAll(final UriInfo uriInfo, final String sqlSearch, - final Long officeId, final String externalId, - final String displayName, final String firstname, - final String lastname, final String hierarchy, - final Integer offset, final Integer limit, - final String orderBy, final String sortOrder, - final Boolean orphansOnly, final boolean isSelfUser) { + public String retrieveAll(final UriInfo uriInfo, final String sqlSearch, final Long officeId, final String externalId, + final String displayName, final String firstname, final String lastname, final String hierarchy, final Integer offset, + final Integer limit, final String orderBy, final String sortOrder, final Boolean orphansOnly, final boolean isSelfUser) { this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); @@ -191,8 +197,9 @@ public class ClientsApiResource { @Path("{clientId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Client", notes = "Example Requests:\n" + "\n" + "clients/1\n" +"\n" + "\n" + "clients/1?template=true\n" + "\n" + "\n" + "clients/1?fields=id,displayName,officeName" ) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.GetClientsClientIdResponse.class)}) + @ApiOperation(value = "Retrieve a Client", notes = "Example Requests:\n" + "\n" + "clients/1\n" + "\n" + "\n" + + "clients/1?template=true\n" + "\n" + "\n" + "clients/1?fields=id,displayName,officeName") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.GetClientsClientIdResponse.class) }) public String retrieveOne(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @Context final UriInfo uriInfo, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly) { @@ -217,12 +224,16 @@ public class ClientsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Client", httpMethod = "POST", notes = "Note:\n\n" + "1. You can enter either:firstname/middlename/lastname - for a person (middlename is optional) OR fullname - for a business or organisation (or person known by one name).\n" + "\n" + "2.If address is enable(enable-address=true), then additional field called address has to be passed.\n\n" + "Mandatory Fields: firstname and lastname OR fullname, officeId, active=true and activationDate OR active=false, if(address enabled) address\n\n" + "Optional Fields: groupId, externalId, accountNo, staffId, mobileNo, savingsProductId, genderId, clientTypeId, clientClassificationId") - @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "ClientData", required = true, type = "body", dataTypeClass = ClientsApiResourceSwagger.PostClientsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.PostClientsResponse.class) }) + @ApiOperation(value = "Create a Client", httpMethod = "POST", notes = "Note:\n\n" + + "1. You can enter either:firstname/middlename/lastname - for a person (middlename is optional) OR fullname - for a business or organisation (or person known by one name).\n" + + "\n" + "2.If address is enable(enable-address=true), then additional field called address has to be passed.\n\n" + + "Mandatory Fields: firstname and lastname OR fullname, officeId, active=true and activationDate OR active=false, if(address enabled) address\n\n" + + "Optional Fields: groupId, externalId, accountNo, staffId, mobileNo, savingsProductId, genderId, clientTypeId, clientClassificationId") + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", dataType = "ClientData", required = true, type = "body", dataTypeClass = ClientsApiResourceSwagger.PostClientsRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.PostClientsResponse.class) }) public String create(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() // .createClient() // .withJson(apiRequestBodyAsJson) // @@ -237,10 +248,15 @@ public class ClientsApiResource { @Path("{clientId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Update a Client", notes = "Note: You can update any of the basic attributes of a client (but not its associations) using this API.\n" + "\n" + "Changing the relationship between a client and its office is not supported through this API. An API specific to handling transfers of clients between offices is available for the same.\n" + "\n" + "The relationship between a client and a group must be removed through the Groups API." ) - @ApiImplicitParams({@ApiImplicitParam( paramType = "body", dataType = "ClientData", required = true, type = "body", dataTypeClass = ClientsApiResourceSwagger.PutClientsClientIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.PutClientsClientIdResponse.class) }) - public String update(@ApiParam(value = "clientId") @PathParam("clientId") final Long clientId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Update a Client", notes = "Note: You can update any of the basic attributes of a client (but not its associations) using this API.\n" + + "\n" + + "Changing the relationship between a client and its office is not supported through this API. An API specific to handling transfers of clients between offices is available for the same.\n" + + "\n" + "The relationship between a client and a group must be removed through the Groups API.") + @ApiImplicitParams({ + @ApiImplicitParam(paramType = "body", dataType = "ClientData", required = true, type = "body", dataTypeClass = ClientsApiResourceSwagger.PutClientsClientIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.PutClientsClientIdResponse.class) }) + public String update(@ApiParam(value = "clientId") @PathParam("clientId") final Long clientId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .updateClient(clientId) // @@ -257,8 +273,10 @@ public class ClientsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Client", notes = "If a client is in Pending state, you are allowed to Delete it. The delete is a 'hard delete' and cannot be recovered from. Once clients become active or have loans or savings associated with them, you cannot delete the client but you may Close the client if they have left the program.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientsApiResourceSwagger.DeleteClientsClientIdRequest.class)}) - @ApiResponses(value = {@ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.DeleteClientsClientIdResponse.class) }) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientsApiResourceSwagger.DeleteClientsClientIdRequest.class) }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.DeleteClientsClientIdResponse.class) }) public String delete(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -274,10 +292,41 @@ public class ClientsApiResource { @Path("{clientId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Activate a Client | Close a Client | Reject a Client | Withdraw a Client | Reactivate a Client | UndoReject a Client | UndoWithdraw a Client | Assign a Staff | Unassign a Staff | Update Default Savings Account | Propose a Client Transfer | Withdraw a Client Transfer | Reject a Client Transfer | Accept a Client Transfer | Propose and Accept a Client Transfer", notes = "Activate a Client:\n\n" + "Clients can be created in a Pending state. This API exists to enable client activation (for when a client becomes an approved member of the financial Institution).\n" + "\n" + "If the client happens to be already active this API will result in an error.\n\n" + "Close a Client:\n\n" + "Clients can be closed if they do not have any non-closed loans/savingsAccount. This API exists to close a client .\n" + "\n" + "If the client have any active loans/savingsAccount this API will result in an error.\n\n" + "Reject a Client:\n\n" + "Clients can be rejected when client is in pending for activation status.\n" + "\n" + "If the client is any other status, this API throws an error.\n\n" + "Mandatory Fields: rejectionDate, rejectionReasonId\n\n" + "Withdraw a Client:\n\n" + "Client applications can be withdrawn when client is in a pending for activation status.\n" + "\n" + "If the client is any other status, this API throws an error.\n\n" + "Mandatory Fields: withdrawalDate, withdrawalReasonId\n\n" + "Reactivate a Client: Clients can be reactivated after they have been closed.\n" + "\n" + "Trying to reactivate a client in any other state throws an error.\n\n" + "Mandatory Fields: reactivationDate\n\n" + "UndoReject a Client:\n\n" + "Clients can be reactivated after they have been rejected.\n" + "\n" + "Trying to reactivate a client in any other state throws an error.\n\n" + "Mandatory Fields: reopenedDate" + "UndoWithdraw a Client:\n\n" + "Clients can be reactivated after they have been withdrawn.\n" + "\n" + "Trying to reactivate a client in any other state throws an error.\n\n" + "Mandatory Fields: reopenedDate\n\n" + "Assign a Staff:\n\n" + "Allows you to assign a Staff for existed Client.\n" + "\n" + "The selected Staff should belong to the same office (or an officer higher up in the hierarchy) as the Client he manages.\n\n" + "Unassign a Staff:\n\n" + "Allows you to unassign the Staff assigned to a Client.\n\n" + "Update Default Savings Account:\n\n" + "Allows you to modify or assign a default savings account for an existing Client.\n" + "\n" + "The selected savings account should be one among the existing savings account for a particular customer.\n\n" + "Propose a Client Transfer:\n\n" + "Allows you to propose the transfer of a Client to a different Office.\n\n" + "Withdraw a Client Transfer:\n\n" + "Allows you to withdraw the proposed transfer of a Client to a different Office.\n" + "\n" + "Withdrawal can happen only if the destination Branch (to which the transfer was proposed) has not already accepted the transfer proposal\n\n" + "Reject a Client Transfer:\n\n" + "Allows the Destination Branch to reject the proposed Client Transfer.\n\n" + "Accept a Client Transfer:\n\n" + "Allows the Destination Branch to accept the proposed Client Transfer.\n" + "\n" + "The destination branch may also choose to link this client to a group (in which case, any existing active JLG loan of the client is rescheduled to match the meeting frequency of the group) and loan Officer at the time of accepting the transfer\n\n" + "Propose and Accept a Client Transfer:\n\n" + "Abstraction over the Propose and Accept Client Transfer API's which enable a user with Data Scope over both the Target and Destination Branches to directly transfer a Client to the destination Office.\n\n" + "Showing request/response for 'Reject a Client Transfer'") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientsApiResourceSwagger.PostClientsClientIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK",response = ClientsApiResourceSwagger.PostClientsClientIdResponse.class)}) - public String activate(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiOperation(value = "Activate a Client | Close a Client | Reject a Client | Withdraw a Client | Reactivate a Client | UndoReject a Client | UndoWithdraw a Client | Assign a Staff | Unassign a Staff | Update Default Savings Account | Propose a Client Transfer | Withdraw a Client Transfer | Reject a Client Transfer | Accept a Client Transfer | Propose and Accept a Client Transfer", notes = "Activate a Client:\n\n" + + "Clients can be created in a Pending state. This API exists to enable client activation (for when a client becomes an approved member of the financial Institution).\n" + + "\n" + "If the client happens to be already active this API will result in an error.\n\n" + "Close a Client:\n\n" + + "Clients can be closed if they do not have any non-closed loans/savingsAccount. This API exists to close a client .\n" + "\n" + + "If the client have any active loans/savingsAccount this API will result in an error.\n\n" + "Reject a Client:\n\n" + + "Clients can be rejected when client is in pending for activation status.\n" + "\n" + + "If the client is any other status, this API throws an error.\n\n" + "Mandatory Fields: rejectionDate, rejectionReasonId\n\n" + + "Withdraw a Client:\n\n" + "Client applications can be withdrawn when client is in a pending for activation status.\n" + "\n" + + "If the client is any other status, this API throws an error.\n\n" + + "Mandatory Fields: withdrawalDate, withdrawalReasonId\n\n" + + "Reactivate a Client: Clients can be reactivated after they have been closed.\n" + "\n" + + "Trying to reactivate a client in any other state throws an error.\n\n" + "Mandatory Fields: reactivationDate\n\n" + + "UndoReject a Client:\n\n" + "Clients can be reactivated after they have been rejected.\n" + "\n" + + "Trying to reactivate a client in any other state throws an error.\n\n" + "Mandatory Fields: reopenedDate" + + "UndoWithdraw a Client:\n\n" + "Clients can be reactivated after they have been withdrawn.\n" + "\n" + + "Trying to reactivate a client in any other state throws an error.\n\n" + "Mandatory Fields: reopenedDate\n\n" + + "Assign a Staff:\n\n" + "Allows you to assign a Staff for existed Client.\n" + "\n" + + "The selected Staff should belong to the same office (or an officer higher up in the hierarchy) as the Client he manages.\n\n" + + "Unassign a Staff:\n\n" + "Allows you to unassign the Staff assigned to a Client.\n\n" + "Update Default Savings Account:\n\n" + + "Allows you to modify or assign a default savings account for an existing Client.\n" + "\n" + + "The selected savings account should be one among the existing savings account for a particular customer.\n\n" + + "Propose a Client Transfer:\n\n" + "Allows you to propose the transfer of a Client to a different Office.\n\n" + + "Withdraw a Client Transfer:\n\n" + "Allows you to withdraw the proposed transfer of a Client to a different Office.\n" + "\n" + + "Withdrawal can happen only if the destination Branch (to which the transfer was proposed) has not already accepted the transfer proposal\n\n" + + "Reject a Client Transfer:\n\n" + "Allows the Destination Branch to reject the proposed Client Transfer.\n\n" + + "Accept a Client Transfer:\n\n" + "Allows the Destination Branch to accept the proposed Client Transfer.\n" + "\n" + + "The destination branch may also choose to link this client to a group (in which case, any existing active JLG loan of the client is rescheduled to match the meeting frequency of the group) and loan Officer at the time of accepting the transfer\n\n" + + "Propose and Accept a Client Transfer:\n\n" + + "Abstraction over the Propose and Accept Client Transfer API's which enable a user with Data Scope over both the Target and Destination Branches to directly transfer a Client to the destination Office.\n\n" + + "Showing request/response for 'Reject a Client Transfer'") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ClientsApiResourceSwagger.PostClientsClientIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.PostClientsClientIdResponse.class) }) + public String activate(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); @@ -333,9 +382,11 @@ public class ClientsApiResource { result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); } - if (result == null) { throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { "activate", - "unassignStaff", "assignStaff", "close", "proposeTransfer", "withdrawTransfer", "acceptTransfer", "rejectTransfer", - "updateSavingsAccount", "reject", "withdraw", "reactivate" }); } + if (result == null) { + throw new UnrecognizedQueryParamException("command", commandParam, + new Object[] { "activate", "unassignStaff", "assignStaff", "close", "proposeTransfer", "withdrawTransfer", + "acceptTransfer", "rejectTransfer", "updateSavingsAccount", "reject", "withdraw", "reactivate" }); + } return this.toApiJsonSerializer.serialize(result); } @@ -348,18 +399,20 @@ public class ClientsApiResource { @Path("{clientId}/accounts") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve client accounts overview", notes = "An example of how a loan portfolio summary can be provided. This is requested in a specific use case of the community application.\n" + "It is quite reasonable to add resources like this to simplify User Interface development.\n" + "\n" + "Example Requests:\n " + "\n" + "clients/1/accounts\n"+ "\n" + "clients/1/accounts?fields=loanAccounts,savingsAccounts" ) - @ApiResponses({ - @ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.GetClientsClientIdAccountsResponse.class), - @ApiResponse(code = 400, message = "Bad Request") - }) - public String retrieveAssociatedAccounts(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve client accounts overview", notes = "An example of how a loan portfolio summary can be provided. This is requested in a specific use case of the community application.\n" + + "It is quite reasonable to add resources like this to simplify User Interface development.\n" + "\n" + "Example Requests:\n " + + "\n" + "clients/1/accounts\n" + "\n" + "clients/1/accounts?fields=loanAccounts,savingsAccounts") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ClientsApiResourceSwagger.GetClientsClientIdAccountsResponse.class), + @ApiResponse(code = 400, message = "Bad Request") }) + public String retrieveAssociatedAccounts(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); final AccountSummaryCollectionData clientAccount = this.accountDetailsReadPlatformService.retrieveClientAccountDetails(clientId); - final Set CLIENT_ACCOUNTS_DATA_PARAMETERS = new HashSet<>(Arrays.asList("loanAccounts", "savingsAccounts", "shareAccounts")); + final Set CLIENT_ACCOUNTS_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("loanAccounts", "savingsAccounts", "shareAccounts")); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.clientAccountSummaryToApiJsonSerializer.serialize(settings, clientAccount, CLIENT_ACCOUNTS_DATA_PARAMETERS); @@ -368,19 +421,19 @@ public class ClientsApiResource { @GET @Path("downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getClientTemplate(@QueryParam("legalFormType")final String legalFormType, - @QueryParam("officeId")final Long officeId,@QueryParam("staffId")final Long staffId, - @QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(legalFormType, officeId, staffId,dateFormat); + public Response getClientTemplate(@QueryParam("legalFormType") final String legalFormType, @QueryParam("officeId") final Long officeId, + @QueryParam("staffId") final Long staffId, @QueryParam("dateFormat") final String dateFormat) { + return bulkImportWorkbookPopulatorService.getTemplate(legalFormType, officeId, staffId, dateFormat); } @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) - public String postClientTemplate(@QueryParam("legalFormType")final String legalFormType,@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, - @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId = bulkImportWorkbookService.importWorkbook(legalFormType, uploadedInputStream,fileDetail,locale,dateFormat); + public String postClientTemplate(@QueryParam("legalFormType") final String legalFormType, + @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, + @FormDataParam("locale") final String locale, @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = bulkImportWorkbookService.importWorkbook(legalFormType, uploadedInputStream, fileDetail, locale, + dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } @@ -407,4 +460,4 @@ public class ClientsApiResource { final Date transferDate = this.clientReadPlatformService.retrieveClientTransferProposalDate(clientId); return this.toApiJsonSerializer.serialize((transferDate != null ? new LocalDate(transferDate) : null)); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientsApiResourceSwagger.java index 8f308d593..552a4ccec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/api/ClientsApiResourceSwagger.java @@ -28,17 +28,17 @@ import java.util.Set; * Created by Chirag Gupta on 01/13/18. */ final class ClientsApiResourceSwagger { - private ClientsApiResourceSwagger() { - } + + private ClientsApiResourceSwagger() {} @ApiModel(value = "GetClientsTemplateResponse") public final static class GetClientsTemplateResponse { - private GetClientsTemplateResponse() { - } + + private GetClientsTemplateResponse() {} final class GetClientsOfficeOptions { - private GetClientsOfficeOptions() { - } + + private GetClientsOfficeOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -49,8 +49,8 @@ final class ClientsApiResourceSwagger { } final class GetClientsStaffOptions { - private GetClientsStaffOptions() { - } + + private GetClientsStaffOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -71,8 +71,8 @@ final class ClientsApiResourceSwagger { } final class GetClientsSavingProductOptions { - private GetClientsSavingProductOptions() { - } + + private GetClientsSavingProductOptions() {} @ApiModelProperty(example = "4") public Integer id; @@ -85,12 +85,12 @@ final class ClientsApiResourceSwagger { } final class GetClientsDataTables { - private GetClientsDataTables() { - } + + private GetClientsDataTables() {} final class GetClientsColumnHeaderData { - private GetClientsColumnHeaderData() { - } + + private GetClientsColumnHeaderData() {} @ApiModelProperty(example = "client_id") public String columnName; @@ -127,16 +127,16 @@ final class ClientsApiResourceSwagger { @ApiModel(value = "GetClientsResponse") public final static class GetClientsResponse { - private GetClientsResponse() { - } + + private GetClientsResponse() {} final class GetClientsPageItemsResponse { - private GetClientsPageItemsResponse() { - } + + private GetClientsPageItemsResponse() {} final class GetClientStatus { - private GetClientStatus() { - } + + private GetClientStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -170,12 +170,12 @@ final class ClientsApiResourceSwagger { @ApiModel(value = "GetClientsClientIdResponse") public final static class GetClientsClientIdResponse { - private GetClientsClientIdResponse() { - } + + private GetClientsClientIdResponse() {} final class GetClientsClientIdStatus { - private GetClientsClientIdStatus() { - } + + private GetClientsClientIdStatus() {} @ApiModelProperty(example = "300") public Integer id; @@ -186,8 +186,8 @@ final class ClientsApiResourceSwagger { } final class GetClientsTimeline { - private GetClientsTimeline() { - } + + private GetClientsTimeline() {} @ApiModelProperty(example = "[2013, 1, 1]") public LocalDate submittedOnDate; @@ -238,8 +238,8 @@ final class ClientsApiResourceSwagger { @ApiModel(value = "PostClientsRequest") public final static class PostClientsRequest { - private PostClientsRequest() { - } + + private PostClientsRequest() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -259,8 +259,8 @@ final class ClientsApiResourceSwagger { @ApiModel(value = "PostClientsResponse") public final static class PostClientsResponse { - private PostClientsResponse() { - } + + private PostClientsResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -274,8 +274,8 @@ final class ClientsApiResourceSwagger { @ApiModel(value = "PutClientsClientIdRequest") public final static class PutClientsClientIdRequest { - private PutClientsClientIdRequest() { - } + + private PutClientsClientIdRequest() {} @ApiModelProperty(example = "786444UUUYYH7") public String externalId; @@ -283,8 +283,8 @@ final class ClientsApiResourceSwagger { @ApiModel(value = "PutClientsClientIdResponse") public final static class PutClientsClientIdResponse { - private PutClientsClientIdResponse() { - } + + private PutClientsClientIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -297,14 +297,14 @@ final class ClientsApiResourceSwagger { @ApiModel(value = "DeleteClientsClientIdRequest") public final static class DeleteClientsClientIdRequest { - private DeleteClientsClientIdRequest() { - } + + private DeleteClientsClientIdRequest() {} } @ApiModel(value = "DeleteClientsClientIdResponse") public final static class DeleteClientsClientIdResponse { - private DeleteClientsClientIdResponse() { - } + + private DeleteClientsClientIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -316,8 +316,8 @@ final class ClientsApiResourceSwagger { @ApiModel(value = "PostClientsClientIdRequest") public final static class PostClientsClientIdRequest { - private PostClientsClientIdRequest() { - } + + private PostClientsClientIdRequest() {} @ApiModelProperty(example = "We cannot accept transfers of clients having loans with less than 1 repayment left") public String note; @@ -325,8 +325,8 @@ final class ClientsApiResourceSwagger { @ApiModel(value = "PostClientsClientIdResponse") public final static class PostClientsClientIdResponse { - private PostClientsClientIdResponse() { - } + + private PostClientsClientIdResponse() {} @ApiModelProperty(example = "2") public Integer clientId; @@ -336,16 +336,16 @@ final class ClientsApiResourceSwagger { @ApiModel(value = "GetClientsClientIdAccountsResponse") public final static class GetClientsClientIdAccountsResponse { - private GetClientsClientIdAccountsResponse() { - } + + private GetClientsClientIdAccountsResponse() {} final class GetClientsLoanAccounts { - private GetClientsLoanAccounts() { - } + + private GetClientsLoanAccounts() {} final class GetClientsLoanAccountsStatus { - private GetClientsLoanAccountsStatus() { - } + + private GetClientsLoanAccountsStatus() {} @ApiModelProperty(example = "300") public Integer id; @@ -372,8 +372,8 @@ final class ClientsApiResourceSwagger { } final class GetClientsLoanAccountsType { - private GetClientsLoanAccountsType() { - } + + private GetClientsLoanAccountsType() {} @ApiModelProperty(example = "1") public Integer id; @@ -400,12 +400,12 @@ final class ClientsApiResourceSwagger { } final class GetClientsSavingsAccounts { - private GetClientsSavingsAccounts() { - } + + private GetClientsSavingsAccounts() {} final class GetClientsSavingsAccountsCurrency { - private GetClientsSavingsAccountsCurrency() { - } + + private GetClientsSavingsAccountsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -422,8 +422,8 @@ final class ClientsApiResourceSwagger { } final class GetClientsSavingsAccountsStatus { - private GetClientsSavingsAccountsStatus() { - } + + private GetClientsSavingsAccountsStatus() {} @ApiModelProperty(example = "100") public Integer id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/command/ClientIdentifierCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/command/ClientIdentifierCommand.java index 5dd834524..2bd7c7238 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/command/ClientIdentifierCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/command/ClientIdentifierCommand.java @@ -34,7 +34,8 @@ public class ClientIdentifierCommand { private final String description; private final String status; - public ClientIdentifierCommand(final Long documentTypeId, final String documentKey, final String statusString, final String description) { + public ClientIdentifierCommand(final Long documentTypeId, final String documentKey, final String statusString, + final String description) { this.documentTypeId = documentTypeId; this.documentKey = documentKey; this.status = statusString; @@ -61,8 +62,10 @@ public class ClientIdentifierCommand { baseDataValidator.reset().parameter("documentTypeId").value(this.documentTypeId).notNull().integerGreaterThanZero(); baseDataValidator.reset().parameter("documentKey").value(this.documentKey).notBlank(); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForUpdate() { @@ -79,7 +82,9 @@ public class ClientIdentifierCommand { baseDataValidator.reset().anyOfNotNull(this.documentTypeId, this.documentKey); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/command/ClientNoteCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/command/ClientNoteCommand.java index a439ae26b..7a61a410e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/command/ClientNoteCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/command/ClientNoteCommand.java @@ -42,7 +42,9 @@ public class ClientNoteCommand { baseDataValidator.reset().parameter("note").value(this.note).notBlank().notExceedingLengthOf(1000); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientApiCollectionConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientApiCollectionConstants.java index ee4586fec..d66f97d1a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientApiCollectionConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientApiCollectionConstants.java @@ -23,30 +23,30 @@ import java.util.HashSet; import java.util.Set; import org.apache.fineract.portfolio.client.api.ClientApiConstants; +public class ClientApiCollectionConstants extends ClientApiConstants { -public class ClientApiCollectionConstants extends ClientApiConstants{ - - protected static final Set CLIENT_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(familyMembers,address,localeParamName, dateFormatParamName, groupIdParamName, accountNoParamName, externalIdParamName, - mobileNoParamName, emailAddressParamName, firstnameParamName, middlenameParamName, lastnameParamName, fullnameParamName, officeIdParamName, - activeParamName, activationDateParamName, staffIdParamName, submittedOnDateParamName, savingsProductIdParamName, - dateOfBirthParamName, genderIdParamName, clientTypeIdParamName, clientClassificationIdParamName, - clientNonPersonDetailsParamName, displaynameParamName, legalFormIdParamName, datatables, isStaffParamName)); + protected static final Set CLIENT_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(familyMembers, address, + localeParamName, dateFormatParamName, groupIdParamName, accountNoParamName, externalIdParamName, mobileNoParamName, + emailAddressParamName, firstnameParamName, middlenameParamName, lastnameParamName, fullnameParamName, officeIdParamName, + activeParamName, activationDateParamName, staffIdParamName, submittedOnDateParamName, savingsProductIdParamName, + dateOfBirthParamName, genderIdParamName, clientTypeIdParamName, clientClassificationIdParamName, + clientNonPersonDetailsParamName, displaynameParamName, legalFormIdParamName, datatables, isStaffParamName)); protected static final Set CLIENT_NON_PERSON_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(familyMembers,address,localeParamName, dateFormatParamName, incorpNumberParamName, remarksParamName, incorpValidityTillParamName, - constitutionIdParamName, mainBusinessLineIdParamName, datatables)); + Arrays.asList(familyMembers, address, localeParamName, dateFormatParamName, incorpNumberParamName, remarksParamName, + incorpValidityTillParamName, constitutionIdParamName, mainBusinessLineIdParamName, datatables)); protected static final Set CLIENT_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(localeParamName, - dateFormatParamName, accountNoParamName, externalIdParamName, mobileNoParamName, emailAddressParamName, firstnameParamName, middlenameParamName, + dateFormatParamName, accountNoParamName, externalIdParamName, mobileNoParamName, emailAddressParamName, firstnameParamName, + middlenameParamName, lastnameParamName, fullnameParamName, activeParamName, activationDateParamName, staffIdParamName, savingsProductIdParamName, - dateOfBirthParamName, genderIdParamName, clientTypeIdParamName, clientClassificationIdParamName, submittedOnDateParamName, clientNonPersonDetailsParamName, displaynameParamName, legalFormIdParamName, isStaffParamName)); - - protected static final Set CLIENT_NON_PERSON_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(localeParamName, - dateFormatParamName, incorpNumberParamName, remarksParamName, incorpValidityTillParamName, - constitutionIdParamName, mainBusinessLineIdParamName)); + dateOfBirthParamName, genderIdParamName, clientTypeIdParamName, clientClassificationIdParamName, submittedOnDateParamName, + clientNonPersonDetailsParamName, displaynameParamName, legalFormIdParamName, isStaffParamName)); + protected static final Set CLIENT_NON_PERSON_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(localeParamName, dateFormatParamName, incorpNumberParamName, remarksParamName, incorpValidityTillParamName, + constitutionIdParamName, mainBusinessLineIdParamName)); /** * These parameters will match the class level parameters of @@ -81,5 +81,4 @@ public class ClientApiCollectionConstants extends ClientApiConstants{ transactionDateParamName, dateFormatParamName, localeParamName, paymentTypeIdParamName, transactionAccountNumberParamName, checkNumberParamName, routingCodeParamName, receiptNumberParamName, bankNumberParamName)); - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientData.java index fce056fde..5a8e0badd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientData.java @@ -105,10 +105,9 @@ final public class ClientData implements Comparable, Serializable { private final Boolean isAddressEnabled; - private final List datatables; - //import fields + // import fields private transient Integer rowIndex; private String dateFormat; private String locale; @@ -118,54 +117,54 @@ final public class ClientData implements Comparable, Serializable { private Long legalFormId; private LocalDate submittedOnDate; - public static ClientData importClientEntityInstance(Long legalFormId,Integer rowIndex,String fullname,Long officeId, Long clientTypeId, - Long clientClassificationId,Long staffId,Boolean active,LocalDate activationDate,LocalDate submittedOnDate, - String externalId,LocalDate dateOfBirth,String mobileNo,ClientNonPersonData clientNonPersonDetails, - Collection address,String locale,String dateFormat){ - return new ClientData(legalFormId,rowIndex,fullname, null, null, null, submittedOnDate,activationDate,active, externalId, - officeId, staffId,mobileNo,dateOfBirth,clientTypeId, null,clientClassificationId,null, - address,clientNonPersonDetails, locale,dateFormat); + public static ClientData importClientEntityInstance(Long legalFormId, Integer rowIndex, String fullname, Long officeId, + Long clientTypeId, Long clientClassificationId, Long staffId, Boolean active, LocalDate activationDate, + LocalDate submittedOnDate, String externalId, LocalDate dateOfBirth, String mobileNo, + ClientNonPersonData clientNonPersonDetails, Collection address, String locale, String dateFormat) { + return new ClientData(legalFormId, rowIndex, fullname, null, null, null, submittedOnDate, activationDate, active, externalId, + officeId, staffId, mobileNo, dateOfBirth, clientTypeId, null, clientClassificationId, null, address, clientNonPersonDetails, + locale, dateFormat); } - public static ClientData importClientPersonInstance(Long legalFormId,Integer rowIndex,String firstname,String lastname,String middlename, - LocalDate submittedOn,LocalDate activationDate,Boolean active,String externalId,Long officeId, - Long staffId,String mobileNo, LocalDate dob,Long clientTypeId,Long genderId, - Long clientClassificationId, Boolean isStaff, Collection address,String locale,String dateFormat){ + public static ClientData importClientPersonInstance(Long legalFormId, Integer rowIndex, String firstname, String lastname, + String middlename, LocalDate submittedOn, LocalDate activationDate, Boolean active, String externalId, Long officeId, + Long staffId, String mobileNo, LocalDate dob, Long clientTypeId, Long genderId, Long clientClassificationId, Boolean isStaff, + Collection address, String locale, String dateFormat) { - return new ClientData(legalFormId,rowIndex, null, firstname,lastname,middlename,submittedOn,activationDate,active,externalId, - officeId,staffId,mobileNo,dob,clientTypeId,genderId,clientClassificationId,isStaff,address, null, locale,dateFormat); + return new ClientData(legalFormId, rowIndex, null, firstname, lastname, middlename, submittedOn, activationDate, active, externalId, + officeId, staffId, mobileNo, dob, clientTypeId, genderId, clientClassificationId, isStaff, address, null, locale, + dateFormat); } public static ClientData emptyInstance(Long clientId) { - return lookup(clientId, null, null, null); + return lookup(clientId, null, null, null); } - private ClientData(Long legalFormId,Integer rowIndex, String fullname, String firstname,String lastname,String middlename, - LocalDate submittedOn,LocalDate activationDate,Boolean active,String externalId,Long officeId, - Long staffId,String mobileNo, LocalDate dob,Long clientTypeId,Long genderId, - Long clientClassificationId,Boolean isStaff, Collection address, ClientNonPersonData clientNonPersonDetails, - String locale,String dateFormat ) { - this.rowIndex=rowIndex; - this.dateFormat=dateFormat; - this.locale= locale; + private ClientData(Long legalFormId, Integer rowIndex, String fullname, String firstname, String lastname, String middlename, + LocalDate submittedOn, LocalDate activationDate, Boolean active, String externalId, Long officeId, Long staffId, + String mobileNo, LocalDate dob, Long clientTypeId, Long genderId, Long clientClassificationId, Boolean isStaff, + Collection address, ClientNonPersonData clientNonPersonDetails, String locale, String dateFormat) { + this.rowIndex = rowIndex; + this.dateFormat = dateFormat; + this.locale = locale; this.firstname = firstname; this.lastname = lastname; this.middlename = middlename; this.fullname = fullname; - this.activationDate=activationDate; - this.submittedOnDate=submittedOn; - this.active=active; - this.externalId=externalId; - this.officeId=officeId; - this.staffId=staffId; - this.legalFormId=legalFormId; - this.mobileNo=mobileNo; - this.dateOfBirth=dob; - this.clientTypeId=clientTypeId; - this.genderId=genderId; - this.clientClassificationId=clientClassificationId; - this.isStaff=isStaff; - this.address=address; + this.activationDate = activationDate; + this.submittedOnDate = submittedOn; + this.active = active; + this.externalId = externalId; + this.officeId = officeId; + this.staffId = staffId; + this.legalFormId = legalFormId; + this.mobileNo = mobileNo; + this.dateOfBirth = dob; + this.clientTypeId = clientTypeId; + this.genderId = genderId; + this.clientClassificationId = clientClassificationId; + this.isStaff = isStaff; + this.address = address; this.id = null; this.accountNo = null; this.status = null; @@ -176,14 +175,14 @@ final public class ClientData implements Comparable, Serializable { this.clientClassification = null; this.officeName = null; this.transferToOfficeId = null; - this.transferToOfficeName =null; + this.transferToOfficeName = null; this.imageId = null; this.imagePresent = null; this.staffName = null; this.timeline = null; this.savingsProductId = null; this.savingsProductName = null; - this.savingsAccountId =null; + this.savingsAccountId = null; this.legalForm = null; this.groups = null; this.officeOptions = null; @@ -198,14 +197,12 @@ final public class ClientData implements Comparable, Serializable { this.clientNonPersonMainBusinessLineOptions = null; this.clientLegalFormOptions = null; this.clientNonPersonDetails = null; - this.isAddressEnabled =null; + this.isAddressEnabled = null; this.datatables = null; - this.familyMemberOptions=null; + this.familyMemberOptions = null; this.emailAddress = null; } - - public Integer getRowIndex() { return rowIndex; } @@ -214,7 +211,9 @@ final public class ClientData implements Comparable, Serializable { return savingsAccountId; } - public Long getId(){return id;} + public Long getId() { + return id; + } public String getOfficeName() { return officeName; @@ -223,9 +222,11 @@ final public class ClientData implements Comparable, Serializable { public static ClientData template(final Long officeId, final LocalDate joinedDate, final Collection officeOptions, final Collection staffOptions, final Collection narrations, final Collection genderOptions, final Collection savingProductOptions, - final Collection clientTypeOptions, final Collection clientClassificationOptions, final Collection clientNonPersonConstitutionOptions, - final Collection clientNonPersonMainBusinessLineOptions, final List clientLegalFormOptions,final ClientFamilyMembersData familyMemberOptions, final Collection address, - final Boolean isAddressEnabled, final List datatables) { + final Collection clientTypeOptions, final Collection clientClassificationOptions, + final Collection clientNonPersonConstitutionOptions, + final Collection clientNonPersonMainBusinessLineOptions, final List clientLegalFormOptions, + final ClientFamilyMembersData familyMemberOptions, final Collection address, final Boolean isAddressEnabled, + final List datatables) { final String accountNo = null; final EnumOptionData status = null; final CodeValueData subStatus = null; @@ -258,11 +259,12 @@ final public class ClientData implements Comparable, Serializable { final Boolean isStaff = false; final ClientNonPersonData clientNonPersonDetails = null; return new ClientData(accountNo, status, subStatus, officeId, officeName, transferToOfficeId, transferToOfficeName, id, firstname, - middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, joinedDate, imageId, staffId, - staffName, officeOptions, groups, staffOptions, narrations, genderOptions, timeline, savingProductOptions, + middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, joinedDate, imageId, + staffId, staffName, officeOptions, groups, staffOptions, narrations, genderOptions, timeline, savingProductOptions, savingsProductId, savingsProductName, savingsAccountId, savingAccountOptions, clientType, clientClassification, clientTypeOptions, clientClassificationOptions, clientNonPersonConstitutionOptions, clientNonPersonMainBusinessLineOptions, - clientNonPersonDetails, clientLegalFormOptions,familyMemberOptions, legalForm,address, isAddressEnabled, datatables, isStaff); + clientNonPersonDetails, clientLegalFormOptions, familyMemberOptions, legalForm, address, isAddressEnabled, datatables, + isStaff); } @@ -270,14 +272,16 @@ final public class ClientData implements Comparable, Serializable { return new ClientData(clientData.accountNo, clientData.status, clientData.subStatus, clientData.officeId, clientData.officeName, clientData.transferToOfficeId, clientData.transferToOfficeName, clientData.id, clientData.firstname, clientData.middlename, - clientData.lastname, clientData.fullname, clientData.displayName, clientData.externalId, clientData.mobileNo, clientData.emailAddress, - clientData.dateOfBirth, clientData.gender, clientData.activationDate, clientData.imageId, clientData.staffId, - clientData.staffName, templateData.officeOptions, clientData.groups, templateData.staffOptions, templateData.narrations, - templateData.genderOptions, clientData.timeline, templateData.savingProductOptions, clientData.savingsProductId, - clientData.savingsProductName, clientData.savingsAccountId, clientData.savingAccountOptions, clientData.clientType, - clientData.clientClassification, templateData.clientTypeOptions, templateData.clientClassificationOptions, - templateData.clientNonPersonConstitutionOptions, templateData.clientNonPersonMainBusinessLineOptions, clientData.clientNonPersonDetails, - templateData.clientLegalFormOptions,templateData.familyMemberOptions, clientData.legalForm, clientData.address,clientData.isAddressEnabled, null, clientData.isStaff); + clientData.lastname, clientData.fullname, clientData.displayName, clientData.externalId, clientData.mobileNo, + clientData.emailAddress, clientData.dateOfBirth, clientData.gender, clientData.activationDate, clientData.imageId, + clientData.staffId, clientData.staffName, templateData.officeOptions, clientData.groups, templateData.staffOptions, + templateData.narrations, templateData.genderOptions, clientData.timeline, templateData.savingProductOptions, + clientData.savingsProductId, clientData.savingsProductName, clientData.savingsAccountId, clientData.savingAccountOptions, + clientData.clientType, clientData.clientClassification, templateData.clientTypeOptions, + templateData.clientClassificationOptions, templateData.clientNonPersonConstitutionOptions, + templateData.clientNonPersonMainBusinessLineOptions, clientData.clientNonPersonDetails, templateData.clientLegalFormOptions, + templateData.familyMemberOptions, clientData.legalForm, clientData.address, clientData.isAddressEnabled, null, + clientData.isStaff); } @@ -286,28 +290,31 @@ final public class ClientData implements Comparable, Serializable { return new ClientData(clientData.accountNo, clientData.status, clientData.subStatus, clientData.officeId, clientData.officeName, clientData.transferToOfficeId, clientData.transferToOfficeName, clientData.id, clientData.firstname, clientData.middlename, - clientData.lastname, clientData.fullname, clientData.displayName, clientData.externalId, clientData.mobileNo, clientData.emailAddress, - clientData.dateOfBirth, clientData.gender, clientData.activationDate, clientData.imageId, clientData.staffId, - clientData.staffName, clientData.officeOptions, clientData.groups, clientData.staffOptions, clientData.narrations, - clientData.genderOptions, clientData.timeline, clientData.savingProductOptions, clientData.savingsProductId, - clientData.savingsProductName, clientData.savingsAccountId, savingAccountOptions, clientData.clientType, - clientData.clientClassification, clientData.clientTypeOptions, clientData.clientClassificationOptions, - clientData.clientNonPersonConstitutionOptions, clientData.clientNonPersonMainBusinessLineOptions, clientData.clientNonPersonDetails, - clientData.clientLegalFormOptions,clientData.familyMemberOptions, clientData.legalForm,clientData.address, clientData.isAddressEnabled, null, clientData.isStaff); + clientData.lastname, clientData.fullname, clientData.displayName, clientData.externalId, clientData.mobileNo, + clientData.emailAddress, clientData.dateOfBirth, clientData.gender, clientData.activationDate, clientData.imageId, + clientData.staffId, clientData.staffName, clientData.officeOptions, clientData.groups, clientData.staffOptions, + clientData.narrations, clientData.genderOptions, clientData.timeline, clientData.savingProductOptions, + clientData.savingsProductId, clientData.savingsProductName, clientData.savingsAccountId, savingAccountOptions, + clientData.clientType, clientData.clientClassification, clientData.clientTypeOptions, + clientData.clientClassificationOptions, clientData.clientNonPersonConstitutionOptions, + clientData.clientNonPersonMainBusinessLineOptions, clientData.clientNonPersonDetails, clientData.clientLegalFormOptions, + clientData.familyMemberOptions, clientData.legalForm, clientData.address, clientData.isAddressEnabled, null, + clientData.isStaff); } public static ClientData setParentGroups(final ClientData clientData, final Collection parentGroups) { return new ClientData(clientData.accountNo, clientData.status, clientData.subStatus, clientData.officeId, clientData.officeName, clientData.transferToOfficeId, clientData.transferToOfficeName, clientData.id, clientData.firstname, clientData.middlename, - clientData.lastname, clientData.fullname, clientData.displayName, clientData.externalId, clientData.mobileNo, clientData.emailAddress, - clientData.dateOfBirth, clientData.gender, clientData.activationDate, clientData.imageId, clientData.staffId, - clientData.staffName, clientData.officeOptions, parentGroups, clientData.staffOptions, null, null, clientData.timeline, - clientData.savingProductOptions, clientData.savingsProductId, clientData.savingsProductName, clientData.savingsAccountId, - clientData.savingAccountOptions, clientData.clientType, clientData.clientClassification, clientData.clientTypeOptions, - clientData.clientClassificationOptions, clientData.clientNonPersonConstitutionOptions, clientData.clientNonPersonMainBusinessLineOptions, - clientData.clientNonPersonDetails, clientData.clientLegalFormOptions,clientData.familyMemberOptions, clientData.legalForm,clientData.address, - clientData.isAddressEnabled, null, clientData.isStaff); + clientData.lastname, clientData.fullname, clientData.displayName, clientData.externalId, clientData.mobileNo, + clientData.emailAddress, clientData.dateOfBirth, clientData.gender, clientData.activationDate, clientData.imageId, + clientData.staffId, clientData.staffName, clientData.officeOptions, parentGroups, clientData.staffOptions, null, null, + clientData.timeline, clientData.savingProductOptions, clientData.savingsProductId, clientData.savingsProductName, + clientData.savingsAccountId, clientData.savingAccountOptions, clientData.clientType, clientData.clientClassification, + clientData.clientTypeOptions, clientData.clientClassificationOptions, clientData.clientNonPersonConstitutionOptions, + clientData.clientNonPersonMainBusinessLineOptions, clientData.clientNonPersonDetails, clientData.clientLegalFormOptions, + clientData.familyMemberOptions, clientData.legalForm, clientData.address, clientData.isAddressEnabled, null, + clientData.isStaff); } @@ -343,18 +350,19 @@ final public class ClientData implements Comparable, Serializable { final Collection clientNonPersonConstitutionOptions = null; final Collection clientNonPersonMainBusinessLineOptions = null; final List clientLegalFormOptions = null; - final ClientFamilyMembersData familyMemberOptions=null; + final ClientFamilyMembersData familyMemberOptions = null; final EnumOptionData status = null; final CodeValueData subStatus = null; final EnumOptionData legalForm = null; final Boolean isStaff = false; final ClientNonPersonData clientNonPerson = null; return new ClientData(accountNo, status, subStatus, officeId, officeName, transferToOfficeId, transferToOfficeName, id, firstname, - middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, activationDate, imageId, staffId, - staffName, allowedOffices, groups, staffOptions, closureReasons, genderOptions, timeline, savingProductOptions, - savingsProductId, savingsProductName, savingsAccountId, savingAccountOptions, clientType, clientClassification, - clientTypeOptions, clientClassificationOptions, clientNonPersonConstitutionOptions, clientNonPersonMainBusinessLineOptions, - clientNonPerson, clientLegalFormOptions,familyMemberOptions, legalForm,null,null, null, isStaff); + middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, activationDate, + imageId, staffId, staffName, allowedOffices, groups, staffOptions, closureReasons, genderOptions, timeline, + savingProductOptions, savingsProductId, savingsProductName, savingsAccountId, savingAccountOptions, clientType, + clientClassification, clientTypeOptions, clientClassificationOptions, clientNonPersonConstitutionOptions, + clientNonPersonMainBusinessLineOptions, clientNonPerson, clientLegalFormOptions, familyMemberOptions, legalForm, null, null, + null, isStaff); } public static ClientData lookup(final Long id, final String displayName, final Long officeId, final String officeName) { @@ -394,32 +402,34 @@ final public class ClientData implements Comparable, Serializable { final Collection clientNonPersonConstitutionOptions = null; final Collection clientNonPersonMainBusinessLineOptions = null; final List clientLegalFormOptions = null; - final ClientFamilyMembersData familyMemberOptions=null; + final ClientFamilyMembersData familyMemberOptions = null; final EnumOptionData legalForm = null; final Boolean isStaff = false; final ClientNonPersonData clientNonPerson = null; return new ClientData(accountNo, status, subStatus, officeId, officeName, transferToOfficeId, transferToOfficeName, id, firstname, - middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, activationDate, imageId, staffId, - staffName, allowedOffices, groups, staffOptions, closureReasons, genderOptions, timeline, savingProductOptions, - savingsProductId, savingsProductName, savingsAccountId, savingAccountOptions, clientType, clientClassification, - clientTypeOptions, clientClassificationOptions, clientNonPersonConstitutionOptions, clientNonPersonMainBusinessLineOptions, - clientNonPerson, clientLegalFormOptions,familyMemberOptions, legalForm,null,null, null, isStaff); + middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, activationDate, + imageId, staffId, staffName, allowedOffices, groups, staffOptions, closureReasons, genderOptions, timeline, + savingProductOptions, savingsProductId, savingsProductName, savingsAccountId, savingAccountOptions, clientType, + clientClassification, clientTypeOptions, clientClassificationOptions, clientNonPersonConstitutionOptions, + clientNonPersonMainBusinessLineOptions, clientNonPerson, clientLegalFormOptions, familyMemberOptions, legalForm, null, null, + null, isStaff); } - public static ClientData instance(final Long id, final String displayName){ - final Long officeId = null; - final String officeName = null; - return lookup(id, displayName, officeId, officeName); + public static ClientData instance(final Long id, final String displayName) { + final Long officeId = null; + final String officeName = null; + return lookup(id, displayName, officeId, officeName); } public static ClientData instance(final String accountNo, final EnumOptionData status, final CodeValueData subStatus, final Long officeId, final String officeName, final Long transferToOfficeId, final String transferToOfficeName, final Long id, final String firstname, final String middlename, final String lastname, final String fullname, final String displayName, - final String externalId, final String mobileNo, final String emailAddress, final LocalDate dateOfBirth, final CodeValueData gender, - final LocalDate activationDate, final Long imageId, final Long staffId, final String staffName, + final String externalId, final String mobileNo, final String emailAddress, final LocalDate dateOfBirth, + final CodeValueData gender, final LocalDate activationDate, final Long imageId, final Long staffId, final String staffName, final ClientTimelineData timeline, final Long savingsProductId, final String savingsProductName, final Long savingsAccountId, - final CodeValueData clientType, final CodeValueData clientClassification, final EnumOptionData legalForm, final ClientNonPersonData clientNonPerson, final Boolean isStaff) { + final CodeValueData clientType, final CodeValueData clientClassification, final EnumOptionData legalForm, + final ClientNonPersonData clientNonPerson, final Boolean isStaff) { final Collection allowedOffices = null; final Collection groups = null; @@ -432,21 +442,21 @@ final public class ClientData implements Comparable, Serializable { final Collection clientNonPersonConstitutionOptions = null; final Collection clientNonPersonMainBusinessLineOptions = null; final List clientLegalFormOptions = null; - final ClientFamilyMembersData familyMemberOptions=null; + final ClientFamilyMembersData familyMemberOptions = null; return new ClientData(accountNo, status, subStatus, officeId, officeName, transferToOfficeId, transferToOfficeName, id, firstname, - middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, activationDate, imageId, staffId, - staffName, allowedOffices, groups, staffOptions, closureReasons, genderOptions, timeline, savingProductOptions, - savingsProductId, savingsProductName, savingsAccountId, null, clientType, clientClassification, clientTypeOptions, - clientClassificationOptions, clientNonPersonConstitutionOptions, clientNonPersonMainBusinessLineOptions, clientNonPerson, - clientLegalFormOptions,familyMemberOptions, legalForm,null,null, null, isStaff); + middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, activationDate, + imageId, staffId, staffName, allowedOffices, groups, staffOptions, closureReasons, genderOptions, timeline, + savingProductOptions, savingsProductId, savingsProductName, savingsAccountId, null, clientType, clientClassification, + clientTypeOptions, clientClassificationOptions, clientNonPersonConstitutionOptions, clientNonPersonMainBusinessLineOptions, + clientNonPerson, clientLegalFormOptions, familyMemberOptions, legalForm, null, null, null, isStaff); } private ClientData(final String accountNo, final EnumOptionData status, final CodeValueData subStatus, final Long officeId, final String officeName, final Long transferToOfficeId, final String transferToOfficeName, final Long id, final String firstname, final String middlename, final String lastname, final String fullname, final String displayName, - final String externalId, final String mobileNo, final String emailAddress, final LocalDate dateOfBirth, final CodeValueData gender, - final LocalDate activationDate, final Long imageId, final Long staffId, final String staffName, + final String externalId, final String mobileNo, final String emailAddress, final LocalDate dateOfBirth, + final CodeValueData gender, final LocalDate activationDate, final Long imageId, final Long staffId, final String staffName, final Collection allowedOffices, final Collection groups, final Collection staffOptions, final Collection narrations, final Collection genderOptions, final ClientTimelineData timeline, @@ -455,8 +465,9 @@ final public class ClientData implements Comparable, Serializable { final CodeValueData clientClassification, final Collection clientTypeOptions, final Collection clientClassificationOptions, final Collection clientNonPersonConstitutionOptions, final Collection clientNonPersonMainBusinessLineOptions, final ClientNonPersonData clientNonPerson, - final List clientLegalFormOptions,final ClientFamilyMembersData familyMemberOptions, final EnumOptionData legalForm, final Collection address, - final Boolean isAddressEnabled, final List datatables, final Boolean isStaff) { + final List clientLegalFormOptions, final ClientFamilyMembersData familyMemberOptions, + final EnumOptionData legalForm, final Collection address, final Boolean isAddressEnabled, + final List datatables, final Boolean isStaff) { this.accountNo = accountNo; this.status = status; if (status != null) { @@ -507,7 +518,7 @@ final public class ClientData implements Comparable, Serializable { this.clientNonPersonConstitutionOptions = clientNonPersonConstitutionOptions; this.clientNonPersonMainBusinessLineOptions = clientNonPersonMainBusinessLineOptions; this.clientLegalFormOptions = clientLegalFormOptions; - this.familyMemberOptions=familyMemberOptions; + this.familyMemberOptions = familyMemberOptions; this.timeline = timeline; this.savingProductOptions = savingProductOptions; @@ -519,7 +530,7 @@ final public class ClientData implements Comparable, Serializable { this.isStaff = isStaff; this.clientNonPersonDetails = clientNonPerson; - this.address = address; + this.address = address; this.isAddressEnabled = isAddressEnabled; this.datatables = datatables; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientDataValidator.java index 4ab441311..27a75f696 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientDataValidator.java @@ -61,12 +61,14 @@ public final class ClientDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, ClientApiCollectionConstants.CLIENT_CREATE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + ClientApiCollectionConstants.CLIENT_CREATE_REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.clientNonPersonDetailsParamName, element)) { - final String clientNonPersonJson = this.fromApiJsonHelper.toJson(element.getAsJsonObject().get(ClientApiConstants.clientNonPersonDetailsParamName)); - if(clientNonPersonJson != null) { + final String clientNonPersonJson = this.fromApiJsonHelper + .toJson(element.getAsJsonObject().get(ClientApiConstants.clientNonPersonDetailsParamName)); + if (clientNonPersonJson != null) { this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, clientNonPersonJson, ClientApiCollectionConstants.CLIENT_NON_PERSON_CREATE_REQUEST_DATA_PARAMETERS); } @@ -99,13 +101,17 @@ public final class ClientDataValidator { final Long savingsProductId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.savingsProductIdParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.savingsProductIdParamName).value(savingsProductId).ignoreIfNull() .longGreaterThanZero(); - /*if (savingsProductId != null && this.fromApiJsonHelper.parameterExists(ClientApiConstants.datatables, element)) { - final JsonArray datatables = this.fromApiJsonHelper.extractJsonArrayNamed(ClientApiConstants.datatables, element); - if (datatables.size() > 0) { - baseDataValidator.reset().parameter(ClientApiConstants.savingsProductIdParamName).value(savingsProductId) - .failWithCodeNoParameterAddedToErrorCode("should.not.be.used.with.datatables.parameter"); - } - }*/ + /* + * if (savingsProductId != null && + * this.fromApiJsonHelper.parameterExists(ClientApiConstants. + * datatables, element)) { final JsonArray datatables = + * this.fromApiJsonHelper.extractJsonArrayNamed(ClientApiConstants. + * datatables, element); if (datatables.size() > 0) { + * baseDataValidator.reset().parameter(ClientApiConstants. + * savingsProductIdParamName).value(savingsProductId) + * .failWithCodeNoParameterAddedToErrorCode( + * "should.not.be.used.with.datatables.parameter"); } } + */ } if (isFullnameProvided(element) || isIndividualNameProvided(element)) { @@ -166,10 +172,14 @@ public final class ClientDataValidator { final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.activationDateParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.activationDateParamName).value(joinedDate).notNull(); - /*if(this.fromApiJsonHelper.parameterExists(ClientApiConstants.datatables,element)){ - baseDataValidator.reset().parameter(ClientApiConstants.activeParamName).value(active) - .failWithCodeNoParameterAddedToErrorCode("should.not.be.used.with.datatables.parameter"); - }*/ + /* + * if(this.fromApiJsonHelper.parameterExists(ClientApiConstants. + * datatables,element)){ + * baseDataValidator.reset().parameter(ClientApiConstants. + * activeParamName).value(active) + * .failWithCodeNoParameterAddedToErrorCode( + * "should.not.be.used.with.datatables.parameter"); } + */ } } else { baseDataValidator.reset().parameter(ClientApiConstants.activeParamName).value(active).trueOrFalseRequired(false); @@ -199,18 +209,20 @@ public final class ClientDataValidator { } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.clientClassificationIdParamName, element)) { - final Integer clientClassification = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - ClientApiConstants.clientClassificationIdParamName, element); + final Integer clientClassification = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(ClientApiConstants.clientClassificationIdParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.clientClassificationIdParamName).value(clientClassification) .integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.legalFormIdParamName, element)) { - final Integer legalFormId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.legalFormIdParamName, element); - baseDataValidator.reset().parameter(ClientApiConstants.legalFormIdParamName).value(legalFormId).ignoreIfNull().inMinMaxRange(1, 2); + final Integer legalFormId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.legalFormIdParamName, + element); + baseDataValidator.reset().parameter(ClientApiConstants.legalFormIdParamName).value(legalFormId).ignoreIfNull().inMinMaxRange(1, + 2); } - if(this.fromApiJsonHelper.parameterExists(ClientApiConstants.datatables, element)){ + if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.datatables, element)) { final JsonArray datatables = this.fromApiJsonHelper.extractJsonArrayNamed(ClientApiConstants.datatables, element); baseDataValidator.reset().parameter(ClientApiConstants.datatables).value(datatables).notNull().jsonArrayNotEmpty(); } @@ -220,21 +232,19 @@ public final class ClientDataValidator { baseDataValidator.reset().parameter("isStaff").value(isStaffFlag).notNull(); } - - if(this.configurationReadPlatformService - .retrieveGlobalConfiguration("Enable-Address").isEnabled()){ - final JsonArray address =this.fromApiJsonHelper.extractJsonArrayNamed(ClientApiConstants.address, element); + if (this.configurationReadPlatformService.retrieveGlobalConfiguration("Enable-Address").isEnabled()) { + final JsonArray address = this.fromApiJsonHelper.extractJsonArrayNamed(ClientApiConstants.address, element); baseDataValidator.reset().parameter(ClientApiConstants.address).value(address).notNull().jsonArrayNotEmpty(); } - List dataValidationErrorsForClientNonPerson = getDataValidationErrorsForCreateOnClientNonPerson(element.getAsJsonObject().get(ClientApiConstants.clientNonPersonDetailsParamName)); + List dataValidationErrorsForClientNonPerson = getDataValidationErrorsForCreateOnClientNonPerson( + element.getAsJsonObject().get(ClientApiConstants.clientNonPersonDetailsParamName)); dataValidationErrors.addAll(dataValidationErrorsForClientNonPerson); throwExceptionIfValidationWarningsExist(dataValidationErrors); } - List getDataValidationErrorsForCreateOnClientNonPerson(JsonElement element) - { + List getDataValidationErrorsForCreateOnClientNonPerson(JsonElement element) { final List dataValidationErrors = new ArrayList<>(); @@ -254,26 +264,30 @@ public final class ClientDataValidator { } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.incorpValidityTillParamName, element)) { - final LocalDate incorpValidityTill = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.incorpValidityTillParamName, element); + final LocalDate incorpValidityTill = this.fromApiJsonHelper + .extractLocalDateNamed(ClientApiConstants.incorpValidityTillParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.incorpValidityTillParamName).value(incorpValidityTill).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.constitutionIdParamName, element)) { final Integer constitution = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.constitutionIdParamName, element); - baseDataValidator.reset().parameter(ClientApiConstants.constitutionIdParamName).value(constitution).ignoreIfNull().integerGreaterThanZero(); + baseDataValidator.reset().parameter(ClientApiConstants.constitutionIdParamName).value(constitution).ignoreIfNull() + .integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.mainBusinessLineIdParamName, element)) { - final Integer mainBusinessLine = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.mainBusinessLineIdParamName, - element); - baseDataValidator.reset().parameter(ClientApiConstants.mainBusinessLineIdParamName).value(mainBusinessLine).integerGreaterThanZero(); + final Integer mainBusinessLine = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(ClientApiConstants.mainBusinessLineIdParamName, element); + baseDataValidator.reset().parameter(ClientApiConstants.mainBusinessLineIdParamName).value(mainBusinessLine) + .integerGreaterThanZero(); } return dataValidationErrors; } - private void validateIndividualNamePartsCannotBeUsedWithFullname(final JsonElement element, final DataValidatorBuilder baseDataValidator) { + private void validateIndividualNamePartsCannotBeUsedWithFullname(final JsonElement element, + final DataValidatorBuilder baseDataValidator) { final String firstnameParam = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.firstnameParamName, element); if (StringUtils.isNotBlank(firstnameParam)) { final String fullnameParam = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.fullnameParamName, element); @@ -343,12 +357,14 @@ public final class ClientDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, ClientApiCollectionConstants.CLIENT_UPDATE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + ClientApiCollectionConstants.CLIENT_UPDATE_REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.clientNonPersonDetailsParamName, element)) { - final String clientNonPersonJson = this.fromApiJsonHelper.toJson(element.getAsJsonObject().get(ClientApiConstants.clientNonPersonDetailsParamName)); - if(clientNonPersonJson != null) { + final String clientNonPersonJson = this.fromApiJsonHelper + .toJson(element.getAsJsonObject().get(ClientApiConstants.clientNonPersonDetailsParamName)); + if (clientNonPersonJson != null) { this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, clientNonPersonJson, ClientApiCollectionConstants.CLIENT_NON_PERSON_UPDATE_REQUEST_DATA_PARAMETERS); } @@ -477,8 +493,8 @@ public final class ClientDataValidator { if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.clientClassificationIdParamName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer clientClassification = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - ClientApiConstants.clientClassificationIdParamName, element); + final Integer clientClassification = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(ClientApiConstants.clientClassificationIdParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.clientClassificationIdParamName).value(clientClassification) .integerGreaterThanZero(); } @@ -492,8 +508,10 @@ public final class ClientDataValidator { if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.legalFormIdParamName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer legalFormId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.legalFormIdParamName, element); - baseDataValidator.reset().parameter(ClientApiConstants.legalFormIdParamName).value(legalFormId).ignoreIfNull().inMinMaxRange(1, 2); + final Integer legalFormId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.legalFormIdParamName, + element); + baseDataValidator.reset().parameter(ClientApiConstants.legalFormIdParamName).value(legalFormId).ignoreIfNull().inMinMaxRange(1, + 2); } if (this.fromApiJsonHelper.parameterExists("isStaff", element)) { @@ -501,7 +519,8 @@ public final class ClientDataValidator { baseDataValidator.reset().parameter("isStaff").value(isStaffFlag).notNull(); } - Map parameterUpdateStatusDetails = getParameterUpdateStatusAndDataValidationErrorsForUpdateOnClientNonPerson(element.getAsJsonObject().get(ClientApiConstants.clientNonPersonDetailsParamName)); + Map parameterUpdateStatusDetails = getParameterUpdateStatusAndDataValidationErrorsForUpdateOnClientNonPerson( + element.getAsJsonObject().get(ClientApiConstants.clientNonPersonDetailsParamName)); boolean atLeastOneParameterPassedForClientNonPersonUpdate = (boolean) parameterUpdateStatusDetails.get("parameterUpdateStatus"); if (!atLeastOneParameterPassedForUpdate && !atLeastOneParameterPassedForClientNonPersonUpdate) { @@ -510,14 +529,14 @@ public final class ClientDataValidator { } @SuppressWarnings("unchecked") - List dataValidationErrorsForClientNonPerson = (List) parameterUpdateStatusDetails.get("dataValidationErrors"); + List dataValidationErrorsForClientNonPerson = (List) parameterUpdateStatusDetails + .get("dataValidationErrors"); dataValidationErrors.addAll(dataValidationErrorsForClientNonPerson); throwExceptionIfValidationWarningsExist(dataValidationErrors); } - Map getParameterUpdateStatusAndDataValidationErrorsForUpdateOnClientNonPerson(JsonElement element) - { + Map getParameterUpdateStatusAndDataValidationErrorsForUpdateOnClientNonPerson(JsonElement element) { boolean atLeastOneParameterPassedForUpdate = false; final List dataValidationErrors = new ArrayList<>(); @@ -527,7 +546,8 @@ public final class ClientDataValidator { if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.incorpNumberParamName, element)) { atLeastOneParameterPassedForUpdate = true; final String incorpNo = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.incorpNumberParamName, element); - baseDataValidator.reset().parameter(ClientApiConstants.incorpNumberParamName).value(incorpNo).ignoreIfNull().notExceedingLengthOf(50); + baseDataValidator.reset().parameter(ClientApiConstants.incorpNumberParamName).value(incorpNo).ignoreIfNull() + .notExceedingLengthOf(50); } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.remarksParamName, element)) { @@ -538,20 +558,25 @@ public final class ClientDataValidator { if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.incorpValidityTillParamName, element)) { atLeastOneParameterPassedForUpdate = true; - final LocalDate incorpValidityTill = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.incorpValidityTillParamName, element); + final LocalDate incorpValidityTill = this.fromApiJsonHelper + .extractLocalDateNamed(ClientApiConstants.incorpValidityTillParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.incorpValidityTillParamName).value(incorpValidityTill); } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.constitutionIdParamName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer constitutionId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.constitutionIdParamName, element); - baseDataValidator.reset().parameter(ClientApiConstants.constitutionIdParamName).value(constitutionId).ignoreIfNull().integerGreaterThanZero(); + final Integer constitutionId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.constitutionIdParamName, + element); + baseDataValidator.reset().parameter(ClientApiConstants.constitutionIdParamName).value(constitutionId).ignoreIfNull() + .integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.mainBusinessLineIdParamName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer mainBusinessLineId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(ClientApiConstants.mainBusinessLineIdParamName, element); - baseDataValidator.reset().parameter(ClientApiConstants.mainBusinessLineIdParamName).value(mainBusinessLineId).integerGreaterThanZero(); + final Integer mainBusinessLineId = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(ClientApiConstants.mainBusinessLineIdParamName, element); + baseDataValidator.reset().parameter(ClientApiConstants.mainBusinessLineIdParamName).value(mainBusinessLineId) + .integerGreaterThanZero(); } Map parameterUpdateStatusDetails = new HashMap<>(); @@ -568,7 +593,8 @@ public final class ClientDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, ClientApiCollectionConstants.ACTIVATION_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + ClientApiCollectionConstants.ACTIVATION_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -644,7 +670,8 @@ public final class ClientDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, ClientApiCollectionConstants.CLIENT_CLOSE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + ClientApiCollectionConstants.CLIENT_CLOSE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -745,7 +772,8 @@ public final class ClientDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, ClientApiCollectionConstants.REACTIVATION_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + ClientApiCollectionConstants.REACTIVATION_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -761,7 +789,6 @@ public final class ClientDataValidator { } - public void validateUndoRejection(final JsonCommand command) { final String json = command.json(); @@ -769,7 +796,8 @@ public final class ClientDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, ClientApiCollectionConstants.UNDOREJECTION_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + ClientApiCollectionConstants.UNDOREJECTION_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -777,14 +805,14 @@ public final class ClientDataValidator { final JsonElement element = command.parsedJson(); - final LocalDate undoRejectionDate = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.reopenedDateParamName, - element); + final LocalDate undoRejectionDate = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.reopenedDateParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.reopenedDateParamName).value(undoRejectionDate).notNull() .validateDateBeforeOrEqual(DateUtils.getLocalDateOfTenant()); throwExceptionIfValidationWarningsExist(dataValidationErrors); } + public void validateUndoWithDrawn(final JsonCommand command) { final String json = command.json(); @@ -792,7 +820,8 @@ public final class ClientDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, ClientApiCollectionConstants.UNDOWITHDRAWN_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + ClientApiCollectionConstants.UNDOWITHDRAWN_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -800,8 +829,7 @@ public final class ClientDataValidator { final JsonElement element = command.parsedJson(); - final LocalDate undoWithdrawnDate = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.reopenedDateParamName, - element); + final LocalDate undoWithdrawnDate = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.reopenedDateParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.reopenedDateParamName).value(undoWithdrawnDate).notNull() .validateDateBeforeOrEqual(DateUtils.getLocalDateOfTenant()); @@ -809,4 +837,4 @@ public final class ClientDataValidator { } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientFamilyMembersData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientFamilyMembersData.java index f5eb98af3..6e1f750d9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientFamilyMembersData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientFamilyMembersData.java @@ -69,11 +69,11 @@ public class ClientFamilyMembersData implements Serializable { private final Collection professionIdOptions; private ClientFamilyMembersData(final Long id, final Long clientId, final String firstName, final String middleName, - final String lastName, final String qualification,final String mobileNumber,final Long age,final Boolean isDependent, final String relationship, final Long relationshipId, - final String maritalStatus, final Long maritalStatusId, final String gender, final Long genderId, - final LocalDate dateOfBirth, final String profession, final Long professionId, - final Collection relationshipIdOptions,final Collection genderIdOptions,final Collection maritalStatusIdOptions, - final Collection professionIdOptions) { + final String lastName, final String qualification, final String mobileNumber, final Long age, final Boolean isDependent, + final String relationship, final Long relationshipId, final String maritalStatus, final Long maritalStatusId, + final String gender, final Long genderId, final LocalDate dateOfBirth, final String profession, final Long professionId, + final Collection relationshipIdOptions, final Collection genderIdOptions, + final Collection maritalStatusIdOptions, final Collection professionIdOptions) { this.id = id; this.clientId = clientId; this.firstName = firstName; @@ -89,35 +89,31 @@ public class ClientFamilyMembersData implements Serializable { this.dateOfBirth = dateOfBirth; this.profession = profession; this.professionId = professionId; - this.mobileNumber=mobileNumber; - this.age=age; - this.isDependent=isDependent; - this.relationshipIdOptions=relationshipIdOptions; - this.genderIdOptions=genderIdOptions; - this.maritalStatusIdOptions=maritalStatusIdOptions; - this.professionIdOptions=professionIdOptions; + this.mobileNumber = mobileNumber; + this.age = age; + this.isDependent = isDependent; + this.relationshipIdOptions = relationshipIdOptions; + this.genderIdOptions = genderIdOptions; + this.maritalStatusIdOptions = maritalStatusIdOptions; + this.professionIdOptions = professionIdOptions; } - public static ClientFamilyMembersData instance(final Long id, final Long clientId, final String firstName, - final String middleName, final String lastName, final String qualification,final String mobileNumber,final Long age,final Boolean isDependent, final String relationship, - final Long relationshipId, final String maritalStatus, final Long maritalStatusId, final String gender, - final Long genderId, final LocalDate dateOfBirth, final String profession, final Long professionId - ) { - return new ClientFamilyMembersData(id, clientId, firstName, middleName, lastName, qualification,mobileNumber,age,isDependent, relationship, - relationshipId, maritalStatus, maritalStatusId, gender, genderId, dateOfBirth, profession, - professionId,null,null,null,null); + public static ClientFamilyMembersData instance(final Long id, final Long clientId, final String firstName, final String middleName, + final String lastName, final String qualification, final String mobileNumber, final Long age, final Boolean isDependent, + final String relationship, final Long relationshipId, final String maritalStatus, final Long maritalStatusId, + final String gender, final Long genderId, final LocalDate dateOfBirth, final String profession, final Long professionId) { + return new ClientFamilyMembersData(id, clientId, firstName, middleName, lastName, qualification, mobileNumber, age, isDependent, + relationship, relationshipId, maritalStatus, maritalStatusId, gender, genderId, dateOfBirth, profession, professionId, null, + null, null, null); } - public static ClientFamilyMembersData templateInstance(final Collection relationshipIdOptions, - final Collection genderIdOptions,final Collection maritalStatusIdOptions, + final Collection genderIdOptions, final Collection maritalStatusIdOptions, final Collection professionIdOptions) { - - return new ClientFamilyMembersData(null, null, null, null, null, null,null, - null, null, null, null, null, null, null, - null,null,null,null,relationshipIdOptions,genderIdOptions,maritalStatusIdOptions,professionIdOptions); + return new ClientFamilyMembersData(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, + null, null, relationshipIdOptions, genderIdOptions, maritalStatusIdOptions, professionIdOptions); } public Long getId() { @@ -192,6 +188,4 @@ public class ClientFamilyMembersData implements Serializable { return this.isDependent; } - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientIdentifierData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientIdentifierData.java index 645b37954..7d8ad2fe6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientIdentifierData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientIdentifierData.java @@ -45,7 +45,8 @@ public class ClientIdentifierData { } public static ClientIdentifierData template(final ClientIdentifierData data, final Collection codeValues) { - return new ClientIdentifierData(data.id, data.clientId, data.documentType, data.documentKey, data.description, data.status, codeValues); + return new ClientIdentifierData(data.id, data.clientId, data.documentType, data.documentKey, data.description, data.status, + codeValues); } public ClientIdentifierData(final Long id, final Long clientId, final CodeValueData documentType, final String documentKey, @@ -59,4 +60,4 @@ public class ClientIdentifierData { this.allowedDocumentTypes = allowedDocumentTypes; this.status = status; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientNonPersonData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientNonPersonData.java index fa6c5c025..d5da41b2b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientNonPersonData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientNonPersonData.java @@ -34,27 +34,28 @@ public class ClientNonPersonData implements Serializable { private final CodeValueData mainBusinessLine; private final String remarks; - //import fields + // import fields private Long mainBusinessLineId; private Long constitutionId; private String locale; private String dateFormat; - public static ClientNonPersonData importInstance(String incorporationNo, LocalDate incorpValidityTillDate, - String remarks, Long mainBusinessLineId, Long constitutionId,String locale,String dateFormat){ - return new ClientNonPersonData(incorporationNo,incorpValidityTillDate,remarks, - mainBusinessLineId,constitutionId,locale,dateFormat); + public static ClientNonPersonData importInstance(String incorporationNo, LocalDate incorpValidityTillDate, String remarks, + Long mainBusinessLineId, Long constitutionId, String locale, String dateFormat) { + return new ClientNonPersonData(incorporationNo, incorpValidityTillDate, remarks, mainBusinessLineId, constitutionId, locale, + dateFormat); } - private ClientNonPersonData(String incorpNumber, LocalDate incorpValidityTillDate, - String remarks, Long mainBusinessLineId, Long constitutionId,String locale,String dateFormat) { + + private ClientNonPersonData(String incorpNumber, LocalDate incorpValidityTillDate, String remarks, Long mainBusinessLineId, + Long constitutionId, String locale, String dateFormat) { this.incorpNumber = incorpNumber; this.incorpValidityTillDate = incorpValidityTillDate; this.remarks = remarks; this.mainBusinessLineId = mainBusinessLineId; this.constitutionId = constitutionId; - this.dateFormat= dateFormat; - this.locale= locale; + this.dateFormat = dateFormat; + this.locale = locale; this.constitution = null; this.mainBusinessLine = null; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientTimelineData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientTimelineData.java index f43a3e486..685188550 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientTimelineData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientTimelineData.java @@ -64,4 +64,4 @@ public class ClientTimelineData implements Serializable { } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/AccountNumberGenerator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/AccountNumberGenerator.java index cba278456..33f199ad5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/AccountNumberGenerator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/AccountNumberGenerator.java @@ -45,7 +45,7 @@ public class AccountNumberGenerator { private final static String OFFICE_NAME = "officeName"; private final static String LOAN_PRODUCT_SHORT_NAME = "loanProductShortName"; private final static String SAVINGS_PRODUCT_SHORT_NAME = "savingsProductShortName"; - private final static String SHARE_PRODUCT_SHORT_NAME = "sharesProductShortName" ; + private final static String SHARE_PRODUCT_SHORT_NAME = "sharesProductShortName"; public String generate(Client client, AccountNumberFormat accountNumberFormat) { Map propertyMap = new HashMap<>(); @@ -78,7 +78,7 @@ public class AccountNumberGenerator { Map propertyMap = new HashMap<>(); propertyMap.put(ID, shareaccount.getId().toString()); propertyMap.put(SHARE_PRODUCT_SHORT_NAME, shareaccount.getShareProduct().getShortName()); - return generateAccountNumber(propertyMap, accountNumberFormat) ; + return generateAccountNumber(propertyMap, accountNumberFormat); } private String generateAccountNumber(Map propertyMap, AccountNumberFormat accountNumberFormat) { @@ -109,7 +109,8 @@ public class AccountNumberGenerator { } // FINERACT-590 - // Because account_no is limited to 20 chars, we can only use the first 10 chars of prefix - trim if necessary + // Because account_no is limited to 20 chars, we can only use the + // first 10 chars of prefix - trim if necessary if (prefix != null) { prefix = prefix.substring(0, Math.min(prefix.length(), 10)); } @@ -133,5 +134,4 @@ public class AccountNumberGenerator { return generateAccountNumber(propertyMap, accountNumberFormat); } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/Client.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/Client.java index 20fc64b4d..7b32b74ea 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/Client.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/Client.java @@ -134,7 +134,7 @@ public final class Client extends AbstractPersistableCustom { @JoinColumn(name = "staff_id") private Staff staff; - @ManyToMany(fetch=FetchType.LAZY) + @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "m_group_client", joinColumns = @JoinColumn(name = "client_id"), inverseJoinColumns = @JoinColumn(name = "group_id")) private Set groups; @@ -157,7 +157,7 @@ public final class Client extends AbstractPersistableCustom { @Temporal(TemporalType.DATE) private Date rejectionDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "rejectedon_userid", nullable = true) private AppUser rejectedBy; @@ -169,7 +169,7 @@ public final class Client extends AbstractPersistableCustom { @Temporal(TemporalType.DATE) private Date withdrawalDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "withdraw_on_userid", nullable = true) private AppUser withdrawnBy; @@ -177,11 +177,11 @@ public final class Client extends AbstractPersistableCustom { @Temporal(TemporalType.DATE) private Date reactivateDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "reactivated_on_userid", nullable = true) private AppUser reactivatedBy; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "closedon_userid", nullable = true) private AppUser closedBy; @@ -189,7 +189,7 @@ public final class Client extends AbstractPersistableCustom { @Temporal(TemporalType.DATE) private Date submittedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "submittedon_userid", nullable = true) private AppUser submittedBy; @@ -197,11 +197,11 @@ public final class Client extends AbstractPersistableCustom { @Temporal(TemporalType.DATE) private Date updatedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "updated_by", nullable = true) private AppUser updatedBy; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "activatedon_userid", nullable = true) private AppUser activatedBy; @@ -232,7 +232,7 @@ public final class Client extends AbstractPersistableCustom { @Column(name = "proposed_transfer_date", nullable = true) @Temporal(TemporalType.DATE) - private Date proposedTransferDate; + private Date proposedTransferDate; public static Client createNew(final AppUser currentUser, final Office clientOffice, final Group clientParentGroup, final Staff staff, final Long savingsProductId, final CodeValue gender, final CodeValue clientType, final CodeValue clientClassification, @@ -275,8 +275,8 @@ public final class Client extends AbstractPersistableCustom { } final Long savingsAccountId = null; return new Client(currentUser, status, clientOffice, clientParentGroup, accountNo, firstname, middlename, lastname, fullname, - activationDate, officeJoiningDate, externalId, mobileNo, emailAddress, staff, submittedOnDate, savingsProductId, savingsAccountId, dataOfBirth, - gender, clientType, clientClassification, legalForm, isStaff); + activationDate, officeJoiningDate, externalId, mobileNo, emailAddress, staff, submittedOnDate, savingsProductId, + savingsAccountId, dataOfBirth, gender, clientType, clientClassification, legalForm, isStaff); } protected Client() { @@ -285,9 +285,10 @@ public final class Client extends AbstractPersistableCustom { private Client(final AppUser currentUser, final ClientStatus status, final Office office, final Group clientParentGroup, final String accountNo, final String firstname, final String middlename, final String lastname, final String fullname, - final LocalDate activationDate, final LocalDate officeJoiningDate, final String externalId, final String mobileNo, final String emailAddress, - final Staff staff, final LocalDate submittedOnDate, final Long savingsProductId, final Long savingsAccountId, - final LocalDate dateOfBirth, final CodeValue gender, final CodeValue clientType, final CodeValue clientClassification, final Integer legalForm, final Boolean isStaff) { + final LocalDate activationDate, final LocalDate officeJoiningDate, final String externalId, final String mobileNo, + final String emailAddress, final Staff staff, final LocalDate submittedOnDate, final Long savingsProductId, + final Long savingsAccountId, final LocalDate dateOfBirth, final CodeValue gender, final CodeValue clientType, + final CodeValue clientClassification, final Integer legalForm, final Boolean isStaff) { if (StringUtils.isBlank(accountNo)) { this.accountNumber = new RandomPasswordGenerator(19).generate(); @@ -384,8 +385,10 @@ public final class Client extends AbstractPersistableCustom { private void validateUpdate() { final List dataValidationErrors = new ArrayList<>(); - //Not validating name parts while update request as firstname/lastname can be along with fullname - //when we change clientType from Individual to Organisation or vice-cersa + // Not validating name parts while update request as firstname/lastname + // can be along with fullname + // when we change clientType from Individual to Organisation or + // vice-cersa validateActivationDate(dataValidationErrors); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } @@ -573,29 +576,23 @@ public final class Client extends AbstractPersistableCustom { if (command.isChangeInIntegerParameterNamed(ClientApiConstants.legalFormIdParamName, this.getLegalForm())) { final Integer newValue = command.integerValueOfParameterNamed(ClientApiConstants.legalFormIdParamName); - if(newValue != null) - { + if (newValue != null) { LegalForm legalForm = LegalForm.fromInt(newValue); - if(legalForm != null) - { + if (legalForm != null) { actualChanges.put(ClientApiConstants.legalFormIdParamName, ClientEnumerations.legalForm(newValue)); this.setLegalForm(legalForm.getValue()); - if(legalForm.isPerson()){ + if (legalForm.isPerson()) { this.fullname = null; - }else if(legalForm.isEntity()){ + } else if (legalForm.isEntity()) { this.firstname = null; this.lastname = null; this.displayName = null; } - } - else - { + } else { actualChanges.put(ClientApiConstants.legalFormIdParamName, null); this.setLegalForm(null); } - } - else - { + } else { actualChanges.put(ClientApiConstants.legalFormIdParamName, null); this.setLegalForm(null); } @@ -686,13 +683,11 @@ public final class Client extends AbstractPersistableCustom { dataValidationErrors.add(error); } - if (getReopenedDate() != null && getActivationLocalDate() != null - && getReopenedDate().isAfter(getActivationLocalDate())) { + if (getReopenedDate() != null && getActivationLocalDate() != null && getReopenedDate().isAfter(getActivationLocalDate())) { final String defaultUserMessage = "reopened date cannot be after the submittedon date"; - final ApiParameterError error = ApiParameterError.parameterError( - "error.msg.clients.submittedOnDate.after.reopened.date", defaultUserMessage, - ClientApiConstants.reopenedDateParamName, this.reopenedDate); + final ApiParameterError error = ApiParameterError.parameterError("error.msg.clients.submittedOnDate.after.reopened.date", + defaultUserMessage, ClientApiConstants.reopenedDateParamName, this.reopenedDate); dataValidationErrors.add(error); } @@ -721,8 +716,7 @@ public final class Client extends AbstractPersistableCustom { StringBuilder nameBuilder = new StringBuilder(); Integer legalForm = this.getLegalForm(); - if(legalForm == null || LegalForm.fromInt(legalForm).isPerson()) - { + if (legalForm == null || LegalForm.fromInt(legalForm).isPerson()) { if (StringUtils.isNotBlank(this.firstname)) { nameBuilder.append(this.firstname).append(' '); } @@ -738,9 +732,7 @@ public final class Client extends AbstractPersistableCustom { if (StringUtils.isNotBlank(this.fullname)) { nameBuilder = new StringBuilder(this.fullname); } - } - else if(LegalForm.fromInt(legalForm).isEntity()) - { + } else if (LegalForm.fromInt(legalForm).isEntity()) { if (StringUtils.isNotBlank(this.fullname)) { nameBuilder = new StringBuilder(this.fullname); } @@ -956,9 +948,11 @@ public final class Client extends AbstractPersistableCustom { public LocalDate getClosureDate() { return ObjectUtils.defaultIfNull(new LocalDate(this.closureDate), null); } + public LocalDate getRejectedDate() { return ObjectUtils.defaultIfNull(new LocalDate(this.rejectionDate), null); } + public LocalDate getWithdrawalDate() { return ObjectUtils.defaultIfNull(new LocalDate(this.withdrawalDate), null); } @@ -1052,12 +1046,16 @@ public final class Client extends AbstractPersistableCustom { } public void loadLazyCollections() { - this.groups.size() ; + this.groups.size(); } - public String getFirstname(){return this.firstname;} + public String getFirstname() { + return this.firstname; + } - public String getMiddlename(){return this.middlename;} + public String getMiddlename() { + return this.middlename; + } public String getLastname() { return this.lastname; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddress.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddress.java index f1f1fb2dd..2fdcd342b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddress.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddress.java @@ -44,8 +44,7 @@ public class ClientAddress extends AbstractPersistableCustom { @Column(name = "is_active") private boolean isActive; - private ClientAddress(final Client client, final Address address, final CodeValue addressType, - final boolean isActive) { + private ClientAddress(final Client client, final Address address, final CodeValue addressType, final boolean isActive) { this.client = client; this.address = address; this.addressType = addressType; @@ -57,8 +56,7 @@ public class ClientAddress extends AbstractPersistableCustom { } - public static ClientAddress fromJson(final boolean isActive, final Client client, final Address address, - final CodeValue address_type) { + public static ClientAddress fromJson(final boolean isActive, final Client client, final Address address, final CodeValue address_type) { return new ClientAddress(client, address, address_type, isActive); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddressRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddressRepository.java index b6add4b4c..a17074deb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddressRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddressRepository.java @@ -22,14 +22,13 @@ import org.apache.fineract.infrastructure.codes.domain.CodeValue; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface ClientAddressRepository - extends JpaRepository, JpaSpecificationExecutor { +public interface ClientAddressRepository extends JpaRepository, JpaSpecificationExecutor { + ClientAddress findByClientId(String clientId); // ClientAddress findByAddressId(long addressId); - ClientAddress findByClientIdAndAddressTypeAndIsActive(final long clientId, final CodeValue addressTypeId, - final boolean isActive); + ClientAddress findByClientIdAndAddressTypeAndIsActive(final long clientId, final CodeValue addressTypeId, final boolean isActive); ClientAddress findByClientIdAndAddressId(final long clientId, final long addressId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddressRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddressRepositoryWrapper.java index 8ac51ec89..598dad5be 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddressRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientAddressRepositoryWrapper.java @@ -24,6 +24,7 @@ import org.springframework.stereotype.Service; @Service public class ClientAddressRepositoryWrapper { + private final ClientAddressRepository clientAddressRepository; @Autowired @@ -33,16 +34,15 @@ public class ClientAddressRepositoryWrapper { public ClientAddress findOneByClientIdAndAddressTypeAndIsActive(final long clientId, final CodeValue addressType, final boolean isActive) { - final ClientAddress clientAddress = this.clientAddressRepository - .findByClientIdAndAddressTypeAndIsActive(clientId, addressType, isActive); + final ClientAddress clientAddress = this.clientAddressRepository.findByClientIdAndAddressTypeAndIsActive(clientId, addressType, + isActive); // if (clientAddress == null) { throw new // AddressNotFoundException(clientId, addressType); } return clientAddress; } public ClientAddress findOneByClientIdAndAddressId(final long clientId, final long addressId) { - final ClientAddress clientAddress = this.clientAddressRepository.findByClientIdAndAddressId(clientId, - addressId); + final ClientAddress clientAddress = this.clientAddressRepository.findByClientIdAndAddressId(clientId, addressId); return clientAddress; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientChargeRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientChargeRepositoryWrapper.java index b07ae463f..3d1fd99bd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientChargeRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientChargeRepositoryWrapper.java @@ -37,8 +37,7 @@ public class ClientChargeRepositoryWrapper { } public ClientCharge findOneWithNotFoundDetection(final Long id) { - final ClientCharge clientCharge = this.repository.findById(id) - .orElseThrow(() -> new ChargeNotFoundException(id)); + final ClientCharge clientCharge = this.repository.findById(id).orElseThrow(() -> new ChargeNotFoundException(id)); // enrich Client charge with details of Organizational currency clientCharge.setCurrency(organisationCurrencyRepository.findOneWithNotFoundDetection(clientCharge.getCharge().getCurrencyCode())); return clientCharge; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientEnumerations.java index 06eb9853b..f5ddd9523 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientEnumerations.java @@ -71,8 +71,7 @@ public class ClientEnumerations { } public static EnumOptionData legalForm(final LegalForm legalForm) { - final EnumOptionData optionData = new EnumOptionData(legalForm.getValue().longValue(), legalForm.getCode(), - legalForm.toString()); + final EnumOptionData optionData = new EnumOptionData(legalForm.getValue().longValue(), legalForm.getCode(), legalForm.toString()); return optionData; } @@ -102,4 +101,4 @@ public class ClientEnumerations { return optionDatas; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientFamilyMembers.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientFamilyMembers.java index 2ff4288fb..524016049 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientFamilyMembers.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientFamilyMembers.java @@ -35,31 +35,30 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; public class ClientFamilyMembers extends AbstractPersistableCustom { @ManyToOne - @JoinColumn(name="client_id") + @JoinColumn(name = "client_id") private Client client; - @Column(name="firstname") + @Column(name = "firstname") private String firstName; - @Column(name="middleName") + @Column(name = "middleName") private String middleName; - @Column(name="lastName") + @Column(name = "lastName") private String lastName; - @Column(name="qualification") + @Column(name = "qualification") private String qualification; - @Column(name="mobile_number") + @Column(name = "mobile_number") private String mobileNumber; - @Column(name="age") + @Column(name = "age") private Long age; - @Column(name="is_dependent") + @Column(name = "is_dependent") private Boolean isDependent; - @ManyToOne @JoinColumn(name = "relationship_cv_id") private CodeValue relationship; @@ -68,7 +67,6 @@ public class ClientFamilyMembers extends AbstractPersistableCustom { @JoinColumn(name = "marital_status_cv_id") private CodeValue maritalStatus; - @ManyToOne @JoinColumn(name = "gender_cv_id") private CodeValue gender; @@ -77,162 +75,142 @@ public class ClientFamilyMembers extends AbstractPersistableCustom { @JoinColumn(name = "profession_cv_id") private CodeValue profession; - @Column(name = "date_of_birth", nullable = true) - @Temporal(TemporalType.DATE) - private Date dateOfBirth; + @Column(name = "date_of_birth", nullable = true) + @Temporal(TemporalType.DATE) + private Date dateOfBirth; - private ClientFamilyMembers(final Client client,final String firstName, - final String middleName,final String lastName,final String qualification, - final String mobileNumber,final Long age,final Boolean isDependent, - final CodeValue relationship,final CodeValue maritalStatus,final CodeValue gender, - final Date dateOfBirth,final CodeValue profession) - { + private ClientFamilyMembers(final Client client, final String firstName, final String middleName, final String lastName, + final String qualification, final String mobileNumber, final Long age, final Boolean isDependent, final CodeValue relationship, + final CodeValue maritalStatus, final CodeValue gender, final Date dateOfBirth, final CodeValue profession) { - this.client=client; - this.firstName=firstName; - this.middleName=middleName; - this.lastName=lastName; - this.qualification=qualification; - this.age=age; - this.mobileNumber=mobileNumber; - this.isDependent=isDependent; - this.relationship=relationship; - this.maritalStatus=maritalStatus; - this.gender=gender; - this.dateOfBirth=dateOfBirth; - this.profession=profession; - } + this.client = client; + this.firstName = firstName; + this.middleName = middleName; + this.lastName = lastName; + this.qualification = qualification; + this.age = age; + this.mobileNumber = mobileNumber; + this.isDependent = isDependent; + this.relationship = relationship; + this.maritalStatus = maritalStatus; + this.gender = gender; + this.dateOfBirth = dateOfBirth; + this.profession = profession; + } + public ClientFamilyMembers() { - public ClientFamilyMembers() - { + } - } + public static ClientFamilyMembers fromJson(final Client client, final String firstName, final String middleName, final String lastName, + final String qualification, final String mobileNumber, final Long age, final Boolean isDependent, final CodeValue relationship, + final CodeValue maritalStatus, final CodeValue gender, final Date dateOfBirth, final CodeValue profession) { + return new ClientFamilyMembers(client, firstName, middleName, lastName, qualification, mobileNumber, age, isDependent, relationship, + maritalStatus, gender, dateOfBirth, profession); + } - public static ClientFamilyMembers fromJson(final Client client,final String firstName, - final String middleName,final String lastName,final String qualification, - final String mobileNumber,final Long age,final Boolean isDependent, - final CodeValue relationship,final CodeValue maritalStatus,final CodeValue gender, - final Date dateOfBirth,final CodeValue profession) - { - return new ClientFamilyMembers(client,firstName,middleName,lastName,qualification, - mobileNumber,age,isDependent,relationship,maritalStatus,gender, - dateOfBirth,profession); - } + public Client getClient() { + return this.client; + } - public Client getClient() { - return this.client; - } + public void setClient(Client client) { + this.client = client; + } - public void setClient(Client client) { - this.client = client; - } + public String getFirstName() { + return this.firstName; + } - public String getFirstName() { - return this.firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public String getMiddleName() { + return this.middleName; + } - public String getMiddleName() { - return this.middleName; - } + public void setMiddleName(String middleName) { + this.middleName = middleName; + } - public void setMiddleName(String middleName) { - this.middleName = middleName; - } + public String getLastName() { + return this.lastName; + } - public String getLastName() { - return this.lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public String getQualification() { + return this.qualification; + } - public String getQualification() { - return this.qualification; - } + public void setQualification(String qualification) { + this.qualification = qualification; + } - public void setQualification(String qualification) { - this.qualification = qualification; - } + public CodeValue getRelationship() { + return this.relationship; + } - public CodeValue getRelationship() { - return this.relationship; - } + public void setRelationship(CodeValue relationship) { + this.relationship = relationship; + } - public void setRelationship(CodeValue relationship) { - this.relationship = relationship; - } + public CodeValue getMaritalStatus() { + return this.maritalStatus; + } - public CodeValue getMaritalStatus() { - return this.maritalStatus; - } + public void setMaritalStatus(CodeValue maritalStatus) { + this.maritalStatus = maritalStatus; + } - public void setMaritalStatus(CodeValue maritalStatus) { - this.maritalStatus = maritalStatus; - } + public CodeValue getGender() { + return this.gender; + } - public CodeValue getGender() { - return this.gender; - } + public void setGender(CodeValue gender) { + this.gender = gender; + } - public void setGender(CodeValue gender) { - this.gender = gender; - } + public CodeValue getProfession() { + return this.profession; + } - public CodeValue getProfession() { - return this.profession; - } + public void setProfession(CodeValue profession) { + this.profession = profession; + } - public void setProfession(CodeValue profession) { - this.profession = profession; - } + public Date getDateOfBirth() { + return this.dateOfBirth; + } - public Date getDateOfBirth() { - return this.dateOfBirth; - } + public void setDateOfBirth(Date dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } - public void setDateOfBirth(Date dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - - - public String getMobileNumber() { - return this.mobileNumber; - } - - - public void setMobileNumber(String mobileNumber) { - this.mobileNumber = mobileNumber; - } - - - public Long getAge() { - return this.age; - } - - - public void setAge(Long age) { - this.age = age; - } - - - public Boolean getIsDependent() { - return this.isDependent; - } - - - public void setIsDependent(Boolean isDependent) { - this.isDependent = isDependent; - } + public String getMobileNumber() { + return this.mobileNumber; + } + public void setMobileNumber(String mobileNumber) { + this.mobileNumber = mobileNumber; + } + public Long getAge() { + return this.age; + } + public void setAge(Long age) { + this.age = age; + } + public Boolean getIsDependent() { + return this.isDependent; + } + public void setIsDependent(Boolean isDependent) { + this.isDependent = isDependent; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientFamilyMembersRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientFamilyMembersRepository.java index 5dec60fc2..2e9dade0b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientFamilyMembersRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientFamilyMembersRepository.java @@ -23,7 +23,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ClientFamilyMembersRepository -extends JpaRepository, JpaSpecificationExecutor -{ + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifier.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifier.java index 626dc6b0d..58615477d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifier.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifier.java @@ -34,7 +34,7 @@ import org.apache.fineract.infrastructure.core.domain.AbstractAuditableCustom; @Entity @Table(name = "m_client_identifier", uniqueConstraints = { @UniqueConstraint(columnNames = { "document_type_id", "document_key" }, name = "unique_identifier_key"), - @UniqueConstraint(columnNames = { "client_id", "document_key", "active" }, name = "unique_active_client_identifier")}) + @UniqueConstraint(columnNames = { "client_id", "document_key", "active" }, name = "unique_active_client_identifier") }) public class ClientIdentifier extends AbstractAuditableCustom { @ManyToOne @@ -68,14 +68,15 @@ public class ClientIdentifier extends AbstractAuditableCustom { // } - private ClientIdentifier(final Client client, final CodeValue documentType, final String documentKey, final String statusName, String description) { + private ClientIdentifier(final Client client, final CodeValue documentType, final String documentKey, final String statusName, + String description) { this.client = client; this.documentType = documentType; this.documentKey = StringUtils.defaultIfEmpty(documentKey, null); this.description = StringUtils.defaultIfEmpty(description, null); ClientIdentifierStatus statusEnum = ClientIdentifierStatus.valueOf(statusName.toUpperCase()); this.active = null; - if(statusEnum.isActive()){ + if (statusEnum.isActive()) { this.active = statusEnum.getValue(); } this.status = statusEnum.getValue(); @@ -110,7 +111,7 @@ public class ClientIdentifier extends AbstractAuditableCustom { } final String statusParamName = "status"; - if(command.isChangeInStringParameterNamed(statusParamName, ClientIdentifierStatus.fromInt(this.status).getCode())){ + if (command.isChangeInStringParameterNamed(statusParamName, ClientIdentifierStatus.fromInt(this.status).getCode())) { final String newValue = command.stringValueOfParameterNamed(descriptionParamName); actualChanges.put(descriptionParamName, ClientIdentifierStatus.valueOf(newValue)); this.status = ClientIdentifierStatus.valueOf(newValue).getValue(); @@ -126,4 +127,4 @@ public class ClientIdentifier extends AbstractAuditableCustom { public Long documentTypeId() { return this.documentType.getId(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifierRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifierRepository.java index a7e13e465..576ee40c4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifierRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifierRepository.java @@ -23,4 +23,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ClientIdentifierRepository extends JpaRepository, JpaSpecificationExecutor { // no behaviour -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifierStatus.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifierStatus.java index 021d702ce..58ae75b5b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifierStatus.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientIdentifierStatus.java @@ -25,8 +25,7 @@ public enum ClientIdentifierStatus { INACTIVE(100, "clientIdentifierStatusType.inactive"), // ACTIVE(200, "clientIdentifierStatusType.active"), // - INVALID(0,"clientIdentifierStatusType.invalid"); - + INVALID(0, "clientIdentifierStatusType.invalid"); private final Integer value; private final String code; @@ -50,9 +49,9 @@ public enum ClientIdentifierStatus { this.code = code; } -// public boolean hasStateOf(final ClientIdentifierStatus state) { -// return this.value.equals(state.getValue()); -// } + // public boolean hasStateOf(final ClientIdentifierStatus state) { + // return this.value.equals(state.getValue()); + // } public Integer getValue() { return this.value; @@ -69,4 +68,4 @@ public enum ClientIdentifierStatus { public boolean isActive() { return this.value.equals(ClientIdentifierStatus.ACTIVE.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPerson.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPerson.java index a1cec48c6..bc746c4d2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPerson.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPerson.java @@ -67,9 +67,8 @@ public class ClientNonPerson extends AbstractPersistableCustom { @Column(name = "remarks", length = 150, nullable = true) private String remarks; - - public static ClientNonPerson createNew(final Client client, final CodeValue constitution, final CodeValue mainBusinessLine, String incorpNumber, LocalDate incorpValidityTill, String remarks) - { + public static ClientNonPerson createNew(final Client client, final CodeValue constitution, final CodeValue mainBusinessLine, + String incorpNumber, LocalDate incorpValidityTill, String remarks) { return new ClientNonPerson(client, constitution, mainBusinessLine, incorpNumber, incorpValidityTill, remarks); } @@ -77,17 +76,17 @@ public class ClientNonPerson extends AbstractPersistableCustom { // } - private ClientNonPerson(final Client client, final CodeValue constitution, final CodeValue mainBusinessLine, final String incorpNumber, final LocalDate incorpValidityTill, final String remarks) - { - if(client != null) { + private ClientNonPerson(final Client client, final CodeValue constitution, final CodeValue mainBusinessLine, final String incorpNumber, + final LocalDate incorpValidityTill, final String remarks) { + if (client != null) { this.client = client; } - if(constitution != null) { + if (constitution != null) { this.constitution = constitution; } - if(mainBusinessLine != null) { + if (mainBusinessLine != null) { this.mainBusinessLine = mainBusinessLine; } @@ -119,7 +118,8 @@ public class ClientNonPerson extends AbstractPersistableCustom { } private void validateIncorpValidityTillDate(final Client client, final List dataValidationErrors) { - if (getIncorpValidityTillLocalDate() != null && client.dateOfBirthLocalDate() != null && client.dateOfBirthLocalDate().isAfter(getIncorpValidityTillLocalDate())) { + if (getIncorpValidityTillLocalDate() != null && client.dateOfBirthLocalDate() != null + && client.dateOfBirthLocalDate().isAfter(getIncorpValidityTillLocalDate())) { final String defaultUserMessage = "incorpvaliditytill date cannot be after the incorporation date"; final ApiParameterError error = ApiParameterError.parameterError("error.msg.clients.incorpValidityTill.after.incorp.date", @@ -200,9 +200,9 @@ public class ClientNonPerson extends AbstractPersistableCustom { actualChanges.put(ClientApiConstants.mainBusinessLineIdParamName, newValue); } - //validate(); + // validate(); return actualChanges; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPersonRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPersonRepository.java index c4b6e1cae..72af64f61 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPersonRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPersonRepository.java @@ -23,7 +23,7 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface ClientNonPersonRepository extends JpaRepository, JpaSpecificationExecutor{ +public interface ClientNonPersonRepository extends JpaRepository, JpaSpecificationExecutor { @Query("select clientNonPerson from ClientNonPerson clientNonPerson where clientNonPerson.client.id = :clientId") ClientNonPerson findByClientId(@Param("clientId") Long clientId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPersonRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPersonRepositoryWrapper.java index 158d47355..0ca2e5a87 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPersonRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientNonPersonRepositoryWrapper.java @@ -24,11 +24,10 @@ import org.apache.fineract.portfolio.client.exception.ClientNonPersonNotFoundExc import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; - /** *

- * Wrapper for {@link ClientNonPersonRepository} that adds NULL checking and Error - * handling capabilities + * Wrapper for {@link ClientNonPersonRepository} that adds NULL checking and + * Error handling capabilities *

*/ @Service @@ -44,8 +43,7 @@ public class ClientNonPersonRepositoryWrapper { } public ClientNonPerson findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new ClientNonPersonNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new ClientNonPersonNotFoundException(id)); } public ClientNonPerson findOneByClientId(final Long clientId) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientRepository.java index 247080b21..4e283363c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientRepository.java @@ -29,4 +29,4 @@ abstract interface ClientRepository extends JpaRepository, JpaSpec @Query(FIND_CLIENT_BY_ACCOUNT_NUMBER) Client getClientByAccountNumber(@Param("accountNumber") String accountNumber); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientRepositoryWrapper.java old mode 100755 new mode 100644 index 64b81bff4..8de708d90 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientRepositoryWrapper.java @@ -46,22 +46,22 @@ public class ClientRepositoryWrapper { } public Client findOneWithNotFoundDetection(final Long id) { - return this.findOneWithNotFoundDetection(id, false) ; + return this.findOneWithNotFoundDetection(id, false); } - @Transactional(readOnly=true) + @Transactional(readOnly = true) public Client findOneWithNotFoundDetection(final Long clientId, final boolean loadLazyCollections) { - final Client client = this.repository.findById(clientId) - .orElseThrow(() -> new ClientNotFoundException(clientId)); - if(loadLazyCollections) { + final Client client = this.repository.findById(clientId).orElseThrow(() -> new ClientNotFoundException(clientId)); + if (loadLazyCollections) { client.loadLazyCollections(); } return client; } public List findAll(final Collection clientIds) { - return this.repository.findAllById(clientIds) ; + return this.repository.findAllById(clientIds); } + public void save(final Client client) { this.repository.save(client); } @@ -85,11 +85,9 @@ public class ClientRepositoryWrapper { return client; } - public Client getClientByAccountNumber(String accountNumber){ + public Client getClientByAccountNumber(String accountNumber) { Client client = this.repository.getClientByAccountNumber(accountNumber); - if(client==null){ - throw new ClientNotFoundException(accountNumber); - } + if (client == null) { throw new ClientNotFoundException(accountNumber); } return client; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientStatus.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientStatus.java index 4fa04c6fc..70cb70868 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientStatus.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientStatus.java @@ -28,10 +28,7 @@ public enum ClientStatus { ACTIVE(300, "clientStatusType.active"), // TRANSFER_IN_PROGRESS(303, "clientStatusType.transfer.in.progress"), // TRANSFER_ON_HOLD(304, "clientStatusType.transfer.on.hold"), // - CLOSED(600, "clientStatusType.closed"), - REJECTED(700,"clientStatusType.rejected"), - WITHDRAWN(800,"clientStatusType.withdraw"); - + CLOSED(600, "clientStatusType.closed"), REJECTED(700, "clientStatusType.rejected"), WITHDRAWN(800, "clientStatusType.withdraw"); private final Integer value; private final String code; @@ -94,12 +91,15 @@ public enum ClientStatus { public boolean isClosed() { return this.value.equals(ClientStatus.CLOSED.getValue()); } - public boolean isRejected(){ + + public boolean isRejected() { return this.value.equals(ClientStatus.REJECTED.getValue()); } - public boolean isWithdrawn(){ + + public boolean isWithdrawn() { return this.value.equals(ClientStatus.WITHDRAWN.getValue()); } + public boolean isTransferInProgress() { return this.value.equals(ClientStatus.TRANSFER_IN_PROGRESS.getValue()); } @@ -111,4 +111,4 @@ public enum ClientStatus { public boolean isUnderTransfer() { return isTransferInProgress() || isTransferOnHold(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransaction.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransaction.java index 91d9ffd18..e052ba7c9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransaction.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransaction.java @@ -93,7 +93,7 @@ public class ClientTransaction extends AbstractPersistableCustom { @JoinColumn(name = "appuser_id", nullable = true) private AppUser appUser; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "clientTransaction", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "clientTransaction", orphanRemoval = true, fetch = FetchType.EAGER) private Set clientChargePaidByCollection = new HashSet<>(); @Transient @@ -204,7 +204,7 @@ public class ClientTransaction extends AbstractPersistableCustom { } public Client getClient() { - return this.client ; + return this.client; } public Money getAmount() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetails.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetails.java index f04fc51e2..6f1408c28 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetails.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetails.java @@ -55,12 +55,10 @@ public class ClientTransferDetails extends AbstractPersistableCustom { @Column(name = "submitted_by", nullable = false) private Long submittedBy; - protected ClientTransferDetails() { - } + protected ClientTransferDetails() {} - private ClientTransferDetails(final Long clientId, final Long fromOfficeId, final Long toOfficeId, - final Date proposedTransferDate, final Integer transferEventType, final Date submittedOn, - final Long submittedBy) { + private ClientTransferDetails(final Long clientId, final Long fromOfficeId, final Long toOfficeId, final Date proposedTransferDate, + final Integer transferEventType, final Date submittedOn, final Long submittedBy) { this.clientId = clientId; this.fromOfficeId = fromOfficeId; this.toOfficeId = toOfficeId; @@ -71,11 +69,10 @@ public class ClientTransferDetails extends AbstractPersistableCustom { } public static ClientTransferDetails instance(final Long clientId, final Long fromOfficeId, final Long toOfficeId, - final Date proposedTransferDate, final Integer transferEventType, final Date submittedOn, - final Long submittedBy) { - return new ClientTransferDetails(clientId, fromOfficeId, toOfficeId, proposedTransferDate, transferEventType, - submittedOn, submittedBy); + final Date proposedTransferDate, final Integer transferEventType, final Date submittedOn, final Long submittedBy) { + return new ClientTransferDetails(clientId, fromOfficeId, toOfficeId, proposedTransferDate, transferEventType, submittedOn, + submittedBy); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetailsRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetailsRepository.java index 32675f41f..3cd10164c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetailsRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetailsRepository.java @@ -25,4 +25,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ClientTransferDetailsRepository extends JpaRepository, JpaSpecificationExecutor { -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetailsRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetailsRepositoryWrapper.java index 4ec3ab75d..d454a532b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetailsRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/domain/ClientTransferDetailsRepositoryWrapper.java @@ -36,4 +36,4 @@ public class ClientTransferDetailsRepositoryWrapper { this.repository.save(clientTransferDetails); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientActiveForUpdateException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientActiveForUpdateException.java old mode 100755 new mode 100644 index 23d6e2662..2553695f2 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientActiveForUpdateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientActiveForUpdateException.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class ClientActiveForUpdateException extends AbstractPlatformDomainRuleException { public ClientActiveForUpdateException(final Long clientId, final String parameterName) { - super("error.msg.client.active.for.update.parameter." + parameterName, "The Client with id `" + clientId - + "` is active,can't update parameter " + parameterName, clientId, parameterName); + super("error.msg.client.active.for.update.parameter." + parameterName, + "The Client with id `" + clientId + "` is active,can't update parameter " + parameterName, clientId, parameterName); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientIdentifierNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientIdentifierNotFoundException.java index da961a26f..ddc64f10a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientIdentifierNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientIdentifierNotFoundException.java @@ -29,4 +29,4 @@ public class ClientIdentifierNotFoundException extends AbstractPlatformResourceN public ClientIdentifierNotFoundException(final Long id) { super("error.msg.clientIdentifier.id.invalid", "Client Identifier with the primary key " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientMustBePendingToBeDeletedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientMustBePendingToBeDeletedException.java index 5ae1bbc4d..e453f5289 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientMustBePendingToBeDeletedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientMustBePendingToBeDeletedException.java @@ -26,7 +26,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class ClientMustBePendingToBeDeletedException extends AbstractPlatformDomainRuleException { public ClientMustBePendingToBeDeletedException(final Long id) { - super("error.msg.clients.cannot.be.deleted", - "Client with identifier " + id + " cannot be deleted as it is not in `Pending` state.", id); + super("error.msg.clients.cannot.be.deleted", "Client with identifier " + id + " cannot be deleted as it is not in `Pending` state.", + id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNonPersonNotFoundByClientIdException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNonPersonNotFoundByClientIdException.java index 872989425..cf2be2425 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNonPersonNotFoundByClientIdException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNonPersonNotFoundByClientIdException.java @@ -21,7 +21,8 @@ package org.apache.fineract.portfolio.client.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when clientNonPerson resources are not found. + * A {@link RuntimeException} thrown when clientNonPerson resources are not + * found. */ public class ClientNonPersonNotFoundByClientIdException extends AbstractPlatformResourceNotFoundException { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNonPersonNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNonPersonNotFoundException.java index 99320ad1e..9ae84d7b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNonPersonNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNonPersonNotFoundException.java @@ -21,7 +21,8 @@ package org.apache.fineract.portfolio.client.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when clientNonPerson resources are not found. + * A {@link RuntimeException} thrown when clientNonPerson resources are not + * found. */ public class ClientNonPersonNotFoundException extends AbstractPlatformResourceNotFoundException { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNotFoundException.java index 23a6cad42..197567d9d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientNotFoundException.java @@ -34,6 +34,6 @@ public class ClientNotFoundException extends AbstractPlatformResourceNotFoundExc } public ClientNotFoundException(String accountNumber) { - super("error.msg.client.not.found.with.account.number", "Client not found with account number "+accountNumber+"."); + super("error.msg.client.not.found.with.account.number", "Client not found with account number " + accountNumber + "."); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientTransactionCannotBeUndoneException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientTransactionCannotBeUndoneException.java index 3fe0c3389..6ad72e599 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientTransactionCannotBeUndoneException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ClientTransactionCannotBeUndoneException.java @@ -29,4 +29,4 @@ public class ClientTransactionCannotBeUndoneException extends AbstractPlatformDo super("error.msg.clients.transaction.cannot.be.undone", "Client transaction with identifier " + transactionId + " for client with identifier " + clientId + " has already been reversed", transactionId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/DuplicateClientIdentifierException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/DuplicateClientIdentifierException.java index 531ea2701..9e95acf9f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/DuplicateClientIdentifierException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/DuplicateClientIdentifierException.java @@ -31,14 +31,15 @@ public class DuplicateClientIdentifierException extends AbstractPlatformDomainRu private final String identifierType; public DuplicateClientIdentifierException(final String identifierType) { - super("error.msg.clientIdentifier.type.duplicate", "Active Client identifier of type " + identifierType - + " is already present for this client", identifierType); + super("error.msg.clientIdentifier.type.duplicate", + "Active Client identifier of type " + identifierType + " is already present for this client", identifierType); this.identifierType = identifierType; } public DuplicateClientIdentifierException(final Long documentTypeId, final String identifierType, final String identifierKey) { - super("error.msg.clientIdentifier.identityKey.duplicate", "Client identifier of type " + identifierType + " with value of " - + identifierKey + " already exists.", identifierType, identifierKey); + super("error.msg.clientIdentifier.identityKey.duplicate", + "Client identifier of type " + identifierType + " with value of " + identifierKey + " already exists.", identifierType, + identifierKey); this.documentTypeId = documentTypeId; this.identifierType = identifierType; this.identifierKey = identifierKey; @@ -63,4 +64,4 @@ public class DuplicateClientIdentifierException extends AbstractPlatformDomainRu public String getIdentifierType() { return this.identifierType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ImageNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ImageNotFoundException.java index 691b73fcc..3cfbe7bc1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ImageNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/exception/ImageNotFoundException.java @@ -26,4 +26,4 @@ public class ImageNotFoundException extends AbstractPlatformResourceNotFoundExce super("error.msg.entity.image.invalid", "Image for resource " + resource + " with Identifier " + resourceId + " does not exist", resource, resourceId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/ActivateClientCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/ActivateClientCommandHandler.java index 25322d923..8f71b76b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/ActivateClientCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/ActivateClientCommandHandler.java @@ -44,4 +44,4 @@ public class ActivateClientCommandHandler implements NewCommandSourceHandler { return this.clientWritePlatformService.activateClient(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/AddClientAddressCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/AddClientAddressCommandHandler.java index 731f4c616..b79012ed5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/AddClientAddressCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/AddClientAddressCommandHandler.java @@ -29,6 +29,7 @@ import org.springframework.stereotype.Service; @Service @CommandType(entity = "ADDRESS", action = "CREATE") public class AddClientAddressCommandHandler implements NewCommandSourceHandler { + private final AddressWritePlatformService writePlatformService; @Autowired diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/AddClientFamilyMemberCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/AddClientFamilyMemberCommandHandler.java index 146a78a1e..78a5cdfc0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/AddClientFamilyMemberCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/AddClientFamilyMemberCommandHandler.java @@ -27,18 +27,15 @@ import org.apache.fineract.portfolio.client.service.ClientFamilyMembersWritePlat import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; - @Service @CommandType(entity = "FAMILYMEMBERS", action = "CREATE") -public class AddClientFamilyMemberCommandHandler implements NewCommandSourceHandler -{ +public class AddClientFamilyMemberCommandHandler implements NewCommandSourceHandler { private final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService; @Autowired - public AddClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) - { - this.clientFamilyMembersWritePlatformService=clientFamilyMembersWritePlatformService; + public AddClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) { + this.clientFamilyMembersWritePlatformService = clientFamilyMembersWritePlatformService; } @Override diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/CloseClientCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/CloseClientCommandHandler.java index 02978b94d..cb413c844 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/CloseClientCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/CloseClientCommandHandler.java @@ -44,4 +44,4 @@ public class CloseClientCommandHandler implements NewCommandSourceHandler { return this.clientWritePlatformService.closeClient(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/CreateClientIdentifierCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/CreateClientIdentifierCommandHandler.java index e35428f67..39b457ed1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/CreateClientIdentifierCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/CreateClientIdentifierCommandHandler.java @@ -44,4 +44,4 @@ public class CreateClientIdentifierCommandHandler implements NewCommandSourceHan return this.clientIdentifierWritePlatformService.addClientIdentifier(command.getClientId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientCommandHandler.java index 950274713..baedbe76a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientCommandHandler.java @@ -44,4 +44,4 @@ public class DeleteClientCommandHandler implements NewCommandSourceHandler { return this.clientWritePlatformService.deleteClient(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientFamilyMemberCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientFamilyMemberCommandHandler.java index 08e4b6e84..efef73f3a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientFamilyMemberCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientFamilyMemberCommandHandler.java @@ -31,12 +31,11 @@ import org.springframework.stereotype.Service; @CommandType(entity = "FAMILYMEMBERS", action = "DELETE") public class DeleteClientFamilyMemberCommandHandler implements NewCommandSourceHandler { -private final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService; + private final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService; @Autowired - public DeleteClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) - { - this.clientFamilyMembersWritePlatformService=clientFamilyMembersWritePlatformService; + public DeleteClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) { + this.clientFamilyMembersWritePlatformService = clientFamilyMembersWritePlatformService; } @Override diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientIdentifierCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientIdentifierCommandHandler.java index e202dd2dd..b9b397db8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientIdentifierCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/DeleteClientIdentifierCommandHandler.java @@ -45,4 +45,4 @@ public class DeleteClientIdentifierCommandHandler implements NewCommandSourceHan return this.clientIdentifierWritePlatformService.deleteClientIdentifier(command.getClientId(), command.entityId(), command.commandId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/RejectClientCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/RejectClientCommandHandler.java index 4edc80f9e..cce47a152 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/RejectClientCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/RejectClientCommandHandler.java @@ -17,6 +17,7 @@ * under the License. */ package org.apache.fineract.portfolio.client.handler; + import org.apache.fineract.commands.annotation.CommandType; import org.apache.fineract.commands.handler.NewCommandSourceHandler; import org.apache.fineract.infrastructure.core.api.JsonCommand; @@ -25,11 +26,12 @@ import org.apache.fineract.portfolio.client.service.ClientWritePlatformService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; + @Service @CommandType(entity = "CLIENT", action = "REJECT") public class RejectClientCommandHandler implements NewCommandSourceHandler { - private final ClientWritePlatformService clientWritePlatformService; + private final ClientWritePlatformService clientWritePlatformService; @Autowired public RejectClientCommandHandler(final ClientWritePlatformService clientWritePlatformService) { @@ -44,5 +46,3 @@ public class RejectClientCommandHandler implements NewCommandSourceHandler { } } - - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UndoRejectClientCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UndoRejectClientCommandHandler.java index f95194bec..31a87a270 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UndoRejectClientCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UndoRejectClientCommandHandler.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.portfolio.client.handler; - import org.apache.fineract.commands.annotation.CommandType; import org.apache.fineract.commands.handler.NewCommandSourceHandler; import org.apache.fineract.infrastructure.core.api.JsonCommand; @@ -32,12 +31,12 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "CLIENT", action = "UNDOREJECT") public class UndoRejectClientCommandHandler implements NewCommandSourceHandler { - private final ClientWritePlatformService clientWritePlatformService; + private final ClientWritePlatformService clientWritePlatformService; - @Autowired - public UndoRejectClientCommandHandler(final ClientWritePlatformService clientWritePlatformService) { - this.clientWritePlatformService = clientWritePlatformService; - } + @Autowired + public UndoRejectClientCommandHandler(final ClientWritePlatformService clientWritePlatformService) { + this.clientWritePlatformService = clientWritePlatformService; + } @Transactional @Override diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UndoWithdrawalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UndoWithdrawalCommandHandler.java index c030e17f5..875909b1d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UndoWithdrawalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UndoWithdrawalCommandHandler.java @@ -17,6 +17,7 @@ * under the License. */ package org.apache.fineract.portfolio.client.handler; + import org.apache.fineract.commands.annotation.CommandType; import org.apache.fineract.commands.handler.NewCommandSourceHandler; import org.apache.fineract.infrastructure.core.api.JsonCommand; @@ -30,12 +31,12 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "CLIENT", action = "UNDOWITHDRAWAL") public class UndoWithdrawalCommandHandler implements NewCommandSourceHandler { - private final ClientWritePlatformService clientWritePlatformService; + private final ClientWritePlatformService clientWritePlatformService; - @Autowired - public UndoWithdrawalCommandHandler(final ClientWritePlatformService clientWritePlatformService) { - this.clientWritePlatformService = clientWritePlatformService; - } + @Autowired + public UndoWithdrawalCommandHandler(final ClientWritePlatformService clientWritePlatformService) { + this.clientWritePlatformService = clientWritePlatformService; + } @Transactional @Override @@ -44,5 +45,3 @@ public class UndoWithdrawalCommandHandler implements NewCommandSourceHandler { return this.clientWritePlatformService.undoWithdrawal(command.entityId(), command); } } - - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientCommandHandler.java index 65a7aaa91..2809ea552 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateClientCommandHandler implements NewCommandSourceHandler { return this.clientWritePlatformService.updateClient(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientFamilyMemberCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientFamilyMemberCommandHandler.java index 46c4e7c41..4fbee47f5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientFamilyMemberCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientFamilyMemberCommandHandler.java @@ -27,7 +27,6 @@ import org.apache.fineract.portfolio.client.service.ClientFamilyMembersWritePlat import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; - @Service @CommandType(entity = "FAMILYMEMBERS", action = "UPDATE") public class UpdateClientFamilyMemberCommandHandler implements NewCommandSourceHandler { @@ -35,9 +34,8 @@ public class UpdateClientFamilyMemberCommandHandler implements NewCommandSourceH private final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService; @Autowired - public UpdateClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) - { - this.clientFamilyMembersWritePlatformService=clientFamilyMembersWritePlatformService; + public UpdateClientFamilyMemberCommandHandler(final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService) { + this.clientFamilyMembersWritePlatformService = clientFamilyMembersWritePlatformService; } @Override diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientIdentifierCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientIdentifierCommandHandler.java index 0961def6b..59b349044 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientIdentifierCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientIdentifierCommandHandler.java @@ -43,4 +43,4 @@ public class UpdateClientIdentifierCommandHandler implements NewCommandSourceHan public CommandProcessingResult processCommand(final JsonCommand command) { return this.clientIdentifierWritePlatformService.updateClientIdentifier(command.getClientId(), command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientSavingsAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientSavingsAccountCommandHandler.java old mode 100755 new mode 100644 index 056a67e57..2ea830e67 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientSavingsAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/UpdateClientSavingsAccountCommandHandler.java @@ -34,7 +34,7 @@ public class UpdateClientSavingsAccountCommandHandler implements NewCommandSourc private final ClientWritePlatformService clientWritePlatformService; @Autowired - public UpdateClientSavingsAccountCommandHandler(final ClientWritePlatformService clientWritePlatformService){ + public UpdateClientSavingsAccountCommandHandler(final ClientWritePlatformService clientWritePlatformService) { this.clientWritePlatformService = clientWritePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/WithdrawClientCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/WithdrawClientCommandHandler.java index 196264c18..e3e2f9b7f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/WithdrawClientCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/handler/WithdrawClientCommandHandler.java @@ -27,23 +27,22 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - @Service @CommandType(entity = "CLIENT", action = "WITHDRAW") -public class WithdrawClientCommandHandler implements NewCommandSourceHandler { +public class WithdrawClientCommandHandler implements NewCommandSourceHandler { private final ClientWritePlatformService clientWritePlatformService; -@Autowired -public WithdrawClientCommandHandler(final ClientWritePlatformService clientWritePlatformService) { - this.clientWritePlatformService = clientWritePlatformService; -} + @Autowired + public WithdrawClientCommandHandler(final ClientWritePlatformService clientWritePlatformService) { + this.clientWritePlatformService = clientWritePlatformService; + } -@Transactional -@Override -public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.clientWritePlatformService.withdrawClient(command.entityId(), command); -} + return this.clientWritePlatformService.withdrawClient(command.entityId(), command); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/serialization/ClientFamilyMemberCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/serialization/ClientFamilyMemberCommandFromApiJsonDeserializer.java index 626a5f462..a29648025 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/serialization/ClientFamilyMemberCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/serialization/ClientFamilyMemberCommandFromApiJsonDeserializer.java @@ -41,269 +41,203 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class ClientFamilyMemberCommandFromApiJsonDeserializer -{ +public class ClientFamilyMemberCommandFromApiJsonDeserializer { + private final FromJsonHelper fromApiJsonHelper; - private final Set supportedParameters = new HashSet<>(Arrays.asList("id","clientId","firstName","middleName","lastName","qualification","mobileNumber", - "age","isDependent","relationshipId","maritalStatusId","genderId","dateOfBirth","professionId","locale","dateFormat","familyMembers")); + private final Set supportedParameters = new HashSet<>(Arrays.asList("id", "clientId", "firstName", "middleName", "lastName", + "qualification", "mobileNumber", "age", "isDependent", "relationshipId", "maritalStatusId", "genderId", "dateOfBirth", + "professionId", "locale", "dateFormat", "familyMembers")); @Autowired - private ClientFamilyMemberCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) - { - this.fromApiJsonHelper=fromApiJsonHelper; + private ClientFamilyMemberCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; } + public void validateForCreate(String json) { - public void validateForCreate(String json) - { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - final Type typeOfMap = new TypeToken>() { - }.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource("FamilyMembers"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("FamilyMembers"); final JsonElement element = this.fromApiJsonHelper.parse(json); - - - - if(this.fromApiJsonHelper.extractArrayNamed("familyMembers", element)!=null) - { - final JsonArray familyMembers= this.fromApiJsonHelper.extractJsonArrayNamed("familyMembers", element); - baseDataValidator.reset().value(familyMembers).arrayNotEmpty(); - } - else - { - baseDataValidator.reset().value(this.fromApiJsonHelper.extractJsonArrayNamed("familyMembers", element)).arrayNotEmpty(); - } - - - validateForCreate(1,json); - + if (this.fromApiJsonHelper.extractArrayNamed("familyMembers", element) != null) { + final JsonArray familyMembers = this.fromApiJsonHelper.extractJsonArrayNamed("familyMembers", element); + baseDataValidator.reset().value(familyMembers).arrayNotEmpty(); + } else { + baseDataValidator.reset().value(this.fromApiJsonHelper.extractJsonArrayNamed("familyMembers", element)).arrayNotEmpty(); } + validateForCreate(1, json); + } - public void validateForCreate(final long clientId,String json) - { + public void validateForCreate(final long clientId, String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource("FamilyMembers"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("FamilyMembers"); final JsonElement element = this.fromApiJsonHelper.parse(json); baseDataValidator.reset().value(clientId).notBlank().integerGreaterThanZero(); - if(this.fromApiJsonHelper.extractStringNamed("firstName", element)!=null) - { + if (this.fromApiJsonHelper.extractStringNamed("firstName", element) != null) { final String firstName = this.fromApiJsonHelper.extractStringNamed("firstName", element); baseDataValidator.reset().parameter("firstName").value(firstName).notNull().notBlank().notExceedingLengthOf(100); - } - else - { - baseDataValidator.reset().parameter("firstName").value(this.fromApiJsonHelper.extractStringNamed("firstName", element)).notNull().notBlank().notExceedingLengthOf(100); + } else { + baseDataValidator.reset().parameter("firstName").value(this.fromApiJsonHelper.extractStringNamed("firstName", element)) + .notNull().notBlank().notExceedingLengthOf(100); } - if(this.fromApiJsonHelper.extractStringNamed("lastName", element)!=null) - { + if (this.fromApiJsonHelper.extractStringNamed("lastName", element) != null) { final String lastName = this.fromApiJsonHelper.extractStringNamed("lastName", element); baseDataValidator.reset().parameter("lastName").value(lastName).notNull().notBlank().notExceedingLengthOf(100); } - - if(this.fromApiJsonHelper.extractStringNamed("middleName", element)!=null) - { + if (this.fromApiJsonHelper.extractStringNamed("middleName", element) != null) { final String middleName = this.fromApiJsonHelper.extractStringNamed("middleName", element); baseDataValidator.reset().parameter("middleName").value(middleName).notNull().notBlank().notExceedingLengthOf(100); } - - if(this.fromApiJsonHelper.extractStringNamed("qualification", element)!=null) - { + if (this.fromApiJsonHelper.extractStringNamed("qualification", element) != null) { final String qualification = this.fromApiJsonHelper.extractStringNamed("qualification", element); baseDataValidator.reset().parameter("qualification").value(qualification).notNull().notBlank().notExceedingLengthOf(100); } - if(this.fromApiJsonHelper.extractStringNamed("mobileNumber", element)!=null) - { + if (this.fromApiJsonHelper.extractStringNamed("mobileNumber", element) != null) { final String mobileNumber = this.fromApiJsonHelper.extractStringNamed("mobileNumber", element); baseDataValidator.reset().parameter("mobileNumber").value(mobileNumber).notNull().notBlank().notExceedingLengthOf(100); } - if(this.fromApiJsonHelper.extractBooleanNamed("isDependent", element)!=null) - { + if (this.fromApiJsonHelper.extractBooleanNamed("isDependent", element) != null) { final Boolean isDependent = this.fromApiJsonHelper.extractBooleanNamed("isDependent", element); baseDataValidator.reset().parameter("isDependent").value(isDependent).notNull().notBlank().notExceedingLengthOf(100); } - if(this.fromApiJsonHelper.extractLongNamed("relationShipId", element)!=null) - { - final long relationShipId=this.fromApiJsonHelper.extractLongNamed("relationShipId", element); + if (this.fromApiJsonHelper.extractLongNamed("relationShipId", element) != null) { + final long relationShipId = this.fromApiJsonHelper.extractLongNamed("relationShipId", element); baseDataValidator.reset().parameter("relationShipId").value(relationShipId).notBlank().longGreaterThanZero(); - } - else - { - baseDataValidator.reset().parameter("relationShipId").value(this.fromApiJsonHelper.extractLongNamed("relationShipId", element)).notBlank().longGreaterThanZero(); + } else { + baseDataValidator.reset().parameter("relationShipId").value(this.fromApiJsonHelper.extractLongNamed("relationShipId", element)) + .notBlank().longGreaterThanZero(); } - if(this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element)!=null) - { - final long maritalStatusId=this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element); + if (this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element) != null) { + final long maritalStatusId = this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element); baseDataValidator.reset().parameter("maritalStatusId").value(maritalStatusId).notBlank().longGreaterThanZero(); } - if(this.fromApiJsonHelper.extractLongNamed("genderId", element)!=null) - { - final long genderId=this.fromApiJsonHelper.extractLongNamed("genderId", element); + if (this.fromApiJsonHelper.extractLongNamed("genderId", element) != null) { + final long genderId = this.fromApiJsonHelper.extractLongNamed("genderId", element); baseDataValidator.reset().parameter("genderId").value(genderId).notBlank().longGreaterThanZero(); } - if(this.fromApiJsonHelper.extractLongNamed("age", element)!=null) - { - final long age=this.fromApiJsonHelper.extractLongNamed("age", element); + if (this.fromApiJsonHelper.extractLongNamed("age", element) != null) { + final long age = this.fromApiJsonHelper.extractLongNamed("age", element); baseDataValidator.reset().parameter("age").value(age).notBlank().longGreaterThanZero(); } - if(this.fromApiJsonHelper.extractLongNamed("professionId", element)!=null) - { - final long professionId=this.fromApiJsonHelper.extractLongNamed("professionId", element); + if (this.fromApiJsonHelper.extractLongNamed("professionId", element) != null) { + final long professionId = this.fromApiJsonHelper.extractLongNamed("professionId", element); baseDataValidator.reset().parameter("professionId").value(professionId).notBlank().longGreaterThanZero(); } - - if(this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element)!=null) - { - final LocalDate dateOfBirth=this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element); + if (this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element) != null) { + final LocalDate dateOfBirth = this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element); baseDataValidator.reset().parameter("dateOfBirth").value(dateOfBirth).value(dateOfBirth).notNull() - .validateDateBefore(DateUtils.getLocalDateOfTenant()); + .validateDateBefore(DateUtils.getLocalDateOfTenant()); } - - } + public void validateForUpdate(final long familyMemberId, String json) { - public void validateForUpdate(final long familyMemberId,String json) - { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - final Type typeOfMap = new TypeToken>() { - }.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource("FamilyMembers"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("FamilyMembers"); final JsonElement element = this.fromApiJsonHelper.parse(json); baseDataValidator.reset().value(familyMemberId).notBlank().integerGreaterThanZero(); - if(this.fromApiJsonHelper.extractStringNamed("firstName", element)!=null) - { + if (this.fromApiJsonHelper.extractStringNamed("firstName", element) != null) { final String firstName = this.fromApiJsonHelper.extractStringNamed("firstName", element); baseDataValidator.reset().parameter("firstName").value(firstName).notNull().notBlank().notExceedingLengthOf(100); } - - if(this.fromApiJsonHelper.extractStringNamed("lastName", element)!=null) - { + if (this.fromApiJsonHelper.extractStringNamed("lastName", element) != null) { final String lastName = this.fromApiJsonHelper.extractStringNamed("lastName", element); baseDataValidator.reset().parameter("lastName").value(lastName).notNull().notBlank().notExceedingLengthOf(100); } - - if(this.fromApiJsonHelper.extractStringNamed("middleName", element)!=null) - { + if (this.fromApiJsonHelper.extractStringNamed("middleName", element) != null) { final String middleName = this.fromApiJsonHelper.extractStringNamed("middleName", element); baseDataValidator.reset().parameter("middleName").value(middleName).notNull().notBlank().notExceedingLengthOf(100); } - - if(this.fromApiJsonHelper.extractStringNamed("qualification", element)!=null) - { + if (this.fromApiJsonHelper.extractStringNamed("qualification", element) != null) { final String qualification = this.fromApiJsonHelper.extractStringNamed("qualification", element); baseDataValidator.reset().parameter("qualification").value(qualification).notNull().notBlank().notExceedingLengthOf(100); } - if(this.fromApiJsonHelper.extractLongNamed("relationShipId", element)!=null) - { - final long relationShipId=this.fromApiJsonHelper.extractLongNamed("relationShipId", element); + if (this.fromApiJsonHelper.extractLongNamed("relationShipId", element) != null) { + final long relationShipId = this.fromApiJsonHelper.extractLongNamed("relationShipId", element); baseDataValidator.reset().parameter("relationShipId").value(relationShipId).notBlank().longGreaterThanZero(); } - - if(this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element)!=null) - { - final long maritalStatusId=this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element); + if (this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element) != null) { + final long maritalStatusId = this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element); baseDataValidator.reset().parameter("maritalStatusId").value(maritalStatusId).notBlank().longGreaterThanZero(); } - if(this.fromApiJsonHelper.extractLongNamed("genderId", element)!=null) - { - final long genderId=this.fromApiJsonHelper.extractLongNamed("genderId", element); + if (this.fromApiJsonHelper.extractLongNamed("genderId", element) != null) { + final long genderId = this.fromApiJsonHelper.extractLongNamed("genderId", element); baseDataValidator.reset().parameter("genderId").value(genderId).longGreaterThanZero(); } - if(this.fromApiJsonHelper.extractLongNamed("professionId", element)!=null) - { - final long professionId=this.fromApiJsonHelper.extractLongNamed("professionId", element); + if (this.fromApiJsonHelper.extractLongNamed("professionId", element) != null) { + final long professionId = this.fromApiJsonHelper.extractLongNamed("professionId", element); baseDataValidator.reset().parameter("professionId").value(professionId).longGreaterThanZero(); } - - if(this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element)!=null) - { + if (this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element) != null) { LocalDateTime currentDate = LocalDateTime.now(); - final LocalDate dateOfBirth=this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element); + final LocalDate dateOfBirth = this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element); baseDataValidator.reset().parameter("dateOfBirth").value(dateOfBirth).validateDateBefore(currentDate.toLocalDate()); } - - } - public void validateForDelete(final long familyMemberId) - { - - - + public void validateForDelete(final long familyMemberId) { final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource("FamilyMembers"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("FamilyMembers"); - //final JsonElement element = this.fromApiJsonHelper.parse(json); + // final JsonElement element = this.fromApiJsonHelper.parse(json); baseDataValidator.reset().value(familyMemberId).notBlank().integerGreaterThanZero(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/serialization/ClientIdentifierCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/serialization/ClientIdentifierCommandFromApiJsonDeserializer.java index 3768735a8..ec4d5d975 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/serialization/ClientIdentifierCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/serialization/ClientIdentifierCommandFromApiJsonDeserializer.java @@ -44,7 +44,7 @@ public final class ClientIdentifierCommandFromApiJsonDeserializer extends Abstra /** * The parameters supported for this command. */ - private final Set supportedParameters = new HashSet<>(Arrays.asList("documentTypeId", "documentKey","status", "description")); + private final Set supportedParameters = new HashSet<>(Arrays.asList("documentTypeId", "documentKey", "status", "description")); private final FromJsonHelper fromApiJsonHelper; @@ -68,4 +68,4 @@ public final class ClientIdentifierCommandFromApiJsonDeserializer extends Abstra final String statusString = this.fromApiJsonHelper.extractStringNamed("status", element); return new ClientIdentifierCommand(documentTypeId, documentKey, statusString, documentDescription); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientAddressReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientAddressReadPlatformServiceImpl.java index 4b184029d..ec127f27e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientAddressReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientAddressReadPlatformServiceImpl.java @@ -36,21 +36,20 @@ public class ClientAddressReadPlatformServiceImpl implements ClientAddressReadPl private final PlatformSecurityContext context; @Autowired - public ClientAddressReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { + public ClientAddressReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); } private static final class ClientAddrMapper implements RowMapper { + public String schema() { return "fld.id as fieldConfigurationId,fld.entity as entity,fld.table as entitytable,fld.field as field,fld.is_enabled as is_enabled," + "fld.is_mandatory as is_mandatory,fld.validation_regex as validation_regex from m_field_configuration fld"; } @Override - public ClientAddressData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public ClientAddressData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final long clientAddressId = rs.getLong("clientAddressId"); final long client_id = rs.getLong("client_id"); final long address_id = rs.getLong("address_id"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientChargeWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientChargeWritePlatformServiceJpaRepositoryImpl.java index 5a79aad45..466820b89 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientChargeWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientChargeWritePlatformServiceJpaRepositoryImpl.java @@ -123,9 +123,9 @@ public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements Client .resource(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME); LocalDate activationDate = client.getActivationLocalDate(); LocalDate dueDate = clientCharge.getDueLocalDate(); - if(dueDate.isBefore(activationDate)){ + if (dueDate.isBefore(activationDate)) { baseDataValidator.reset().parameter(ClientApiConstants.dueAsOfDateParamName).value(dueDate.toString(fmt)) - .failWithCodeNoParameterAddedToErrorCode("dueDate.before.activationDate"); + .failWithCodeNoParameterAddedToErrorCode("dueDate.before.activationDate"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } @@ -434,9 +434,10 @@ public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements Client final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("FK_m_client_charge_paid_by_m_client_charge")) { - throw new PlatformDataIntegrityException("error.msg.client.charge.cannot.be.deleted", - "Client charge with id `" + clientChargeId + "` cannot be deleted as transactions have been made on the same", - "clientChargeId", clientChargeId); } + throw new PlatformDataIntegrityException("error.msg.client.charge.cannot.be.deleted", + "Client charge with id `" + clientChargeId + "` cannot be deleted as transactions have been made on the same", + "clientChargeId", clientChargeId); + } LOG.error("Error occured.", dve); throw new PlatformDataIntegrityException("error.msg.client.charges.unknown.data.integrity.issue", diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersReadPlatformService.java index 3f91e272f..7dfedcf07 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersReadPlatformService.java @@ -22,8 +22,7 @@ package org.apache.fineract.portfolio.client.service; import java.util.Collection; import org.apache.fineract.portfolio.client.data.ClientFamilyMembersData; -public interface ClientFamilyMembersReadPlatformService -{ +public interface ClientFamilyMembersReadPlatformService { Collection getClientFamilyMembers(long clientId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersReadPlatformServiceImpl.java index 5ea00b471..0c8b8a354 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersReadPlatformServiceImpl.java @@ -36,47 +36,44 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class ClientFamilyMembersReadPlatformServiceImpl implements ClientFamilyMembersReadPlatformService -{ +public class ClientFamilyMembersReadPlatformServiceImpl implements ClientFamilyMembersReadPlatformService { + private final JdbcTemplate jdbcTemplate; private final PlatformSecurityContext context; private final CodeValueReadPlatformService codeValueReadPlatformService; - @Autowired - public ClientFamilyMembersReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource,final CodeValueReadPlatformService codeValueReadPlatformService) { + public ClientFamilyMembersReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, + final CodeValueReadPlatformService codeValueReadPlatformService) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); - this.codeValueReadPlatformService=codeValueReadPlatformService; + this.codeValueReadPlatformService = codeValueReadPlatformService; } private static final class ClientFamilyMembersMapper implements RowMapper { + public String schema() { return "fmb.id AS id, fmb.client_id AS clientId, fmb.firstname AS firstName, fmb.middlename AS middleName," - +"fmb.lastname AS lastName,fmb.qualification AS qualification,fmb.mobile_number as mobileNumber,fmb.age as age,fmb.is_dependent as isDependent,cv.code_value AS relationship,fmb.relationship_cv_id AS relationshipId," - +"c.code_value AS maritalStatus,fmb.marital_status_cv_id AS maritalStatusId," - +"c1.code_value AS gender, fmb.gender_cv_id AS genderId, fmb.date_of_birth AS dateOfBirth, c2.code_value AS profession, fmb.profession_cv_id AS professionId" - +" FROM m_family_members fmb" - +" LEFT JOIN m_code_value cv ON fmb.relationship_cv_id=cv.id" - +" LEFT JOIN m_code_value c ON fmb.marital_status_cv_id=c.id" - +" LEFT JOIN m_code_value c1 ON fmb.gender_cv_id=c1.id" - +" LEFT JOIN m_code_value c2 ON fmb.profession_cv_id=c2.id"; + + "fmb.lastname AS lastName,fmb.qualification AS qualification,fmb.mobile_number as mobileNumber,fmb.age as age,fmb.is_dependent as isDependent,cv.code_value AS relationship,fmb.relationship_cv_id AS relationshipId," + + "c.code_value AS maritalStatus,fmb.marital_status_cv_id AS maritalStatusId," + + "c1.code_value AS gender, fmb.gender_cv_id AS genderId, fmb.date_of_birth AS dateOfBirth, c2.code_value AS profession, fmb.profession_cv_id AS professionId" + + " FROM m_family_members fmb" + " LEFT JOIN m_code_value cv ON fmb.relationship_cv_id=cv.id" + + " LEFT JOIN m_code_value c ON fmb.marital_status_cv_id=c.id" + " LEFT JOIN m_code_value c1 ON fmb.gender_cv_id=c1.id" + + " LEFT JOIN m_code_value c2 ON fmb.profession_cv_id=c2.id"; } @Override - public ClientFamilyMembersData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public ClientFamilyMembersData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final long id = rs.getLong("id"); final long clientId = rs.getLong("clientId"); - final String firstName=rs.getString("firstName"); - final String middleName=rs.getString("middleName"); - final String lastName=rs.getString("lastName"); - final String qualification=rs.getString("qualification"); - final String mobileNumber=rs.getString("mobileNumber"); - final long age=rs.getLong("age"); - final boolean isDependent=rs.getBoolean("isDependent"); + final String firstName = rs.getString("firstName"); + final String middleName = rs.getString("middleName"); + final String lastName = rs.getString("lastName"); + final String qualification = rs.getString("qualification"); + final String mobileNumber = rs.getString("mobileNumber"); + final long age = rs.getLong("age"); + final boolean isDependent = rs.getBoolean("isDependent"); final String relationship = rs.getString("relationship"); final long relationshipId = rs.getLong("relationshipId"); final String maritalStatus = rs.getString("maritalStatus"); @@ -87,15 +84,13 @@ public class ClientFamilyMembersReadPlatformServiceImpl implements ClientFamilyM final String profession = rs.getString("profession"); final long professionId = rs.getLong("professionId"); - return ClientFamilyMembersData.instance(id, clientId, firstName, middleName, lastName, - qualification,mobileNumber,age,isDependent,relationship,relationshipId,maritalStatus,maritalStatusId,gender,genderId,dateOfBirth,profession,professionId); - - + return ClientFamilyMembersData.instance(id, clientId, firstName, middleName, lastName, qualification, mobileNumber, age, + isDependent, relationship, relationshipId, maritalStatus, maritalStatusId, gender, genderId, dateOfBirth, profession, + professionId); } } - @Override public Collection getClientFamilyMembers(long clientId) { @@ -107,7 +102,6 @@ public class ClientFamilyMembersReadPlatformServiceImpl implements ClientFamilyM return this.jdbcTemplate.query(sql, rm, new Object[] { clientId }); } - @Override public ClientFamilyMembersData getClientFamilyMember(long id) { @@ -133,8 +127,7 @@ public class ClientFamilyMembersReadPlatformServiceImpl implements ClientFamilyM final List professionOptions = new ArrayList<>( this.codeValueReadPlatformService.retrieveCodeValuesByCode("PROFESSION")); - return ClientFamilyMembersData.templateInstance(relationshipOptions,genderOptions, - maritalStatusOptions, professionOptions); + return ClientFamilyMembersData.templateInstance(relationshipOptions, genderOptions, maritalStatusOptions, professionOptions); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersWritePlatformService.java index 2d2bfbcd9..f3ca7af40 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersWritePlatformService.java @@ -23,12 +23,11 @@ import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; import org.apache.fineract.portfolio.client.domain.Client; -public interface ClientFamilyMembersWritePlatformService -{ +public interface ClientFamilyMembersWritePlatformService { - CommandProcessingResult addFamilyMember(final long clientId,final JsonCommand command); + CommandProcessingResult addFamilyMember(final long clientId, final JsonCommand command); - CommandProcessingResult addClientFamilyMember(final Client client,final JsonCommand command); + CommandProcessingResult addClientFamilyMember(final Client client, final JsonCommand command); CommandProcessingResult updateFamilyMember(Long familyMemberId, JsonCommand command); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersWritePlatformServiceImpl.java index 145ac82c3..33743914a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientFamilyMembersWritePlatformServiceImpl.java @@ -43,88 +43,79 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class ClientFamilyMembersWritePlatformServiceImpl implements ClientFamilyMembersWritePlatformService -{ +public class ClientFamilyMembersWritePlatformServiceImpl implements ClientFamilyMembersWritePlatformService { + private final static Logger LOG = LoggerFactory.getLogger(ClientFamilyMembersWritePlatformServiceImpl.class); private final PlatformSecurityContext context; private final CodeValueRepository codeValueRepository; private final ClientFamilyMembersRepository clientFamilyRepository; private final ClientRepositoryWrapper clientRepositoryWrapper; - private final ClientFamilyMemberCommandFromApiJsonDeserializer apiJsonDeserializer; - + private final ClientFamilyMemberCommandFromApiJsonDeserializer apiJsonDeserializer; @Autowired - public ClientFamilyMembersWritePlatformServiceImpl(final PlatformSecurityContext context,final CodeValueRepository codeValueRepository, - final ClientFamilyMembersRepository clientFamilyRepository,final ClientRepositoryWrapper clientRepositoryWrapper,final ClientFamilyMemberCommandFromApiJsonDeserializer apiJsonDeserializer - ) - { - this.context=context; - this.codeValueRepository=codeValueRepository; - this.clientFamilyRepository=clientFamilyRepository; - this.clientRepositoryWrapper=clientRepositoryWrapper; - this.apiJsonDeserializer=apiJsonDeserializer; + public ClientFamilyMembersWritePlatformServiceImpl(final PlatformSecurityContext context, final CodeValueRepository codeValueRepository, + final ClientFamilyMembersRepository clientFamilyRepository, final ClientRepositoryWrapper clientRepositoryWrapper, + final ClientFamilyMemberCommandFromApiJsonDeserializer apiJsonDeserializer) { + this.context = context; + this.codeValueRepository = codeValueRepository; + this.clientFamilyRepository = clientFamilyRepository; + this.clientRepositoryWrapper = clientRepositoryWrapper; + this.apiJsonDeserializer = apiJsonDeserializer; } - - @Override - public CommandProcessingResult addFamilyMember(final long clientId,final JsonCommand command) - { - - Long relationshipId=null; - CodeValue relationship=null; - CodeValue maritalStatus=null; - Long maritalStatusId=null; - Long genderId=null; - CodeValue gender=null; - Long professionId=null; - CodeValue profession=null; - String firstName=""; - String middleName=""; - String lastName=""; - String qualification=""; - String mobileNumber=""; - Long age=null; - Boolean isDependent=false; - Date dateOfBirth=null; + public CommandProcessingResult addFamilyMember(final long clientId, final JsonCommand command) { + Long relationshipId = null; + CodeValue relationship = null; + CodeValue maritalStatus = null; + Long maritalStatusId = null; + Long genderId = null; + CodeValue gender = null; + Long professionId = null; + CodeValue profession = null; + String firstName = ""; + String middleName = ""; + String lastName = ""; + String qualification = ""; + String mobileNumber = ""; + Long age = null; + Boolean isDependent = false; + Date dateOfBirth = null; this.context.authenticatedUser(); apiJsonDeserializer.validateForCreate(clientId, command.json()); - - Client client=clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); + Client client = clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); if (command.stringValueOfParameterNamed("firstName") != null) { firstName = command.stringValueOfParameterNamed("firstName"); - } + } if (command.stringValueOfParameterNamed("middleName") != null) { middleName = command.stringValueOfParameterNamed("middleName"); - } + } if (command.stringValueOfParameterNamed("lastName") != null) { lastName = command.stringValueOfParameterNamed("lastName"); - } - + } if (command.stringValueOfParameterNamed("qualification") != null) { qualification = command.stringValueOfParameterNamed("qualification"); - } + } if (command.stringValueOfParameterNamed("mobileNumber") != null) { mobileNumber = command.stringValueOfParameterNamed("mobileNumber"); - } - + } if (command.longValueOfParameterNamed("age") != null) { age = command.longValueOfParameterNamed("age"); - } + } if (command.booleanObjectValueOfParameterNamed("isDependent") != null) { isDependent = command.booleanObjectValueOfParameterNamed("isDependent"); - } + } if (command.longValueOfParameterNamed("relationshipId") != null) { relationshipId = command.longValueOfParameterNamed("relationshipId"); @@ -146,96 +137,84 @@ public class ClientFamilyMembersWritePlatformServiceImpl implements ClientFamily profession = this.codeValueRepository.getOne(professionId); } - if(command.dateValueOfParameterNamed("dateOfBirth")!=null) - { - dateOfBirth=command.dateValueOfParameterNamed("dateOfBirth"); + if (command.dateValueOfParameterNamed("dateOfBirth") != null) { + dateOfBirth = command.dateValueOfParameterNamed("dateOfBirth"); } - ClientFamilyMembers clientFamilyMembers=ClientFamilyMembers.fromJson(client, firstName, middleName, lastName, qualification,mobileNumber,age,isDependent, relationship, maritalStatus, gender, dateOfBirth, profession); + ClientFamilyMembers clientFamilyMembers = ClientFamilyMembers.fromJson(client, firstName, middleName, lastName, qualification, + mobileNumber, age, isDependent, relationship, maritalStatus, gender, dateOfBirth, profession); this.clientFamilyRepository.save(clientFamilyMembers); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()) - .withEntityId(clientFamilyMembers.getId()).build(); - - + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(clientFamilyMembers.getId()).build(); } @Override - public CommandProcessingResult addClientFamilyMember(final Client client,final JsonCommand command) - { - - Long relationshipId=null; - CodeValue relationship=null; - CodeValue maritalStatus=null; - Long maritalStatusId=null; - Long genderId=null; - CodeValue gender=null; - Long professionId=null; - CodeValue profession=null; - String firstName=""; - String middleName=""; - String lastName=""; - String qualification=""; - Date dateOfBirth=null; - String mobileNumber=""; - Long age=null; - Boolean isDependent=false; - - + public CommandProcessingResult addClientFamilyMember(final Client client, final JsonCommand command) { + Long relationshipId = null; + CodeValue relationship = null; + CodeValue maritalStatus = null; + Long maritalStatusId = null; + Long genderId = null; + CodeValue gender = null; + Long professionId = null; + CodeValue profession = null; + String firstName = ""; + String middleName = ""; + String lastName = ""; + String qualification = ""; + Date dateOfBirth = null; + String mobileNumber = ""; + Long age = null; + Boolean isDependent = false; this.context.authenticatedUser(); + // Client + // client=clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); - //Client client=clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); + ClientFamilyMembers familyMember = new ClientFamilyMembers(); - ClientFamilyMembers familyMember=new ClientFamilyMembers(); + // apiJsonDeserializer.validateForCreate(command.json()); - //apiJsonDeserializer.validateForCreate(command.json()); + JsonArray familyMembers = command.arrayOfParameterNamed("familyMembers"); - - JsonArray familyMembers=command.arrayOfParameterNamed("familyMembers"); - - for(JsonElement members :familyMembers) - { + for (JsonElement members : familyMembers) { apiJsonDeserializer.validateForCreate(members.toString()); - JsonObject member=members.getAsJsonObject(); - + JsonObject member = members.getAsJsonObject(); if (member.get("firstName") != null) { firstName = member.get("firstName").getAsString(); - } + } if (member.get("middleName") != null) { middleName = member.get("middleName").getAsString(); - } + } if (member.get("lastName") != null) { lastName = member.get("lastName").getAsString(); - } - + } if (member.get("qualification") != null) { qualification = member.get("qualification").getAsString(); - } + } if (member.get("mobileNumber") != null) { mobileNumber = member.get("mobileNumber").getAsString(); - } - + } if (member.get("age") != null) { age = member.get("age").getAsLong(); - } + } if (member.get("isDependent") != null) { isDependent = member.get("isDependent").getAsBoolean(); - } + } if (member.get("relationshipId") != null) { relationshipId = member.get("relationshipId").getAsLong(); @@ -257,115 +236,106 @@ public class ClientFamilyMembersWritePlatformServiceImpl implements ClientFamily profession = this.codeValueRepository.getOne(professionId); } - if(member.get("dateOfBirth")!=null) - { + if (member.get("dateOfBirth") != null) { DateFormat format = new SimpleDateFormat(member.get("dateFormat").getAsString()); Date date; try { date = format.parse(member.get("dateOfBirth").getAsString()); - dateOfBirth=date; + dateOfBirth = date; } catch (ParseException e) { // TODO Auto-generated catch block - LOG.error("Problem occurred in addClientFamilyMember function",e); + LOG.error("Problem occurred in addClientFamilyMember function", e); } - - - /* this.fromApiJsonHelper.extractDateFormatParameter(member.get("dateOfBirth").getAsJsonObject());*/ - + /* + * this.fromApiJsonHelper.extractDateFormatParameter(member.get( + * "dateOfBirth").getAsJsonObject()); + */ } - familyMember=ClientFamilyMembers.fromJson(client, firstName, middleName, lastName, qualification,mobileNumber,age,isDependent, relationship, maritalStatus, gender, dateOfBirth, profession); + familyMember = ClientFamilyMembers.fromJson(client, firstName, middleName, lastName, qualification, mobileNumber, age, + isDependent, relationship, maritalStatus, gender, dateOfBirth, profession); this.clientFamilyRepository.save(familyMember); } - - - return new CommandProcessingResultBuilder().withCommandId(command.commandId()) - .withEntityId(familyMember.getId()).build(); - + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(familyMember.getId()).build(); } - - @Override public CommandProcessingResult updateFamilyMember(Long familyMemberId, JsonCommand command) { - - Long relationshipId=null; - CodeValue relationship=null; - CodeValue maritalStatus=null; - Long maritalStatusId=null; - Long genderId=null; - CodeValue gender=null; - Long professionId=null; - CodeValue profession=null; - String firstName=""; - String middleName=""; - String lastName=""; - String qualification=""; - Date dateOfBirth=null; - String mobileNumber=""; - Long age=null; - Boolean isDependent=false; - //long clientFamilyMemberId=0; - + Long relationshipId = null; + CodeValue relationship = null; + CodeValue maritalStatus = null; + Long maritalStatusId = null; + Long genderId = null; + CodeValue gender = null; + Long professionId = null; + CodeValue profession = null; + String firstName = ""; + String middleName = ""; + String lastName = ""; + String qualification = ""; + Date dateOfBirth = null; + String mobileNumber = ""; + Long age = null; + Boolean isDependent = false; + // long clientFamilyMemberId=0; this.context.authenticatedUser(); apiJsonDeserializer.validateForUpdate(familyMemberId, command.json()); - /*if (command.stringValueOfParameterNamed("clientFamilyMemberId") != null) { - clientFamilyMemberId = command.longValueOfParameterNamed("clientFamilyMemberId"); - }*/ + /* + * if (command.stringValueOfParameterNamed("clientFamilyMemberId") != + * null) { clientFamilyMemberId = + * command.longValueOfParameterNamed("clientFamilyMemberId"); } + */ + ClientFamilyMembers clientFamilyMember = clientFamilyRepository.getOne(familyMemberId); - ClientFamilyMembers clientFamilyMember=clientFamilyRepository.getOne(familyMemberId); - - //Client client=clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); + // Client + // client=clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); if (command.stringValueOfParameterNamed("firstName") != null) { firstName = command.stringValueOfParameterNamed("firstName"); clientFamilyMember.setFirstName(firstName); - } + } if (command.stringValueOfParameterNamed("middleName") != null) { middleName = command.stringValueOfParameterNamed("middleName"); clientFamilyMember.setMiddleName(middleName); - } + } if (command.stringValueOfParameterNamed("lastName") != null) { lastName = command.stringValueOfParameterNamed("lastName"); clientFamilyMember.setLastName(lastName); - } - + } if (command.stringValueOfParameterNamed("qualification") != null) { qualification = command.stringValueOfParameterNamed("qualification"); clientFamilyMember.setQualification(qualification); - } - + } if (command.stringValueOfParameterNamed("mobileNumber") != null) { mobileNumber = command.stringValueOfParameterNamed("mobileNumber"); clientFamilyMember.setMobileNumber(mobileNumber); - } - + } if (command.longValueOfParameterNamed("age") != null) { age = command.longValueOfParameterNamed("age"); clientFamilyMember.setAge(age); - } + } if (command.booleanObjectValueOfParameterNamed("isDependent") != null) { isDependent = command.booleanObjectValueOfParameterNamed("isDependent"); clientFamilyMember.setIsDependent(isDependent); - } + } if (command.longValueOfParameterNamed("relationShipId") != null) { relationshipId = command.longValueOfParameterNamed("relationShipId"); @@ -391,24 +361,22 @@ public class ClientFamilyMembersWritePlatformServiceImpl implements ClientFamily clientFamilyMember.setProfession(profession); } - if(command.dateValueOfParameterNamed("dateOfBirth")!=null) - { - dateOfBirth=command.dateValueOfParameterNamed("dateOfBirth"); + if (command.dateValueOfParameterNamed("dateOfBirth") != null) { + dateOfBirth = command.dateValueOfParameterNamed("dateOfBirth"); clientFamilyMember.setDateOfBirth(dateOfBirth); - } - //ClientFamilyMembers clientFamilyMembers=ClientFamilyMembers.fromJson(client, firstName, middleName, lastName, qualification, relationship, maritalStatus, gender, dateOfBirth, profession); + // ClientFamilyMembers + // clientFamilyMembers=ClientFamilyMembers.fromJson(client, firstName, + // middleName, lastName, qualification, relationship, maritalStatus, + // gender, dateOfBirth, profession); this.clientFamilyRepository.save(clientFamilyMember); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()) - .withEntityId(clientFamilyMember.getId()).build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(clientFamilyMember.getId()).build(); } - - @Override public CommandProcessingResult deleteFamilyMember(Long clientFamilyMemberId, JsonCommand command) { // TODO Auto-generated method stub @@ -417,32 +385,21 @@ public class ClientFamilyMembersWritePlatformServiceImpl implements ClientFamily apiJsonDeserializer.validateForDelete(clientFamilyMemberId); - ClientFamilyMembers clientFamilyMember=null; + ClientFamilyMembers clientFamilyMember = null; - - - if(clientFamilyMemberId!=null) - { - clientFamilyMember=clientFamilyRepository.getOne(clientFamilyMemberId); + if (clientFamilyMemberId != null) { + clientFamilyMember = clientFamilyRepository.getOne(clientFamilyMemberId); clientFamilyRepository.delete(clientFamilyMember); } - - if(clientFamilyMember!=null) - { - return new CommandProcessingResultBuilder().withCommandId(command.commandId()) - .withEntityId(clientFamilyMember.getId()).build(); - } - else - { - return new CommandProcessingResultBuilder().withCommandId(command.commandId()) - .withEntityId(Long.valueOf(clientFamilyMemberId)).build(); + if (clientFamilyMember != null) { + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(clientFamilyMember.getId()).build(); + } else { + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(Long.valueOf(clientFamilyMemberId)) + .build(); } } - - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierReadPlatformService.java old mode 100755 new mode 100644 index cf6ea09bb..643100a0f --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierReadPlatformService.java @@ -27,4 +27,4 @@ public interface ClientIdentifierReadPlatformService { ClientIdentifierData retrieveClientIdentifier(Long clientId, Long clientIdentifierId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 6d1c7b7fb..2dd7de92a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierReadPlatformServiceImpl.java @@ -76,8 +76,8 @@ public class ClientIdentifierReadPlatformServiceImpl implements ClientIdentifier sql += " and ci.id = ?"; - final ClientIdentifierData clientIdentifierData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { clientId, - hierarchySearchString, clientIdentifierId }); + final ClientIdentifierData clientIdentifierData = this.jdbcTemplate.queryForObject(sql, rm, + new Object[] { clientId, hierarchySearchString, clientIdentifierId }); return clientIdentifierData; } catch (final EmptyResultDataAccessException e) { @@ -114,4 +114,4 @@ public class ClientIdentifierReadPlatformServiceImpl implements ClientIdentifier } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierWritePlatformService.java old mode 100755 new mode 100644 index f763e73a7..1e5d49667 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierWritePlatformService.java @@ -28,4 +28,4 @@ public interface ClientIdentifierWritePlatformService { CommandProcessingResult updateClientIdentifier(Long clientId, Long clientIdentifierId, JsonCommand command); CommandProcessingResult deleteClientIdentifier(Long clientId, Long clientIdentifierId, Long commandId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index e8f00369b..4ea294a56 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientIdentifierWritePlatformServiceJpaRepositoryImpl.java @@ -82,8 +82,8 @@ public class ClientIdentifierWritePlatformServiceJpaRepositoryImpl implements Cl try { final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId); - final CodeValue documentType = this.codeValueRepository.findOneWithNotFoundDetection(clientIdentifierCommand - .getDocumentTypeId()); + final CodeValue documentType = this.codeValueRepository + .findOneWithNotFoundDetection(clientIdentifierCommand.getDocumentTypeId()); documentTypeId = documentType.getId(); documentTypeLabel = documentType.label(); @@ -100,10 +100,10 @@ public class ClientIdentifierWritePlatformServiceJpaRepositoryImpl implements Cl } catch (final DataIntegrityViolationException dve) { handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -162,10 +162,10 @@ public class ClientIdentifierWritePlatformServiceJpaRepositoryImpl implements Cl } catch (final DataIntegrityViolationException dve) { handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve.getMostSpecificCause(), dve); return new CommandProcessingResult(Long.valueOf(-1)); - }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -191,8 +191,9 @@ public class ClientIdentifierWritePlatformServiceJpaRepositoryImpl implements Cl final String documentKey, final Throwable cause, final Exception dve) { if (cause.getMessage().contains("unique_active_client_identifier")) { throw new DuplicateClientIdentifierException(documentTypeLabel); - } else if (cause.getMessage().contains("unique_identifier_key")) { throw new DuplicateClientIdentifierException( - documentTypeId, documentTypeLabel, documentKey); } + } else if (cause.getMessage().contains("unique_identifier_key")) { + throw new DuplicateClientIdentifierException(documentTypeId, documentTypeLabel, documentKey); + } logAsErrorUnexpectedDataIntegrityException(dve); throw new PlatformDataIntegrityException("error.msg.clientIdentifier.unknown.data.integrity.issue", diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientReadPlatformService.java index 5210f2775..8b5237860 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientReadPlatformService.java @@ -49,4 +49,4 @@ public interface ClientReadPlatformService { Date retrieveClientTransferProposalDate(Long clientId); void validateClient(Long clientId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientReadPlatformServiceImpl.java index e3f2941bc..1bb5332a5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientReadPlatformServiceImpl.java @@ -96,19 +96,19 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final OfficeReadPlatformService officeReadPlatformService, final StaffReadPlatformService staffReadPlatformService, final CodeValueReadPlatformService codeValueReadPlatformService, final SavingsProductReadPlatformService savingsProductReadPlatformService, - final AddressReadPlatformService addressReadPlatformService,final ClientFamilyMembersReadPlatformService clientFamilyMembersReadPlatformService, + final AddressReadPlatformService addressReadPlatformService, + final ClientFamilyMembersReadPlatformService clientFamilyMembersReadPlatformService, final ConfigurationReadPlatformService configurationReadPlatformService, - final EntityDatatableChecksReadService entityDatatableChecksReadService, - final ColumnValidator columnValidator) { + final EntityDatatableChecksReadService entityDatatableChecksReadService, final ColumnValidator columnValidator) { this.context = context; this.officeReadPlatformService = officeReadPlatformService; this.jdbcTemplate = new JdbcTemplate(dataSource); this.staffReadPlatformService = staffReadPlatformService; this.codeValueReadPlatformService = codeValueReadPlatformService; this.savingsProductReadPlatformService = savingsProductReadPlatformService; - this.addressReadPlatformService=addressReadPlatformService; - this.clientFamilyMembersReadPlatformService=clientFamilyMembersReadPlatformService; - this.configurationReadPlatformService=configurationReadPlatformService; + this.addressReadPlatformService = addressReadPlatformService; + this.clientFamilyMembersReadPlatformService = clientFamilyMembersReadPlatformService; + this.configurationReadPlatformService = configurationReadPlatformService; this.entityDatatableChecksReadService = entityDatatableChecksReadService; this.columnValidator = columnValidator; } @@ -118,21 +118,21 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService this.context.authenticatedUser(); final Long defaultOfficeId = defaultToUsersOfficeIfNull(officeId); - AddressData address=null; + AddressData address = null; final Collection offices = this.officeReadPlatformService.retrieveAllOfficesForDropdown(); final Collection savingsProductDatas = this.savingsProductReadPlatformService.retrieveAllForLookupByType(null); - final GlobalConfigurationPropertyData configuration=this.configurationReadPlatformService.retrieveGlobalConfiguration("Enable-Address"); + final GlobalConfigurationPropertyData configuration = this.configurationReadPlatformService + .retrieveGlobalConfiguration("Enable-Address"); - final Boolean isAddressEnabled=configuration.isEnabled(); - if(isAddressEnabled) - { - address = this.addressReadPlatformService.retrieveTemplate(); + final Boolean isAddressEnabled = configuration.isEnabled(); + if (isAddressEnabled) { + address = this.addressReadPlatformService.retrieveTemplate(); } - final ClientFamilyMembersData familyMemberOptions=this.clientFamilyMembersReadPlatformService.retrieveTemplate(); + final ClientFamilyMembersData familyMemberOptions = this.clientFamilyMembersReadPlatformService.retrieveTemplate(); Collection staffOptions = null; @@ -168,12 +168,12 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService return ClientData.template(defaultOfficeId, new LocalDate(), offices, staffOptions, null, genderOptions, savingsProductDatas, clientTypeOptions, clientClassificationOptions, clientNonPersonConstitutionOptions, clientNonPersonMainBusinessLineOptions, - clientLegalFormOptions, familyMemberOptions, new ArrayList(Arrays.asList(address)), - isAddressEnabled, datatableTemplates); + clientLegalFormOptions, familyMemberOptions, new ArrayList(Arrays.asList(address)), isAddressEnabled, + datatableTemplates); } @Override - // @Transactional(readOnly=true) + // @Transactional(readOnly=true) public Page retrieveAll(final SearchParameters searchParameters) { final String userOfficeHierarchy = this.context.officeHierarchy(); @@ -190,9 +190,10 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService sqlBuilder.append(this.clientMapper.schema()); sqlBuilder.append(" where (o.hierarchy like ? or transferToOffice.hierarchy like ?) "); - if(searchParameters!=null) { + if (searchParameters != null) { if (searchParameters.isSelfUser()) { - sqlBuilder.append(" and c.id in (select umap.client_id from m_selfservice_user_client_mapping as umap where umap.appuser_id = ? ) "); + sqlBuilder.append( + " and c.id in (select umap.client_id from m_selfservice_user_client_mapping as umap where umap.appuser_id = ? ) "); paramList.add(appUserID); } @@ -219,7 +220,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService } } final String sqlCountRows = "SELECT FOUND_ROWS()"; - return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), paramList.toArray(), this.clientMapper); + return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), paramList.toArray(), + this.clientMapper); } private String buildSqlStringFromClientCriteria(String schemaSql, final SearchParameters searchParameters, List paramList) { @@ -246,18 +248,19 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService if (externalId != null) { paramList.add(externalId); - extraCriteria += " and c.external_id like ? " ; + extraCriteria += " and c.external_id like ? "; } if (displayName != null) { - //extraCriteria += " and concat(ifnull(c.firstname, ''), if(c.firstname > '',' ', '') , ifnull(c.lastname, '')) like " + // extraCriteria += " and concat(ifnull(c.firstname, ''), + // if(c.firstname > '',' ', '') , ifnull(c.lastname, '')) like " paramList.add("%" + displayName + "%"); extraCriteria += " and c.display_name like ? "; } if (firstname != null) { paramList.add(firstname); - extraCriteria += " and c.firstname like ? " ; + extraCriteria += " and c.firstname like ? "; } if (lastname != null) { @@ -270,7 +273,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService extraCriteria += " and o.hierarchy like ? "; } - if(searchParameters.isOrphansOnly()){ + if (searchParameters.isOrphansOnly()) { extraCriteria += " and c.id NOT IN (select client_id from m_group_client) "; } @@ -288,8 +291,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final String sql = "select " + this.clientMapper.schema() + " where ( o.hierarchy like ? or transferToOffice.hierarchy like ?) and c.id = ?"; - final ClientData clientData = this.jdbcTemplate.queryForObject(sql, this.clientMapper, new Object[] { hierarchySearchString, - hierarchySearchString, clientId }); + final ClientData clientData = this.jdbcTemplate.queryForObject(sql, this.clientMapper, + new Object[] { hierarchySearchString, hierarchySearchString, clientId }); final String clientGroupsSql = "select " + this.clientGroupsMapper.parentGroupsSchema(); @@ -356,10 +359,10 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService public ClientMembersOfGroupMapper() { final StringBuilder sqlBuilder = new StringBuilder(200); - sqlBuilder - .append("c.id as id, c.account_no as accountNo, c.external_id as externalId, c.status_enum as statusEnum,c.sub_status as subStatus, "); - sqlBuilder - .append("cvSubStatus.code_value as subStatusValue,cvSubStatus.code_description as subStatusDesc,c.office_id as officeId, o.name as officeName, "); + sqlBuilder.append( + "c.id as id, c.account_no as accountNo, c.external_id as externalId, c.status_enum as statusEnum,c.sub_status as subStatus, "); + sqlBuilder.append( + "cvSubStatus.code_value as subStatusValue,cvSubStatus.code_description as subStatusDesc,c.office_id as officeId, o.name as officeName, "); sqlBuilder.append("c.transfer_to_office_id as transferToOfficeId, transferToOffice.name as transferToOfficeName, "); sqlBuilder.append("c.firstname as firstname, c.middlename as middlename, c.lastname as lastname, "); sqlBuilder.append("c.fullname as fullname, c.display_name as displayName, "); @@ -495,7 +498,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final Integer legalFormEnum = JdbcSupport.getInteger(rs, "legalFormEnum"); EnumOptionData legalForm = null; - if(legalFormEnum != null) { + if (legalFormEnum != null) { legalForm = ClientEnumerations.legalForm(legalFormEnum); } @@ -509,16 +512,17 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final CodeValueData mainBusinessLine = CodeValueData.instance(mainBusinessLineId, mainBusinessLineValue); final String remarks = rs.getString("remarks"); - final ClientNonPersonData clientNonPerson = new ClientNonPersonData(constitution, incorpNo, incorpValidityTill, mainBusinessLine, remarks); + final ClientNonPersonData clientNonPerson = new ClientNonPersonData(constitution, incorpNo, incorpValidityTill, + mainBusinessLine, remarks); final ClientTimelineData timeline = new ClientTimelineData(submittedOnDate, submittedByUsername, submittedByFirstname, submittedByLastname, activationDate, activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, closedByLastname); return ClientData.instance(accountNo, status, subStatus, officeId, officeName, transferToOfficeId, transferToOfficeName, id, - firstname, middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, activationDate, - imageId, staffId, staffName, timeline, savingsProductId, savingsProductName, savingsAccountId, clienttype, - classification, legalForm, clientNonPerson, isStaff); + firstname, middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, + activationDate, imageId, staffId, staffName, timeline, savingsProductId, savingsProductName, savingsAccountId, + clienttype, classification, legalForm, clientNonPerson, isStaff); } } @@ -530,8 +534,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; - final String sql = "select " - + this.membersOfGroupMapper.schema() + final String sql = "select " + this.membersOfGroupMapper.schema() + " left join m_group g on pgc.group_id=g.id where o.hierarchy like ? and g.parent_id = ? and c.status_enum = ? group by c.id"; return this.jdbcTemplate.query(sql, this.membersOfGroupMapper, @@ -545,8 +548,10 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService public ClientMapper() { final StringBuilder builder = new StringBuilder(400); - builder.append("c.id as id, c.account_no as accountNo, c.external_id as externalId, c.status_enum as statusEnum,c.sub_status as subStatus, "); - builder.append("cvSubStatus.code_value as subStatusValue,cvSubStatus.code_description as subStatusDesc,c.office_id as officeId, o.name as officeName, "); + builder.append( + "c.id as id, c.account_no as accountNo, c.external_id as externalId, c.status_enum as statusEnum,c.sub_status as subStatus, "); + builder.append( + "cvSubStatus.code_value as subStatusValue,cvSubStatus.code_description as subStatusDesc,c.office_id as officeId, o.name as officeName, "); builder.append("c.transfer_to_office_id as transferToOfficeId, transferToOffice.name as transferToOfficeName, "); builder.append("c.firstname as firstname, c.middlename as middlename, c.lastname as lastname, "); builder.append("c.fullname as fullname, c.display_name as displayName, "); @@ -680,7 +685,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final Integer legalFormEnum = JdbcSupport.getInteger(rs, "legalFormEnum"); EnumOptionData legalForm = null; - if(legalFormEnum != null) { + if (legalFormEnum != null) { legalForm = ClientEnumerations.legalForm(legalFormEnum); } @@ -694,16 +699,17 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final CodeValueData mainBusinessLine = CodeValueData.instance(mainBusinessLineId, mainBusinessLineValue); final String remarks = rs.getString("remarks"); - final ClientNonPersonData clientNonPerson = new ClientNonPersonData(constitution, incorpNo, incorpValidityTill, mainBusinessLine, remarks); + final ClientNonPersonData clientNonPerson = new ClientNonPersonData(constitution, incorpNo, incorpValidityTill, + mainBusinessLine, remarks); final ClientTimelineData timeline = new ClientTimelineData(submittedOnDate, submittedByUsername, submittedByFirstname, submittedByLastname, activationDate, activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, closedByLastname); return ClientData.instance(accountNo, status, subStatus, officeId, officeName, transferToOfficeId, transferToOfficeName, id, - firstname, middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, activationDate, - imageId, staffId, staffName, timeline, savingsProductId, savingsProductName, savingsAccountId, clienttype, - classification, legalForm, clientNonPerson, isStaff); + firstname, middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, + activationDate, imageId, staffId, staffName, timeline, savingsProductId, savingsProductName, savingsAccountId, + clienttype, classification, legalForm, clientNonPerson, isStaff); } } @@ -808,14 +814,15 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService @Override public ClientData retrieveAllNarrations(final String clientNarrations) { - final List narrations = new ArrayList<>(this.codeValueReadPlatformService.retrieveCodeValuesByCode(clientNarrations)); + final List narrations = new ArrayList<>( + this.codeValueReadPlatformService.retrieveCodeValuesByCode(clientNarrations)); final Collection clientTypeOptions = null; final Collection clientClassificationOptions = null; final Collection clientNonPersonConstitutionOptions = null; final Collection clientNonPersonMainBusinessLineOptions = null; final List clientLegalFormOptions = null; return ClientData.template(null, null, null, null, narrations, null, null, clientTypeOptions, clientClassificationOptions, - clientNonPersonConstitutionOptions, clientNonPersonMainBusinessLineOptions, clientLegalFormOptions,null,null,null, null); + clientNonPersonConstitutionOptions, clientNonPersonMainBusinessLineOptions, clientLegalFormOptions, null, null, null, null); } @Override @@ -839,4 +846,4 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientWritePlatformService.java index f98748f80..c839d8acb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientWritePlatformService.java @@ -49,5 +49,4 @@ public interface ClientWritePlatformService { CommandProcessingResult undoWithdrawal(Long entityId, JsonCommand command); - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java index 4c9821901..837603f10 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java @@ -121,6 +121,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP private final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService; private final BusinessEventNotifierService businessEventNotifierService; private final EntityDatatableChecksWritePlatformService entityDatatableChecksWritePlatformService; + @Autowired public ClientWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final ClientRepositoryWrapper clientRepository, final ClientNonPersonRepositoryWrapper clientNonPersonRepository, @@ -133,7 +134,9 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP final CommandProcessingService commandProcessingService, final ConfigurationDomainService configurationDomainService, final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository, final FromJsonHelper fromApiJsonHelper, final ConfigurationReadPlatformService configurationReadPlatformService, - final AddressWritePlatformService addressWritePlatformService, final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService, final BusinessEventNotifierService businessEventNotifierService, + final AddressWritePlatformService addressWritePlatformService, + final ClientFamilyMembersWritePlatformService clientFamilyMembersWritePlatformService, + final BusinessEventNotifierService businessEventNotifierService, final EntityDatatableChecksWritePlatformService entityDatatableChecksWritePlatformService) { this.context = context; this.clientRepository = clientRepository; @@ -155,7 +158,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP this.fromApiJsonHelper = fromApiJsonHelper; this.configurationReadPlatformService = configurationReadPlatformService; this.addressWritePlatformService = addressWritePlatformService; - this.clientFamilyMembersWritePlatformService=clientFamilyMembersWritePlatformService; + this.clientFamilyMembersWritePlatformService = clientFamilyMembersWritePlatformService; this.businessEventNotifierService = businessEventNotifierService; this.entityDatatableChecksWritePlatformService = entityDatatableChecksWritePlatformService; } @@ -183,7 +186,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP .withEntityId(clientId) // .build(); } catch (DataIntegrityViolationException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); LOG.error("Error occured.", throwable); throw new PlatformDataIntegrityException("error.msg.client.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); @@ -199,16 +202,16 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP if (realCause.getMessage().contains("external_id")) { final String externalId = command.stringValueOfParameterNamed("externalId"); - throw new PlatformDataIntegrityException("error.msg.client.duplicate.externalId", "Client with externalId `" + externalId - + "` already exists", "externalId", externalId); + throw new PlatformDataIntegrityException("error.msg.client.duplicate.externalId", + "Client with externalId `" + externalId + "` already exists", "externalId", externalId); } else if (realCause.getMessage().contains("account_no_UNIQUE")) { final String accountNo = command.stringValueOfParameterNamed("accountNo"); - throw new PlatformDataIntegrityException("error.msg.client.duplicate.accountNo", "Client with accountNo `" + accountNo - + "` already exists", "accountNo", accountNo); + throw new PlatformDataIntegrityException("error.msg.client.duplicate.accountNo", + "Client with accountNo `" + accountNo + "` already exists", "accountNo", accountNo); } else if (realCause.getMessage().contains("mobile_no")) { final String mobileNo = command.stringValueOfParameterNamed("mobileNo"); - throw new PlatformDataIntegrityException("error.msg.client.duplicate.mobileNo", "Client with mobileNo `" + mobileNo - + "` already exists", "mobileNo", mobileNo); + throw new PlatformDataIntegrityException("error.msg.client.duplicate.mobileNo", + "Client with mobileNo `" + mobileNo + "` already exists", "mobileNo", mobileNo); } logAsErrorUnexpectedDataIntegrityException(dve); @@ -240,8 +243,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP Group clientParentGroup = null; if (groupId != null) { - clientParentGroup = this.groupRepository.findById(groupId) - .orElseThrow(() -> new GroupNotFoundException(groupId)); + clientParentGroup = this.groupRepository.findById(groupId).orElseThrow(() -> new GroupNotFoundException(groupId)); } Staff staff = null; @@ -266,11 +268,10 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP CodeValue clientClassification = null; final Long clientClassificationId = command.longValueOfParameterNamed(ClientApiConstants.clientClassificationIdParamName); if (clientClassificationId != null) { - clientClassification = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( - ClientApiConstants.CLIENT_CLASSIFICATION, clientClassificationId); + clientClassification = this.codeValueRepository + .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_CLASSIFICATION, clientClassificationId); } - final Long savingsProductId = command.longValueOfParameterNamed(ClientApiConstants.savingsProductIdParamName); if (savingsProductId != null) { this.savingsProductRepository.findById(savingsProductId) @@ -280,11 +281,9 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP final Integer legalFormParamValue = command.integerValueOfParameterNamed(ClientApiConstants.legalFormIdParamName); boolean isEntity = false; Integer legalFormValue = null; - if(legalFormParamValue != null) - { + if (legalFormParamValue != null) { LegalForm legalForm = LegalForm.fromInt(legalFormParamValue); - if(legalForm != null) - { + if (legalForm != null) { legalFormValue = legalForm.getValue(); isEntity = legalForm.isEntity(); } @@ -320,7 +319,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP } - if(isEntity) { + if (isEntity) { extractAndCreateClientNonPerson(newClient, command); } @@ -328,13 +327,11 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP this.addressWritePlatformService.addNewClientAddress(newClient, command); } - - if(command.arrayOfParameterNamed("familyMembers")!=null) - { + if (command.arrayOfParameterNamed("familyMembers") != null) { this.clientFamilyMembersWritePlatformService.addClientFamilyMember(newClient, command); } - if(command.parameterExists(ClientApiConstants.datatables)){ + if (command.parameterExists(ClientApiConstants.datatables)) { this.entityDatatableChecksWritePlatformService.saveDatatables(StatusEnum.CREATE.getCode().longValue(), EntityTables.CLIENT.getName(), newClient.getId(), null, command.arrayOfParameterNamed(ClientApiConstants.datatables)); @@ -358,51 +355,59 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } /** - * This method extracts ClientNonPerson details from Client command and creates a new ClientNonPerson record + * This method extracts ClientNonPerson details from Client command and + * creates a new ClientNonPerson record + * * @param client * @param command */ - public void extractAndCreateClientNonPerson(Client client, JsonCommand command) - { - final JsonElement clientNonPersonElement = this.fromApiJsonHelper.parse(command.jsonFragment(ClientApiConstants.clientNonPersonDetailsParamName)); + public void extractAndCreateClientNonPerson(Client client, JsonCommand command) { + final JsonElement clientNonPersonElement = this.fromApiJsonHelper + .parse(command.jsonFragment(ClientApiConstants.clientNonPersonDetailsParamName)); - if(clientNonPersonElement != null && !isEmpty(clientNonPersonElement)) - { - final String incorpNumber = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.incorpNumberParamName, clientNonPersonElement); + if (clientNonPersonElement != null && !isEmpty(clientNonPersonElement)) { + final String incorpNumber = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.incorpNumberParamName, + clientNonPersonElement); final String remarks = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.remarksParamName, clientNonPersonElement); - final LocalDate incorpValidityTill = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.incorpValidityTillParamName, clientNonPersonElement); + final LocalDate incorpValidityTill = this.fromApiJsonHelper + .extractLocalDateNamed(ClientApiConstants.incorpValidityTillParamName, clientNonPersonElement); - //JsonCommand clientNonPersonCommand = JsonCommand.fromExistingCommand(command, command.arrayOfParameterNamed(ClientApiConstants.clientNonPersonDetailsParamName).getAsJsonObject()); + // JsonCommand clientNonPersonCommand = + // JsonCommand.fromExistingCommand(command, + // command.arrayOfParameterNamed(ClientApiConstants.clientNonPersonDetailsParamName).getAsJsonObject()); CodeValue clientNonPersonConstitution = null; - final Long clientNonPersonConstitutionId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.constitutionIdParamName, clientNonPersonElement); + final Long clientNonPersonConstitutionId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.constitutionIdParamName, + clientNonPersonElement); if (clientNonPersonConstitutionId != null) { - clientNonPersonConstitution = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_NON_PERSON_CONSTITUTION, - clientNonPersonConstitutionId); + clientNonPersonConstitution = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( + ClientApiConstants.CLIENT_NON_PERSON_CONSTITUTION, clientNonPersonConstitutionId); } CodeValue clientNonPersonMainBusinessLine = null; - final Long clientNonPersonMainBusinessLineId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.mainBusinessLineIdParamName, clientNonPersonElement); + final Long clientNonPersonMainBusinessLineId = this.fromApiJsonHelper + .extractLongNamed(ClientApiConstants.mainBusinessLineIdParamName, clientNonPersonElement); if (clientNonPersonMainBusinessLineId != null) { - clientNonPersonMainBusinessLine = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_NON_PERSON_MAIN_BUSINESS_LINE, - clientNonPersonMainBusinessLineId); + clientNonPersonMainBusinessLine = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( + ClientApiConstants.CLIENT_NON_PERSON_MAIN_BUSINESS_LINE, clientNonPersonMainBusinessLineId); } - final ClientNonPerson newClientNonPerson = ClientNonPerson.createNew(client, clientNonPersonConstitution, clientNonPersonMainBusinessLine, incorpNumber, incorpValidityTill, remarks); + final ClientNonPerson newClientNonPerson = ClientNonPerson.createNew(client, clientNonPersonConstitution, + clientNonPersonMainBusinessLine, incorpNumber, incorpValidityTill, remarks); this.clientNonPersonRepository.save(newClientNonPerson); } } - public boolean isEmpty(final JsonElement element){ - return element.toString().trim().length()<4; + public boolean isEmpty(final JsonElement element) { + return element.toString().trim().length() < 4; } @Transactional @@ -424,8 +429,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.staffIdParamName); Staff newStaff = null; if (newValue != null) { - newStaff = this.staffRepository.findByOfficeHierarchyWithNotFoundDetection(newValue, clientForUpdate.getOffice() - .getHierarchy()); + newStaff = this.staffRepository.findByOfficeHierarchyWithNotFoundDetection(newValue, + clientForUpdate.getOffice().getHierarchy()); } clientForUpdate.updateStaff(newStaff); } @@ -441,8 +446,9 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP } if (changes.containsKey(ClientApiConstants.savingsProductIdParamName)) { - if (clientForUpdate.isActive()) { throw new ClientActiveForUpdateException(clientId, - ClientApiConstants.savingsProductIdParamName); } + if (clientForUpdate.isActive()) { + throw new ClientActiveForUpdateException(clientId, ClientApiConstants.savingsProductIdParamName); + } final Long savingsProductId = command.longValueOfParameterNamed(ClientApiConstants.savingsProductIdParamName); if (savingsProductId != null) { this.savingsProductRepository.findById(savingsProductId) @@ -474,8 +480,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.clientClassificationIdParamName); CodeValue newCodeVal = null; if (newValue != null) { - newCodeVal = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( - ClientApiConstants.CLIENT_CLASSIFICATION, newValue); + newCodeVal = this.codeValueRepository + .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_CLASSIFICATION, newValue); } clientForUpdate.updateClientClassification(newCodeVal); } @@ -487,49 +493,49 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP if (changes.containsKey(ClientApiConstants.legalFormIdParamName)) { Integer legalFormValue = clientForUpdate.getLegalForm(); boolean isChangedToEntity = false; - if(legalFormValue != null) - { + if (legalFormValue != null) { LegalForm legalForm = LegalForm.fromInt(legalFormValue); - if(legalForm != null) { + if (legalForm != null) { isChangedToEntity = legalForm.isEntity(); } } - if(isChangedToEntity) - { + if (isChangedToEntity) { extractAndCreateClientNonPerson(clientForUpdate, command); - } - else - { + } else { final ClientNonPerson clientNonPerson = this.clientNonPersonRepository.findOneByClientId(clientForUpdate.getId()); - if(clientNonPerson != null) { + if (clientNonPerson != null) { this.clientNonPersonRepository.delete(clientNonPerson); } } } final ClientNonPerson clientNonPersonForUpdate = this.clientNonPersonRepository.findOneByClientId(clientId); - if(clientNonPersonForUpdate != null) - { + if (clientNonPersonForUpdate != null) { final JsonElement clientNonPersonElement = command.jsonElement(ClientApiConstants.clientNonPersonDetailsParamName); - final Map clientNonPersonChanges = clientNonPersonForUpdate.update(JsonCommand.fromExistingCommand(command, clientNonPersonElement)); + final Map clientNonPersonChanges = clientNonPersonForUpdate + .update(JsonCommand.fromExistingCommand(command, clientNonPersonElement)); if (clientNonPersonChanges.containsKey(ClientApiConstants.constitutionIdParamName)) { - final Long newValue = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.constitutionIdParamName, clientNonPersonElement); + final Long newValue = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.constitutionIdParamName, + clientNonPersonElement); CodeValue constitution = null; if (newValue != null) { - constitution = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_NON_PERSON_CONSTITUTION, newValue); + constitution = this.codeValueRepository + .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_NON_PERSON_CONSTITUTION, newValue); } clientNonPersonForUpdate.updateConstitution(constitution); } if (clientNonPersonChanges.containsKey(ClientApiConstants.mainBusinessLineIdParamName)) { - final Long newValue = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.mainBusinessLineIdParamName, clientNonPersonElement); + final Long newValue = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.mainBusinessLineIdParamName, + clientNonPersonElement); CodeValue mainBusinessLine = null; if (newValue != null) { - mainBusinessLine = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_NON_PERSON_MAIN_BUSINESS_LINE, newValue); + mainBusinessLine = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( + ClientApiConstants.CLIENT_NON_PERSON_MAIN_BUSINESS_LINE, newValue); } clientNonPersonForUpdate.updateMainBusinessLine(mainBusinessLine); } @@ -562,10 +568,10 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -701,8 +707,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP final LocalDate closureDate = command.localDateValueOfParameterNamed(ClientApiConstants.closureDateParamName); final Long closureReasonId = command.longValueOfParameterNamed(ClientApiConstants.closureReasonIdParamName); - final CodeValue closureReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( - ClientApiConstants.CLIENT_CLOSURE_REASON, closureReasonId); + final CodeValue closureReason = this.codeValueRepository + .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_CLOSURE_REASON, closureReasonId); if (ClientStatus.fromInt(client.getStatus()).isClosed()) { final String errorMessage = "Client is already closed."; @@ -717,8 +723,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP throw new InvalidClientStateTransitionException("close", "date.cannot.before.client.actvation.date", errorMessage, closureDate, client.getActivationLocalDate()); } - entityDatatableChecksWritePlatformService.runTheCheck(clientId,EntityTables.CLIENT.getName(), - StatusEnum.CLOSE.getCode().longValue(),EntityTables.CLIENT.getForeignKeyColumnNameOnDatatable()); + entityDatatableChecksWritePlatformService.runTheCheck(clientId, EntityTables.CLIENT.getName(), + StatusEnum.CLOSE.getCode().longValue(), EntityTables.CLIENT.getForeignKeyColumnNameOnDatatable()); final List clientLoans = this.loanRepositoryWrapper.findLoanByClientId(clientId); for (final Loan loan : clientLoans) { @@ -807,15 +813,16 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP * reduce maxNumberOfClients by 1 **/ final boolean validationsuccess = group.isGroupsClientCountWithinMaxRange(maxNumberOfClients - 1); - if (!validationsuccess) { throw new GroupMemberCountNotInPermissibleRangeException(group.getId(), minNumberOfClients, - maxNumberOfClients); } + if (!validationsuccess) { + throw new GroupMemberCountNotInPermissibleRangeException(group.getId(), minNumberOfClients, maxNumberOfClients); + } } } } private void runEntityDatatableCheck(final Long clientId) { - entityDatatableChecksWritePlatformService.runTheCheck(clientId, EntityTables.CLIENT.getName(), StatusEnum.ACTIVATE.getCode() - .longValue(), EntityTables.CLIENT.getForeignKeyColumnNameOnDatatable()); + entityDatatableChecksWritePlatformService.runTheCheck(clientId, EntityTables.CLIENT.getName(), + StatusEnum.ACTIVATE.getCode().longValue(), EntityTables.CLIENT.getForeignKeyColumnNameOnDatatable()); } @Override @@ -827,8 +834,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP final LocalDate rejectionDate = command.localDateValueOfParameterNamed(ClientApiConstants.rejectionDateParamName); final Long rejectionReasonId = command.longValueOfParameterNamed(ClientApiConstants.rejectionReasonIdParamName); - final CodeValue rejectionReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( - ClientApiConstants.CLIENT_REJECT_REASON, rejectionReasonId); + final CodeValue rejectionReason = this.codeValueRepository + .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_REJECT_REASON, rejectionReasonId); if (client.isNotPending()) { final String errorMessage = "Only clients pending activation may be withdrawn."; @@ -859,8 +866,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP final LocalDate withdrawalDate = command.localDateValueOfParameterNamed(ClientApiConstants.withdrawalDateParamName); final Long withdrawalReasonId = command.longValueOfParameterNamed(ClientApiConstants.withdrawalReasonIdParamName); - final CodeValue withdrawalReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( - ClientApiConstants.CLIENT_WITHDRAW_REASON, withdrawalReasonId); + final CodeValue withdrawalReason = this.codeValueRepository + .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_WITHDRAW_REASON, withdrawalReasonId); if (client.isNotPending()) { final String errorMessage = "Only clients pending activation may be withdrawn."; @@ -911,16 +918,15 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP this.fromApiJsonDeserializer.validateUndoRejection(command); final Client client = this.clientRepository.findOneWithNotFoundDetection(entityId); - final LocalDate undoRejectDate = command - .localDateValueOfParameterNamed(ClientApiConstants.reopenedDateParamName); + final LocalDate undoRejectDate = command.localDateValueOfParameterNamed(ClientApiConstants.reopenedDateParamName); if (!client.isRejected()) { final String errorMessage = "only rejected clients may be reactivated."; throw new InvalidClientStateTransitionException("undorejection", "on.nonrejected.account", errorMessage); } else if (client.getRejectedDate().isAfter(undoRejectDate)) { final String errorMessage = "The client reactivation date cannot be before the client rejected date."; - throw new InvalidClientStateTransitionException("reopened", "date.cannot.before.client.rejected.date", - errorMessage, undoRejectDate, client.getRejectedDate()); + throw new InvalidClientStateTransitionException("reopened", "date.cannot.before.client.rejected.date", errorMessage, + undoRejectDate, client.getRejectedDate()); } client.reOpened(currentUser, undoRejectDate.toDate()); @@ -939,16 +945,15 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP this.fromApiJsonDeserializer.validateUndoWithDrawn(command); final Client client = this.clientRepository.findOneWithNotFoundDetection(entityId); - final LocalDate undoWithdrawalDate = command - .localDateValueOfParameterNamed(ClientApiConstants.reopenedDateParamName); + final LocalDate undoWithdrawalDate = command.localDateValueOfParameterNamed(ClientApiConstants.reopenedDateParamName); if (!client.isWithdrawn()) { final String errorMessage = "only withdrawal clients may be reactivated."; throw new InvalidClientStateTransitionException("undoWithdrawal", "on.nonwithdrawal.account", errorMessage); } else if (client.getWithdrawalDate().isAfter(undoWithdrawalDate)) { final String errorMessage = "The client reactivation date cannot be before the client withdrawal date."; - throw new InvalidClientStateTransitionException("reopened", "date.cannot.before.client.withdrawal.date", - errorMessage, undoWithdrawalDate, client.getWithdrawalDate()); + throw new InvalidClientStateTransitionException("reopened", "date.cannot.before.client.withdrawal.date", errorMessage, + undoWithdrawalDate, client.getWithdrawalDate()); } client.reOpened(currentUser, undoWithdrawalDate.toDate()); this.clientRepository.saveAndFlush(client); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/LoanStatusMapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/LoanStatusMapper.java index 00e5cc15d..1b9f8e66b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/LoanStatusMapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/client/service/LoanStatusMapper.java @@ -53,4 +53,4 @@ public class LoanStatusMapper { public boolean isOverpaid() { return Integer.valueOf(700).equals(this.statusId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralApiConstants.java old mode 100755 new mode 100644 index 98d57792e..524bf5964 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralApiConstants.java @@ -29,7 +29,9 @@ public class CollateralApiConstants { * Enum of all parameters passed in while creating/updating a collateral ***/ public static enum CollateralJSONinputParams { - LOAN_ID("loanId"), COLLATERAL_ID("collateralId"), COLLATERAL_TYPE_ID("collateralTypeId"), VALUE("value"), DESCRIPTION("description"); + + LOAN_ID("loanId"), COLLATERAL_ID("collateralId"), COLLATERAL_TYPE_ID("collateralTypeId"), VALUE("value"), DESCRIPTION( + "description"); private final String value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralsApiResource.java old mode 100755 new mode 100644 index 2b7065367..b7cd47787 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralsApiResource.java @@ -62,14 +62,13 @@ import org.springframework.stereotype.Component; @Path("/loans/{loanId}/collaterals") @Component @Scope("singleton") -@Api(tags = {"Loan Collateral"}) +@Api(tags = { "Loan Collateral" }) @SwaggerDefinition(tags = { - @Tag(name = "Loan Collateral", description = "In lending agreements, collateral is a borrower's pledge of specific property to a lender, to secure repayment of a loan. The collateral serves as protection for a lender against a borrower's default - that is, any borrower failing to pay the principal and interest under the terms of a loan obligation. If a borrower does default on a loan (due to insolvency or other event), that borrower forfeits (gives up) the property pledged as collateral - and the lender then becomes the owner of the collateral") -}) + @Tag(name = "Loan Collateral", description = "In lending agreements, collateral is a borrower's pledge of specific property to a lender, to secure repayment of a loan. The collateral serves as protection for a lender against a borrower's default - that is, any borrower failing to pay the principal and interest under the terms of a loan obligation. If a borrower does default on a loan (due to insolvency or other event), that borrower forfeits (gives up) the property pledged as collateral - and the lender then becomes the owner of the collateral") }) public class CollateralsApiResource { - private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "type", "value", "description", - "allowedCollateralTypes", "currency")); + private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "type", "value", "description", "allowedCollateralTypes", "currency")); private final String resourceNameForPermission = "COLLATERAL"; @@ -82,8 +81,7 @@ public class CollateralsApiResource { @Autowired public CollateralsApiResource(final PlatformSecurityContext context, final CollateralReadPlatformService collateralReadPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, + final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final CodeValueReadPlatformService codeValueReadPlatformService) { this.context = context; @@ -98,8 +96,10 @@ public class CollateralsApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Collateral Details Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "loans/1/collaterals/template") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.GetLoansLoanIdCollateralsTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Collateral Details Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "loans/1/collaterals/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.GetLoansLoanIdCollateralsTemplateResponse.class) }) public String newCollateralTemplate(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); @@ -115,9 +115,12 @@ public class CollateralsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Loan Collaterals", httpMethod = "GET", notes = "Example Requests:\n" + "\n" + "loans/1/collaterals\n" + "\n" + "\n" + "loans/1/collaterals?fields=value,description") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.GetLoansLoanIdCollateralsResponse.class, responseContainer = "List")}) - public String retrieveCollateralDetails(@Context final UriInfo uriInfo, @PathParam("loanId") @ApiParam(value = "loanId") final Long loanId) { + @ApiOperation(value = "List Loan Collaterals", httpMethod = "GET", notes = "Example Requests:\n" + "\n" + "loans/1/collaterals\n" + "\n" + + "\n" + "loans/1/collaterals?fields=value,description") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.GetLoansLoanIdCollateralsResponse.class, responseContainer = "List") }) + public String retrieveCollateralDetails(@Context final UriInfo uriInfo, + @PathParam("loanId") @ApiParam(value = "loanId") final Long loanId) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); final List CollateralDatas = this.collateralReadPlatformService.retrieveCollateralsForValidLoan(loanId); @@ -131,9 +134,12 @@ public class CollateralsApiResource { @Path("{collateralId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Collateral", httpMethod = "GET", notes = "Example Requests:\n" + "\n" + "/loans/1/collaterals/1\n" + "\n" + "\n" + "/loans/1/collaterals/1?fields=value,description") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.GetLoansLoanIdCollateralsResponse.class)}) - public String retrieveCollateralDetails(@Context final UriInfo uriInfo, @PathParam("loanId") @ApiParam(value = "loanId")final Long loanId, + @ApiOperation(value = "Retrieve a Collateral", httpMethod = "GET", notes = "Example Requests:\n" + "\n" + "/loans/1/collaterals/1\n" + + "\n" + "\n" + "/loans/1/collaterals/1?fields=value,description") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.GetLoansLoanIdCollateralsResponse.class) }) + public String retrieveCollateralDetails(@Context final UriInfo uriInfo, + @PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @PathParam("collateralId") @ApiParam(value = "collateralId") final Long CollateralId) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); @@ -153,9 +159,12 @@ public class CollateralsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create a Collateral", httpMethod = "POST", notes = "Note: Currently, Collaterals may be added only before a Loan is approved") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CollateralsApiResourceSwagger.PostLoansLoanIdCollateralsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.PostLoansLoanIdCollateralsResponse.class)}) - public String createCollateral(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CollateralsApiResourceSwagger.PostLoansLoanIdCollateralsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.PostLoansLoanIdCollateralsResponse.class) }) + public String createCollateral(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createCollateral(loanId).withJson(apiRequestBodyAsJson).build(); @@ -169,9 +178,12 @@ public class CollateralsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Collateral", httpMethod = "PUT") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CollateralsApiResourceSwagger.PutLoansLoandIdCollateralsCollateralIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.PutLoansLoanIdCollateralsCollateralIdResponse.class)}) - public String updateCollateral(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @PathParam("collateralId") @ApiParam(value = "collateralId") final Long collateralId, + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CollateralsApiResourceSwagger.PutLoansLoandIdCollateralsCollateralIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.PutLoansLoanIdCollateralsCollateralIdResponse.class) }) + public String updateCollateral(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @PathParam("collateralId") @ApiParam(value = "collateralId") final Long collateralId, @ApiParam(hidden = true) final String jsonRequestBody) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCollateral(loanId, collateralId).withJson(jsonRequestBody) .build(); @@ -186,8 +198,10 @@ public class CollateralsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Remove a Collateral", httpMethod = "DELETE", notes = "Note: A collateral can only be removed from Loans that are not yet approved.") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.DeleteLoansLoanIdCollateralsCollateralIdResponse.class)}) - public String deleteCollateral(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @PathParam("collateralId") @ApiParam(value = "collateralId")final Long collateralId) { + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = CollateralsApiResourceSwagger.DeleteLoansLoanIdCollateralsCollateralIdResponse.class) }) + public String deleteCollateral(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @PathParam("collateralId") @ApiParam(value = "collateralId") final Long collateralId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteCollateral(loanId, collateralId).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralsApiResourceSwagger.java index 340319ea4..356c2cd58 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/api/CollateralsApiResourceSwagger.java @@ -26,17 +26,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/01/17. */ final class CollateralsApiResourceSwagger { - private CollateralsApiResourceSwagger() { - } + + private CollateralsApiResourceSwagger() {} @ApiModel(value = "GetLoansLoanIdCollateralsResponse") public static final class GetLoansLoanIdCollateralsResponse { - private GetLoansLoanIdCollateralsResponse() { - } + + private GetLoansLoanIdCollateralsResponse() {} final class GetCollateralTypeResponse { - private GetCollateralTypeResponse() { - } + + private GetCollateralTypeResponse() {} @ApiModelProperty(example = "8") public Integer id; @@ -45,8 +45,8 @@ final class CollateralsApiResourceSwagger { } final class GetCollateralCurrencyResponse { - private GetCollateralCurrencyResponse() { - } + + private GetCollateralCurrencyResponse() {} @ApiModelProperty(example = "USD") public String code; @@ -74,8 +74,8 @@ final class CollateralsApiResourceSwagger { @ApiModel(value = "PostLoansLoanIdCollateralsRequest") public static final class PostLoansLoanIdCollateralsRequest { - private PostLoansLoanIdCollateralsRequest() { - } + + private PostLoansLoanIdCollateralsRequest() {} @ApiModelProperty(example = "9") public Integer collateralTypeId; @@ -83,8 +83,8 @@ final class CollateralsApiResourceSwagger { @ApiModel(value = "PostLoansLoanIdCollateralsResponse") public static final class PostLoansLoanIdCollateralsResponse { - private PostLoansLoanIdCollateralsResponse() { - } + + private PostLoansLoanIdCollateralsResponse() {} @ApiModelProperty(example = "1") public Integer loanId; @@ -94,8 +94,8 @@ final class CollateralsApiResourceSwagger { @ApiModel(value = "PutLoansLoandIdCollateralsCollateralIdRequest") public static final class PutLoansLoandIdCollateralsCollateralIdRequest { - private PutLoansLoandIdCollateralsCollateralIdRequest() { - } + + private PutLoansLoandIdCollateralsCollateralIdRequest() {} @ApiModelProperty(example = "22 Carat Gold chain weighing 12 grams") public String description; @@ -103,8 +103,8 @@ final class CollateralsApiResourceSwagger { @ApiModel(value = "PutLoansLoanIdCollateralsCollateralIdResponse") public static final class PutLoansLoanIdCollateralsCollateralIdResponse { - private PutLoansLoanIdCollateralsCollateralIdResponse() { - } + + private PutLoansLoanIdCollateralsCollateralIdResponse() {} @ApiModelProperty(example = "1") public Integer loanId; @@ -115,12 +115,12 @@ final class CollateralsApiResourceSwagger { @ApiModel(value = "GetLoansLoanIdCollateralsTemplateResponse") public static final class GetLoansLoanIdCollateralsTemplateResponse { - private GetLoansLoanIdCollateralsTemplateResponse() { - } + + private GetLoansLoanIdCollateralsTemplateResponse() {} final class GetCollateralsTemplateAllowedTypes { - private GetCollateralsTemplateAllowedTypes() { - } + + private GetCollateralsTemplateAllowedTypes() {} @ApiModelProperty(example = "9") public Integer id; @@ -135,8 +135,8 @@ final class CollateralsApiResourceSwagger { @ApiModel(value = "DeleteLoansLoanIdCollateralsCollateralIdResponse") public static final class DeleteLoansLoanIdCollateralsCollateralIdResponse { - private DeleteLoansLoanIdCollateralsCollateralIdResponse() { - } + + private DeleteLoansLoanIdCollateralsCollateralIdResponse() {} @ApiModelProperty(example = "1") public Integer loanId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/command/CollateralCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/command/CollateralCommand.java old mode 100755 new mode 100644 index e792d0022..f2036ee9e --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/command/CollateralCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/command/CollateralCommand.java @@ -58,15 +58,16 @@ public class CollateralCommand { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("collateral"); - baseDataValidator.reset().parameter(CollateralJSONinputParams.COLLATERAL_TYPE_ID.getValue()).value(this.collateralTypeId) - .notNull().integerGreaterThanZero(); - baseDataValidator.reset().parameter(CollateralJSONinputParams.VALUE.getValue()).value(this.value).ignoreIfNull() - .positiveAmount(); + baseDataValidator.reset().parameter(CollateralJSONinputParams.COLLATERAL_TYPE_ID.getValue()).value(this.collateralTypeId).notNull() + .integerGreaterThanZero(); + baseDataValidator.reset().parameter(CollateralJSONinputParams.VALUE.getValue()).value(this.value).ignoreIfNull().positiveAmount(); baseDataValidator.reset().parameter(CollateralJSONinputParams.DESCRIPTION.getValue()).value(this.description).ignoreIfNull() .notExceedingLengthOf(500); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForUpdate() { @@ -76,12 +77,13 @@ public class CollateralCommand { baseDataValidator.reset().parameter(CollateralJSONinputParams.COLLATERAL_TYPE_ID.getValue()).value(this.collateralTypeId) .ignoreIfNull().integerGreaterThanZero(); - baseDataValidator.reset().parameter(CollateralJSONinputParams.VALUE.getValue()).value(this.value).ignoreIfNull() - .positiveAmount(); + baseDataValidator.reset().parameter(CollateralJSONinputParams.VALUE.getValue()).value(this.value).ignoreIfNull().positiveAmount(); baseDataValidator.reset().parameter(CollateralJSONinputParams.DESCRIPTION.getValue()).value(this.description).ignoreIfNull() .notExceedingLengthOf(500); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/data/CollateralData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/data/CollateralData.java index dbcfa1200..28cc06bb1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/data/CollateralData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/data/CollateralData.java @@ -69,4 +69,4 @@ public class CollateralData { return new CollateralData(collateralData.id, collateralData.type, collateralData.value, collateralData.description, collateralData.currency, codeValues); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/domain/LoanCollateral.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/domain/LoanCollateral.java index f2b4b17b1..3fed35c79 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/domain/LoanCollateral.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/domain/LoanCollateral.java @@ -120,27 +120,17 @@ public class LoanCollateral extends AbstractPersistableCustom { this.type = type; } - /* @Override - public boolean equals(final Object obj) { - if (obj == null) { return false; } - if (obj == this) { return true; } - if (obj.getClass() != getClass()) { return false; } - final LoanCollateral rhs = (LoanCollateral) obj; - return new EqualsBuilder().appendSuper(super.equals(obj)) // - .append(getId(), rhs.getId()) // - .append(this.type.getId(), rhs.type.getId()) // - .append(this.description, rhs.description) // - .append(this.value, this.value)// - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(3, 5) // - .append(getId()) // - .append(this.type.getId()) // - .append(this.description) // - .append(this.value)// - .toHashCode(); - }*/ -} \ No newline at end of file + /* + * @Override public boolean equals(final Object obj) { if (obj == null) { + * return false; } if (obj == this) { return true; } if (obj.getClass() != + * getClass()) { return false; } final LoanCollateral rhs = (LoanCollateral) + * obj; return new EqualsBuilder().appendSuper(super.equals(obj)) // + * .append(getId(), rhs.getId()) // .append(this.type.getId(), + * rhs.type.getId()) // .append(this.description, rhs.description) // + * .append(this.value, this.value)// .isEquals(); } + * + * @Override public int hashCode() { return new HashCodeBuilder(3, 5) // + * .append(getId()) // .append(this.type.getId()) // + * .append(this.description) // .append(this.value)// .toHashCode(); } + */ +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeCreatedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeCreatedException.java old mode 100755 new mode 100644 index 178faf06e..33847e318 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeCreatedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeCreatedException.java @@ -24,15 +24,20 @@ public class CollateralCannotBeCreatedException extends AbstractPlatformDomainRu /*** enum of reasons of why Loan Charge cannot be waived **/ public static enum LoanCollateralCannotBeCreatedReason { + LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE; public String errorMessage() { - if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "This collateral cannot be created as the loan it is associated with is not in submitted and pending approval stage"; } + if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { + return "This collateral cannot be created as the loan it is associated with is not in submitted and pending approval stage"; + } return name().toString(); } public String errorCode() { - if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "error.msg.loan.collateral.associated.loan.not.in.submitted.and.pending.approval.stage"; } + if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { + return "error.msg.loan.collateral.associated.loan.not.in.submitted.and.pending.approval.stage"; + } return name().toString(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeDeletedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeDeletedException.java old mode 100755 new mode 100644 index 5b541a857..7294d54b7 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeDeletedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeDeletedException.java @@ -24,15 +24,20 @@ public class CollateralCannotBeDeletedException extends AbstractPlatformDomainRu /*** enum of reasons of why Loan Charge cannot be waived **/ public static enum LoanCollateralCannotBeDeletedReason { + LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE; public String errorMessage() { - if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "This collateral cannot be updated as the loan it is associated with is not in submitted and pending approval stage"; } + if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { + return "This collateral cannot be updated as the loan it is associated with is not in submitted and pending approval stage"; + } return name().toString(); } public String errorCode() { - if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "error.msg.loan.collateral.associated.loan.not.in.submitted.and.pending.approval.stage"; } + if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { + return "error.msg.loan.collateral.associated.loan.not.in.submitted.and.pending.approval.stage"; + } return name().toString(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeUpdatedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeUpdatedException.java old mode 100755 new mode 100644 index 9ebf00e49..703f7d2d0 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeUpdatedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralCannotBeUpdatedException.java @@ -24,15 +24,20 @@ public class CollateralCannotBeUpdatedException extends AbstractPlatformDomainRu /*** enum of reasons of why Loan Charge cannot be waived **/ public static enum LoanCollateralCannotBeUpdatedReason { + LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE; public String errorMessage() { - if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "This collateral cannot be updated as the loan it is associated with is not in submitted and pending approval stage"; } + if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { + return "This collateral cannot be updated as the loan it is associated with is not in submitted and pending approval stage"; + } return name().toString(); } public String errorCode() { - if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { return "error.msg.loan.collateral.associated.loan.not.in.submitted.and.pending.approval.stage"; } + if (name().toString().equalsIgnoreCase("LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE")) { + return "error.msg.loan.collateral.associated.loan.not.in.submitted.and.pending.approval.stage"; + } return name().toString(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralNotFoundException.java old mode 100755 new mode 100644 index bf35bae34..3c134bfc6 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/exception/CollateralNotFoundException.java @@ -33,4 +33,4 @@ public class CollateralNotFoundException extends AbstractPlatformResourceNotFoun public CollateralNotFoundException(final Long id) { super("error.msg.loan.collateral.id.invalid", "Loan collateral with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/CreateCollateralCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/CreateCollateralCommandHandler.java old mode 100755 new mode 100644 index 80360eeed..663785ce9 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/CreateCollateralCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/CreateCollateralCommandHandler.java @@ -43,4 +43,4 @@ public class CreateCollateralCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.addCollateral(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/DeleteCollateralCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/DeleteCollateralCommandHandler.java old mode 100755 new mode 100644 index eef610015..b03b27a6a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/DeleteCollateralCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/DeleteCollateralCommandHandler.java @@ -43,4 +43,4 @@ public class DeleteCollateralCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.collateralWritePlatformService.deleteCollateral(command.getLoanId(), command.entityId(), command.commandId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/UpdateCollateralCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/UpdateCollateralCommandHandler.java old mode 100755 new mode 100644 index 83d582d99..a2b6b9d2b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/UpdateCollateralCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/handler/UpdateCollateralCommandHandler.java @@ -43,4 +43,4 @@ public class UpdateCollateralCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.updateCollateral(command.getLoanId(), command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/serialization/CollateralCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/serialization/CollateralCommandFromApiJsonDeserializer.java old mode 100755 new mode 100644 index c75a23a8c..dd33d62bb --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/serialization/CollateralCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/serialization/CollateralCommandFromApiJsonDeserializer.java @@ -67,9 +67,8 @@ public final class CollateralCommandFromApiJsonDeserializer extends AbstractFrom final Long collateralTypeId = this.fromApiJsonHelper.extractLongNamed(CollateralJSONinputParams.COLLATERAL_TYPE_ID.getValue(), element); final String description = this.fromApiJsonHelper.extractStringNamed(CollateralJSONinputParams.DESCRIPTION.getValue(), element); - final BigDecimal value = this.fromApiJsonHelper.extractBigDecimalNamed(CollateralJSONinputParams.VALUE.getValue(), element, - locale); + final BigDecimal value = this.fromApiJsonHelper.extractBigDecimalNamed(CollateralJSONinputParams.VALUE.getValue(), element, locale); return new CollateralCommand(collateralTypeId, value, description); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralReadPlatformServiceImpl.java index 51fa9a182..618148f1b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralReadPlatformServiceImpl.java @@ -55,11 +55,11 @@ public class CollateralReadPlatformServiceImpl implements CollateralReadPlatform private final StringBuilder sqlBuilder = new StringBuilder( "lc.id as id, lc.description as description, lc.value as value, cv.id as typeId, cv.code_value as typeName, oc.code as currencyCode, ") - .append(" oc.name as currencyName,oc.decimal_places as currencyDecimalPlaces, oc.currency_multiplesof as inMultiplesOf, oc.display_symbol as currencyDisplaySymbol, oc.internationalized_name_code as currencyNameCode") - .append(" FROM m_loan_collateral lc") // - .append(" JOIN m_code_value cv on lc.type_cv_id = cv.id")// - .append(" JOIN m_loan loan on lc.loan_id = loan.id")// - .append(" JOIN m_organisation_currency oc on loan.currency_code = oc.code"); + .append(" oc.name as currencyName,oc.decimal_places as currencyDecimalPlaces, oc.currency_multiplesof as inMultiplesOf, oc.display_symbol as currencyDisplaySymbol, oc.internationalized_name_code as currencyNameCode") + .append(" FROM m_loan_collateral lc") // + .append(" JOIN m_code_value cv on lc.type_cv_id = cv.id")// + .append(" JOIN m_loan loan on lc.loan_id = loan.id")// + .append(" JOIN m_organisation_currency oc on loan.currency_code = oc.code"); public String schema() { return this.sqlBuilder.toString(); @@ -120,4 +120,4 @@ public class CollateralReadPlatformServiceImpl implements CollateralReadPlatform return retrieveCollaterals(loanId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralWritePlatformService.java old mode 100755 new mode 100644 index 7d3f6a32f..903afad3c --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralWritePlatformService.java @@ -28,4 +28,4 @@ public interface CollateralWritePlatformService { CommandProcessingResult updateCollateral(Long loanId, Long collateralId, JsonCommand command); CommandProcessingResult deleteCollateral(Long loanId, Long collateralId, Long commandId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index b04aa049e..1c82125c5 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collateral/service/CollateralWritePlatformServiceJpaRepositoryImpl.java @@ -60,8 +60,9 @@ public class CollateralWritePlatformServiceJpaRepositoryImpl implements Collater private final CollateralCommandFromApiJsonDeserializer collateralCommandFromApiJsonDeserializer; @Autowired - public CollateralWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final LoanRepositoryWrapper loanRepositoryWrapper, - final LoanCollateralRepository collateralRepository, final CodeValueRepositoryWrapper codeValueRepository, + public CollateralWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, + final LoanRepositoryWrapper loanRepositoryWrapper, final LoanCollateralRepository collateralRepository, + final CodeValueRepositoryWrapper codeValueRepository, final CollateralCommandFromApiJsonDeserializer collateralCommandFromApiJsonDeserializer) { this.context = context; this.loanRepositoryWrapper = loanRepositoryWrapper; @@ -88,8 +89,10 @@ public class CollateralWritePlatformServiceJpaRepositoryImpl implements Collater * Collaterals may be added only when the loan associated with them * are yet to be approved **/ - if (!loan.status().isSubmittedAndPendingApproval()) { throw new CollateralCannotBeCreatedException( - LoanCollateralCannotBeCreatedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loan.getId()); } + if (!loan.status().isSubmittedAndPendingApproval()) { + throw new CollateralCannotBeCreatedException( + LoanCollateralCannotBeCreatedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loan.getId()); + } this.collateralRepository.save(collateral); @@ -124,8 +127,8 @@ public class CollateralWritePlatformServiceJpaRepositoryImpl implements Collater if (changes.containsKey(CollateralJSONinputParams.COLLATERAL_TYPE_ID.getValue())) { - collateralType = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( - CollateralApiConstants.COLLATERAL_CODE_NAME, collateralTypeId); + collateralType = this.codeValueRepository + .findOneByCodeNameAndIdWithNotFoundDetection(CollateralApiConstants.COLLATERAL_CODE_NAME, collateralTypeId); collateralForUpdate.setCollateralType(collateralType); } @@ -133,8 +136,10 @@ public class CollateralWritePlatformServiceJpaRepositoryImpl implements Collater * Collaterals may be updated only when the loan associated with * them are yet to be approved **/ - if (!loan.status().isSubmittedAndPendingApproval()) { throw new CollateralCannotBeUpdatedException( - LoanCollateralCannotBeUpdatedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loan.getId()); } + if (!loan.status().isSubmittedAndPendingApproval()) { + throw new CollateralCannotBeUpdatedException( + LoanCollateralCannotBeUpdatedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loan.getId()); + } if (!changes.isEmpty()) { this.collateralRepository.saveAndFlush(collateralForUpdate); @@ -155,7 +160,7 @@ public class CollateralWritePlatformServiceJpaRepositoryImpl implements Collater @Transactional @Override public CommandProcessingResult deleteCollateral(final Long loanId, final Long collateralId, final Long commandId) { - final Loan loan = this.loanRepositoryWrapper.findOneWithNotFoundDetection(loanId, true) ; + final Loan loan = this.loanRepositoryWrapper.findOneWithNotFoundDetection(loanId, true); final LoanCollateral collateral = this.collateralRepository.findByLoanIdAndId(loanId, collateralId); if (collateral == null) { throw new CollateralNotFoundException(loanId, collateralId); } @@ -163,8 +168,10 @@ public class CollateralWritePlatformServiceJpaRepositoryImpl implements Collater * Collaterals may be deleted only when the loan associated with them * are yet to be approved **/ - if (!loan.status().isSubmittedAndPendingApproval()) { throw new CollateralCannotBeDeletedException( - LoanCollateralCannotBeDeletedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loanId, collateralId); } + if (!loan.status().isSubmittedAndPendingApproval()) { + throw new CollateralCannotBeDeletedException( + LoanCollateralCannotBeDeletedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loanId, collateralId); + } this.collateralRepository.delete(collateral); return new CommandProcessingResultBuilder().withCommandId(commandId).withLoanId(loanId).withEntityId(collateralId).build(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/CollectionSheetConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/CollectionSheetConstants.java index 7fe3a8584..8d23cb816 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/CollectionSheetConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/CollectionSheetConstants.java @@ -45,4 +45,4 @@ public class CollectionSheetConstants { public static final String savingsIdParamName = "savingsId"; public static final String transactionAmountParamName = "transactionAmount"; public static final String depositAccountTypeParamName = "depositAccountType"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/api/CollectionSheetApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/api/CollectionSheetApiResourceSwagger.java index 651bbac1a..8450888e6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/api/CollectionSheetApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/api/CollectionSheetApiResourceSwagger.java @@ -26,17 +26,17 @@ import java.util.List; * Created by Chirag Gupta on 12/17/17. */ final class CollectionSheetApiResourceSwagger { - private CollectionSheetApiResourceSwagger() { - } + + private CollectionSheetApiResourceSwagger() {} @ApiModel(value = "PostCollectionSheetRequest") public final static class PostCollectionSheetRequest { - private PostCollectionSheetRequest() { - } + + private PostCollectionSheetRequest() {} final class PostCollectionSheetBulkRepaymentTransactions { - private PostCollectionSheetBulkRepaymentTransactions() { - } + + private PostCollectionSheetBulkRepaymentTransactions() {} @ApiModelProperty(example = "10") public Integer loanId; @@ -63,12 +63,12 @@ final class CollectionSheetApiResourceSwagger { @ApiModel(value = "PostCollectionSheetResponse") public final static class PostCollectionSheetResponse { - private PostCollectionSheetResponse() { - } + + private PostCollectionSheetResponse() {} final class PostCollectionSheetChanges { - private PostCollectionSheetChanges() { - } + + private PostCollectionSheetChanges() {} @ApiModelProperty(example = "en") public String locale; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/api/CollectionSheetApiResourse.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/api/CollectionSheetApiResourse.java old mode 100755 new mode 100644 index 5fb10355d..bbf052fdc --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/api/CollectionSheetApiResourse.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/api/CollectionSheetApiResourse.java @@ -81,11 +81,16 @@ public class CollectionSheetApiResourse { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Generate Individual Collection Sheet | Save Collection Sheet", httpMethod = "POST", notes = "Generate Individual Collection Sheet:\n\n" + "This Api retrieves repayment details of all individual loans under a office as on a specified meeting date.\n\n" + "Save Collection Sheet:\n\n" + "This Api allows the loan officer to perform bulk repayments of individual loans and deposit of mandatory savings on a given meeting date.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CollectionSheetApiResourceSwagger.PostCollectionSheetRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CollectionSheetApiResourceSwagger.PostCollectionSheetResponse.class)}) - public String generateCollectionSheet(@QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Generate Individual Collection Sheet | Save Collection Sheet", httpMethod = "POST", notes = "Generate Individual Collection Sheet:\n\n" + + "This Api retrieves repayment details of all individual loans under a office as on a specified meeting date.\n\n" + + "Save Collection Sheet:\n\n" + + "This Api allows the loan officer to perform bulk repayments of individual loans and deposit of mandatory savings on a given meeting date.") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CollectionSheetApiResourceSwagger.PostCollectionSheetRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = CollectionSheetApiResourceSwagger.PostCollectionSheetResponse.class) }) + public String generateCollectionSheet(@QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiParam(hidden = true) final String apiRequestBodyAsJson, @Context final UriInfo uriInfo) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); CommandProcessingResult result = null; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/CollectionSheetBulkDisbursalCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/CollectionSheetBulkDisbursalCommand.java index 05a25429b..61a4af75a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/CollectionSheetBulkDisbursalCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/CollectionSheetBulkDisbursalCommand.java @@ -48,4 +48,4 @@ public class CollectionSheetBulkDisbursalCommand { return this.transactionDate; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/CollectionSheetBulkRepaymentCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/CollectionSheetBulkRepaymentCommand.java index 4f6543b93..230afc248 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/CollectionSheetBulkRepaymentCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/CollectionSheetBulkRepaymentCommand.java @@ -48,4 +48,4 @@ public class CollectionSheetBulkRepaymentCommand { return this.transactionDate; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/SingleDisbursalCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/SingleDisbursalCommand.java index 5fa1e00c3..a9f8a4906 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/SingleDisbursalCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/SingleDisbursalCommand.java @@ -48,4 +48,4 @@ public class SingleDisbursalCommand { return this.transactionDate; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/SingleRepaymentCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/SingleRepaymentCommand.java index 5c115f6d0..f5c4a91e7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/SingleRepaymentCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/command/SingleRepaymentCommand.java @@ -55,4 +55,4 @@ public class SingleRepaymentCommand { public PaymentDetail getPaymentDetail() { return this.paymentDetail; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/CollectionSheetTransactionDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/CollectionSheetTransactionDataValidator.java index a6c42a280..fac949488 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/CollectionSheetTransactionDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/CollectionSheetTransactionDataValidator.java @@ -49,25 +49,22 @@ import org.springframework.stereotype.Component; public class CollectionSheetTransactionDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set COLLECTIONSHEET_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList - (CollectionSheetConstants.localeParamName, - CollectionSheetConstants.dateFormatParamName, CollectionSheetConstants.transactionDateParamName, - CollectionSheetConstants.actualDisbursementDateParamName, - CollectionSheetConstants.bulkRepaymentTransactionsParamName, - CollectionSheetConstants.bulkDisbursementTransactionsParamName, CollectionSheetConstants.noteParamName, - CollectionSheetConstants.calendarIdParamName, - CollectionSheetConstants.clientsAttendanceParamName, - CollectionSheetConstants.bulkSavingsDueTransactionsParamName, PaymentDetailConstants.paymentTypeParamName, - PaymentDetailConstants.accountNumberParamName, PaymentDetailConstants.checkNumberParamName, - PaymentDetailConstants.routingCodeParamName, PaymentDetailConstants.receiptNumberParamName, - PaymentDetailConstants.bankNumberParamName, CollectionSheetConstants.isTransactionDateOnNonMeetingDateParamName)); + private static final Set COLLECTIONSHEET_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(CollectionSheetConstants.localeParamName, CollectionSheetConstants.dateFormatParamName, + CollectionSheetConstants.transactionDateParamName, CollectionSheetConstants.actualDisbursementDateParamName, + CollectionSheetConstants.bulkRepaymentTransactionsParamName, + CollectionSheetConstants.bulkDisbursementTransactionsParamName, CollectionSheetConstants.noteParamName, + CollectionSheetConstants.calendarIdParamName, CollectionSheetConstants.clientsAttendanceParamName, + CollectionSheetConstants.bulkSavingsDueTransactionsParamName, PaymentDetailConstants.paymentTypeParamName, + PaymentDetailConstants.accountNumberParamName, PaymentDetailConstants.checkNumberParamName, + PaymentDetailConstants.routingCodeParamName, PaymentDetailConstants.receiptNumberParamName, + PaymentDetailConstants.bankNumberParamName, CollectionSheetConstants.isTransactionDateOnNonMeetingDateParamName)); private static final Set INDIVIDUAL_COLLECTIONSHEET_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( CollectionSheetConstants.localeParamName, CollectionSheetConstants.dateFormatParamName, CollectionSheetConstants.transactionDateParamName, CollectionSheetConstants.actualDisbursementDateParamName, - CollectionSheetConstants.bulkRepaymentTransactionsParamName, - CollectionSheetConstants.bulkDisbursementTransactionsParamName, CollectionSheetConstants.noteParamName, - CollectionSheetConstants.bulkSavingsDueTransactionsParamName)); + CollectionSheetConstants.bulkRepaymentTransactionsParamName, CollectionSheetConstants.bulkDisbursementTransactionsParamName, + CollectionSheetConstants.noteParamName, CollectionSheetConstants.bulkSavingsDueTransactionsParamName)); private static final Set PAYMENT_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(PaymentDetailConstants.accountNumberParamName, PaymentDetailConstants.checkNumberParamName, @@ -92,19 +89,16 @@ public class CollectionSheetTransactionDataValidator { final JsonElement element = this.fromApiJsonHelper.parse(json); - final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(CollectionSheetConstants - .transactionDateParamName, element); - baseDataValidator.reset().parameter(CollectionSheetConstants.transactionDateParamName).value(transactionDate) - .notNull(); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(CollectionSheetConstants.transactionDateParamName, + element); + baseDataValidator.reset().parameter(CollectionSheetConstants.transactionDateParamName).value(transactionDate).notNull(); final String note = this.fromApiJsonHelper.extractStringNamed(CollectionSheetConstants.noteParamName, element); if (StringUtils.isNotBlank(note)) { - baseDataValidator.reset().parameter(CollectionSheetConstants.noteParamName).value(note) - .notExceedingLengthOf(1000); + baseDataValidator.reset().parameter(CollectionSheetConstants.noteParamName).value(note).notExceedingLengthOf(1000); } - final Long calendarId = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants.calendarIdParamName, - element); + final Long calendarId = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants.calendarIdParamName, element); baseDataValidator.reset().parameter(CollectionSheetConstants.calendarIdParamName).value(calendarId).notNull(); validateAttendanceDetails(element, baseDataValidator); @@ -125,8 +119,7 @@ public class CollectionSheetTransactionDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - INDIVIDUAL_COLLECTIONSHEET_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, INDIVIDUAL_COLLECTIONSHEET_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -134,15 +127,14 @@ public class CollectionSheetTransactionDataValidator { final JsonElement element = this.fromApiJsonHelper.parse(json); - final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(CollectionSheetConstants - .transactionDateParamName, element); - baseDataValidator.reset().parameter(CollectionSheetConstants.transactionDateParamName).value(transactionDate) - .notNull().validateDateBeforeOrEqual(DateUtils.getLocalDateOfTenant()); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(CollectionSheetConstants.transactionDateParamName, + element); + baseDataValidator.reset().parameter(CollectionSheetConstants.transactionDateParamName).value(transactionDate).notNull() + .validateDateBeforeOrEqual(DateUtils.getLocalDateOfTenant()); final String note = this.fromApiJsonHelper.extractStringNamed(CollectionSheetConstants.noteParamName, element); if (StringUtils.isNotBlank(note)) { - baseDataValidator.reset().parameter(CollectionSheetConstants.noteParamName).value(note) - .notExceedingLengthOf(1000); + baseDataValidator.reset().parameter(CollectionSheetConstants.noteParamName).value(note).notExceedingLengthOf(1000); } validateDisbursementTransactions(element, baseDataValidator); @@ -157,21 +149,20 @@ public class CollectionSheetTransactionDataValidator { private void validateAttendanceDetails(final JsonElement element, final DataValidatorBuilder baseDataValidator) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); if (element.isJsonObject()) { - if (topLevelJsonElement.has(CollectionSheetConstants.clientsAttendanceParamName) && topLevelJsonElement - .get(CollectionSheetConstants.clientsAttendanceParamName).isJsonArray()) { - final JsonArray array = topLevelJsonElement.get(CollectionSheetConstants.clientsAttendanceParamName) - .getAsJsonArray(); + if (topLevelJsonElement.has(CollectionSheetConstants.clientsAttendanceParamName) + && topLevelJsonElement.get(CollectionSheetConstants.clientsAttendanceParamName).isJsonArray()) { + final JsonArray array = topLevelJsonElement.get(CollectionSheetConstants.clientsAttendanceParamName).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject attendanceElement = array.get(i).getAsJsonObject(); - final Long clientId = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants - .clientIdParamName, attendanceElement); - final Long attendanceType = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants - .attendanceTypeParamName, attendanceElement); - baseDataValidator.reset().parameter(CollectionSheetConstants.clientsAttendanceParamName + "[" + i - + "]." + CollectionSheetConstants.clientIdParamName).value(clientId) - .notNull().integerGreaterThanZero(); - baseDataValidator.reset().parameter(CollectionSheetConstants.clientsAttendanceParamName + "[" + i - + "]." + CollectionSheetConstants.attendanceTypeParamName) + final Long clientId = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants.clientIdParamName, + attendanceElement); + final Long attendanceType = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants.attendanceTypeParamName, + attendanceElement); + baseDataValidator.reset().parameter(CollectionSheetConstants.clientsAttendanceParamName + "[" + i + "]." + + CollectionSheetConstants.clientIdParamName).value(clientId).notNull().integerGreaterThanZero(); + baseDataValidator.reset() + .parameter(CollectionSheetConstants.clientsAttendanceParamName + "[" + i + "]." + + CollectionSheetConstants.attendanceTypeParamName) .value(attendanceType).notNull().integerGreaterThanZero(); } } @@ -183,18 +174,16 @@ public class CollectionSheetTransactionDataValidator { final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (element.isJsonObject()) { if (topLevelJsonElement.has(CollectionSheetConstants.bulkDisbursementTransactionsParamName) - && topLevelJsonElement.get(CollectionSheetConstants.bulkDisbursementTransactionsParamName) - .isJsonArray()) { - final JsonArray array = topLevelJsonElement.get(CollectionSheetConstants - .bulkDisbursementTransactionsParamName).getAsJsonArray(); + && topLevelJsonElement.get(CollectionSheetConstants.bulkDisbursementTransactionsParamName).isJsonArray()) { + final JsonArray array = topLevelJsonElement.get(CollectionSheetConstants.bulkDisbursementTransactionsParamName) + .getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject loanTransactionElement = array.get(i).getAsJsonObject(); - final Long loanId = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants - .loanIdParamName, loanTransactionElement); - final BigDecimal disbursementAmount = this.fromApiJsonHelper.extractBigDecimalNamed - (CollectionSheetConstants.transactionAmountParamName, - loanTransactionElement, locale); + final Long loanId = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants.loanIdParamName, + loanTransactionElement); + final BigDecimal disbursementAmount = this.fromApiJsonHelper + .extractBigDecimalNamed(CollectionSheetConstants.transactionAmountParamName, loanTransactionElement, locale); baseDataValidator.reset().parameter("bulktransaction" + "[" + i + "].loan.id").value(loanId).notNull() .integerGreaterThanZero(); @@ -210,18 +199,16 @@ public class CollectionSheetTransactionDataValidator { final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (element.isJsonObject()) { if (topLevelJsonElement.has(CollectionSheetConstants.bulkRepaymentTransactionsParamName) - && topLevelJsonElement.get(CollectionSheetConstants.bulkRepaymentTransactionsParamName) - .isJsonArray()) { - final JsonArray array = topLevelJsonElement.get(CollectionSheetConstants - .bulkRepaymentTransactionsParamName).getAsJsonArray(); + && topLevelJsonElement.get(CollectionSheetConstants.bulkRepaymentTransactionsParamName).isJsonArray()) { + final JsonArray array = topLevelJsonElement.get(CollectionSheetConstants.bulkRepaymentTransactionsParamName) + .getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject loanTransactionElement = array.get(i).getAsJsonObject(); - final Long loanId = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants - .loanIdParamName, loanTransactionElement); - final BigDecimal disbursementAmount = this.fromApiJsonHelper.extractBigDecimalNamed - (CollectionSheetConstants.transactionAmountParamName, - loanTransactionElement, locale); + final Long loanId = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants.loanIdParamName, + loanTransactionElement); + final BigDecimal disbursementAmount = this.fromApiJsonHelper + .extractBigDecimalNamed(CollectionSheetConstants.transactionAmountParamName, loanTransactionElement, locale); baseDataValidator.reset().parameter("bulktransaction" + "[" + i + "].loan.id").value(loanId).notNull() .integerGreaterThanZero(); @@ -239,18 +226,16 @@ public class CollectionSheetTransactionDataValidator { final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (element.isJsonObject()) { if (topLevelJsonElement.has(CollectionSheetConstants.bulkSavingsDueTransactionsParamName) - && topLevelJsonElement.get(CollectionSheetConstants.bulkSavingsDueTransactionsParamName) - .isJsonArray()) { - final JsonArray array = topLevelJsonElement.get(CollectionSheetConstants - .bulkSavingsDueTransactionsParamName).getAsJsonArray(); + && topLevelJsonElement.get(CollectionSheetConstants.bulkSavingsDueTransactionsParamName).isJsonArray()) { + final JsonArray array = topLevelJsonElement.get(CollectionSheetConstants.bulkSavingsDueTransactionsParamName) + .getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject savingsTransactionElement = array.get(i).getAsJsonObject(); - final Long savingsId = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants - .savingsIdParamName, savingsTransactionElement); - final BigDecimal dueAmount = this.fromApiJsonHelper.extractBigDecimalNamed - (CollectionSheetConstants.transactionAmountParamName, - savingsTransactionElement, locale); + final Long savingsId = this.fromApiJsonHelper.extractLongNamed(CollectionSheetConstants.savingsIdParamName, + savingsTransactionElement); + final BigDecimal dueAmount = this.fromApiJsonHelper + .extractBigDecimalNamed(CollectionSheetConstants.transactionAmountParamName, savingsTransactionElement, locale); baseDataValidator.reset().parameter("bulktransaction" + "[" + i + "].savings.id").value(savingsId).notNull() .integerGreaterThanZero(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualClientData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualClientData.java old mode 100755 new mode 100644 index 5eabd1ce9..e219a81df --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualClientData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualClientData.java @@ -98,9 +98,7 @@ public class IndividualClientData { @Override public boolean equals(final Object obj) { - if (!(obj instanceof IndividualClientData)) { - return false; - } + if (!(obj instanceof IndividualClientData)) { return false; } final IndividualClientData clientData = (IndividualClientData) obj; return clientData.clientId.compareTo(this.clientId) == 0; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualCollectionSheetData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualCollectionSheetData.java old mode 100755 new mode 100644 index 6f42f4a17..fca2417d1 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualCollectionSheetData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualCollectionSheetData.java @@ -47,4 +47,4 @@ public class IndividualCollectionSheetData { this.paymentTypeOptions = paymentTypeOptions; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualCollectionSheetLoanFlatData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualCollectionSheetLoanFlatData.java old mode 100755 new mode 100644 index de0e562b7..fe989027d --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualCollectionSheetLoanFlatData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/IndividualCollectionSheetLoanFlatData.java @@ -141,4 +141,4 @@ public class IndividualCollectionSheetLoanFlatData { return this.feePaid; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGClientData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGClientData.java index 78bb56eaf..049573c03 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGClientData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGClientData.java @@ -34,26 +34,25 @@ public class JLGClientData { @SuppressWarnings("unused") private final EnumOptionData attendanceType; - public static JLGClientData instance(final Long clientId, final String clientName, final EnumOptionData attendanceType){ + public static JLGClientData instance(final Long clientId, final String clientName, final EnumOptionData attendanceType) { final Collection loans = null; final Collection savings = null; return new JLGClientData(clientId, clientName, loans, savings, attendanceType); } - public static JLGClientData withSavings(final JLGClientData client, final Collection savings){ + public static JLGClientData withSavings(final JLGClientData client, final Collection savings) { final Collection loans = null; final EnumOptionData attendanceType = null; return new JLGClientData(client.clientId, client.clientName, loans, savings, attendanceType); } - /*public JLGClientData(final Long clientId, final String clientName, final Collection loans, - final EnumOptionData attendanceType) { - this.clientId = clientId; - this.clientName = clientName; - this.loans = loans; - this.attendanceType = attendanceType; - }*/ + /* + * public JLGClientData(final Long clientId, final String clientName, final + * Collection loans, final EnumOptionData attendanceType) { + * this.clientId = clientId; this.clientName = clientName; this.loans = + * loans; this.attendanceType = attendanceType; } + */ public static JLGClientData withAttendance(final Long clientId, final String clientName, final EnumOptionData attendanceType) { final Collection loans = null; @@ -97,16 +96,13 @@ public class JLGClientData { return this.savings; } - public void setSavings(Collection savings) { this.savings = savings; } @Override public boolean equals(final Object obj) { - if (!(obj instanceof JLGClientData)) { - return false; - } + if (!(obj instanceof JLGClientData)) { return false; } final JLGClientData clientData = (JLGClientData) obj; return clientData.clientId.compareTo(this.clientId) == 0; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGCollectionSheetData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGCollectionSheetData.java index dcb125395..89bbfc85d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGCollectionSheetData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGCollectionSheetData.java @@ -75,4 +75,4 @@ public class JLGCollectionSheetData { return this.loanProducts; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGCollectionSheetFlatData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGCollectionSheetFlatData.java index cf9c1d4a9..c4409faee 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGCollectionSheetFlatData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGCollectionSheetFlatData.java @@ -55,9 +55,9 @@ public class JLGCollectionSheetFlatData { public JLGCollectionSheetFlatData(final String groupName, final Long groupId, final Long staffId, final String staffName, final Long levelId, final String levelName, final String clientName, final Long clientId, final Long loanId, final String accountId, final Integer accountStatusId, final String productShortName, final Long productId, - final CurrencyData currency, final BigDecimal disbursementAmount, final BigDecimal principalDue, - final BigDecimal principalPaid, final BigDecimal interestDue, final BigDecimal interestPaid, final BigDecimal chargesDue, - final EnumOptionData attendanceType, final BigDecimal feeDue, final BigDecimal feePaid) { + final CurrencyData currency, final BigDecimal disbursementAmount, final BigDecimal principalDue, final BigDecimal principalPaid, + final BigDecimal interestDue, final BigDecimal interestPaid, final BigDecimal chargesDue, final EnumOptionData attendanceType, + final BigDecimal feeDue, final BigDecimal feePaid) { this.groupName = groupName; this.groupId = groupId; this.staffId = staffId; @@ -185,4 +185,4 @@ public class JLGCollectionSheetFlatData { public BigDecimal getFeePaid() { return this.feePaid; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGGroupData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGGroupData.java index 7cab44067..a63e83000 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGGroupData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/JLGGroupData.java @@ -34,12 +34,12 @@ public class JLGGroupData { private final String levelName; private Collection clients; - public static JLGGroupData instance(final Long groupId, final String groupName, final Long staffId, final String staffName, final Long levelId, - final String levelName){ + public static JLGGroupData instance(final Long groupId, final String groupName, final Long staffId, final String staffName, + final Long levelId, final String levelName) { return new JLGGroupData(groupId, groupName, staffId, staffName, levelId, levelName, null); } - public static JLGGroupData withClients(final JLGGroupData group, Collection clients){ + public static JLGGroupData withClients(final JLGGroupData group, Collection clients) { return new JLGGroupData(group.groupId, group.groupName, group.staffId, group.staffName, group.levelId, group.levelName, clients); } @@ -88,9 +88,7 @@ public class JLGGroupData { @Override public boolean equals(final Object obj) { - if (!(obj instanceof JLGGroupData)) { - return false; - } + if (!(obj instanceof JLGGroupData)) { return false; } final JLGGroupData groupData = (JLGGroupData) obj; return groupData.groupId.compareTo(this.groupId) == 0; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/LoanDueData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/LoanDueData.java index d27fd9061..f7974d246 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/LoanDueData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/LoanDueData.java @@ -120,4 +120,4 @@ public class LoanDueData { return this.feePaid; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/SavingsDueData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/SavingsDueData.java index f5807c64f..88cd98109 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/SavingsDueData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/data/SavingsDueData.java @@ -43,7 +43,8 @@ public class SavingsDueData { private String depositAccountType; public static SavingsDueData instance(final Long savingsId, final String accountId, final Integer accountStatusId, - final String productName, final Long productId, final CurrencyData currency, final BigDecimal dueAmount, final String depositAccountType) { + final String productName, final Long productId, final CurrencyData currency, final BigDecimal dueAmount, + final String depositAccountType) { return new SavingsDueData(savingsId, accountId, accountStatusId, productName, productId, currency, dueAmount, depositAccountType); } @@ -71,4 +72,4 @@ public class SavingsDueData { return depositAccountType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer.java index 29580b4b8..4ec3804f9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer.java @@ -39,8 +39,8 @@ import org.springframework.stereotype.Component; * {@link CollectionSheetBulkDisbursalCommand}'s. */ @Component -public final class CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer extends - AbstractFromApiJsonDeserializer { +public final class CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer + extends AbstractFromApiJsonDeserializer { private final FromJsonHelper fromApiJsonHelper; @@ -79,4 +79,4 @@ public final class CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer ex } return new CollectionSheetBulkDisbursalCommand(note, transactionDate, loanDisbursementTransactions); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer.java index 97e0883de..8b26b9ba0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer.java @@ -41,8 +41,8 @@ import org.springframework.stereotype.Component; * {@link CollectionSheetBulkRepaymentCommand}'s. */ @Component -public final class CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer extends - AbstractFromApiJsonDeserializer { +public final class CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer + extends AbstractFromApiJsonDeserializer { private final FromJsonHelper fromApiJsonHelper; private final PaymentDetailAssembler paymentDetailAssembler; @@ -79,7 +79,8 @@ public final class CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer ex SingleRepaymentCommand[] loanRepaymentTransactions = null; if (element.isJsonObject()) { - if (topLevelJsonElement.has("bulkRepaymentTransactions") && topLevelJsonElement.get("bulkRepaymentTransactions").isJsonArray()) { + if (topLevelJsonElement.has("bulkRepaymentTransactions") + && topLevelJsonElement.get("bulkRepaymentTransactions").isJsonArray()) { final JsonArray array = topLevelJsonElement.get("bulkRepaymentTransactions").getAsJsonArray(); loanRepaymentTransactions = new SingleRepaymentCommand[array.size()]; for (int i = 0; i < array.size(); i++) { @@ -92,7 +93,7 @@ public final class CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer ex if (paymentDetail == null) { detail = this.paymentDetailAssembler.fetchPaymentDetail(loanTransactionElement); } - if(transactionAmount != null && transactionAmount.intValue() > 0){ + if (transactionAmount != null && transactionAmount.intValue() > 0) { loanRepaymentTransactions[i] = new SingleRepaymentCommand(loanId, transactionAmount, transactionDate, detail); } } @@ -101,4 +102,4 @@ public final class CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer ex return new CollectionSheetBulkRepaymentCommand(note, transactionDate, loanRepaymentTransactions); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetGenerateCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetGenerateCommandFromApiJsonDeserializer.java index 4c6db451e..031063df5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetGenerateCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/serialization/CollectionSheetGenerateCommandFromApiJsonDeserializer.java @@ -53,8 +53,8 @@ public class CollectionSheetGenerateCommandFromApiJsonDeserializer { final Set supportedParameters = new HashSet<>( Arrays.asList(transactionDateParamName, localeParamName, dateFormatParamName, calendarIdParamName)); - private static final Set INDIVIDUAL_COLLECTIONSHEET_SUPPORTED_PARAMS = new HashSet<>(Arrays.asList( - transactionDateParamName, localeParamName, dateFormatParamName, officeIdParamName, staffIdParamName)); + private static final Set INDIVIDUAL_COLLECTIONSHEET_SUPPORTED_PARAMS = new HashSet<>( + Arrays.asList(transactionDateParamName, localeParamName, dateFormatParamName, officeIdParamName, staffIdParamName)); private final FromJsonHelper fromApiJsonHelper; @@ -86,8 +86,10 @@ public class CollectionSheetGenerateCommandFromApiJsonDeserializer { final Long calendarId = this.fromApiJsonHelper.extractLongNamed(calendarIdParamName, element); baseDataValidator.reset().parameter(calendarIdParamName).value(calendarId).notNull(); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForGenerateCollectionSheetOfIndividuals(final String json) { @@ -116,8 +118,10 @@ public class CollectionSheetGenerateCommandFromApiJsonDeserializer { final Long staffId = this.fromApiJsonHelper.extractLongNamed(staffIdParamName, element); baseDataValidator.reset().parameter(staffIdParamName).value(staffId).longGreaterThanZero(); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/service/CollectionSheetReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/service/CollectionSheetReadPlatformServiceImpl.java index 11c36da38..ffc780d7d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/service/CollectionSheetReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/service/CollectionSheetReadPlatformServiceImpl.java @@ -101,7 +101,8 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe final CollectionSheetGenerateCommandFromApiJsonDeserializer collectionSheetGenerateCommandFromApiJsonDeserializer, final CalendarRepositoryWrapper calendarRepositoryWrapper, final AttendanceDropdownReadPlatformService attendanceDropdownReadPlatformService, - final CodeValueReadPlatformService codeValueReadPlatformService, final PaymentTypeReadPlatformService paymentTypeReadPlatformService, + final CodeValueReadPlatformService codeValueReadPlatformService, + final PaymentTypeReadPlatformService paymentTypeReadPlatformService, final CalendarReadPlatformService calendarReadPlatformService, final ConfigurationDomainService configurationDomainService, final CalendarInstanceRepository calendarInstanceRepository) { this.context = context; @@ -132,7 +133,6 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe Long prevClientId = null; final Collection paymentOptions = this.paymentTypeReadPlatformService.retrieveAllPaymentTypes(); - final List jlgGroupsData = new ArrayList<>(); List clientsData = new ArrayList<>(); List loansDueData = new ArrayList<>(); @@ -217,19 +217,11 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe public String collectionSheetSchema(final boolean isCenterCollection) { StringBuilder sql = new StringBuilder(400); sql.append("SELECT loandata.*, sum(lc.amount_outstanding_derived) as chargesDue from ") - .append("(SELECT gp.display_name As groupName, ") - .append("gp.id As groupId, ") - .append("cl.display_name As clientName, ") - .append("sf.id As staffId, ") - .append("sf.display_name As staffName, ") - .append("gl.id As levelId, ") - .append("gl.level_name As levelName, ") - .append("cl.id As clientId, ") - .append("ln.id As loanId, ") - .append("ln.account_no As accountId, ") - .append("ln.loan_status_id As accountStatusId, ") - .append("pl.short_name As productShortName, ") - .append("ln.product_id As productId, ") + .append("(SELECT gp.display_name As groupName, ").append("gp.id As groupId, ").append("cl.display_name As clientName, ") + .append("sf.id As staffId, ").append("sf.display_name As staffName, ").append("gl.id As levelId, ") + .append("gl.level_name As levelName, ").append("cl.id As clientId, ").append("ln.id As loanId, ") + .append("ln.account_no As accountId, ").append("ln.loan_status_id As accountStatusId, ") + .append("pl.short_name As productShortName, ").append("ln.product_id As productId, ") .append("ln.currency_code as currencyCode, ln.currency_digits as currencyDigits, ln.currency_multiplesof as inMultiplesOf, rc.`name` as currencyName, rc.display_symbol as currencyDisplaySymbol, rc.internationalized_name_code as currencyNameCode, ") .append("if(ln.loan_status_id = 200 , ln.principal_amount , null) As disbursementAmount, ") .append("sum(ifnull(if(ln.loan_status_id = 300, ls.principal_amount, 0.0), 0.0) - ifnull(if(ln.loan_status_id = 300, ls.principal_completed_derived, 0.0), 0.0)) As principalDue, ") @@ -237,14 +229,11 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe .append("sum(ifnull(if(ln.loan_status_id = 300, ls.interest_amount, 0.0), 0.0) - ifnull(if(ln.loan_status_id = 300, ls.interest_completed_derived, 0.0), 0.0) - IFNULL(IF(ln.loan_status_id = 300, ls.interest_waived_derived, 0.0), 0.0)) As interestDue, ") .append("ln.interest_repaid_derived As interestPaid, ") .append("sum(ifnull(if(ln.loan_status_id = 300, ls.fee_charges_amount, 0.0), 0.0) - ifnull(if(ln.loan_status_id = 300, ls.fee_charges_completed_derived, 0.0), 0.0)) As feeDue, ") - .append("ln.fee_charges_repaid_derived As feePaid, ") - .append("ca.attendance_type_enum as attendanceTypeId ") + .append("ln.fee_charges_repaid_derived As feePaid, ").append("ca.attendance_type_enum as attendanceTypeId ") .append("FROM m_group gp ") .append("LEFT JOIN m_office of ON of.id = gp.office_id AND of.hierarchy like :officeHierarchy ") - .append("JOIN m_group_level gl ON gl.id = gp.level_Id ") - .append("LEFT JOIN m_staff sf ON sf.id = gp.staff_id ") - .append("JOIN m_group_client gc ON gc.group_id = gp.id ") - .append("JOIN m_client cl ON cl.id = gc.client_id ") + .append("JOIN m_group_level gl ON gl.id = gp.level_Id ").append("LEFT JOIN m_staff sf ON sf.id = gp.staff_id ") + .append("JOIN m_group_client gc ON gc.group_id = gp.id ").append("JOIN m_client cl ON cl.id = gc.client_id ") .append("LEFT JOIN m_loan ln ON cl.id = ln.client_id and ln.group_id=gp.id AND ln.group_id is not null AND ( ln.loan_status_id = 300 ) ") .append("LEFT JOIN m_product_loan pl ON pl.id = ln.product_id ") .append("LEFT JOIN m_currency rc on rc.`code` = ln.currency_code ") @@ -262,8 +251,7 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe sql.append("and (gp.status_enum = 300 or (gp.status_enum = 600 and gp.closedon_date >= :dueDate)) ") .append("and (cl.status_enum = 300 or (cl.status_enum = 600 and cl.closedon_date >= :dueDate)) ") - .append("GROUP BY gp.id, cl.id, ln.id, ca.attendance_type_enum ORDER BY gp.id , cl.id , ln.id ") - .append(") loandata ") + .append("GROUP BY gp.id, cl.id, ln.id, ca.attendance_type_enum ORDER BY gp.id , cl.id , ln.id ").append(") loandata ") .append("LEFT JOIN m_loan_charge lc ON lc.loan_id = loandata.loanId AND lc.is_paid_derived = 0 AND lc.is_active = 1 ") .append("AND ( lc.due_for_collection_as_of_date <= :dueDate OR lc.charge_time_enum = 1) ") .append("GROUP BY loandata.groupId, loandata.clientId, loandata.loanId ") @@ -341,46 +329,45 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe final CalendarEntityType entityType = group.isChildGroup() ? CalendarEntityType.CENTERS : CalendarEntityType.GROUPS; Long entityId = null; - if(group.isChildGroup()){ + if (group.isChildGroup()) { entityId = group.getParentId(); - }else{ + } else { entityId = group.getId(); } Boolean isSkipMeetingOnFirstDay = false; Integer numberOfDays = 0; boolean isSkipRepaymentOnFirstMonthEnabled = this.configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); - if(isSkipRepaymentOnFirstMonthEnabled){ + if (isSkipRepaymentOnFirstMonthEnabled) { numberOfDays = this.configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); isSkipMeetingOnFirstDay = this.calendarReadPlatformService.isCalendarAssociatedWithEntity(entityId, calendar.getId(), entityType.getValue().longValue()); } - if (!calendar.isValidRecurringDate(transactionDate, isSkipMeetingOnFirstDay, numberOfDays)) { throw new NotValidRecurringDateException("collectionsheet", "The date '" - + transactionDate + "' is not a valid meeting date.", transactionDate); } + if (!calendar.isValidRecurringDate(transactionDate, isSkipMeetingOnFirstDay, numberOfDays)) { + throw new NotValidRecurringDateException("collectionsheet", "The date '" + transactionDate + "' is not a valid meeting date.", + transactionDate); + } final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String officeHierarchy = hierarchy + "%"; - - final JLGCollectionSheetFaltDataMapper mapper = new JLGCollectionSheetFaltDataMapper(); - final SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("dueDate", transactionDateStr) .addValue("groupId", group.getId()).addValue("officeHierarchy", officeHierarchy) .addValue("entityTypeId", entityType.getValue()); - final Collection collectionSheetFlatDatas = this.namedParameterjdbcTemplate.query( - mapper.collectionSheetSchema(false), namedParameters, mapper); + final Collection collectionSheetFlatDatas = this.namedParameterjdbcTemplate + .query(mapper.collectionSheetSchema(false), namedParameters, mapper); // loan data for collection sheet JLGCollectionSheetData collectionSheetData = buildJLGCollectionSheet(transactionDate, collectionSheetFlatDatas); // mandatory savings data for collection sheet - Collection groupsWithSavingsData = this.namedParameterjdbcTemplate.query( - mandatorySavingsExtractor.collectionSheetSchema(false), namedParameters, mandatorySavingsExtractor); + Collection groupsWithSavingsData = this.namedParameterjdbcTemplate + .query(mandatorySavingsExtractor.collectionSheetSchema(false), namedParameters, mandatorySavingsExtractor); // merge savings data into loan data mergeSavingsGroupDataIntoCollectionsheetData(groupsWithSavingsData, collectionSheetData); @@ -407,9 +394,7 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe private void mergeGroup(final JLGGroupData groupSavingsData, final List groupsWithLoanData) { final int index = groupsWithLoanData.indexOf(groupSavingsData); - if (index < 0) { - return; - } + if (index < 0) { return; } JLGGroupData groupLoanData = groupsWithLoanData.get(index); List clientsLoanData = (List) groupLoanData.getClients(); @@ -427,9 +412,7 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe private void mergeClient(final JLGClientData clientSavingsData, List clientsLoanData) { final int index = clientsLoanData.indexOf(clientSavingsData); - if (index < 0) { - return; - } + if (index < 0) { return; } JLGClientData clientLoanData = clientsLoanData.get(index); clientLoanData.setSavings(clientSavingsData.getSavings()); @@ -484,8 +467,8 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe JLGCollectionSheetData collectionSheetData = buildJLGCollectionSheet(transactionDate, collectionSheetFlatDatas); // mandatory savings data for collection sheet - Collection groupsWithSavingsData = this.namedParameterjdbcTemplate.query( - mandatorySavingsExtractor.collectionSheetSchema(true), namedParameters, mandatorySavingsExtractor); + Collection groupsWithSavingsData = this.namedParameterjdbcTemplate + .query(mandatorySavingsExtractor.collectionSheetSchema(true), namedParameters, mandatorySavingsExtractor); // merge savings data into loan data mergeSavingsGroupDataIntoCollectionsheetData(groupsWithSavingsData, collectionSheetData); @@ -503,23 +486,13 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe public String collectionSheetSchema(final boolean isCenterCollection) { final StringBuilder sql = new StringBuilder(400); - sql.append("SELECT gp.display_name As groupName, ") - .append("gp.id As groupId, ") - .append("cl.display_name As clientName, ") - .append("cl.id As clientId, ") - .append("sf.id As staffId, ") - .append("sf.display_name As staffName, ") - .append("gl.id As levelId, ") - .append("gl.level_name As levelName, ") - .append("sa.id As savingsId, ") - .append("sa.account_no As accountId, ") - .append("sa.status_enum As accountStatusId, ") - .append("sp.short_name As productShortName, ") - .append("sp.id As productId, ") - .append("sa.currency_code as currencyCode, ") - .append("sa.currency_digits as currencyDigits, ") - .append("sa.currency_multiplesof as inMultiplesOf, ") - .append("rc.`name` as currencyName, ") + sql.append("SELECT gp.display_name As groupName, ").append("gp.id As groupId, ").append("cl.display_name As clientName, ") + .append("cl.id As clientId, ").append("sf.id As staffId, ").append("sf.display_name As staffName, ") + .append("gl.id As levelId, ").append("gl.level_name As levelName, ").append("sa.id As savingsId, ") + .append("sa.account_no As accountId, ").append("sa.status_enum As accountStatusId, ") + .append("sp.short_name As productShortName, ").append("sp.id As productId, ") + .append("sa.currency_code as currencyCode, ").append("sa.currency_digits as currencyDigits, ") + .append("sa.currency_multiplesof as inMultiplesOf, ").append("rc.`name` as currencyName, ") .append("rc.display_symbol as currencyDisplaySymbol, ") .append("if(sa.deposit_type_enum=100,'Saving Deposit',if(sa.deposit_type_enum=300,'Recurring Deposit','Current Deposit')) as depositAccountType, ") .append("rc.internationalized_name_code as currencyNameCode, ") @@ -527,10 +500,8 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe .append("FROM m_group gp ") .append("LEFT JOIN m_office of ON of.id = gp.office_id AND of.hierarchy like :officeHierarchy ") - .append("JOIN m_group_level gl ON gl.id = gp.level_Id ") - .append("LEFT JOIN m_staff sf ON sf.id = gp.staff_id ") - .append("JOIN m_group_client gc ON gc.group_id = gp.id ") - .append("JOIN m_client cl ON cl.id = gc.client_id ") + .append("JOIN m_group_level gl ON gl.id = gp.level_Id ").append("LEFT JOIN m_staff sf ON sf.id = gp.staff_id ") + .append("JOIN m_group_client gc ON gc.group_id = gp.id ").append("JOIN m_client cl ON cl.id = gc.client_id ") .append("JOIN m_savings_account sa ON sa.client_id=cl.id and sa.status_enum=300 ") .append("JOIN m_savings_product sp ON sa.product_id=sp.id ") .append("LEFT JOIN m_deposit_account_recurring_detail dard ON sa.id = dard.savings_account_id AND dard.is_mandatory = true AND dard.is_calendar_inherited = true ") @@ -677,10 +648,11 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); final String depositAccountType = rs.getString("depositAccountType"); // currency - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); - return SavingsDueData.instance(savingsId, accountId, accountStatusId, productName, productId, currency, dueAmount, depositAccountType); + return SavingsDueData.instance(savingsId, accountId, accountStatusId, productName, productId, currency, dueAmount, + depositAccountType); } } @@ -705,8 +677,8 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe final IndividualCollectionSheetFaltDataMapper mapper = new IndividualCollectionSheetFaltDataMapper(checkForOfficeId, checkForStaffId); - final SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("dueDate", transactionDateStr).addValue( - "officeHierarchy", officeHierarchy); + final SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("dueDate", transactionDateStr) + .addValue("officeHierarchy", officeHierarchy); if (checkForOfficeId) { ((MapSqlParameterSource) namedParameters).addValue("officeId", officeId); @@ -715,14 +687,14 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe ((MapSqlParameterSource) namedParameters).addValue("staffId", staffId); } - final Collection collectionSheetFlatDatas = this.namedParameterjdbcTemplate.query( - mapper.sqlSchema(), namedParameters, mapper); + final Collection collectionSheetFlatDatas = this.namedParameterjdbcTemplate + .query(mapper.sqlSchema(), namedParameters, mapper); IndividualMandatorySavingsCollectionsheetExtractor mandatorySavingsExtractor = new IndividualMandatorySavingsCollectionsheetExtractor( checkForOfficeId, checkForStaffId); // mandatory savings data for collection sheet - Collection clientData = this.namedParameterjdbcTemplate.query( - mandatorySavingsExtractor.collectionSheetSchema(), namedParameters, mandatorySavingsExtractor); + Collection clientData = this.namedParameterjdbcTemplate + .query(mandatorySavingsExtractor.collectionSheetSchema(), namedParameters, mandatorySavingsExtractor); // merge savings data into loan data mergeLoanData(collectionSheetFlatDatas, (List) clientData); @@ -744,13 +716,17 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe sb.append("cl.id As clientId, ln.id As loanId, ln.account_no As accountId, ln.loan_status_id As accountStatusId,"); sb.append(" pl.short_name As productShortName, ln.product_id As productId, "); sb.append("ln.currency_code as currencyCode, ln.currency_digits as currencyDigits, ln.currency_multiplesof as inMultiplesOf, "); - sb.append("rc.`name` as currencyName, rc.display_symbol as currencyDisplaySymbol, rc.internationalized_name_code as currencyNameCode, "); + sb.append( + "rc.`name` as currencyName, rc.display_symbol as currencyDisplaySymbol, rc.internationalized_name_code as currencyNameCode, "); sb.append("if(ln.loan_status_id = 200 , ln.principal_amount , null) As disbursementAmount, "); - sb.append("sum(ifnull(if(ln.loan_status_id = 300, ls.principal_amount, 0.0), 0.0) - ifnull(if(ln.loan_status_id = 300, ls.principal_completed_derived, 0.0), 0.0)) As principalDue, "); + sb.append( + "sum(ifnull(if(ln.loan_status_id = 300, ls.principal_amount, 0.0), 0.0) - ifnull(if(ln.loan_status_id = 300, ls.principal_completed_derived, 0.0), 0.0)) As principalDue, "); sb.append("ln.principal_repaid_derived As principalPaid, "); - sb.append("sum(ifnull(if(ln.loan_status_id = 300, ls.interest_amount, 0.0), 0.0) - ifnull(if(ln.loan_status_id = 300, ls.interest_completed_derived, 0.0), 0.0)) As interestDue, "); + sb.append( + "sum(ifnull(if(ln.loan_status_id = 300, ls.interest_amount, 0.0), 0.0) - ifnull(if(ln.loan_status_id = 300, ls.interest_completed_derived, 0.0), 0.0)) As interestDue, "); sb.append("ln.interest_repaid_derived As interestPaid, "); - sb.append("sum(ifnull(if(ln.loan_status_id = 300, ls.fee_charges_amount, 0.0), 0.0) - ifnull(if(ln.loan_status_id = 300, ls.fee_charges_completed_derived, 0.0), 0.0)) As feeDue, "); + sb.append( + "sum(ifnull(if(ln.loan_status_id = 300, ls.fee_charges_amount, 0.0), 0.0) - ifnull(if(ln.loan_status_id = 300, ls.fee_charges_completed_derived, 0.0), 0.0)) As feeDue, "); sb.append("ln.fee_charges_repaid_derived As feePaid "); sb.append("FROM m_loan ln "); sb.append("JOIN m_client cl ON cl.id = ln.client_id "); @@ -767,7 +743,8 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe } sb.append("(ln.loan_status_id = 300) "); sb.append("and ln.group_id is null GROUP BY cl.id , ln.id ORDER BY cl.id , ln.id ) loandata "); - sb.append("LEFT JOIN m_loan_charge lc ON lc.loan_id = loandata.loanId AND lc.is_paid_derived = 0 AND lc.is_active = 1 AND ( lc.due_for_collection_as_of_date <= :dueDate OR lc.charge_time_enum = 1) "); + sb.append( + "LEFT JOIN m_loan_charge lc ON lc.loan_id = loandata.loanId AND lc.is_paid_derived = 0 AND lc.is_active = 1 AND ( lc.due_for_collection_as_of_date <= :dueDate OR lc.charge_time_enum = 1) "); sb.append("GROUP BY loandata.clientId, loandata.loanId ORDER BY loandata.clientId, loandata.loanId "); sql = sb.toString(); @@ -809,14 +786,14 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe final BigDecimal feePaid = rs.getBigDecimal("feePaid"); return new IndividualCollectionSheetLoanFlatData(clientName, clientId, loanId, accountId, accountStatusId, productShortName, - productId, currencyData, disbursementAmount, principalDue, principalPaid, interestDue, interestPaid, chargesDue, - feeDue, feePaid); + productId, currencyData, disbursementAmount, principalDue, principalPaid, interestDue, interestPaid, chargesDue, feeDue, + feePaid); } } - private static final class IndividualMandatorySavingsCollectionsheetExtractor implements - ResultSetExtractor> { + private static final class IndividualMandatorySavingsCollectionsheetExtractor + implements ResultSetExtractor> { private final SavingsDueDataMapper savingsDueDataMapper = new SavingsDueDataMapper(); @@ -825,17 +802,21 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe public IndividualMandatorySavingsCollectionsheetExtractor(final boolean checkForOfficeId, final boolean checkforStaffId) { final StringBuilder sb = new StringBuilder(400); - sb.append("SELECT if(sa.deposit_type_enum=100,'Saving Deposit',if(sa.deposit_type_enum=300,'Recurring Deposit','Current Deposit')) as depositAccountType, cl.display_name As clientName, cl.id As clientId, "); + sb.append( + "SELECT if(sa.deposit_type_enum=100,'Saving Deposit',if(sa.deposit_type_enum=300,'Recurring Deposit','Current Deposit')) as depositAccountType, cl.display_name As clientName, cl.id As clientId, "); sb.append("sa.id As savingsId, sa.account_no As accountId, sa.status_enum As accountStatusId, "); sb.append("sp.short_name As productShortName, sp.id As productId, "); sb.append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); - sb.append("rc.`name` as currencyName, rc.display_symbol as currencyDisplaySymbol, rc.internationalized_name_code as currencyNameCode, "); + sb.append( + "rc.`name` as currencyName, rc.display_symbol as currencyDisplaySymbol, rc.internationalized_name_code as currencyNameCode, "); sb.append("sum(ifnull(mss.deposit_amount,0) - ifnull(mss.deposit_amount_completed_derived,0)) as dueAmount "); sb.append("FROM m_savings_account sa "); sb.append("JOIN m_client cl ON cl.id = sa.client_id "); sb.append("JOIN m_savings_product sp ON sa.product_id=sp.id "); - sb.append("LEFT JOIN m_deposit_account_recurring_detail dard ON sa.id = dard.savings_account_id AND dard.is_mandatory = true AND dard.is_calendar_inherited = false "); - sb.append("LEFT JOIN m_mandatory_savings_schedule mss ON mss.savings_account_id=sa.id AND mss.completed_derived = 0 AND mss.duedate <= :dueDate "); + sb.append( + "LEFT JOIN m_deposit_account_recurring_detail dard ON sa.id = dard.savings_account_id AND dard.is_mandatory = true AND dard.is_calendar_inherited = false "); + sb.append( + "LEFT JOIN m_mandatory_savings_schedule mss ON mss.savings_account_id=sa.id AND mss.completed_derived = 0 AND mss.duedate <= :dueDate "); sb.append("LEFT JOIN m_office of ON of.id = cl.office_id AND of.hierarchy like :officeHierarchy "); sb.append("LEFT JOIN m_currency rc on rc.`code` = sa.currency_code "); sb.append("WHERE sa.status_enum=300 and sa.group_id is null and sa.deposit_type_enum in (100,300,400) "); @@ -882,7 +863,8 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe } } - private void mergeLoanData(final Collection loanFlatDatas, List clientDatas) { + private void mergeLoanData(final Collection loanFlatDatas, + List clientDatas) { IndividualClientData clientSavingsData = null; for (IndividualCollectionSheetLoanFlatData loanFlatData : loanFlatDatas) { @@ -890,9 +872,7 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe if (clientSavingsData == null || !clientSavingsData.equals(clientData)) { if (clientDatas.contains(clientData)) { final int index = clientDatas.indexOf(clientData); - if (index < 0) { - return; - } + if (index < 0) { return; } clientSavingsData = clientDatas.get(index); clientSavingsData.setLoans(new ArrayList()); } else { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/service/CollectionSheetWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/service/CollectionSheetWritePlatformServiceJpaRepositoryImpl.java index 19a9d2d18..e3a0f5ef0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/service/CollectionSheetWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/collectionsheet/service/CollectionSheetWritePlatformServiceJpaRepositoryImpl.java @@ -63,7 +63,8 @@ public class CollectionSheetWritePlatformServiceJpaRepositoryImpl implements Col final CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer bulkDisbursalCommandFromApiJsonDeserializer, final CollectionSheetTransactionDataValidator transactionDataValidator, final MeetingWritePlatformService meetingWritePlatformService, final DepositAccountAssembler accountAssembler, - final DepositAccountWritePlatformService accountWritePlatformService, final PaymentDetailAssembler paymentDetailAssembler, final PaymentDetailWritePlatformService paymentDetailWritePlatformService) { + final DepositAccountWritePlatformService accountWritePlatformService, final PaymentDetailAssembler paymentDetailAssembler, + final PaymentDetailWritePlatformService paymentDetailWritePlatformService) { this.loanWritePlatformService = loanWritePlatformService; this.bulkRepaymentCommandFromApiJsonDeserializer = bulkRepaymentCommandFromApiJsonDeserializer; this.bulkDisbursalCommandFromApiJsonDeserializer = bulkDisbursalCommandFromApiJsonDeserializer; @@ -157,7 +158,8 @@ public class CollectionSheetWritePlatformServiceJpaRepositoryImpl implements Col List depositTransactionIds = new ArrayList<>(); for (SavingsAccountTransactionDTO savingsAccountTransactionDTO : savingsTransactions) { try { - SavingsAccountTransaction savingsAccountTransaction = this.accountWritePlatformService.mandatorySavingsAccountDeposit(savingsAccountTransactionDTO); + SavingsAccountTransaction savingsAccountTransaction = this.accountWritePlatformService + .mandatorySavingsAccountDeposit(savingsAccountTransactionDTO); depositTransactionIds.add(savingsAccountTransaction.getId()); } catch (Exception e) { // TODO: handle exception diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/BusinessEventNotificationConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/BusinessEventNotificationConstants.java old mode 100755 new mode 100644 index d20d35612..225eba44e --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/BusinessEventNotificationConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/BusinessEventNotificationConstants.java @@ -24,21 +24,48 @@ import java.util.Set; public class BusinessEventNotificationConstants { public static enum BusinessEvents { + LOAN_APPROVED("loan_approved"), LOAN_REJECTED("loan_reject"), LOAN_UNDO_APPROVAL("loan_undo_approval"), LOAN_UNDO_DISBURSAL( - "loan_undo_disbursal"), LOAN_UNDO_LASTDISBURSAL("loan_undo_lastdisbursal"), LOAN_UNDO_TRANSACTION("loan_undo_transaction"), LOAN_ADJUST_TRANSACTION( - "loan_adjust_transaction"), LOAN_MAKE_REPAYMENT("loan_repayment_transaction"), LOAN_WRITTEN_OFF("loan_writtenoff"), LOAN_UNDO_WRITTEN_OFF( - "loan_undo_writtenoff"), LOAN_DISBURSAL("loan_disbursal"), LOAN_WAIVE_INTEREST("loan_waive_interest"), LOAN_CLOSE( - "loan_close"), LOAN_CLOSE_AS_RESCHEDULE("loan_close_as_reschedule"), LOAN_ADD_CHARGE("loan_add_charge"), LOAN_UPDATE_CHARGE( - "loan_update_charge"), LOAN_WAIVE_CHARGE("loan_waive_charge"), LOAN_DELETE_CHARGE("loan_delete_charge"), LOAN_CHARGE_PAYMENT( - "loan_charge_payment"), LOAN_INITIATE_TRANSFER("loan_initiate_transfer"), LOAN_ACCEPT_TRANSFER("loan_accept_transfer"), LOAN_WITHDRAW_TRANSFER( - "loan_withdraw_transfer"), LOAN_REJECT_TRANSFER("loan_reject_transfer"), LOAN_REASSIGN_OFFICER("loan_reassign_officer"), LOAN_REMOVE_OFFICER( - "loan_remove_officer"), LOAN_APPLY_OVERDUE_CHARGE("loan_apply_overdue_charge"), LOAN_INTEREST_RECALCULATION("loan_interest_recalculation"), - LOAN_REFUND("loan_refund"), LOAN_FORECLOSURE("loan_foreclosure"), LOAN_CREATE("loan_create"), LOAN_PRODUCT_CREATE("loan_product_create"), SAVINGS_ACTIVATE("savings_activated"), - SAVINGS_REJECT("savings_reject"), SAVINGS_POST_INTEREST("savings_post_interest"), SAVINGS_DEPOSIT("savings_deposit"), SAVINGS_CLOSE("savings_close"), - SAVINGS_WITHDRAWAL("savings_withdrawal"), SAVINGS_APPROVE("savings_approve"), SAVINGS_CREATE("savings_create"), CLIENTS_ACTIVATE("clients_activate"), SHARE_ACCOUNT_CREATE("share_account_create"), - CLIENTS_REJECT("clients_reject"), CLIENTS_CREATE("clients_create"),CENTERS_CREATE("centers_create"), GROUPS_CREATE("groups_create"), - SHARE_PRODUCT_DIVIDENDS_CREATE("share_product_dividends_create"),FIXED_DEPOSIT_ACCOUNT_CREATE("fixed_deposit_account_create"), - SHARE_ACCOUNT_APPROVE("share_account_approve"), RECURRING_DEPOSIT_ACCOUNT_CREATE("recurring_deposit_account_create"); + "loan_undo_disbursal"), LOAN_UNDO_LASTDISBURSAL("loan_undo_lastdisbursal"), LOAN_UNDO_TRANSACTION( + "loan_undo_transaction"), LOAN_ADJUST_TRANSACTION("loan_adjust_transaction"), LOAN_MAKE_REPAYMENT( + "loan_repayment_transaction"), LOAN_WRITTEN_OFF("loan_writtenoff"), LOAN_UNDO_WRITTEN_OFF( + "loan_undo_writtenoff"), LOAN_DISBURSAL("loan_disbursal"), LOAN_WAIVE_INTEREST( + "loan_waive_interest"), LOAN_CLOSE("loan_close"), LOAN_CLOSE_AS_RESCHEDULE( + "loan_close_as_reschedule"), LOAN_ADD_CHARGE("loan_add_charge"), LOAN_UPDATE_CHARGE( + "loan_update_charge"), LOAN_WAIVE_CHARGE( + "loan_waive_charge"), LOAN_DELETE_CHARGE( + "loan_delete_charge"), LOAN_CHARGE_PAYMENT( + "loan_charge_payment"), LOAN_INITIATE_TRANSFER( + "loan_initiate_transfer"), LOAN_ACCEPT_TRANSFER( + "loan_accept_transfer"), LOAN_WITHDRAW_TRANSFER( + "loan_withdraw_transfer"), LOAN_REJECT_TRANSFER( + "loan_reject_transfer"), LOAN_REASSIGN_OFFICER( + "loan_reassign_officer"), LOAN_REMOVE_OFFICER( + "loan_remove_officer"), LOAN_APPLY_OVERDUE_CHARGE( + "loan_apply_overdue_charge"), LOAN_INTEREST_RECALCULATION( + "loan_interest_recalculation"), LOAN_REFUND( + "loan_refund"), LOAN_FORECLOSURE( + "loan_foreclosure"), LOAN_CREATE( + "loan_create"), LOAN_PRODUCT_CREATE( + "loan_product_create"), SAVINGS_ACTIVATE( + "savings_activated"), SAVINGS_REJECT( + "savings_reject"), SAVINGS_POST_INTEREST( + "savings_post_interest"), SAVINGS_DEPOSIT( + "savings_deposit"), SAVINGS_CLOSE( + "savings_close"), SAVINGS_WITHDRAWAL( + "savings_withdrawal"), SAVINGS_APPROVE( + "savings_approve"), SAVINGS_CREATE( + "savings_create"), CLIENTS_ACTIVATE( + "clients_activate"), SHARE_ACCOUNT_CREATE( + "share_account_create"), CLIENTS_REJECT( + "clients_reject"), CLIENTS_CREATE( + "clients_create"), CENTERS_CREATE( + "centers_create"), GROUPS_CREATE( + "groups_create"), SHARE_PRODUCT_DIVIDENDS_CREATE( + "share_product_dividends_create"), FIXED_DEPOSIT_ACCOUNT_CREATE( + "fixed_deposit_account_create"), SHARE_ACCOUNT_APPROVE( + "share_account_approve"), RECURRING_DEPOSIT_ACCOUNT_CREATE( + "recurring_deposit_account_create"); private final String value; @@ -63,9 +90,11 @@ public class BusinessEventNotificationConstants { } public static enum BusinessEntity { + LOAN("loan"), LOAN_TRANSACTION("loan_transaction"), LOAN_CHARGE("loan_charge"), LOAN_ADJUSTED_TRANSACTION( - "loan_adjusted_transaction"), SAVING("saving"), CLIENT("client"), SAVINGS_TRANSACTION("Savings Transaction"), GROUP("group"), - SHARE_ACCOUNT("share_account"), SHARE_PRODUCT("share_product"), DEPOSIT_ACCOUNT("deposit_account"), LOAN_PRODUCT("loan_product"); + "loan_adjusted_transaction"), SAVING("saving"), CLIENT("client"), SAVINGS_TRANSACTION("Savings Transaction"), GROUP( + "group"), SHARE_ACCOUNT("share_account"), SHARE_PRODUCT( + "share_product"), DEPOSIT_ACCOUNT("deposit_account"), LOAN_PRODUCT("loan_product"); private final String value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DayOfWeekType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DayOfWeekType.java old mode 100755 new mode 100644 index fdf0b0555..975a80eb8 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DayOfWeekType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DayOfWeekType.java @@ -22,14 +22,10 @@ import org.joda.time.DateTimeConstants; public enum DayOfWeekType { - MONDAY(DateTimeConstants.MONDAY, "weekDayType.monday"), - TUESDAY(DateTimeConstants.TUESDAY, "weekDayType.tuesday"), - WEDNESDAY(DateTimeConstants.WEDNESDAY, "weekDayType.wednesday"), - THURSDAY(DateTimeConstants.THURSDAY, "weekDayType.thursday"), - FRIDAY(DateTimeConstants.FRIDAY, "weekDayType.friday"), - SATURDAY(DateTimeConstants.SATURDAY, "weekDayType.saturday"), - SUNDAY(DateTimeConstants.SUNDAY, "weekDayType.sunday"), - INVALID(0, "weekDayType.invalid"); + MONDAY(DateTimeConstants.MONDAY, "weekDayType.monday"), TUESDAY(DateTimeConstants.TUESDAY, "weekDayType.tuesday"), WEDNESDAY( + DateTimeConstants.WEDNESDAY, "weekDayType.wednesday"), THURSDAY(DateTimeConstants.THURSDAY, "weekDayType.thursday"), FRIDAY( + DateTimeConstants.FRIDAY, "weekDayType.friday"), SATURDAY(DateTimeConstants.SATURDAY, "weekDayType.saturday"), SUNDAY( + DateTimeConstants.SUNDAY, "weekDayType.sunday"), INVALID(0, "weekDayType.invalid"); private final Integer value; private final String code; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DaysInMonthType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DaysInMonthType.java old mode 100755 new mode 100644 index 5171766fa..f2e0474eb --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DaysInMonthType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DaysInMonthType.java @@ -17,6 +17,7 @@ * under the License. */ package org.apache.fineract.portfolio.common.domain; + import java.util.ArrayList; import java.util.List; @@ -81,4 +82,4 @@ public enum DaysInMonthType { public boolean isDaysInMonth_30() { return DaysInMonthType.DAYS_30.getValue().equals(this.value); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DaysInYearType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DaysInYearType.java old mode 100755 new mode 100644 index 38401aadc..f80bf73d3 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DaysInYearType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/DaysInYearType.java @@ -91,4 +91,4 @@ public enum DaysInYearType { public boolean isActual() { return DaysInYearType.ACTUAL.getValue().equals(this.value); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/NthDayType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/NthDayType.java old mode 100755 new mode 100644 index 3c797feba..4e5d5ff00 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/NthDayType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/NthDayType.java @@ -20,14 +20,8 @@ package org.apache.fineract.portfolio.common.domain; public enum NthDayType { - ONE(1,"nthDayType.one"), - TWO(2,"nthDayType.two"), - THREE(3,"nthDayType.three"), - FOUR(4,"nthDayType.four"), - FIVE(5,"nthDayType.five"), - LAST(-1,"nthDayType.last"), - ONDAY(-2,"nthDayType.onday"), - INVALID(0,"nthDayType.invalid"); + ONE(1, "nthDayType.one"), TWO(2, "nthDayType.two"), THREE(3, "nthDayType.three"), FOUR(4, "nthDayType.four"), FIVE(5, + "nthDayType.five"), LAST(-1, "nthDayType.last"), ONDAY(-2, "nthDayType.onday"), INVALID(0, "nthDayType.invalid"); private final Integer value; private final String code; @@ -80,9 +74,11 @@ public enum NthDayType { public boolean isInvalid() { return this.value.equals(NthDayType.INVALID.value); } + public boolean isLastDay() { return this.value.equals(NthDayType.LAST.value); } + public boolean isOnDay() { return this.value.equals(NthDayType.ONDAY.value); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/PeriodFrequencyType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/PeriodFrequencyType.java index 09021ff77..58a638eb2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/PeriodFrequencyType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/domain/PeriodFrequencyType.java @@ -21,8 +21,8 @@ package org.apache.fineract.portfolio.common.domain; import java.util.ArrayList; import java.util.List; - public enum PeriodFrequencyType { + DAYS(0, "periodFrequencyType.days"), // WEEKS(1, "periodFrequencyType.weeks"), // MONTHS(2, "periodFrequencyType.months"), // @@ -63,7 +63,7 @@ public enum PeriodFrequencyType { repaymentFrequencyType = PeriodFrequencyType.YEARS; break; case 4: - repaymentFrequencyType = PeriodFrequencyType.WHOLE_TERM; + repaymentFrequencyType = PeriodFrequencyType.WHOLE_TERM; break; } } @@ -87,8 +87,9 @@ public enum PeriodFrequencyType { } public boolean isWholeTerm() { - return this.value.equals(PeriodFrequencyType.WHOLE_TERM.getValue()); + return this.value.equals(PeriodFrequencyType.WHOLE_TERM.getValue()); } + public boolean isInvalid() { return this.value.equals(PeriodFrequencyType.INVALID.getValue()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/BusinessEventNotifierServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/BusinessEventNotifierServiceImpl.java old mode 100755 new mode 100644 index 17e07fd26..7d2d318a5 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/BusinessEventNotifierServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/BusinessEventNotifierServiceImpl.java @@ -39,8 +39,7 @@ public class BusinessEventNotifierServiceImpl implements BusinessEventNotifierSe * org.apache.fineract.portfolio.common.service.BusinessEventNotifierService * #notifyBusinessEventToBeExecuted * (org.apache.fineract.portfolio.common.BusinessEventNotificationConstants - * .BusinessEvents, - * org.springframework.data.jpa.domain.AbstractPersistable) + * .BusinessEvents, org.springframework.data.jpa.domain.AbstractPersistable) */ @Override public void notifyBusinessEventToBeExecuted(BusinessEvents businessEvent, Map businessEventEntity) { @@ -59,8 +58,7 @@ public class BusinessEventNotifierServiceImpl implements BusinessEventNotifierSe * org.apache.fineract.portfolio.common.service.BusinessEventNotifierService * #notifyBusinessEventWasExecuted * (org.apache.fineract.portfolio.common.BusinessEventNotificationConstants - * .BusinessEvents, - * org.springframework.data.jpa.domain.AbstractPersistable) + * .BusinessEvents, org.springframework.data.jpa.domain.AbstractPersistable) */ @Override public void notifyBusinessEventWasExecuted(BusinessEvents businessEvent, Map businessEventEntity) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/CommonEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/CommonEnumerations.java old mode 100755 new mode 100644 index b2da63c79..7e2967e00 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/CommonEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/CommonEnumerations.java @@ -49,20 +49,20 @@ public class CommonEnumerations { EnumOptionData optionData = null; switch (type) { case DAYS: - optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + PeriodFrequencyType.DAYS.getCode(), "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"); + 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"); + 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"); + optionData = new EnumOptionData(PeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + PeriodFrequencyType.YEARS.getCode(), "Years"); break; default: optionData = new EnumOptionData(PeriodFrequencyType.INVALID.getValue().longValue(), PeriodFrequencyType.INVALID.getCode(), @@ -84,16 +84,16 @@ public class CommonEnumerations { "equal"); break; case NOT_EQUAL: - optionData = new EnumOptionData(ConditionType.NOT_EQUAL.getValue().longValue(), codePrefix - + ConditionType.NOT_EQUAL.getCode(), "notEqual"); + optionData = new EnumOptionData(ConditionType.NOT_EQUAL.getValue().longValue(), + codePrefix + ConditionType.NOT_EQUAL.getCode(), "notEqual"); break; case GRETERTHAN: - optionData = new EnumOptionData(ConditionType.GRETERTHAN.getValue().longValue(), codePrefix - + ConditionType.GRETERTHAN.getCode(), "greterthan"); + optionData = new EnumOptionData(ConditionType.GRETERTHAN.getValue().longValue(), + codePrefix + ConditionType.GRETERTHAN.getCode(), "greterthan"); break; case LESSTHAN: - optionData = new EnumOptionData(ConditionType.LESSTHAN.getValue().longValue(), codePrefix - + ConditionType.LESSTHAN.getCode(), "lessthan"); + optionData = new EnumOptionData(ConditionType.LESSTHAN.getValue().longValue(), + codePrefix + ConditionType.LESSTHAN.getCode(), "lessthan"); break; default: optionData = new EnumOptionData(ConditionType.INVALID.getValue().longValue(), ConditionType.INVALID.getCode(), "Invalid"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/DropdownReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/DropdownReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 1a6adc589..b35055996 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/DropdownReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/common/service/DropdownReadPlatformServiceImpl.java @@ -39,7 +39,7 @@ public class DropdownReadPlatformServiceImpl implements DropdownReadPlatformServ public List retrievePeriodFrequencyTypeOptions() { final List loanTermFrequencyOptions = Arrays.asList(termFrequencyType(PeriodFrequencyType.DAYS, "frequency"), termFrequencyType(PeriodFrequencyType.WEEKS, "frequency"), termFrequencyType(PeriodFrequencyType.MONTHS, "frequency"), - termFrequencyType(PeriodFrequencyType.YEARS, "frequency"), termFrequencyType(PeriodFrequencyType.WHOLE_TERM, "frequency")); + termFrequencyType(PeriodFrequencyType.YEARS, "frequency"), termFrequencyType(PeriodFrequencyType.WHOLE_TERM, "frequency")); return loanTermFrequencyOptions; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/api/FloatingRatesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/api/FloatingRatesApiResource.java index ebed60aa1..0005dab47 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/api/FloatingRatesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/api/FloatingRatesApiResource.java @@ -58,20 +58,16 @@ import org.springframework.stereotype.Component; @Path("/floatingrates") @Component @Scope("singleton") -@Api(tags = {"Floating Rates"}) +@Api(tags = { "Floating Rates" }) @SwaggerDefinition(tags = { - @Tag(name = "Floating Rates", description = "It lets you create, list, retrieve and upload the floating rates") -}) + @Tag(name = "Floating Rates", description = "It lets you create, list, retrieve and upload the floating rates") }) public class FloatingRatesApiResource { private static final String RESOURCE_NAME = "FLOATINGRATE"; private static final Set LIST_FLOATING_RATES_PARAMETERS = new HashSet<>( - Arrays.asList("id", "name", "isBaseLendingRate", "isActive", - "createdby", "createdOn", "modifiedBy", "modifiedOn")); - private static final Set INDIVIDUAL_FLOATING_RATES_PARAMETERS = new HashSet<>( - Arrays.asList("id", "name", "isBaseLendingRate", "isActive", - "createdBy", "createdOn", "modifiedBy", "modifiedOn", - "ratePeriods")); + Arrays.asList("id", "name", "isBaseLendingRate", "isActive", "createdby", "createdOn", "modifiedBy", "modifiedOn")); + private static final Set INDIVIDUAL_FLOATING_RATES_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "isBaseLendingRate", + "isActive", "createdBy", "createdOn", "modifiedBy", "modifiedOn", "ratePeriods")); private final PlatformSecurityContext context; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final DefaultToApiJsonSerializer toApiJsonSerializer; @@ -79,8 +75,7 @@ public class FloatingRatesApiResource { private final ApiRequestParameterHelper apiRequestParameterHelper; @Autowired - public FloatingRatesApiResource( - final PlatformSecurityContext context, + public FloatingRatesApiResource(final PlatformSecurityContext context, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, @@ -95,15 +90,15 @@ public class FloatingRatesApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a new Floating Rate", httpMethod = "POST", notes = "Creates a new Floating Rate\n" + "Mandatory Fields: name\n" + "Optional Fields: isBaseLendingRate, isActive, ratePeriods") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FloatingRatesApiResourceSwagger.PostFloatingRatesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FloatingRatesApiResourceSwagger.PostFloatingRatesResponse.class)}) + @ApiOperation(value = "Create a new Floating Rate", httpMethod = "POST", notes = "Creates a new Floating Rate\n" + + "Mandatory Fields: name\n" + "Optional Fields: isBaseLendingRate, isActive, ratePeriods") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FloatingRatesApiResourceSwagger.PostFloatingRatesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = FloatingRatesApiResourceSwagger.PostFloatingRatesResponse.class) }) public String createFloatingRate(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .createFloatingRate().withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandWrapper commandRequest = new CommandWrapperBuilder().createFloatingRate().withJson(apiRequestBodyAsJson).build(); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } @@ -111,16 +106,13 @@ public class FloatingRatesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "List Floating Rates", httpMethod = "GET", notes = "Lists Floating Rates") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FloatingRatesApiResourceSwagger.GetFloatingRatesResponse.class, responseContainer = "List")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FloatingRatesApiResourceSwagger.GetFloatingRatesResponse.class, responseContainer = "List") }) public String retrieveAll(@Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission( - RESOURCE_NAME); - final List floatingRates = this.floatingRatesReadPlatformService - .retrieveAll(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, floatingRates, - FloatingRatesApiResource.LIST_FLOATING_RATES_PARAMETERS); + this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME); + final List floatingRates = this.floatingRatesReadPlatformService.retrieveAll(); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, floatingRates, FloatingRatesApiResource.LIST_FLOATING_RATES_PARAMETERS); } @GET @@ -128,18 +120,14 @@ public class FloatingRatesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieve Floating Rate", httpMethod = "GET", notes = "Retrieves Floating Rate") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FloatingRatesApiResourceSwagger.GetFloatingRatesFloatingRateIdResponse.class)}) - public String retrieveOne( - @PathParam("floatingRateId") @ApiParam(value = "floatingRateId") final Long floatingRateId, + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FloatingRatesApiResourceSwagger.GetFloatingRatesFloatingRateIdResponse.class) }) + public String retrieveOne(@PathParam("floatingRateId") @ApiParam(value = "floatingRateId") final Long floatingRateId, @Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission( - RESOURCE_NAME); - final FloatingRateData floatingRates = this.floatingRatesReadPlatformService - .retrieveOne(floatingRateId); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, floatingRates, - FloatingRatesApiResource.INDIVIDUAL_FLOATING_RATES_PARAMETERS); + this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME); + final FloatingRateData floatingRates = this.floatingRatesReadPlatformService.retrieveOne(floatingRateId); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, floatingRates, FloatingRatesApiResource.INDIVIDUAL_FLOATING_RATES_PARAMETERS); } @PUT @@ -147,16 +135,15 @@ public class FloatingRatesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update Floating Rate", httpMethod = "PUT", notes = "Updates new Floating Rate. Rate Periods in the past cannot be modified. All the future rateperiods would be replaced with the new ratePeriods data sent.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FloatingRatesApiResourceSwagger.PutFloatingRatesFloatingRateIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FloatingRatesApiResourceSwagger.PutFloatingRatesFloatingRateIdResponse.class)}) - public String updateFloatingRate( - @PathParam("floatingRateId") @ApiParam(value = "floatingRateId") final Long floatingRateId, + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FloatingRatesApiResourceSwagger.PutFloatingRatesFloatingRateIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FloatingRatesApiResourceSwagger.PutFloatingRatesFloatingRateIdResponse.class) }) + public String updateFloatingRate(@PathParam("floatingRateId") @ApiParam(value = "floatingRateId") final Long floatingRateId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .updateFloatingRate(floatingRateId) - .withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateFloatingRate(floatingRateId).withJson(apiRequestBodyAsJson) + .build(); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/api/FloatingRatesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/api/FloatingRatesApiResourceSwagger.java index cf89c1adc..dc20408c8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/api/FloatingRatesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/api/FloatingRatesApiResourceSwagger.java @@ -26,17 +26,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/17/17. */ final class FloatingRatesApiResourceSwagger { - private FloatingRatesApiResourceSwagger() { - } + + private FloatingRatesApiResourceSwagger() {} @ApiModel(value = "PostFloatingRatesRequest") public final static class PostFloatingRatesRequest { - private PostFloatingRatesRequest() { - } + + private PostFloatingRatesRequest() {} final class PostFloatingRatesRatePeriods { - private PostFloatingRatesRatePeriods() { - } + + private PostFloatingRatesRatePeriods() {} @ApiModelProperty(example = "19 November 2015") public String fromDate; @@ -59,8 +59,8 @@ final class FloatingRatesApiResourceSwagger { @ApiModel(value = "PostFloatingRatesResponse") public final static class PostFloatingRatesResponse { - private PostFloatingRatesResponse() { - } + + private PostFloatingRatesResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -68,8 +68,8 @@ final class FloatingRatesApiResourceSwagger { @ApiModel(value = "GetFloatingRatesResponse") public final static class GetFloatingRatesResponse { - private GetFloatingRatesResponse() { - } + + private GetFloatingRatesResponse() {} @ApiModelProperty(example = "1") public Integer id; @@ -91,12 +91,12 @@ final class FloatingRatesApiResourceSwagger { @ApiModel(value = "GetFloatingRatesFloatingRateIdResponse") public final static class GetFloatingRatesFloatingRateIdResponse { - private GetFloatingRatesFloatingRateIdResponse() { - } + + private GetFloatingRatesFloatingRateIdResponse() {} final class GetFloatingRatesRatePeriods { - private GetFloatingRatesRatePeriods() { - } + + private GetFloatingRatesRatePeriods() {} @ApiModelProperty(example = "1") public Integer id; @@ -139,8 +139,8 @@ final class FloatingRatesApiResourceSwagger { @ApiModel(value = "PutFloatingRatesFloatingRateIdRequest") public final static class PutFloatingRatesFloatingRateIdRequest { - private PutFloatingRatesFloatingRateIdRequest() { - } + + private PutFloatingRatesFloatingRateIdRequest() {} @ApiModelProperty(example = "Floating Rate 1") public String name; @@ -153,12 +153,12 @@ final class FloatingRatesApiResourceSwagger { @ApiModel(value = "PutFloatingRatesFloatingRateIdResponse") public final static class PutFloatingRatesFloatingRateIdResponse { - private PutFloatingRatesFloatingRateIdResponse() { - } + + private PutFloatingRatesFloatingRateIdResponse() {} final class PutFloatingRatesChanges { - private PutFloatingRatesChanges() { - } + + private PutFloatingRatesChanges() {} public Set ratePeriods; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/FloatingRateData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/FloatingRateData.java index 37a7b4ee3..fbbcf9f37 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/FloatingRateData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/FloatingRateData.java @@ -26,7 +26,7 @@ import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.fineract.infrastructure.core.data.EnumOptionData; import org.joda.time.LocalDate; -public class FloatingRateData implements Comparable , Serializable { +public class FloatingRateData implements Comparable, Serializable { private final Long id; private final String name; @@ -40,10 +40,8 @@ public class FloatingRateData implements Comparable , Serializ @SuppressWarnings("unused") private final List interestRateFrequencyTypeOptions; - public FloatingRateData(Long id, String name, boolean isBaseLendingRate, - boolean isActive, String createdBy, LocalDate createdOn, - String modifiedBy, LocalDate modifiedOn, - List ratePeriods, + public FloatingRateData(Long id, String name, boolean isBaseLendingRate, boolean isActive, String createdBy, LocalDate createdOn, + String modifiedBy, LocalDate modifiedOn, List ratePeriods, List interestRateFrequencyTypeOptions) { this.id = id; this.name = name; @@ -95,9 +93,7 @@ public class FloatingRateData implements Comparable , Serializ @Override public int compareTo(final FloatingRateData obj) { - if (obj == null) { - return -1; - } + if (obj == null) { return -1; } return new CompareToBuilder() // .append(this.id, obj.id) // .append(this.name, obj.name) // @@ -108,15 +104,9 @@ public class FloatingRateData implements Comparable , Serializ @Override public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (!(obj instanceof FloatingRateData)) { - return false; - } + if (obj == null) { return false; } + if (obj == this) { return true; } + if (!(obj instanceof FloatingRateData)) { return false; } final FloatingRateData rhs = (FloatingRateData) obj; return new EqualsBuilder() // .append(this.id, rhs.id) // @@ -136,10 +126,8 @@ public class FloatingRateData implements Comparable , Serializ .toHashCode(); } - public static FloatingRateData toTemplate( - List interestRateFrequencyTypeOptions) { + public static FloatingRateData toTemplate(List interestRateFrequencyTypeOptions) { // TODO Auto-generated method stub - return new FloatingRateData(null, null, false, true, null, null, null, - null, null, interestRateFrequencyTypeOptions); + return new FloatingRateData(null, null, false, true, null, null, null, null, null, interestRateFrequencyTypeOptions); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/FloatingRatePeriodData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/FloatingRatePeriodData.java index 9b446b05e..2ddf0db07 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/FloatingRatePeriodData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/FloatingRatePeriodData.java @@ -25,8 +25,7 @@ import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.joda.time.LocalDate; -public class FloatingRatePeriodData implements - Comparable, Serializable { +public class FloatingRatePeriodData implements Comparable, Serializable { private Long id; private LocalDate fromDate; @@ -38,10 +37,8 @@ public class FloatingRatePeriodData implements private String modifiedBy; private LocalDate modifiedOn; - public FloatingRatePeriodData(Long id, LocalDate fromDate, - BigDecimal interestRate, boolean isDifferentialToBaseLendingRate, - boolean isActive, String createdBy, LocalDate createdOn, - String modifiedBy, LocalDate modifiedOn) { + public FloatingRatePeriodData(Long id, LocalDate fromDate, BigDecimal interestRate, boolean isDifferentialToBaseLendingRate, + boolean isActive, String createdBy, LocalDate createdOn, String modifiedBy, LocalDate modifiedOn) { this.id = id; this.fromDate = fromDate; this.interestRate = interestRate; @@ -95,9 +92,7 @@ public class FloatingRatePeriodData implements @Override public int compareTo(final FloatingRatePeriodData obj) { - if (obj == null) { - return -1; - } + if (obj == null) { return -1; } return new CompareToBuilder() // .append(this.id, obj.id) // .append(this.fromDate, obj.fromDate) // @@ -107,15 +102,9 @@ public class FloatingRatePeriodData implements @Override public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (!(obj instanceof FloatingRatePeriodData)) { - return false; - } + if (obj == null) { return false; } + if (obj == this) { return true; } + if (!(obj instanceof FloatingRatePeriodData)) { return false; } final FloatingRatePeriodData rhs = (FloatingRatePeriodData) obj; return new EqualsBuilder() // .append(this.id, rhs.id) // diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/InterestRatePeriodData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/InterestRatePeriodData.java index ebc9b022f..d52d28fa9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/InterestRatePeriodData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/data/InterestRatePeriodData.java @@ -32,8 +32,7 @@ public class InterestRatePeriodData { private BigDecimal loanProductDifferentialInterestRate; private BigDecimal effectiveInterestRate; - public InterestRatePeriodData(Date fromDate, BigDecimal interestRate, - boolean isDifferentialToBLR, Date blrFromDate, + public InterestRatePeriodData(Date fromDate, BigDecimal interestRate, boolean isDifferentialToBLR, Date blrFromDate, BigDecimal blrInterestRate) { this.fromDate = fromDate; this.interestRate = interestRate; @@ -70,8 +69,7 @@ public class InterestRatePeriodData { return this.loanDifferentialInterestRate; } - public void setLoanDifferentialInterestRate( - BigDecimal loanDifferentialInterestRate) { + public void setLoanDifferentialInterestRate(BigDecimal loanDifferentialInterestRate) { this.loanDifferentialInterestRate = loanDifferentialInterestRate; } @@ -79,8 +77,7 @@ public class InterestRatePeriodData { return this.loanProductDifferentialInterestRate; } - public void setLoanProductDifferentialInterestRate( - BigDecimal loanProductDifferentialInterestRate) { + public void setLoanProductDifferentialInterestRate(BigDecimal loanProductDifferentialInterestRate) { this.loanProductDifferentialInterestRate = loanProductDifferentialInterestRate; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRate.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRate.java index 35fff2d56..65a0e1bf5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRate.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRate.java @@ -62,14 +62,14 @@ public class FloatingRate extends AbstractPersistableCustom { private boolean isActive; @OrderBy(value = "fromDate,id") - @OneToMany(cascade = CascadeType.ALL, mappedBy = "floatingRate", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "floatingRate", orphanRemoval = true, fetch = FetchType.EAGER) private List floatingRatePeriods; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "createdby_id", nullable = false) private AppUser createdBy; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "lastmodifiedby_id", nullable = false) private AppUser modifiedBy; @@ -83,10 +83,8 @@ public class FloatingRate extends AbstractPersistableCustom { } - public FloatingRate(String name, boolean isBaseLendingRate, - boolean isActive, List floatingRatePeriods, - AppUser createdBy, AppUser modifiedBy, Date createdOn, - Date modifiedOn) { + public FloatingRate(String name, boolean isBaseLendingRate, boolean isActive, List floatingRatePeriods, + AppUser createdBy, AppUser modifiedBy, Date createdOn, Date modifiedOn) { this.name = name; this.isBaseLendingRate = isBaseLendingRate; this.isActive = isActive; @@ -102,48 +100,35 @@ public class FloatingRate extends AbstractPersistableCustom { } } - public static FloatingRate createNew(AppUser currentUser, - JsonCommand command) { + public static FloatingRate createNew(AppUser currentUser, JsonCommand command) { final String name = command.stringValueOfParameterNamed("name"); - final boolean isBaseLendingRate = command - .parameterExists("isBaseLendingRate") ? command - .booleanPrimitiveValueOfParameterNamed("isBaseLendingRate") + final boolean isBaseLendingRate = command.parameterExists("isBaseLendingRate") + ? command.booleanPrimitiveValueOfParameterNamed("isBaseLendingRate") : false; - final boolean isActive = command.parameterExists("isActive") ? command - .booleanPrimitiveValueOfParameterNamed("isActive") : true; - final List floatingRatePeriods = getRatePeriods( - currentUser, command); + final boolean isActive = command.parameterExists("isActive") ? command.booleanPrimitiveValueOfParameterNamed("isActive") : true; + final List floatingRatePeriods = getRatePeriods(currentUser, command); final LocalDate currentDate = DateUtils.getLocalDateOfTenant(); - return new FloatingRate(name, isBaseLendingRate, isActive, - floatingRatePeriods, currentUser, currentUser, - currentDate.toDate(), currentDate.toDate()); + return new FloatingRate(name, isBaseLendingRate, isActive, floatingRatePeriods, currentUser, currentUser, currentDate.toDate(), + currentDate.toDate()); } - private static List getRatePeriods( - final AppUser currentUser, final JsonCommand command) { - if (!command.parameterExists("ratePeriods")) { - return null; - } + private static List getRatePeriods(final AppUser currentUser, final JsonCommand command) { + if (!command.parameterExists("ratePeriods")) { return null; } List ratePeriods = new ArrayList<>(); - JsonArray arrayOfParameterNamed = command - .arrayOfParameterNamed("ratePeriods"); + JsonArray arrayOfParameterNamed = command.arrayOfParameterNamed("ratePeriods"); for (final JsonElement ratePeriod : arrayOfParameterNamed) { final JsonObject ratePeriodObject = ratePeriod.getAsJsonObject(); final JsonParserHelper helper = new JsonParserHelper(); - final Date fromDate = helper.extractLocalDateNamed("fromDate", - ratePeriod, new HashSet()).toDate(); - final BigDecimal interestRate = ratePeriodObject - .get("interestRate").getAsBigDecimal(); - final boolean isDifferentialToBaseLendingRate = helper - .parameterExists("isDifferentialToBaseLendingRate", - ratePeriod) ? ratePeriodObject.get( - "isDifferentialToBaseLendingRate").getAsBoolean() : false; + final Date fromDate = helper.extractLocalDateNamed("fromDate", ratePeriod, new HashSet()).toDate(); + final BigDecimal interestRate = ratePeriodObject.get("interestRate").getAsBigDecimal(); + final boolean isDifferentialToBaseLendingRate = helper.parameterExists("isDifferentialToBaseLendingRate", ratePeriod) + ? ratePeriodObject.get("isDifferentialToBaseLendingRate").getAsBoolean() + : false; final boolean isActive = true; final Date currentDate = DateUtils.getDateOfTenant(); - ratePeriods.add(new FloatingRatePeriod(fromDate, interestRate, - isDifferentialToBaseLendingRate, isActive, currentUser, + ratePeriods.add(new FloatingRatePeriod(fromDate, interestRate, isDifferentialToBaseLendingRate, isActive, currentUser, currentUser, currentDate, currentDate)); } @@ -182,8 +167,7 @@ public class FloatingRate extends AbstractPersistableCustom { return this.modifiedOn; } - public Map update(final JsonCommand command, - final AppUser appUser) { + public Map update(final JsonCommand command, final AppUser appUser) { final Map actualChanges = new LinkedHashMap<>(9); @@ -193,39 +177,32 @@ public class FloatingRate extends AbstractPersistableCustom { this.name = newValue; } - if (command.isChangeInBooleanParameterNamed("isBaseLendingRate", - this.isBaseLendingRate)) { - final boolean newValue = command - .booleanPrimitiveValueOfParameterNamed("isBaseLendingRate"); + if (command.isChangeInBooleanParameterNamed("isBaseLendingRate", this.isBaseLendingRate)) { + final boolean newValue = command.booleanPrimitiveValueOfParameterNamed("isBaseLendingRate"); actualChanges.put("isBaseLendingRate", newValue); this.isBaseLendingRate = newValue; } if (command.isChangeInBooleanParameterNamed("isActive", this.isActive)) { - final boolean newValue = command - .booleanPrimitiveValueOfParameterNamed("isActive"); + final boolean newValue = command.booleanPrimitiveValueOfParameterNamed("isActive"); actualChanges.put("isActive", newValue); this.isActive = newValue; } - final List newRatePeriods = getRatePeriods(appUser, - command); + final List newRatePeriods = getRatePeriods(appUser, command); if (newRatePeriods != null && !newRatePeriods.isEmpty()) { updateRatePeriods(newRatePeriods, appUser); - actualChanges.put("ratePeriods", - command.jsonFragment("ratePeriods")); + actualChanges.put("ratePeriods", command.jsonFragment("ratePeriods")); } return actualChanges; } - private void updateRatePeriods( - final List newRatePeriods, final AppUser appUser) { + private void updateRatePeriods(final List newRatePeriods, final AppUser appUser) { final LocalDate today = DateUtils.getLocalDateOfTenant(); if (this.floatingRatePeriods != null) { for (FloatingRatePeriod ratePeriod : this.floatingRatePeriods) { - LocalDate fromDate = LocalDate.fromDateFields(ratePeriod - .getFromDate()); + LocalDate fromDate = LocalDate.fromDateFields(ratePeriod.getFromDate()); if (fromDate.isAfter(today)) { ratePeriod.setActive(false); ratePeriod.setModifiedBy(appUser); @@ -239,31 +216,25 @@ public class FloatingRate extends AbstractPersistableCustom { } } - public Collection fetchInterestRates( - final FloatingRateDTO floatingRateDTO) { + public Collection fetchInterestRates(final FloatingRateDTO floatingRateDTO) { Collection applicableRates = new ArrayList<>(); FloatingRatePeriod previousPeriod = null; boolean addPeriodData = false; for (FloatingRatePeriod floatingRatePeriod : this.floatingRatePeriods) { if (floatingRatePeriod.isActive()) { // will enter - if (applicableRates.isEmpty() - && floatingRateDTO.getStartDate().isBefore( - floatingRatePeriod.fetchFromDate())) { + if (applicableRates.isEmpty() && floatingRateDTO.getStartDate().isBefore(floatingRatePeriod.fetchFromDate())) { if (floatingRateDTO.isFloatingInterestRate()) { addPeriodData = true; } if (previousPeriod != null) { - applicableRates.add(previousPeriod - .toData(floatingRateDTO)); + applicableRates.add(previousPeriod.toData(floatingRateDTO)); } else if (!addPeriodData) { - applicableRates.add(floatingRatePeriod - .toData(floatingRateDTO)); + applicableRates.add(floatingRatePeriod.toData(floatingRateDTO)); } } if (addPeriodData) { - applicableRates.add(floatingRatePeriod - .toData(floatingRateDTO)); + applicableRates.add(floatingRatePeriod.toData(floatingRateDTO)); } previousPeriod = floatingRatePeriod; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRatePeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRatePeriod.java index bf696b0c6..f1cc0b25c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRatePeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRatePeriod.java @@ -53,11 +53,11 @@ public class FloatingRatePeriod extends AbstractPersistableCustom { @Column(name = "is_active", nullable = false) private boolean isActive; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "createdby_id", nullable = false) private AppUser createdBy; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "lastmodifiedby_id", nullable = false) private AppUser modifiedBy; @@ -71,10 +71,8 @@ public class FloatingRatePeriod extends AbstractPersistableCustom { } - public FloatingRatePeriod(Date fromDate, BigDecimal interestRate, - boolean isDifferentialToBaseLendingRate, boolean isActive, - AppUser createdBy, AppUser modifiedBy, Date createdOn, - Date modifiedOn) { + public FloatingRatePeriod(Date fromDate, BigDecimal interestRate, boolean isDifferentialToBaseLendingRate, boolean isActive, + AppUser createdBy, AppUser modifiedBy, Date createdOn, Date modifiedOn) { this.fromDate = fromDate; this.interestRate = interestRate; this.isDifferentialToBaseLendingRate = isDifferentialToBaseLendingRate; @@ -143,21 +141,17 @@ public class FloatingRatePeriod extends AbstractPersistableCustom { public FloatingRatePeriodData toData(final FloatingRateDTO floatingRateDTO) { - BigDecimal interest = getInterestRate().add( - floatingRateDTO.getInterestRateDiff()); + BigDecimal interest = getInterestRate().add(floatingRateDTO.getInterestRateDiff()); if (isDifferentialToBaseLendingRate()) { - interest = interest.add(floatingRateDTO - .fetchBaseRate(fetchFromDate())); + interest = interest.add(floatingRateDTO.fetchBaseRate(fetchFromDate())); } final LocalDate fromDate = new LocalDateTime(getFromDate()).toLocalDate(); final LocalDate createdOn = new LocalDateTime(getCreatedOn()).toLocalDate(); final LocalDate modidiedOn = new LocalDateTime(getModifiedOn()).toLocalDate(); - return new FloatingRatePeriodData(getId(), fromDate, interest, - isDifferentialToBaseLendingRate(), isActive(), getCreatedBy() - .getUsername(), createdOn, getModifiedBy() - .getUsername(), modidiedOn); + return new FloatingRatePeriodData(getId(), fromDate, interest, isDifferentialToBaseLendingRate(), isActive(), + getCreatedBy().getUsername(), createdOn, getModifiedBy().getUsername(), modidiedOn); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRateRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRateRepository.java index b0a8a3ba2..690d33c42 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRateRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRateRepository.java @@ -23,18 +23,14 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; -public interface FloatingRateRepository extends - JpaRepository, - JpaSpecificationExecutor { +public interface FloatingRateRepository extends JpaRepository, JpaSpecificationExecutor { @Query("select floatingRate from FloatingRate floatingRate where floatingRate.isBaseLendingRate = true and floatingRate.isActive = true") FloatingRate retrieveBaseLendingRate(); - @Query("select floatingRate from FloatingRate floatingRate " + - " inner join floatingRate.floatingRatePeriods as periods" + - " where floatingRate.isActive = true " + - " and periods.isActive = true " + - " and periods.isDifferentialToBaseLendingRate = true") + @Query("select floatingRate from FloatingRate floatingRate " + " inner join floatingRate.floatingRatePeriods as periods" + + " where floatingRate.isActive = true " + " and periods.isActive = true " + + " and periods.isDifferentialToBaseLendingRate = true") Collection retrieveFloatingRatesLinkedToBLR(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRateRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRateRepositoryWrapper.java index cddedb25e..6a608c6ba 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRateRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/domain/FloatingRateRepositoryWrapper.java @@ -28,8 +28,7 @@ public class FloatingRateRepositoryWrapper { private final FloatingRateRepository floatingRateRepository; @Autowired - public FloatingRateRepositoryWrapper( - final FloatingRateRepository floatingRateRepository) { + public FloatingRateRepositoryWrapper(final FloatingRateRepository floatingRateRepository) { this.floatingRateRepository = floatingRateRepository; } @@ -38,8 +37,7 @@ public class FloatingRateRepositoryWrapper { } public FloatingRate findOneWithNotFoundDetection(final Long id) { - return this.floatingRateRepository - .findById(id).orElseThrow(() -> new FloatingRateNotFoundException(id)); + return this.floatingRateRepository.findById(id).orElseThrow(() -> new FloatingRateNotFoundException(id)); } public void save(FloatingRate newFloatingRate) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/exception/FloatingRateNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/exception/FloatingRateNotFoundException.java index 3c8b37b18..525448804 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/exception/FloatingRateNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/exception/FloatingRateNotFoundException.java @@ -20,12 +20,10 @@ package org.apache.fineract.portfolio.floatingrates.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; -public class FloatingRateNotFoundException extends - AbstractPlatformResourceNotFoundException { +public class FloatingRateNotFoundException extends AbstractPlatformResourceNotFoundException { public FloatingRateNotFoundException(final Long id) { - super("error.msg.floatingrate.id.invalid", - "Floating Rate with identifier " + id + " does not exist", id); + super("error.msg.floatingrate.id.invalid", "Floating Rate with identifier " + id + " does not exist", id); } public FloatingRateNotFoundException(final String globalisationMessageCode) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/handler/CreateFloatingRateCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/handler/CreateFloatingRateCommandHandler.java index 2be0e8d4f..92881ce70 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/handler/CreateFloatingRateCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/handler/CreateFloatingRateCommandHandler.java @@ -29,14 +29,12 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "FLOATINGRATE", action = "CREATE") -public class CreateFloatingRateCommandHandler implements - NewCommandSourceHandler { +public class CreateFloatingRateCommandHandler implements NewCommandSourceHandler { private final FloatingRateWritePlatformService writePlatformService; @Autowired - public CreateFloatingRateCommandHandler( - final FloatingRateWritePlatformService writePlatformService) { + public CreateFloatingRateCommandHandler(final FloatingRateWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/handler/UpdateFloatingRateCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/handler/UpdateFloatingRateCommandHandler.java index f38c2b6e0..c5846138d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/handler/UpdateFloatingRateCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/handler/UpdateFloatingRateCommandHandler.java @@ -29,14 +29,12 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "FLOATINGRATE", action = "UPDATE") -public class UpdateFloatingRateCommandHandler implements - NewCommandSourceHandler { +public class UpdateFloatingRateCommandHandler implements NewCommandSourceHandler { private final FloatingRateWritePlatformService writePlatformService; @Autowired - public UpdateFloatingRateCommandHandler( - final FloatingRateWritePlatformService writePlatformService) { + public UpdateFloatingRateCommandHandler(final FloatingRateWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/serialization/FloatingRateDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/serialization/FloatingRateDataValidator.java index c9d7da23e..78d5d52da 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/serialization/FloatingRateDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/serialization/FloatingRateDataValidator.java @@ -45,74 +45,55 @@ import org.springframework.stereotype.Component; public class FloatingRateDataValidator { private final Set supportedParametersForFloatingRates = new HashSet<>( - Arrays.asList("name", "isBaseLendingRate", "isActive", - "ratePeriods")); + Arrays.asList("name", "isBaseLendingRate", "isActive", "ratePeriods")); private final Set supportedParametersForFloatingRatePeriods = new HashSet<>( - Arrays.asList("fromDate", "interestRate", - "isDifferentialToBaseLendingRate", "locale", "dateFormat")); + Arrays.asList("fromDate", "interestRate", "isDifferentialToBaseLendingRate", "locale", "dateFormat")); private final FromJsonHelper fromApiJsonHelper; private final FloatingRateRepository floatingRateRepository; @Autowired - public FloatingRateDataValidator(final FromJsonHelper fromApiJsonHelper, - final FloatingRateRepository floatingRateRepository) { + public FloatingRateDataValidator(final FromJsonHelper fromApiJsonHelper, final FloatingRateRepository floatingRateRepository) { this.fromApiJsonHelper = fromApiJsonHelper; this.floatingRateRepository = floatingRateRepository; } public void validateForCreate(String json) { - final Type typeOfMap = new TypeToken>() { - }.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - this.supportedParametersForFloatingRates); + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForFloatingRates); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( - dataValidationErrors).resource("floatingrate"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("floatingrate"); final JsonElement element = this.fromApiJsonHelper.parse(json); - final String name = this.fromApiJsonHelper.extractStringNamed("name", - element); - baseDataValidator.reset().parameter("name").value(name).notBlank() - .notExceedingLengthOf(200); + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); + baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(200); Boolean isBaseLendingRate = null; - if (this.fromApiJsonHelper - .parameterExists("isBaseLendingRate", element)) { - isBaseLendingRate = this.fromApiJsonHelper - .extractBooleanNamed("isBaseLendingRate", element); + if (this.fromApiJsonHelper.parameterExists("isBaseLendingRate", element)) { + isBaseLendingRate = this.fromApiJsonHelper.extractBooleanNamed("isBaseLendingRate", element); - baseDataValidator.reset().parameter("isBaseLendingRate") - .value(isBaseLendingRate).notNull(); + baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate).notNull(); if (isBaseLendingRate == null) { - baseDataValidator.reset().parameter("isBaseLendingRate") - .trueOrFalseRequired(false); + baseDataValidator.reset().parameter("isBaseLendingRate").trueOrFalseRequired(false); } else if (isBaseLendingRate) { - FloatingRate baseLendingRate = this.floatingRateRepository - .retrieveBaseLendingRate(); + FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate(); if (baseLendingRate != null) { - baseDataValidator - .reset() - .parameter("isBaseLendingRate") - .value(isBaseLendingRate) - .failWithCode("baselendingrate.duplicate", - "Base Lending Rate already exists"); + baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate) + .failWithCode("baselendingrate.duplicate", "Base Lending Rate already exists"); } } } if (this.fromApiJsonHelper.parameterExists("isActive", element)) { - final Boolean isActive = this.fromApiJsonHelper - .extractBooleanNamed("isActive", element); + final Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element); if (isActive == null) { - baseDataValidator.reset().parameter("isActive") - .trueOrFalseRequired(false); + baseDataValidator.reset().parameter("isActive").trueOrFalseRequired(false); } } - if(isBaseLendingRate == null){ + if (isBaseLendingRate == null) { isBaseLendingRate = false; } validateRatePeriods(baseDataValidator, element, isBaseLendingRate, false); @@ -120,89 +101,52 @@ public class FloatingRateDataValidator { throwExceptionIfValidationWarningsExist(dataValidationErrors); } - private void validateRatePeriods(DataValidatorBuilder baseDataValidator, - JsonElement element, boolean isBaseLendingRate, boolean isBLRModifiedAsNonBLR) { + private void validateRatePeriods(DataValidatorBuilder baseDataValidator, JsonElement element, boolean isBaseLendingRate, + boolean isBLRModifiedAsNonBLR) { if (this.fromApiJsonHelper.parameterExists("ratePeriods", element)) { - final JsonArray ratePeriods = this.fromApiJsonHelper - .extractJsonArrayNamed("ratePeriods", element); - baseDataValidator.reset().parameter("ratePeriods") - .value(ratePeriods).notBlank().jsonArrayNotEmpty(); + final JsonArray ratePeriods = this.fromApiJsonHelper.extractJsonArrayNamed("ratePeriods", element); + baseDataValidator.reset().parameter("ratePeriods").value(ratePeriods).notBlank().jsonArrayNotEmpty(); if (ratePeriods != null) { List fromDates = new ArrayList<>(); for (int i = 0; i < ratePeriods.size(); i++) { final JsonElement ratePeriod = ratePeriods.get(i); - this.fromApiJsonHelper.checkForUnsupportedParameters( - ratePeriod.getAsJsonObject(), + this.fromApiJsonHelper.checkForUnsupportedParameters(ratePeriod.getAsJsonObject(), this.supportedParametersForFloatingRatePeriods); - final LocalDate fromDate = this.fromApiJsonHelper - .extractLocalDateNamed("fromDate", ratePeriod); - baseDataValidator - .reset() - .parameter("fromDate") - .parameterAtIndexArray("fromDate", i + 1) - .value(fromDate) - .notBlank() - .validateDateAfter( - DateUtils.getLocalDateOfTenant() - .plusDays(1)); + final LocalDate fromDate = this.fromApiJsonHelper.extractLocalDateNamed("fromDate", ratePeriod); + baseDataValidator.reset().parameter("fromDate").parameterAtIndexArray("fromDate", i + 1).value(fromDate).notBlank() + .validateDateAfter(DateUtils.getLocalDateOfTenant().plusDays(1)); if (fromDate != null) { fromDates.add(fromDate); } - final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper - .extractBigDecimalWithLocaleNamed("interestRate", - ratePeriod); - baseDataValidator.reset().parameter("interestRate") - .parameterAtIndexArray("interestRate", i + 1) - .value(interestRatePerPeriod).notNull() - .zeroOrPositiveAmount(); + final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRate", + ratePeriod); + baseDataValidator.reset().parameter("interestRate").parameterAtIndexArray("interestRate", i + 1) + .value(interestRatePerPeriod).notNull().zeroOrPositiveAmount(); - if (this.fromApiJsonHelper.parameterExists( - "isDifferentialToBaseLendingRate", ratePeriod)) { + if (this.fromApiJsonHelper.parameterExists("isDifferentialToBaseLendingRate", ratePeriod)) { final Boolean isDifferentialToBaseLendingRate = this.fromApiJsonHelper - .extractBooleanNamed( - "isDifferentialToBaseLendingRate", - ratePeriod); + .extractBooleanNamed("isDifferentialToBaseLendingRate", ratePeriod); if (isDifferentialToBaseLendingRate == null) { - baseDataValidator - .reset() - .parameter( - "isDifferentialToBaseLendingRate") - .parameterAtIndexArray( - "isDifferentialToBaseLendingRate", - i + 1).trueOrFalseRequired(false); + baseDataValidator.reset().parameter("isDifferentialToBaseLendingRate") + .parameterAtIndexArray("isDifferentialToBaseLendingRate", i + 1).trueOrFalseRequired(false); } else if (isDifferentialToBaseLendingRate) { - FloatingRate baseLendingRate = this.floatingRateRepository - .retrieveBaseLendingRate(); + FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate(); if (baseLendingRate == null || isBLRModifiedAsNonBLR) { - baseDataValidator - .reset() - .parameter( - "isDifferentialToBaseLendingRate") - .parameterAtIndexArray( - "isDifferentialToBaseLendingRate", - i + 1) + baseDataValidator.reset().parameter("isDifferentialToBaseLendingRate") + .parameterAtIndexArray("isDifferentialToBaseLendingRate", i + 1) .value(isDifferentialToBaseLendingRate) - .failWithCode( - "no.baselending.rate.defined", - "Base Lending Rate doesn't exists"); + .failWithCode("no.baselending.rate.defined", "Base Lending Rate doesn't exists"); } - if(isBaseLendingRate){ - baseDataValidator - .reset() - .parameter( - "isDifferentialToBaseLendingRate") - .parameterAtIndexArray( - "isDifferentialToBaseLendingRate", - i + 1) - .value(isDifferentialToBaseLendingRate) - .failWithCode( - "cannot.be.true.for.baselendingrate", - "isDifferentialToBaseLendingRate cannot be true for floating rate marked as Base Lending Rate."); + if (isBaseLendingRate) { + baseDataValidator.reset().parameter("isDifferentialToBaseLendingRate") + .parameterAtIndexArray("isDifferentialToBaseLendingRate", i + 1) + .value(isDifferentialToBaseLendingRate).failWithCode("cannot.be.true.for.baselendingrate", + "isDifferentialToBaseLendingRate cannot be true for floating rate marked as Base Lending Rate."); } } @@ -210,111 +154,85 @@ public class FloatingRateDataValidator { } Set uniqueFromDates = new HashSet<>(fromDates); if (fromDates.size() != uniqueFromDates.size()) { - baseDataValidator - .reset() - .parameter("fromDate") - .failWithCode("multiple.same.date", - "More than one entry in ratePeriods have same fromDate."); + baseDataValidator.reset().parameter("fromDate").failWithCode("multiple.same.date", + "More than one entry in ratePeriods have same fromDate."); } } } } - public void validateForUpdate(String json, - FloatingRate floatingRateForUpdate) { - final Type typeOfMap = new TypeToken>() { - }.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - this.supportedParametersForFloatingRates); + public void validateForUpdate(String json, FloatingRate floatingRateForUpdate) { + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForFloatingRates); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( - dataValidationErrors).resource("floatingrate"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("floatingrate"); final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists("name", element)) { - final String name = this.fromApiJsonHelper.extractStringNamed( - "name", element); - baseDataValidator.reset().parameter("name").value(name).notBlank() - .notExceedingLengthOf(200); + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); + baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(200); } Boolean isBaseLendingRate = null; Boolean isBLRModifiedAsNonBLR = false; - FloatingRate baseLendingRate = this.floatingRateRepository - .retrieveBaseLendingRate(); - if (this.fromApiJsonHelper - .parameterExists("isBaseLendingRate", element)) { - isBaseLendingRate = this.fromApiJsonHelper - .extractBooleanNamed("isBaseLendingRate", element); + FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate(); + if (this.fromApiJsonHelper.parameterExists("isBaseLendingRate", element)) { + isBaseLendingRate = this.fromApiJsonHelper.extractBooleanNamed("isBaseLendingRate", element); - baseDataValidator.reset().parameter("isBaseLendingRate") - .value(isBaseLendingRate).notNull(); + baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate).notNull(); if (isBaseLendingRate == null) { - baseDataValidator.reset().parameter("isBaseLendingRate") - .trueOrFalseRequired(false); + baseDataValidator.reset().parameter("isBaseLendingRate").trueOrFalseRequired(false); } else if (isBaseLendingRate) { if (baseLendingRate != null && !baseLendingRate.getId().equals(floatingRateForUpdate.getId())) { - baseDataValidator - .reset() - .parameter("isBaseLendingRate") - .value(isBaseLendingRate) - .failWithCode("baselendingrate.duplicate", - "Base Lending Rate already exists"); + baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate) + .failWithCode("baselendingrate.duplicate", "Base Lending Rate already exists"); } } } Boolean isActive = null; if (this.fromApiJsonHelper.parameterExists("isActive", element)) { - isActive = this.fromApiJsonHelper - .extractBooleanNamed("isActive", element); + isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element); if (isActive == null) { - baseDataValidator.reset().parameter("isActive") - .trueOrFalseRequired(false); + baseDataValidator.reset().parameter("isActive").trueOrFalseRequired(false); } } - if(isBaseLendingRate == null){ + if (isBaseLendingRate == null) { isBaseLendingRate = floatingRateForUpdate.isBaseLendingRate(); } - if(isActive == null){ + if (isActive == null) { isActive = floatingRateForUpdate.isActive(); } - if(baseLendingRate != null && baseLendingRate.getId().equals(floatingRateForUpdate.getId())){ - if(!isBaseLendingRate || !isActive){ + if (baseLendingRate != null && baseLendingRate.getId().equals(floatingRateForUpdate.getId())) { + if (!isBaseLendingRate || !isActive) { isBLRModifiedAsNonBLR = true; } } - if(isBLRModifiedAsNonBLR){ + if (isBLRModifiedAsNonBLR) { Collection floatingRates = this.floatingRateRepository.retrieveFloatingRatesLinkedToBLR(); - if(floatingRates != null && floatingRates.size() > 0){ - baseDataValidator - .reset() - .parameter("isBaseLendingRate") - .value(isBaseLendingRate) - .failWithCode("cannot.be.marked.non.baselendingrate", + if (floatingRates != null && floatingRates.size() > 0) { + baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate).failWithCode( + "cannot.be.marked.non.baselendingrate", "There are floating rates linked to this Base Lending Rate, cannot be marked as non-Base Lending Rate."); } } - validateRatePeriods(baseDataValidator, element, isBaseLendingRate, isBLRModifiedAsNonBLR); throwExceptionIfValidationWarningsExist(dataValidationErrors); } - private void throwExceptionIfValidationWarningsExist( - final List dataValidationErrors) { + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRateWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRateWritePlatformServiceImpl.java index f4102a24b..572013c92 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRateWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRateWritePlatformServiceImpl.java @@ -38,20 +38,16 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -public class FloatingRateWritePlatformServiceImpl implements - FloatingRateWritePlatformService { +public class FloatingRateWritePlatformServiceImpl implements FloatingRateWritePlatformService { - private final static Logger LOG = LoggerFactory - .getLogger(FloatingRateWritePlatformServiceImpl.class); + private final static Logger LOG = LoggerFactory.getLogger(FloatingRateWritePlatformServiceImpl.class); private final PlatformSecurityContext context; private final FloatingRateDataValidator fromApiJsonDeserializer; private final FloatingRateRepositoryWrapper floatingRateRepository; @Autowired - public FloatingRateWritePlatformServiceImpl( - final PlatformSecurityContext context, - final FloatingRateDataValidator fromApiJsonDeserializer, - final FloatingRateRepositoryWrapper floatingRateRepository) { + public FloatingRateWritePlatformServiceImpl(final PlatformSecurityContext context, + final FloatingRateDataValidator fromApiJsonDeserializer, final FloatingRateRepositoryWrapper floatingRateRepository) { this.context = context; this.fromApiJsonDeserializer = fromApiJsonDeserializer; this.floatingRateRepository = floatingRateRepository; @@ -63,8 +59,7 @@ public class FloatingRateWritePlatformServiceImpl implements try { this.fromApiJsonDeserializer.validateForCreate(command.json()); final AppUser currentUser = this.context.authenticatedUser(); - final FloatingRate newFloatingRate = FloatingRate.createNew( - currentUser, command); + final FloatingRate newFloatingRate = FloatingRate.createNew(currentUser, command); this.floatingRateRepository.save(newFloatingRate); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -73,10 +68,10 @@ public class FloatingRateWritePlatformServiceImpl implements } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -84,13 +79,10 @@ public class FloatingRateWritePlatformServiceImpl implements @Override public CommandProcessingResult updateFloatingRate(final JsonCommand command) { try { - final FloatingRate floatingRateForUpdate = this.floatingRateRepository - .findOneWithNotFoundDetection(command.entityId()); - this.fromApiJsonDeserializer.validateForUpdate(command.json(), - floatingRateForUpdate); + final FloatingRate floatingRateForUpdate = this.floatingRateRepository.findOneWithNotFoundDetection(command.entityId()); + this.fromApiJsonDeserializer.validateForUpdate(command.json(), floatingRateForUpdate); final AppUser currentUser = this.context.authenticatedUser(); - final Map changes = floatingRateForUpdate.update( - command, currentUser); + final Map changes = floatingRateForUpdate.update(command, currentUser); if (!changes.isEmpty()) { this.floatingRateRepository.save(floatingRateForUpdate); @@ -104,40 +96,33 @@ public class FloatingRateWritePlatformServiceImpl implements } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } - private void handleDataIntegrityIssues(final JsonCommand command, final Throwable realCause, - final Exception dve) { + private void handleDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { if (realCause.getMessage().contains("unq_name")) { final String name = command.stringValueOfParameterNamed("name"); - throw new PlatformDataIntegrityException( - "error.msg.floatingrates.duplicate.name", - "Floating Rate with name `" + name + "` already exists", - "name", name); + throw new PlatformDataIntegrityException("error.msg.floatingrates.duplicate.name", + "Floating Rate with name `" + name + "` already exists", "name", name); } if (realCause.getMessage().contains("unq_rate_period")) { - throw new PlatformDataIntegrityException( - "error.msg.floatingrates.duplicate.active.fromdate", - "Attempt to add multiple floating rate periods with same fromdate", - "fromdate", ""); + throw new PlatformDataIntegrityException("error.msg.floatingrates.duplicate.active.fromdate", + "Attempt to add multiple floating rate periods with same fromdate", "fromdate", ""); } logAsErrorUnexpectedDataIntegrityException(dve); - throw new PlatformDataIntegrityException( - "error.msg.floatingrates.unknown.data.integrity.issue", + throw new PlatformDataIntegrityException("error.msg.floatingrates.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); } - private void logAsErrorUnexpectedDataIntegrityException( - Exception dve) { + private void logAsErrorUnexpectedDataIntegrityException(Exception dve) { LOG.error("Error occured.", dve); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRatesReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRatesReadPlatformServiceImpl.java index 17413e2d3..5d1943fab 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRatesReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/floatingrates/service/FloatingRatesReadPlatformServiceImpl.java @@ -37,14 +37,12 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class FloatingRatesReadPlatformServiceImpl implements - FloatingRatesReadPlatformService { +public class FloatingRatesReadPlatformServiceImpl implements FloatingRatesReadPlatformService { private final JdbcTemplate jdbcTemplate; @Autowired - public FloatingRatesReadPlatformServiceImpl( - final RoutingDataSource dataSource) { + public FloatingRatesReadPlatformServiceImpl(final RoutingDataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @@ -58,16 +56,14 @@ public class FloatingRatesReadPlatformServiceImpl implements @Override public List retrieveAllActive() { FloatingRateRowMapper rateMapper = new FloatingRateRowMapper(false); - final String sql = "select " + rateMapper.schema() - + " where rate.is_active = 1 "; + final String sql = "select " + rateMapper.schema() + " where rate.is_active = 1 "; return this.jdbcTemplate.query(sql, rateMapper); } @Override public List retrieveLookupActive() { FloatingRateLookupMapper rateMapper = new FloatingRateLookupMapper(); - final String sql = "select " + rateMapper.schema() - + " where rate.is_active = 1 "; + final String sql = "select " + rateMapper.schema() + " where rate.is_active = 1 "; return this.jdbcTemplate.query(sql, rateMapper); } @@ -75,22 +71,18 @@ public class FloatingRatesReadPlatformServiceImpl implements public FloatingRateData retrieveOne(final Long floatingRateId) { try { FloatingRateRowMapper rateMapper = new FloatingRateRowMapper(true); - final String sql = "select " + rateMapper.schema() - + " where rate.id = ?"; - return this.jdbcTemplate.queryForObject(sql, rateMapper, - new Object[] { floatingRateId }); + final String sql = "select " + rateMapper.schema() + " where rate.id = ?"; + return this.jdbcTemplate.queryForObject(sql, rateMapper, new Object[] { floatingRateId }); } catch (final EmptyResultDataAccessException e) { throw new FloatingRateNotFoundException(floatingRateId); } } @Override - public List retrieveInterestRatePeriods( - final Long productId) { + public List retrieveInterestRatePeriods(final Long productId) { try { FloatingInterestRatePeriodRowMapper mapper = new FloatingInterestRatePeriodRowMapper(); - return this.jdbcTemplate.query(mapper.schema(), mapper, - new Object[] { productId }); + return this.jdbcTemplate.query(mapper.schema(), mapper, new Object[] { productId }); } catch (final EmptyResultDataAccessException e) { throw new FloatingRateNotFoundException("error.msg.floatingrate.not.found.for.product"); } @@ -100,32 +92,22 @@ public class FloatingRatesReadPlatformServiceImpl implements public FloatingRateData retrieveBaseLendingRate() { try { FloatingRateRowMapper rateMapper = new FloatingRateRowMapper(true); - final String sql = "select " - + rateMapper.schema() - + " where rate.is_base_lending_rate = 1 and rate.is_active = 1"; + final String sql = "select " + rateMapper.schema() + " where rate.is_base_lending_rate = 1 and rate.is_active = 1"; return this.jdbcTemplate.queryForObject(sql, rateMapper); } catch (final EmptyResultDataAccessException e) { - throw new FloatingRateNotFoundException( - "error.msg.floatingrate.base.lending.rate.not.found"); + throw new FloatingRateNotFoundException("error.msg.floatingrate.base.lending.rate.not.found"); } } - private final class FloatingRateRowMapper implements - RowMapper { + private final class FloatingRateRowMapper implements RowMapper { private final boolean addRatePeriods; - private final StringBuilder sqlQuery = new StringBuilder() - .append("rate.id as id, ") - .append("rate.name as name, ") - .append("rate.is_base_lending_rate as isBaseLendingRate, ") - .append("rate.is_active as isActive, ") - .append("crappu.username as createdBy, ") - .append("rate.created_date as createdOn, ") - .append("moappu.username as modifiedBy, ") - .append("rate.lastmodified_date as modifiedOn ") - .append("FROM m_floating_rates as rate ") - .append("LEFT JOIN m_appuser as crappu on rate.createdby_id = crappu.id ") + private final StringBuilder sqlQuery = new StringBuilder().append("rate.id as id, ").append("rate.name as name, ") + .append("rate.is_base_lending_rate as isBaseLendingRate, ").append("rate.is_active as isActive, ") + .append("crappu.username as createdBy, ").append("rate.created_date as createdOn, ") + .append("moappu.username as modifiedBy, ").append("rate.lastmodified_date as modifiedOn ") + .append("FROM m_floating_rates as rate ").append("LEFT JOIN m_appuser as crappu on rate.createdby_id = crappu.id ") .append("LEFT JOIN m_appuser as moappu on rate.lastmodifiedby_id = moappu.id "); public FloatingRateRowMapper(final boolean addRatePeriods) { @@ -133,13 +115,10 @@ public class FloatingRatesReadPlatformServiceImpl implements } @Override - public FloatingRateData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public FloatingRateData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); final String name = rs.getString("name"); - final boolean isBaseLendingRate = rs - .getBoolean("isBaseLendingRate"); + final boolean isBaseLendingRate = rs.getBoolean("isBaseLendingRate"); final boolean isActive = rs.getBoolean("isActive"); final String createdBy = rs.getString("createdBy"); final LocalDate createdOn = JdbcSupport.getLocalDate(rs, "createdOn"); @@ -148,15 +127,11 @@ public class FloatingRatesReadPlatformServiceImpl implements List ratePeriods = null; if (addRatePeriods) { FloatingRatePeriodRowMapper ratePeriodMapper = new FloatingRatePeriodRowMapper(); - final String sql = "select " - + ratePeriodMapper.schema() - + " where period.is_active = 1 and period.floating_rates_id = ? " + final String sql = "select " + ratePeriodMapper.schema() + " where period.is_active = 1 and period.floating_rates_id = ? " + " order by period.from_date desc "; - ratePeriods = jdbcTemplate.query(sql, ratePeriodMapper, - new Object[] { id }); + ratePeriods = jdbcTemplate.query(sql, ratePeriodMapper, new Object[] { id }); } - return new FloatingRateData(id, name, isBaseLendingRate, isActive, - createdBy, createdOn, modifiedBy, modifiedOn, ratePeriods, + return new FloatingRateData(id, name, isBaseLendingRate, isActive, createdBy, createdOn, modifiedBy, modifiedOn, ratePeriods, null); } @@ -165,40 +140,30 @@ public class FloatingRatesReadPlatformServiceImpl implements } } - private final class FloatingRatePeriodRowMapper implements - RowMapper { + private final class FloatingRatePeriodRowMapper implements RowMapper { - private final StringBuilder sqlQuery = new StringBuilder() - .append("period.id as id, ") - .append("period.from_date as fromDate, ") + private final StringBuilder sqlQuery = new StringBuilder().append("period.id as id, ").append("period.from_date as fromDate, ") .append("period.interest_rate as interestRate, ") .append("period.is_differential_to_base_lending_rate as isDifferentialToBaseLendingRate, ") - .append("period.is_active as isActive, ") - .append("crappu.username as createdBy, ") - .append("period.created_date as createdOn, ") - .append("moappu.username as modifiedBy, ") - .append("period.lastmodified_date as modifiedOn ") - .append("FROM m_floating_rates_periods as period ") + .append("period.is_active as isActive, ").append("crappu.username as createdBy, ") + .append("period.created_date as createdOn, ").append("moappu.username as modifiedBy, ") + .append("period.lastmodified_date as modifiedOn ").append("FROM m_floating_rates_periods as period ") .append("LEFT JOIN m_appuser as crappu on period.createdby_id = crappu.id ") .append("LEFT JOIN m_appuser as moappu on period.lastmodifiedby_id = moappu.id "); @Override - public FloatingRatePeriodData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public FloatingRatePeriodData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); final LocalDate fromDate = JdbcSupport.getLocalDate(rs, "fromDate"); final BigDecimal interestRate = rs.getBigDecimal("interestRate"); - final boolean isDifferentialToBaseLendingRate = rs - .getBoolean("isDifferentialToBaseLendingRate"); + final boolean isDifferentialToBaseLendingRate = rs.getBoolean("isDifferentialToBaseLendingRate"); final boolean isActive = rs.getBoolean("isActive"); final String createdBy = rs.getString("createdBy"); final LocalDate createdOn = JdbcSupport.getLocalDate(rs, "createdOn"); final String modifiedBy = rs.getString("modifiedBy"); final LocalDate modifiedOn = JdbcSupport.getLocalDate(rs, "modifiedOn"); - return new FloatingRatePeriodData(id, fromDate, interestRate, - isDifferentialToBaseLendingRate, isActive, createdBy, - createdOn, modifiedBy, modifiedOn); + return new FloatingRatePeriodData(id, fromDate, interestRate, isDifferentialToBaseLendingRate, isActive, createdBy, createdOn, + modifiedBy, modifiedOn); } public String schema() { @@ -206,24 +171,17 @@ public class FloatingRatesReadPlatformServiceImpl implements } } - private final class FloatingRateLookupMapper implements - RowMapper { + private final class FloatingRateLookupMapper implements RowMapper { - private final StringBuilder sqlQuery = new StringBuilder() - .append("rate.id as id, ").append("rate.name as name, ") - .append("rate.is_base_lending_rate as isBaseLendingRate ") - .append("FROM m_floating_rates as rate "); + private final StringBuilder sqlQuery = new StringBuilder().append("rate.id as id, ").append("rate.name as name, ") + .append("rate.is_base_lending_rate as isBaseLendingRate ").append("FROM m_floating_rates as rate "); @Override - public FloatingRateData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public FloatingRateData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); final String name = rs.getString("name"); - final boolean isBaseLendingRate = rs - .getBoolean("isBaseLendingRate"); - return new FloatingRateData(id, name, isBaseLendingRate, true, - null, null, null, null, null, null); + final boolean isBaseLendingRate = rs.getBoolean("isBaseLendingRate"); + return new FloatingRateData(id, name, isBaseLendingRate, true, null, null, null, null, null, null); } public String schema() { @@ -231,60 +189,41 @@ public class FloatingRatesReadPlatformServiceImpl implements } } - private final class FloatingInterestRatePeriodRowMapper implements - RowMapper { + private final class FloatingInterestRatePeriodRowMapper implements RowMapper { - private final StringBuilder sqlQuery = new StringBuilder() - .append("select ") + private final StringBuilder sqlQuery = new StringBuilder().append("select ") .append(" linkedrateperiods.from_date as linkedrateperiods_from_date, ") .append(" linkedrateperiods.interest_rate as linkedrateperiods_interest_rate, ") .append(" linkedrateperiods.is_differential_to_base_lending_rate as linkedrateperiods_is_differential_to_base_lending_rate, ") - .append(" baserate.from_date as baserate_from_date, ") - .append(" baserate.interest_rate as baserate_interest_rate ") + .append(" baserate.from_date as baserate_from_date, ").append(" baserate.interest_rate as baserate_interest_rate ") .append(" from m_product_loan as lp ") - .append(" join m_product_loan_floating_rates as plfr on lp.id = plfr.loan_product_id ") - .append(" join m_floating_rates as linkedrate on linkedrate.id = plfr.floating_rates_id ") + .append(" join m_product_loan_floating_rates as plfr on lp.id = plfr.loan_product_id ") + .append(" join m_floating_rates as linkedrate on linkedrate.id = plfr.floating_rates_id ") .append("left join m_floating_rates_periods as linkedrateperiods on (linkedrate.id = linkedrateperiods.floating_rates_id and linkedrateperiods.is_active = 1) ") - .append("left join ( ") - .append(" select blr.name, ") - .append(" blr.is_base_lending_rate, ") - .append(" blr.is_active, ") - .append(" blrperiods.from_date, ") - .append(" blrperiods.interest_rate ") + .append("left join ( ").append(" select blr.name, ").append(" blr.is_base_lending_rate, ") + .append(" blr.is_active, ").append(" blrperiods.from_date, ").append(" blrperiods.interest_rate ") .append(" from m_floating_rates as blr ") .append(" left join m_floating_rates_periods as blrperiods on (blr.id = blrperiods.floating_rates_id and blrperiods.is_active = 1) ") .append(" where blr.is_base_lending_rate = 1 and blr.is_active = 1 ") .append(") as baserate on (linkedrateperiods.is_differential_to_base_lending_rate = 1 and linkedrate.is_base_lending_rate = 0) ") - .append("where (baserate.from_date is null ") - .append(" or baserate.from_date = (select MAX(b.from_date) ") - .append(" from (select blr.name, ") - .append(" blr.is_base_lending_rate, ") - .append(" blr.is_active, ") - .append(" blrperiods.from_date, ") - .append(" blrperiods.interest_rate ") - .append(" from m_floating_rates as blr ") + .append("where (baserate.from_date is null ").append(" or baserate.from_date = (select MAX(b.from_date) ") + .append(" from (select blr.name, ").append(" blr.is_base_lending_rate, ") + .append(" blr.is_active, ").append(" blrperiods.from_date, ") + .append(" blrperiods.interest_rate ").append(" from m_floating_rates as blr ") .append(" left join m_floating_rates_periods as blrperiods on (blr.id = blrperiods.floating_rates_id and blrperiods.is_active = 1) ") - .append(" where blr.is_base_lending_rate = 1 and blr.is_active = 1 ") - .append(" ) as b ") - .append(" where b.from_date <= linkedrateperiods.from_date)) ") - .append("and lp.id = ? ") + .append(" where blr.is_base_lending_rate = 1 and blr.is_active = 1 ").append(" ) as b ") + .append(" where b.from_date <= linkedrateperiods.from_date)) ").append("and lp.id = ? ") .append("order by linkedratePeriods_from_date desc "); @Override - public InterestRatePeriodData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public InterestRatePeriodData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Date fromDate = rs.getDate("linkedrateperiods_from_date"); - final BigDecimal interestRate = rs - .getBigDecimal("linkedrateperiods_interest_rate"); - final boolean isDifferentialToBLR = rs - .getBoolean("linkedrateperiods_is_differential_to_base_lending_rate"); + final BigDecimal interestRate = rs.getBigDecimal("linkedrateperiods_interest_rate"); + final boolean isDifferentialToBLR = rs.getBoolean("linkedrateperiods_is_differential_to_base_lending_rate"); final Date blrFromDate = rs.getDate("baserate_from_date"); - final BigDecimal blrInterestRate = rs - .getBigDecimal("baserate_interest_rate"); + final BigDecimal blrInterestRate = rs.getBigDecimal("baserate_interest_rate"); - return new InterestRatePeriodData(fromDate, interestRate, - isDifferentialToBLR, blrFromDate, blrInterestRate); + return new InterestRatePeriodData(fromDate, interestRate, isDifferentialToBLR, blrFromDate, blrInterestRate); } public String schema() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/api/FundsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/api/FundsApiResource.java index 7cffbf3bf..b3b4ceb19 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/api/FundsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/api/FundsApiResource.java @@ -87,8 +87,10 @@ public class FundsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Funds", httpMethod = "GET", notes = "Returns the list of funds.\n" + "\n" + "Example Requests:\n" + "\n" + "funds") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FundsApiResourceSwagger.GetFundsResponse.class, responseContainer = "List")}) + @ApiOperation(value = "Retrieve Funds", httpMethod = "GET", notes = "Returns the list of funds.\n" + "\n" + "Example Requests:\n" + "\n" + + "funds") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FundsApiResourceSwagger.GetFundsResponse.class, responseContainer = "List") }) public String retrieveFunds(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -103,8 +105,9 @@ public class FundsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create a Fund", httpMethod = "POST", notes = "Creates a Fund") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FundsApiResourceSwagger.PostFundsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FundsApiResourceSwagger.PostFundsResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FundsApiResourceSwagger.PostFundsRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = FundsApiResourceSwagger.PostFundsResponse.class) }) public String createFund(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createFund().withJson(apiRequestBodyAsJson).build(); @@ -118,8 +121,9 @@ public class FundsApiResource { @Path("{fundId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Fund", httpMethod = "GET", notes = "Returns the details of a Fund.\n" + "\n" + "Example Requests:\n" + "\n" + "funds/1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FundsApiResourceSwagger.GetFundsResponse.class)}) + @ApiOperation(value = "Retrieve a Fund", httpMethod = "GET", notes = "Returns the details of a Fund.\n" + "\n" + "Example Requests:\n" + + "\n" + "funds/1") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = FundsApiResourceSwagger.GetFundsResponse.class) }) public String retreiveFund(@PathParam("fundId") @ApiParam(value = "fundId") final Long fundId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -135,9 +139,11 @@ public class FundsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Fund", httpMethod = "PUT", notes = "Updates the details of a fund.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FundsApiResourceSwagger.PutFundsFundIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FundsApiResourceSwagger.PutFundsFundIdResponse.class)}) - public String updateFund(@PathParam("fundId") @ApiParam(value = "fundId") final Long fundId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FundsApiResourceSwagger.PutFundsFundIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = FundsApiResourceSwagger.PutFundsFundIdResponse.class) }) + public String updateFund(@PathParam("fundId") @ApiParam(value = "fundId") final Long fundId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateFund(fundId).withJson(apiRequestBodyAsJson).build(); @@ -145,4 +151,4 @@ public class FundsApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/api/FundsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/api/FundsApiResourceSwagger.java index f15a6863c..f8dc0e691 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/api/FundsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/api/FundsApiResourceSwagger.java @@ -25,13 +25,13 @@ import io.swagger.annotations.ApiModelProperty; * Created by Chirag Gupta on 12/08/17. */ final class FundsApiResourceSwagger { - private FundsApiResourceSwagger() { - } + + private FundsApiResourceSwagger() {} @ApiModel(value = "GetFundsResponse") public static final class GetFundsResponse { - private GetFundsResponse() { - } + + private GetFundsResponse() {} @ApiModelProperty(example = "1") public Integer id; @@ -41,8 +41,8 @@ final class FundsApiResourceSwagger { @ApiModel(value = "PostFundsRequest") public static final class PostFundsRequest { - private PostFundsRequest() { - } + + private PostFundsRequest() {} @ApiModelProperty(example = "EU Agri Fund") public String name; @@ -50,8 +50,8 @@ final class FundsApiResourceSwagger { @ApiModel(value = "PostFundsResponse") public static final class PostFundsResponse { - private PostFundsResponse() { - } + + private PostFundsResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -59,8 +59,8 @@ final class FundsApiResourceSwagger { @ApiModel(value = "PutFundsFundIdRequest") public static final class PutFundsFundIdRequest { - private PutFundsFundIdRequest() { - } + + private PutFundsFundIdRequest() {} @ApiModelProperty(example = "EU Agri Fund (2010-2020)") public String name; @@ -68,8 +68,8 @@ final class FundsApiResourceSwagger { @ApiModel(value = "PutFundsFundIdResponse") public static final class PutFundsFundIdResponse { - private PutFundsFundIdResponse() { - } + + private PutFundsFundIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/data/FundData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/data/FundData.java index 2857cafad..2ff5ed4b9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/data/FundData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/data/FundData.java @@ -49,4 +49,4 @@ public class FundData implements Serializable { public Long getId() { return id; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/domain/Fund.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/domain/Fund.java index f2bea61f9..d876499f5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/domain/Fund.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/domain/Fund.java @@ -79,4 +79,4 @@ public class Fund extends AbstractPersistableCustom { return actualChanges; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/domain/FundRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/domain/FundRepository.java index 36a522ffe..f64cf80da 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/domain/FundRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/domain/FundRepository.java @@ -23,4 +23,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface FundRepository extends JpaRepository, JpaSpecificationExecutor { // no added behaviour -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/exception/FundNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/exception/FundNotFoundException.java index 9805af85c..a2c27f746 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/exception/FundNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/exception/FundNotFoundException.java @@ -28,4 +28,4 @@ public class FundNotFoundException extends AbstractPlatformResourceNotFoundExcep public FundNotFoundException(final Long id) { super("error.msg.fund.id.invalid", "Fund with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/handler/CreateFundCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/handler/CreateFundCommandHandler.java index 44ea75028..1cfed4c51 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/handler/CreateFundCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/handler/CreateFundCommandHandler.java @@ -44,4 +44,4 @@ public class CreateFundCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createFund(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/handler/UpdateFundCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/handler/UpdateFundCommandHandler.java index dfb8d8014..63313d217 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/handler/UpdateFundCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/handler/UpdateFundCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateFundCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.updateFund(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/serialization/FundCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/serialization/FundCommandFromApiJsonDeserializer.java index 4b8118591..8b0fd34f7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/serialization/FundCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/serialization/FundCommandFromApiJsonDeserializer.java @@ -95,7 +95,9 @@ public final class FundCommandFromApiJsonDeserializer { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundReadPlatformService.java index 299093db7..a1aaa22c5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundReadPlatformService.java @@ -26,4 +26,4 @@ public interface FundReadPlatformService { Collection retrieveAllFunds(); FundData retrieveFund(Long fundId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundReadPlatformServiceImpl.java index 29b99ab37..1dd6bfd37 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundReadPlatformServiceImpl.java @@ -89,4 +89,4 @@ public class FundReadPlatformServiceImpl implements FundReadPlatformService { throw new FundNotFoundException(fundId); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundWritePlatformService.java index d3c4723a2..3eeddd82b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundWritePlatformService.java @@ -26,4 +26,4 @@ public interface FundWritePlatformService { CommandProcessingResult createFund(JsonCommand command); CommandProcessingResult updateFund(Long fundId, JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java index 5c76ea21f..1a1581c3b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java @@ -73,10 +73,10 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf } catch (final DataIntegrityViolationException dve) { handleFundDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleFundDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -90,8 +90,7 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf this.fromApiJsonDeserializer.validateForUpdate(command.json()); - final Fund fund = this.fundRepository.findById(fundId) - .orElseThrow(() -> new FundNotFoundException(fundId)); + final Fund fund = this.fundRepository.findById(fundId).orElseThrow(() -> new FundNotFoundException(fundId)); final Map changes = fund.update(command); if (!changes.isEmpty()) { @@ -102,10 +101,10 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf } catch (final DataIntegrityViolationException dve) { handleFundDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleFundDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -113,11 +112,11 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf * Guaranteed to throw an exception no matter what the data integrity issue * is. */ - private void handleFundDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { + private void handleFundDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { if (realCause.getMessage().contains("fund_externalid_org")) { final String externalId = command.stringValueOfParameterNamed("externalId"); - throw new PlatformDataIntegrityException("error.msg.fund.duplicate.externalId", "A fund with external id '" + externalId - + "' already exists", "externalId", externalId); + throw new PlatformDataIntegrityException("error.msg.fund.duplicate.externalId", + "A fund with external id '" + externalId + "' already exists", "externalId", externalId); } else if (realCause.getMessage().contains("fund_name_org")) { final String name = command.stringValueOfParameterNamed("name"); throw new PlatformDataIntegrityException("error.msg.fund.duplicate.name", "A fund with name '" + name + "' already exists", diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/CentersApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/CentersApiResource.java index 18212d899..7e444843c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/CentersApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/CentersApiResource.java @@ -93,14 +93,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; - @Path("/centers") @Component @Scope("singleton") -@Api(tags = {"Centers"}) +@Api(tags = { "Centers" }) @SwaggerDefinition(tags = { - @Tag(name = "Centers", description = "Centers along with Groups are used to provided a distinctive banking distribution channel used in microfinance. Its common in areas such as Southern Asia to use Centers and Group as administrative units in grameen style lending. Typically groups will contain one to five people and centers themselves will be made of anywhere between 2-10 groups.") -}) + @Tag(name = "Centers", description = "Centers along with Groups are used to provided a distinctive banking distribution channel used in microfinance. Its common in areas such as Southern Asia to use Centers and Group as administrative units in grameen style lending. Typically groups will contain one to five people and centers themselves will be made of anywhere between 2-10 groups.") }) public class CentersApiResource { private final PlatformSecurityContext context; @@ -144,17 +142,19 @@ public class CentersApiResource { this.calendarReadPlatformService = calendarReadPlatformService; this.meetingReadPlatformService = meetingReadPlatformService; this.entityDatatableChecksReadService = entityDatatableChecksReadService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; - this.bulkImportWorkbookService=bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Center Template", httpMethod = "GET", notes = "Retrieves a Center Template\n\n" + "Example Requests:\n\n" + "\n\n" + "centers/template\n\n" + "\n\n" + "centers/template?officeId=2") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.GetCentersTemplateResponse.class)}) - public String retrieveTemplate(@Context final UriInfo uriInfo, @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiOperation(value = "Retrieve a Center Template", httpMethod = "GET", notes = "Retrieves a Center Template\n\n" + + "Example Requests:\n\n" + "\n\n" + "centers/template\n\n" + "\n\n" + "centers/template?officeId=2") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.GetCentersTemplateResponse.class) }) + public String retrieveTemplate(@Context final UriInfo uriInfo, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly) { @@ -179,15 +179,24 @@ public class CentersApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Centers", httpMethod = "GET", notes = "The default implementation supports pagination and sorting with the default pagination size set to 200 records. The parameter limit with value -1 will return all entries.\n\n" + "Example Requests:\n\n" + "\n\n" + "centers\n\n" + "\n\n" + "centers?fields=name,officeName,joinedDate\n\n" + "\n\n" + "centers?offset=10&limit=50\n\n" + "\n\n" + "centers?orderBy=name&sortOrder=DESC") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.GetCentersResponse.class)}) - public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, - @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, @QueryParam("staffId") @ApiParam(value = "staffId") final Long staffId, - @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, @QueryParam("name") @ApiParam(value = "name") final String name, - @QueryParam("underHierarchy") @ApiParam(value = "underHierarchy") final String hierarchy, @QueryParam("paged") @ApiParam(value = "paged") final Boolean paged, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, - @QueryParam("meetingDate") @ApiParam(value = "meetingDate") final DateParam meetingDateParam, @QueryParam("dateFormat") @ApiParam(value = "dateFormat") final String dateFormat, + @ApiOperation(value = "List Centers", httpMethod = "GET", notes = "The default implementation supports pagination and sorting with the default pagination size set to 200 records. The parameter limit with value -1 will return all entries.\n\n" + + "Example Requests:\n\n" + "\n\n" + "centers\n\n" + "\n\n" + "centers?fields=name,officeName,joinedDate\n\n" + "\n\n" + + "centers?offset=10&limit=50\n\n" + "\n\n" + "centers?orderBy=name&sortOrder=DESC") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.GetCentersResponse.class) }) + public String retrieveAll(@Context final UriInfo uriInfo, + @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, + @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, + @QueryParam("staffId") @ApiParam(value = "staffId") final Long staffId, + @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, + @QueryParam("name") @ApiParam(value = "name") final String name, + @QueryParam("underHierarchy") @ApiParam(value = "underHierarchy") final String hierarchy, + @QueryParam("paged") @ApiParam(value = "paged") final Boolean paged, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, + @QueryParam("meetingDate") @ApiParam(value = "meetingDate") final DateParam meetingDateParam, + @QueryParam("dateFormat") @ApiParam(value = "dateFormat") final String dateFormat, @QueryParam("locale") @ApiParam(value = "locale") final String locale) { this.context.authenticatedUser().validateHasReadPermission(GroupingTypesApiConstants.CENTER_RESOURCE_NAME); @@ -216,8 +225,9 @@ public class CentersApiResource { @Path("{centerId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Center", httpMethod = "GET", notes = "Retrieves a Center\n\n" + "Example Requests:\n\n" + "\n\n" + "centers/1\n\n" + "\n\n" + "centers/1?associations=groupMembers") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.GetCentersCenterIdResponse.class)}) + @ApiOperation(value = "Retrieve a Center", httpMethod = "GET", notes = "Retrieves a Center\n\n" + "Example Requests:\n\n" + "\n\n" + + "centers/1\n\n" + "\n\n" + "centers/1?associations=groupMembers") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.GetCentersCenterIdResponse.class) }) public String retrieveOne(@Context final UriInfo uriInfo, @PathParam("centerId") @ApiParam(value = "centerId") final Long centerId, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly) { @@ -244,12 +254,12 @@ public class CentersApiResource { if (collectionMeetingCalendar != null) { final boolean withHistory = true; final LocalDate tillDate = null; - final Collection recurringDates = this.calendarReadPlatformService.generateRecurringDates( - collectionMeetingCalendar, withHistory, tillDate); + final Collection recurringDates = this.calendarReadPlatformService + .generateRecurringDates(collectionMeetingCalendar, withHistory, tillDate); final Collection nextTenRecurringDates = this.calendarReadPlatformService .generateNextTenRecurringDates(collectionMeetingCalendar); - final MeetingData lastMeeting = this.meetingReadPlatformService.retrieveLastMeeting(collectionMeetingCalendar - .getCalendarInstanceId()); + final MeetingData lastMeeting = this.meetingReadPlatformService + .retrieveLastMeeting(collectionMeetingCalendar.getCalendarInstanceId()); final LocalDate recentEligibleMeetingDate = this.calendarReadPlatformService .generateNextEligibleMeetingDateForCollection(collectionMeetingCalendar, lastMeeting); collectionMeetingCalendar = CalendarData.withRecurringDates(collectionMeetingCalendar, recurringDates, @@ -267,9 +277,12 @@ public class CentersApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Center", httpMethod = "POST", notes = "Creates a Center\n\n" + "Mandatory Fields: name, officeId, active, activationDate (if active=true)\n\n" + "Optional Fields: externalId, staffId, groupMembers") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CentersApiResourceSwagger.PostCentersRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.PostCentersResponse.class)}) + @ApiOperation(value = "Create a Center", httpMethod = "POST", notes = "Creates a Center\n\n" + + "Mandatory Fields: name, officeId, active, activationDate (if active=true)\n\n" + + "Optional Fields: externalId, staffId, groupMembers") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CentersApiResourceSwagger.PostCentersRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.PostCentersResponse.class) }) public String create(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -286,9 +299,11 @@ public class CentersApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Center", httpMethod = "PUT", notes = "Updates a Center") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CentersApiResourceSwagger.PutCentersCenterIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.PutCentersCenterIdResponse.class)}) - public String update(@PathParam("centerId") @ApiParam(value = "centerId") final Long centerId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CentersApiResourceSwagger.PutCentersCenterIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.PutCentersCenterIdResponse.class) }) + public String update(@PathParam("centerId") @ApiParam(value = "centerId") final Long centerId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .updateCenter(centerId) // @@ -303,7 +318,7 @@ public class CentersApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Center", httpMethod = "DELETE", notes = "A Center can be deleted if it is in pending state and has no association - groups, loans or savings") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.DeleteCentersCenterIdResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.DeleteCentersCenterIdResponse.class) }) public String delete(@PathParam("centerId") @ApiParam(value = "centerId") final Long centerId) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -317,11 +332,23 @@ public class CentersApiResource { @Path("{centerId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Activate a Center | Generate Collection Sheet | Save Collection Sheet | Close a Center | Associate Groups | Disassociate Groups", httpMethod = "POST", notes = "Activate a Center:\n\n" + "Centers can be created in a Pending state. This API exists to enable center activation. If the center happens to be already active, this API will result in an error.\n\n" + "Close a Center:\n\n" + "Centers can be closed if they don't have any non-closed groups or saving accounts. If the Center has any active groups or savings accounts, this API will result in an error.\n\n" + "Associate Groups:\n\n" + "This API allows associating existing groups to a center. The groups are listed from the office to which the center is associated. If group(s) is already associated with a center, this API will result in an error.\n\n" + "Disassociate Groups:\n\n" + "This API allows to disassociate groups from a center.\n\n" + "Generate Collection Sheet:\n\n" + "This Api retrieves repayment details of all jlg loans under a center as on a specified meeting date.\n\n" + "Save Collection Sheet:\n\n" + "This Api allows the loan officer to perform bulk repayments of JLG loans for a center on a given meeting date.\n\n" + "Showing Request/Response for Close a Center") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CentersApiResourceSwagger.PostCentersCenterIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.PostCentersCenterIdResponse.class)}) - public String activate(@PathParam("centerId") @ApiParam(value = "centerId") final Long centerId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, - @ApiParam(hidden = true) final String apiRequestBodyAsJson, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Activate a Center | Generate Collection Sheet | Save Collection Sheet | Close a Center | Associate Groups | Disassociate Groups", httpMethod = "POST", notes = "Activate a Center:\n\n" + + "Centers can be created in a Pending state. This API exists to enable center activation. If the center happens to be already active, this API will result in an error.\n\n" + + "Close a Center:\n\n" + + "Centers can be closed if they don't have any non-closed groups or saving accounts. If the Center has any active groups or savings accounts, this API will result in an error.\n\n" + + "Associate Groups:\n\n" + + "This API allows associating existing groups to a center. The groups are listed from the office to which the center is associated. If group(s) is already associated with a center, this API will result in an error.\n\n" + + "Disassociate Groups:\n\n" + "This API allows to disassociate groups from a center.\n\n" + "Generate Collection Sheet:\n\n" + + "This Api retrieves repayment details of all jlg loans under a center as on a specified meeting date.\n\n" + + "Save Collection Sheet:\n\n" + + "This Api allows the loan officer to perform bulk repayments of JLG loans for a center on a given meeting date.\n\n" + + "Showing Request/Response for Close a Center") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = CentersApiResourceSwagger.PostCentersCenterIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.PostCentersCenterIdResponse.class) }) + public String activate(@PathParam("centerId") @ApiParam(value = "centerId") final Long centerId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiParam(hidden = true) final String apiRequestBodyAsJson, @Context final UriInfo uriInfo) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); @@ -368,16 +395,20 @@ public class CentersApiResource { @Path("{centerId}/accounts") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Center accounts overview", httpMethod = "GET", notes = "An example of how a savings summary for a Center can be provided. This is requested in a specific use case of the reference application.\n\n" + "It is quite reasonable to add resources like this to simplify User Interface development.\n\n" + "\n\n" + "Example Requests:\n\n" + "\n\n" + "centers/9/accounts") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.GetCentersCenterIdAccountsResponse.class)}) - public String retrieveGroupAccount(@PathParam("centerId") @ApiParam(value = "centerId") final Long centerId, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve Center accounts overview", httpMethod = "GET", notes = "An example of how a savings summary for a Center can be provided. This is requested in a specific use case of the reference application.\n\n" + + "It is quite reasonable to add resources like this to simplify User Interface development.\n\n" + "\n\n" + + "Example Requests:\n\n" + "\n\n" + "centers/9/accounts") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = CentersApiResourceSwagger.GetCentersCenterIdAccountsResponse.class) }) + public String retrieveGroupAccount(@PathParam("centerId") @ApiParam(value = "centerId") final Long centerId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(GroupingTypesApiConstants.CENTER_RESOURCE_NAME); final AccountSummaryCollectionData groupAccount = this.accountDetailsReadPlatformService.retrieveGroupAccountDetails(centerId); - final Set GROUP_ACCOUNTS_DATA_PARAMETERS = new HashSet<>(Arrays.asList("loanAccounts", "savingsAccounts", - "memberLoanAccounts", "memberSavingsAccounts")); + final Set GROUP_ACCOUNTS_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("loanAccounts", "savingsAccounts", "memberLoanAccounts", "memberSavingsAccounts")); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.groupSummaryToApiJsonSerializer.serialize(settings, groupAccount, GROUP_ACCOUNTS_DATA_PARAMETERS); @@ -386,17 +417,19 @@ public class CentersApiResource { @GET @Path("downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getCentersTemplate(@QueryParam("officeId")final Long officeId,@QueryParam("staffId")final Long staffId, + public Response getCentersTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("staffId") final Long staffId, @QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.CENTERS.toString(), officeId,staffId,dateFormat); + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.CENTERS.toString(), officeId, staffId, dateFormat); } + @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postCentersTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId=this. bulkImportWorkbookService.importWorkbook(GlobalEntityType.CENTERS.toString(), uploadedInputStream,fileDetail,locale,dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.CENTERS.toString(), + uploadedInputStream, fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/CentersApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/CentersApiResourceSwagger.java index 9a5b80bea..e56228b7f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/CentersApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/CentersApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/18/17. */ final class CentersApiResourceSwagger { - private CentersApiResourceSwagger() { - } + + private CentersApiResourceSwagger() {} @ApiModel(value = "GetCentersTemplateResponse") public final static class GetCentersTemplateResponse { - private GetCentersTemplateResponse() { - } + + private GetCentersTemplateResponse() {} final class GetCentersOfficeOptions { - private GetCentersOfficeOptions() { - } + + private GetCentersOfficeOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -48,8 +48,8 @@ final class CentersApiResourceSwagger { } final class GetCentersStaffOptions { - private GetCentersStaffOptions() { - } + + private GetCentersStaffOptions() {} @ApiModelProperty(example = "2") public Integer id; @@ -57,7 +57,6 @@ final class CentersApiResourceSwagger { public String displayName; } - @ApiModelProperty(example = "false") public Boolean active; @ApiModelProperty(example = "[2013, 4, 18]") @@ -70,16 +69,16 @@ final class CentersApiResourceSwagger { @ApiModel(value = "GetCentersResponse") public final static class GetCentersResponse { - private GetCentersResponse() { - } + + private GetCentersResponse() {} final class GetCentersPageItems { - private GetCentersPageItems() { - } + + private GetCentersPageItems() {} final class GetCentersStatus { - private GetCentersStatus() { - } + + private GetCentersStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -111,8 +110,8 @@ final class CentersApiResourceSwagger { @ApiModel(value = "GetCentersCenterIdResponse") public final static class GetCentersCenterIdResponse { - private GetCentersCenterIdResponse() { - } + + private GetCentersCenterIdResponse() {} @ApiModelProperty(example = "8") public Integer id; @@ -131,8 +130,8 @@ final class CentersApiResourceSwagger { @ApiModel(value = "PostCentersRequest") public final static class PostCentersRequest { - private PostCentersRequest() { - } + + private PostCentersRequest() {} @ApiModelProperty(example = "First Center (No groups)") public String name; @@ -144,8 +143,8 @@ final class CentersApiResourceSwagger { @ApiModel(value = "PostCentersResponse") public final static class PostCentersResponse { - private PostCentersResponse() { - } + + private PostCentersResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -157,8 +156,8 @@ final class CentersApiResourceSwagger { @ApiModel(value = "PutCentersCenterIdRequest") public final static class PutCentersCenterIdRequest { - private PutCentersCenterIdRequest() { - } + + private PutCentersCenterIdRequest() {} @ApiModelProperty(example = "First Center (No groups)") public String name; @@ -166,12 +165,12 @@ final class CentersApiResourceSwagger { @ApiModel(value = "PutCentersCenterIdResponse") public final static class PutCentersCenterIdResponse { - private PutCentersCenterIdResponse() { - } + + private PutCentersCenterIdResponse() {} final class PutCentersChanges { - private PutCentersChanges() { - } + + private PutCentersChanges() {} @ApiModelProperty(example = "First Center (No groups) - modified") public String name; @@ -188,12 +187,12 @@ final class CentersApiResourceSwagger { @ApiModel(value = "DeleteCentersCenterIdResponse") public final static class DeleteCentersCenterIdResponse { - private DeleteCentersCenterIdResponse() { - } + + private DeleteCentersCenterIdResponse() {} final class DeleteCentersChanges { - private DeleteCentersChanges() { - } + + private DeleteCentersChanges() {} } @ApiModelProperty(example = "1") @@ -203,8 +202,8 @@ final class CentersApiResourceSwagger { @ApiModel(value = "PostCentersCenterIdRequest") public final static class PostCentersCenterIdRequest { - private PostCentersCenterIdRequest() { - } + + private PostCentersCenterIdRequest() {} @ApiModelProperty(example = "32") public Integer closureReasonId; @@ -218,8 +217,8 @@ final class CentersApiResourceSwagger { @ApiModel(value = "PostCentersCenterIdResponse") public final static class PostCentersCenterIdResponse { - private PostCentersCenterIdResponse() { - } + + private PostCentersCenterIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -227,16 +226,16 @@ final class CentersApiResourceSwagger { @ApiModel(value = "GetCentersCenterIdAccountsResponse") public final static class GetCentersCenterIdAccountsResponse { - private GetCentersCenterIdAccountsResponse() { - } + + private GetCentersCenterIdAccountsResponse() {} final class GetCentersSavingsAccounts { - private GetCentersSavingsAccounts() { - } + + private GetCentersSavingsAccounts() {} final class GetCentersCenterIdStatus { - private GetCentersCenterIdStatus() { - } + + private GetCentersCenterIdStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -265,8 +264,8 @@ final class CentersApiResourceSwagger { } final class GetCentersCenterIdCurrency { - private GetCentersCenterIdCurrency() { - } + + private GetCentersCenterIdCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -285,8 +284,8 @@ final class CentersApiResourceSwagger { } final class GetCentersAccountType { - private GetCentersAccountType() { - } + + private GetCentersAccountType() {} @ApiModelProperty(example = "2") public Integer id; @@ -297,8 +296,8 @@ final class CentersApiResourceSwagger { } final class GetCentersTimeline { - private GetCentersTimeline() { - } + + private GetCentersTimeline() {} @ApiModelProperty(example = "[2014, 5, 1]") public LocalDate submittedOnDate; @@ -311,8 +310,8 @@ final class CentersApiResourceSwagger { } final class GetCentersDepositType { - private GetCentersDepositType() { - } + + private GetCentersDepositType() {} @ApiModelProperty(example = "100") public Integer id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupingTypesApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupingTypesApiConstants.java old mode 100755 new mode 100644 index dc5038b46..9b7dcc190 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupingTypesApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupingTypesApiConstants.java @@ -57,7 +57,7 @@ public class GroupingTypesApiConstants { public static final String groupMembersParamName = "groupMembers"; public static final String submittedOnDateParamName = "submittedOnDate"; - public static final String inheritStaffForClientAccounts = "inheritStaffForClientAccounts"; + public static final String inheritStaffForClientAccounts = "inheritStaffForClientAccounts"; // group parameters public static final String centerIdParamName = "centerId"; @@ -93,26 +93,22 @@ public class GroupingTypesApiConstants { * {@link CenterData}. Where possible, we try to get response parameters to * match those of request parameters. */ - protected static final Set CENTER_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, - nameParamName, - externalIdParamName, officeIdParamName, officeNameParamName, staffIdParamName, staffNameParamName, hierarchyParamName, - officeOptionsParamName, staffOptionsParamName, statusParamName, activeParamName, activationDateParamName, timeLine, - groupMembersParamName, collectionMeetingCalendar, closureReasons, datatables)); + protected static final Set CENTER_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(idParamName, nameParamName, externalIdParamName, officeIdParamName, officeNameParamName, staffIdParamName, + staffNameParamName, hierarchyParamName, officeOptionsParamName, staffOptionsParamName, statusParamName, activeParamName, + activationDateParamName, timeLine, groupMembersParamName, collectionMeetingCalendar, closureReasons, datatables)); - protected static final Set CENTER_GROUP_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, - nameParamName, + protected static final Set CENTER_GROUP_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, nameParamName, externalIdParamName, officeIdParamName, officeNameParamName, staffIdParamName, staffNameParamName, hierarchyParamName, officeOptionsParamName, staffOptionsParamName, clientOptionsParamName, datatables)); - protected static final Set GROUP_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, - nameParamName, - externalIdParamName, officeIdParamName, officeNameParamName, "parentId", "parentName", staffIdParamName, staffNameParamName, - hierarchyParamName, officeOptionsParamName, statusParamName, activeParamName, activationDateParamName, staffOptionsParamName, - clientOptionsParamName, timeLine, datatables)); + protected static final Set GROUP_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(idParamName, nameParamName, externalIdParamName, officeIdParamName, officeNameParamName, "parentId", "parentName", + staffIdParamName, staffNameParamName, hierarchyParamName, officeOptionsParamName, statusParamName, activeParamName, + activationDateParamName, staffOptionsParamName, clientOptionsParamName, timeLine, datatables)); - protected static final Set COLLECTIONSHEET_DATA_PARAMETERS = new HashSet<>( - Arrays.asList("dueDate", "loanProducts", "groups")); + protected static final Set COLLECTIONSHEET_DATA_PARAMETERS = new HashSet<>(Arrays.asList("dueDate", "loanProducts", "groups")); protected static final Set STAFF_CENTER_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(staffIdParamName, staffNameParamName, meetingFallCenters, totalCollected, totalOverdue, totaldue, installmentDue)); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsApiResource.java old mode 100755 new mode 100644 index d33141e24..f54a2cc04 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsApiResource.java @@ -104,10 +104,11 @@ import org.springframework.util.CollectionUtils; @Path("/groups") @Component @Scope("singleton") -@Api(tags = {"Groups"}) +@Api(tags = { "Groups" }) @SwaggerDefinition(tags = { - @Tag(name = "Groups", description = "Groups are used to provide a distinctive banking distribution channel used in microfinances throughout the world. The Group is an administrative unit. It can contain as few as 5 people or as many as 40 depending on how its used.\n" + "\n" + "Different styles of group lending - Joint-Liability Group, Grameen Model (Center-Group), Self-Help Groups, Village/Communal Banks)") -}) + @Tag(name = "Groups", description = "Groups are used to provide a distinctive banking distribution channel used in microfinances throughout the world. The Group is an administrative unit. It can contain as few as 5 people or as many as 40 depending on how its used.\n" + + "\n" + + "Different styles of group lending - Joint-Liability Group, Grameen Model (Center-Group), Self-Help Groups, Village/Communal Banks)") }) public class GroupsApiResource { private final PlatformSecurityContext context; @@ -133,7 +134,6 @@ public class GroupsApiResource { private final GLIMAccountInfoReadPlatformService glimAccountInfoReadPlatformService; private final GSIMReadPlatformService gsimReadPlatformService; - @Autowired public GroupsApiResource(final PlatformSecurityContext context, final GroupReadPlatformService groupReadPlatformService, final CenterReadPlatformService centerReadPlatformService, final ClientReadPlatformService clientReadPlatformService, @@ -153,15 +153,15 @@ public class GroupsApiResource { final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService, final GLIMAccountInfoReadPlatformService glimAccountInfoReadPlatformService, final GSIMReadPlatformService gsimReadPlatformService) { - this.context = context; + this.context = context; this.groupReadPlatformService = groupReadPlatformService; this.centerReadPlatformService = centerReadPlatformService; this.clientReadPlatformService = clientReadPlatformService; this.toApiJsonSerializer = toApiJsonSerializer; this.groupGeneralApiJsonSerializer = groupTopOfHierarchyApiJsonSerializer; this.groupSummaryToApiJsonSerializer = groupSummaryToApiJsonSerializer; - this.glimContainerToApiJsonSerializer=glimContainerToApiJsonSerializer; - this.gsimContainerToApiJsonSerializer=gsimContainerToApiJsonSerializer; + this.glimContainerToApiJsonSerializer = glimContainerToApiJsonSerializer; + this.gsimContainerToApiJsonSerializer = gsimContainerToApiJsonSerializer; this.apiRequestParameterHelper = apiRequestParameterHelper; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; this.collectionSheetReadPlatformService = collectionSheetReadPlatformService; @@ -171,10 +171,10 @@ public class GroupsApiResource { this.calendarReadPlatformService = calendarReadPlatformService; this.meetingReadPlatformService = meetingReadPlatformService; this.entityDatatableChecksReadService = entityDatatableChecksReadService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.glimAccountInfoReadPlatformService=glimAccountInfoReadPlatformService; - this.gsimReadPlatformService=gsimReadPlatformService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.glimAccountInfoReadPlatformService = glimAccountInfoReadPlatformService; + this.gsimReadPlatformService = gsimReadPlatformService; } @@ -182,10 +182,15 @@ public class GroupsApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Group Template", httpMethod = "GET", notes = "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:\n\n" + "\n\n" + "Field Defaults\n\n" + "Allowed Value Lists\n\n" + "Example Requests:\n\n" + "\n\n" + "groups/template\n\n" + "\n\n" + "groups/template?officeId=2\n\n" + "\n\n" + "groups/template?centerId=1\n\n" + "\n\n" + "groups/template?centerId=1&staffInSelectedOfficeOnly=true") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.GetGroupsTemplateResponse.class)}) - public String retrieveTemplate(@Context final UriInfo uriInfo, @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, - @QueryParam("center") @ApiParam(value = "center") final boolean isCenterGroup, @QueryParam("centerId") @ApiParam(value = "centerId") final Long centerId, + @ApiOperation(value = "Retrieve Group Template", httpMethod = "GET", notes = "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:\n\n" + + "\n\n" + "Field Defaults\n\n" + "Allowed Value Lists\n\n" + "Example Requests:\n\n" + "\n\n" + "groups/template\n\n" + "\n\n" + + "groups/template?officeId=2\n\n" + "\n\n" + "groups/template?centerId=1\n\n" + "\n\n" + + "groups/template?centerId=1&staffInSelectedOfficeOnly=true") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.GetGroupsTemplateResponse.class) }) + public String retrieveTemplate(@Context final UriInfo uriInfo, + @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, + @QueryParam("center") @ApiParam(value = "center") final boolean isCenterGroup, + @QueryParam("centerId") @ApiParam(value = "centerId") final Long centerId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly) { @@ -220,14 +225,22 @@ public class GroupsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Groups", httpMethod = "GET", notes = "The default implementation of listing Groups returns 200 entries with support for pagination and sorting. Using the parameter limit with value -1 returns all entries.\n\n" + "Example Requests:\n\n" + "\n\n" + "groups\n\n" + "\n\n" + "groups?fields=name,officeName,joinedDate\n\n" + "\n\n" + "groups?offset=10&limit=50\n\n" + "\n\n" + "groups?orderBy=name&sortOrder=DESC") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.GetGroupsResponse.class)}) - public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, - @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, @QueryParam("staffId") @ApiParam(value = "staffId") final Long staffId, - @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, @QueryParam("name") @ApiParam(value = "name") final String name, - @QueryParam("underHierarchy") @ApiParam(value = "underHierarchy") final String hierarchy, @QueryParam("paged") @ApiParam(value = "paged") final Boolean paged, - @QueryParam("offset")@ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, + @ApiOperation(value = "List Groups", httpMethod = "GET", notes = "The default implementation of listing Groups returns 200 entries with support for pagination and sorting. Using the parameter limit with value -1 returns all entries.\n\n" + + "Example Requests:\n\n" + "\n\n" + "groups\n\n" + "\n\n" + "groups?fields=name,officeName,joinedDate\n\n" + "\n\n" + + "groups?offset=10&limit=50\n\n" + "\n\n" + "groups?orderBy=name&sortOrder=DESC") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.GetGroupsResponse.class) }) + public String retrieveAll(@Context final UriInfo uriInfo, + @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, + @QueryParam("officeId") @ApiParam(value = "officeId") final Long officeId, + @QueryParam("staffId") @ApiParam(value = "staffId") final Long staffId, + @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, + @QueryParam("name") @ApiParam(value = "name") final String name, + @QueryParam("underHierarchy") @ApiParam(value = "underHierarchy") final String hierarchy, + @QueryParam("paged") @ApiParam(value = "paged") final Boolean paged, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, @QueryParam("orphansOnly") @ApiParam(value = "orphansOnly") final Boolean orphansOnly) { this.context.authenticatedUser().validateHasReadPermission(GroupingTypesApiConstants.GROUP_RESOURCE_NAME); @@ -249,8 +262,9 @@ public class GroupsApiResource { @Path("{groupId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Group", httpMethod = "GET", notes = "Retrieve group information.\n\n" + "Example Requests:\n\n" + "\n\n" + "groups/1\n\n" + "\n\n" + "groups/1?associations=clientMembers") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.GetGroupsGroupIdResponse.class)}) + @ApiOperation(value = "Retrieve a Group", httpMethod = "GET", notes = "Retrieve group information.\n\n" + "Example Requests:\n\n" + + "\n\n" + "groups/1\n\n" + "\n\n" + "groups/1?associations=clientMembers") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.GetGroupsGroupIdResponse.class) }) public String retrieveOne(@Context final UriInfo uriInfo, @PathParam("groupId") @ApiParam(value = "groupId") final Long groupId, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, @QueryParam("roleId") @ApiParam(value = "roleId") final Long roleId) { @@ -271,8 +285,8 @@ public class GroupsApiResource { if (!associationParameters.isEmpty()) { if (associationParameters.contains("all")) { - associationParameters.addAll(Arrays.asList("clientMembers", "activeClientMembers", - "groupRoles", "calendars", "collectionMeetingCalendar")); + associationParameters.addAll( + Arrays.asList("clientMembers", "activeClientMembers", "groupRoles", "calendars", "collectionMeetingCalendar")); } if (associationParameters.contains("clientMembers")) { membersOfGroup = this.clientReadPlatformService.retrieveClientMembersOfGroup(groupId); @@ -311,12 +325,12 @@ public class GroupsApiResource { if (collectionMeetingCalendar != null) { final boolean withHistory = true; final LocalDate tillDate = null; - final Collection recurringDates = this.calendarReadPlatformService.generateRecurringDates( - collectionMeetingCalendar, withHistory, tillDate); + final Collection recurringDates = this.calendarReadPlatformService + .generateRecurringDates(collectionMeetingCalendar, withHistory, tillDate); final Collection nextTenRecurringDates = this.calendarReadPlatformService .generateNextTenRecurringDates(collectionMeetingCalendar); - final MeetingData lastMeeting = this.meetingReadPlatformService.retrieveLastMeeting(collectionMeetingCalendar - .getCalendarInstanceId()); + final MeetingData lastMeeting = this.meetingReadPlatformService + .retrieveLastMeeting(collectionMeetingCalendar.getCalendarInstanceId()); final LocalDate recentEligibleMeetingDate = this.calendarReadPlatformService .generateNextEligibleMeetingDateForCollection(collectionMeetingCalendar, lastMeeting); collectionMeetingCalendar = CalendarData.withRecurringDates(collectionMeetingCalendar, recurringDates, @@ -324,8 +338,8 @@ public class GroupsApiResource { } } - group = GroupGeneralData.withAssocations(group, membersOfGroup, activeClientMembers, - groupRoles, calendars, collectionMeetingCalendar); + group = GroupGeneralData.withAssocations(group, membersOfGroup, activeClientMembers, groupRoles, calendars, + collectionMeetingCalendar); } if (roleId != null) { @@ -348,9 +362,12 @@ public class GroupsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Group", httpMethod = "POST", notes = "Creates a Group\n\n" + "Mandatory Fields: name, officeId, active, activationDate (if active=true)\n\n" + "Optional Fields: externalId, staffId, clientMembers") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = GroupsApiResourceSwagger.PostGroupsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.PostGroupsResponse.class)}) + @ApiOperation(value = "Create a Group", httpMethod = "POST", notes = "Creates a Group\n\n" + + "Mandatory Fields: name, officeId, active, activationDate (if active=true)\n\n" + + "Optional Fields: externalId, staffId, clientMembers") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = GroupsApiResourceSwagger.PostGroupsRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.PostGroupsResponse.class) }) public String create(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -365,10 +382,14 @@ public class GroupsApiResource { @Path("{groupId}/command/unassign_staff") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Unassign a Staff", httpMethod = "POST", notes = "Allows you to unassign the Staff.\n\n" + "Mandatory Fields: staffId") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = GroupsApiResourceSwagger.PostGroupsGroupIdCommandUnassignStaffRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.PostGroupsGroupIdCommandUnassignStaffResponse.class )}) - public String unassignLoanOfficer(@PathParam("groupId") @ApiParam(value = "groupId") final Long groupId,@ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Unassign a Staff", httpMethod = "POST", notes = "Allows you to unassign the Staff.\n\n" + + "Mandatory Fields: staffId") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = GroupsApiResourceSwagger.PostGroupsGroupIdCommandUnassignStaffRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.PostGroupsGroupIdCommandUnassignStaffResponse.class) }) + public String unassignLoanOfficer(@PathParam("groupId") @ApiParam(value = "groupId") final Long groupId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .unassignGroupStaff(groupId) // @@ -384,9 +405,11 @@ public class GroupsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Group", httpMethod = "PUT", notes = "Updates a Group") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = GroupsApiResourceSwagger.PutGroupsGroupIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.PutGroupsGroupIdResponse.class)}) - public String update(@PathParam("groupId")@ApiParam(value = "groupId") final Long groupId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = GroupsApiResourceSwagger.PutGroupsGroupIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.PutGroupsGroupIdResponse.class) }) + public String update(@PathParam("groupId") @ApiParam(value = "groupId") final Long groupId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // .updateGroup(groupId) // @@ -401,7 +424,7 @@ public class GroupsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Group", httpMethod = "DELETE", notes = "A group can be deleted if it is in pending state and has no associations - clients, loans or savings") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.DeleteGroupsGroupIdResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.DeleteGroupsGroupIdResponse.class) }) public String delete(@PathParam("groupId") @ApiParam(value = "groupId") final Long groupId) { final CommandWrapper commandRequest = new CommandWrapperBuilder() // @@ -415,11 +438,43 @@ public class GroupsApiResource { @Path("{groupId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Activate a Group | Associate Clients | Disassociate Clients | Transfer Clients across groups | Generate Collection Sheet | Save Collection Sheet | Unassign a Staff | Assign a Staff | Close a Group | Unassign a Role | Update a Role", httpMethod = "POST", notes = "Activate a Group:\n\n" + "Groups can be created in a Pending state. This API exists to enable group activation.\n\n" + "\n\n" + "If the group happens to be already active this API will result in an error.\n\n" + "Mandatory Fields: activationDate\n\n" + "Associate Clients:\n\n" + "This API allows to associate existing clients to a group.\n\n" + "\n\n" + "The clients are listed from the office to which the group is associated.\n\n" + "\n\n" + "If client(s) is already associated with group then API will result in an error.\n\n" + "Mandatory Fields: clientMembers\n\n" + "Disassociate Clients:\n\n" + "This API allows to disassociate clients from a group.\n\n" + "\n\n" + "Disassociating a client with active joint liability group loans results in an error.\n\n" + "Mandatory Fields: clientMembers\n\n" + "Transfer Clients across groups:\n\n" + "This API allows to transfer clients from one group to another\n\n" + "Mandatory Fields: destinationGroupId and clients\n\n" + "Optional Fields: inheritDestinationGroupLoanOfficer (defaults to true) and transferActiveLoans (defaults to true)\n\n" + "Generate Collection Sheet:\n\n" + "This API retrieves repayment details of all jlg loans of all members of a group on a specified meeting date.\n\n" + "Mandatory Fields: calendarId and transactionDate\n\n" + "Save Collection Sheet:\n\n" + "This api allows the loan officer to perform bulk repayments of JLG loans for a group on its meeting date.\n\n" + "Mandatory Fields: calendarId, transactionDate, actualDisbursementDate\n\n" + "Optional Fields: clientsAttendance, bulkRepaymentTransaction, bulkDisbursementTransactions\n\n" + "Unassign a Staff:\n\n" + "Allows you to unassign the Staff.\n\n" + "Mandatory Fields: staffId\n\n" + "Assign a Staff:\n\n" + "Allows you to assign Staff to an existing Group.\n\n" + "\n\n" + "The selected Staff should be belong to the same office (or an office higher up in the hierarchy) as this group" + "Mandatory Fields: staffId\n\n" + "Optional Fields: inheritStaffForClientAccounts (Optional: Boolean if true all members of the group (i.e all clients with active loans and savings ) will inherit the staffId)\n\n" + "Close a Group:\n\n" + "This API exists to close a group. Groups can be closed if they don't have any non-closed clients/loans/savingsAccounts.\n\n" + "\n\n" + "If the group has any active clients/loans/savingsAccount, this API will result in an error." + "Assign a Role:\n\n" + "Allows you to assign a Role to an existing member of a group.\n\n" + "\n\n" + "We can define the different roles applicable to group members by adding code values to the pre-defined system code GROUPROLE. Example:Group leader etc.\n\n" + "Mandatory Fields: clientId, role\n\n" + "Unassign a Role:\n\n" + "Allows you to unassign Roles associated tp Group members.\n\n" + "Update a Role:\n\n" + "Allows you to update the member Role.\n\n" + "Mandatory Fields: role\n\n" + "Showing request/response for Transfer Clients across groups") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = GroupsApiResourceSwagger.PostGroupsGroupIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.PostGroupsGroupIdResponse.class)}) + @ApiOperation(value = "Activate a Group | Associate Clients | Disassociate Clients | Transfer Clients across groups | Generate Collection Sheet | Save Collection Sheet | Unassign a Staff | Assign a Staff | Close a Group | Unassign a Role | Update a Role", httpMethod = "POST", notes = "Activate a Group:\n\n" + + "Groups can be created in a Pending state. This API exists to enable group activation.\n\n" + "\n\n" + + "If the group happens to be already active this API will result in an error.\n\n" + "Mandatory Fields: activationDate\n\n" + + "Associate Clients:\n\n" + "This API allows to associate existing clients to a group.\n\n" + "\n\n" + + "The clients are listed from the office to which the group is associated.\n\n" + "\n\n" + + "If client(s) is already associated with group then API will result in an error.\n\n" + "Mandatory Fields: clientMembers\n\n" + + "Disassociate Clients:\n\n" + "This API allows to disassociate clients from a group.\n\n" + "\n\n" + + "Disassociating a client with active joint liability group loans results in an error.\n\n" + + "Mandatory Fields: clientMembers\n\n" + "Transfer Clients across groups:\n\n" + + "This API allows to transfer clients from one group to another\n\n" + "Mandatory Fields: destinationGroupId and clients\n\n" + + "Optional Fields: inheritDestinationGroupLoanOfficer (defaults to true) and transferActiveLoans (defaults to true)\n\n" + + "Generate Collection Sheet:\n\n" + + "This API retrieves repayment details of all jlg loans of all members of a group on a specified meeting date.\n\n" + + "Mandatory Fields: calendarId and transactionDate\n\n" + "Save Collection Sheet:\n\n" + + "This api allows the loan officer to perform bulk repayments of JLG loans for a group on its meeting date.\n\n" + + "Mandatory Fields: calendarId, transactionDate, actualDisbursementDate\n\n" + + "Optional Fields: clientsAttendance, bulkRepaymentTransaction, bulkDisbursementTransactions\n\n" + "Unassign a Staff:\n\n" + + "Allows you to unassign the Staff.\n\n" + "Mandatory Fields: staffId\n\n" + "Assign a Staff:\n\n" + + "Allows you to assign Staff to an existing Group.\n\n" + "\n\n" + + "The selected Staff should be belong to the same office (or an office higher up in the hierarchy) as this group" + + "Mandatory Fields: staffId\n\n" + + "Optional Fields: inheritStaffForClientAccounts (Optional: Boolean if true all members of the group (i.e all clients with active loans and savings ) will inherit the staffId)\n\n" + + "Close a Group:\n\n" + + "This API exists to close a group. Groups can be closed if they don't have any non-closed clients/loans/savingsAccounts.\n\n" + + "\n\n" + "If the group has any active clients/loans/savingsAccount, this API will result in an error." + "Assign a Role:\n\n" + + "Allows you to assign a Role to an existing member of a group.\n\n" + "\n\n" + + "We can define the different roles applicable to group members by adding code values to the pre-defined system code GROUPROLE. Example:Group leader etc.\n\n" + + "Mandatory Fields: clientId, role\n\n" + "Unassign a Role:\n\n" + + "Allows you to unassign Roles associated tp Group members.\n\n" + "Update a Role:\n\n" + + "Allows you to update the member Role.\n\n" + "Mandatory Fields: role\n\n" + + "Showing request/response for Transfer Clients across groups") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = GroupsApiResourceSwagger.PostGroupsGroupIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.PostGroupsGroupIdResponse.class) }) public String activateOrGenerateCollectionSheet(@PathParam("groupId") @ApiParam(value = "groupId") final Long groupId, - @QueryParam("command") @ApiParam(value = "command") final String commandParam, @QueryParam("roleId") @ApiParam(value = "roleId") final Long roleId, @ApiParam(hidden = true) final String apiRequestBodyAsJson, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @QueryParam("roleId") @ApiParam(value = "roleId") final Long roleId, @ApiParam(hidden = true) final String apiRequestBodyAsJson, @Context final UriInfo uriInfo) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); @@ -490,39 +545,39 @@ public class GroupsApiResource { @Path("{groupId}/accounts") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Group accounts overview", httpMethod = "GET", notes = "Retrieves details of all Loan and Savings accounts associated with this group.\n\n" + "\n\n" + "Example Requests:\n\n" + "\n\n" + "groups/1/accounts\n\n" + "\n\n" + "\n\n" + "groups/1/accounts?fields=loanAccounts,savingsAccounts,memberLoanAccounts,\n\n" + "memberSavingsAccounts") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.GetGroupsGroupIdAccountsResponse.class)}) + @ApiOperation(value = "Retrieve Group accounts overview", httpMethod = "GET", notes = "Retrieves details of all Loan and Savings accounts associated with this group.\n\n" + + "\n\n" + "Example Requests:\n\n" + "\n\n" + "groups/1/accounts\n\n" + "\n\n" + "\n\n" + + "groups/1/accounts?fields=loanAccounts,savingsAccounts,memberLoanAccounts,\n\n" + "memberSavingsAccounts") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = GroupsApiResourceSwagger.GetGroupsGroupIdAccountsResponse.class) }) public String retrieveAccounts(@PathParam("groupId") @ApiParam(value = "groupId") final Long groupId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission("GROUP"); final AccountSummaryCollectionData groupAccount = this.accountDetailsReadPlatformService.retrieveGroupAccountDetails(groupId); - final Set GROUP_ACCOUNTS_DATA_PARAMETERS = new HashSet<>(Arrays.asList("loanAccounts", "groupLoanIndividualMonitoringAccounts","savingsAccounts", - "memberLoanAccounts", "memberSavingsAccounts")); + final Set GROUP_ACCOUNTS_DATA_PARAMETERS = new HashSet<>(Arrays.asList("loanAccounts", + "groupLoanIndividualMonitoringAccounts", "savingsAccounts", "memberLoanAccounts", "memberSavingsAccounts")); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.groupSummaryToApiJsonSerializer.serialize(settings, groupAccount, GROUP_ACCOUNTS_DATA_PARAMETERS); } - @GET @Path("downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getGroupsTemplate(@QueryParam("officeId")final Long officeId, - @QueryParam("staffId")final Long staffId,@QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.GROUPS.toString(), - officeId, staffId,dateFormat); + public Response getGroupsTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("staffId") final Long staffId, + @QueryParam("dateFormat") final String dateFormat) { + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.GROUPS.toString(), officeId, staffId, dateFormat); } @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postGroupTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId = this. bulkImportWorkbookService.importWorkbook(GlobalEntityType.GROUPS.toString(), - uploadedInputStream,fileDetail,locale,dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.GROUPS.toString(), uploadedInputStream, + fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } @@ -530,59 +585,51 @@ public class GroupsApiResource { @Path("{groupId}/glimaccounts") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveglimAccounts(@PathParam("groupId") final Long groupId, @QueryParam("parentLoanAccountNo")final String parentLoanAccountNo, @Context final UriInfo uriInfo) - { - this.context.authenticatedUser().validateHasReadPermission("GROUP"); - List glimContainer = Collections.emptyList(); - if(parentLoanAccountNo==null) - { - glimContainer=(List)glimAccountInfoReadPlatformService.findGlimAccount(groupId); - } - else - { - glimContainer=(List)glimAccountInfoReadPlatformService.findGlimAccountbyGroupAndAccount(groupId,parentLoanAccountNo); - } + public String retrieveglimAccounts(@PathParam("groupId") final Long groupId, + @QueryParam("parentLoanAccountNo") final String parentLoanAccountNo, @Context final UriInfo uriInfo) { + this.context.authenticatedUser().validateHasReadPermission("GROUP"); + List glimContainer = Collections.emptyList(); + if (parentLoanAccountNo == null) { + glimContainer = (List) glimAccountInfoReadPlatformService.findGlimAccount(groupId); + } else { + glimContainer = (List) glimAccountInfoReadPlatformService.findGlimAccountbyGroupAndAccount(groupId, + parentLoanAccountNo); + } + final Set GLIM_ACCOUNTS_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("groupId", "accountNumber", "childGLIMAccounts", "memberLoanAccounts", "parentPrincipalAmount")); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.glimContainerToApiJsonSerializer.serialize(settings, glimContainer, GLIM_ACCOUNTS_DATA_PARAMETERS); - final Set GLIM_ACCOUNTS_DATA_PARAMETERS = new HashSet<>(Arrays.asList("groupId", "accountNumber","childGLIMAccounts","memberLoanAccounts", "parentPrincipalAmount")); + } - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.glimContainerToApiJsonSerializer.serialize(settings, glimContainer, GLIM_ACCOUNTS_DATA_PARAMETERS); + @GET + @Path("{groupId}/gsimaccounts") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveGsimAccounts(@PathParam("groupId") final Long groupId, + @QueryParam("parentGSIMAccountNo") final String parentGSIMAccountNo, @QueryParam("parentGSIMId") final Long parentGSIMId, + @Context final UriInfo uriInfo) { + List gsimContainer; + this.context.authenticatedUser().validateHasReadPermission("GROUP"); - } + if (parentGSIMAccountNo == null && parentGSIMId != null) { + gsimContainer = this.gsimReadPlatformService.findGsimAccountContainerbyGsimAccountId(parentGSIMId); + } else if (parentGSIMAccountNo != null && parentGSIMId == null) { + gsimContainer = (List) this.gsimReadPlatformService + .findGsimAccountContainerbyGsimAccountNumber(parentGSIMAccountNo); + } else { + gsimContainer = (List) this.gsimReadPlatformService.findGSIMAccountContainerByGroupId(groupId); - @GET - @Path("{groupId}/gsimaccounts") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveGsimAccounts(@PathParam("groupId") final Long groupId, @QueryParam("parentGSIMAccountNo")final String parentGSIMAccountNo, - @QueryParam("parentGSIMId")final Long parentGSIMId,@Context final UriInfo uriInfo) - { - List gsimContainer; - this.context.authenticatedUser().validateHasReadPermission("GROUP"); + } - if(parentGSIMAccountNo==null && parentGSIMId!=null) - { - gsimContainer= this.gsimReadPlatformService.findGsimAccountContainerbyGsimAccountId(parentGSIMId); - } - else if(parentGSIMAccountNo !=null && parentGSIMId==null ) - { - gsimContainer= (List)this.gsimReadPlatformService.findGsimAccountContainerbyGsimAccountNumber(parentGSIMAccountNo); - } - else - { - gsimContainer= (List)this.gsimReadPlatformService.findGSIMAccountContainerByGroupId(groupId); + final Set GSIM_ACCOUNTS_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("gsimId", "groupId", "accountNumber", "childGSIMAccounts", "parentBalance", "savingsStatus")); - } + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.gsimContainerToApiJsonSerializer.serialize(settings, gsimContainer, GSIM_ACCOUNTS_DATA_PARAMETERS); - - final Set GSIM_ACCOUNTS_DATA_PARAMETERS = new HashSet<>(Arrays.asList("gsimId","groupId", "accountNumber","childGSIMAccounts", - "parentBalance", "savingsStatus")); - - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.gsimContainerToApiJsonSerializer.serialize(settings, gsimContainer, GSIM_ACCOUNTS_DATA_PARAMETERS); - - } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsApiResourceSwagger.java index ba7cf0f53..be059eacc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/10/17. */ final class GroupsApiResourceSwagger { - private GroupsApiResourceSwagger() { - } + + private GroupsApiResourceSwagger() {} @ApiModel(value = "GetGroupsTemplateResponse") public final static class GetGroupsTemplateResponse { - private GetGroupsTemplateResponse() { - } + + private GetGroupsTemplateResponse() {} final class GetGroupsTemplateOfficeOptions { - private GetGroupsTemplateOfficeOptions() { - } + + private GetGroupsTemplateOfficeOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -48,8 +48,8 @@ final class GroupsApiResourceSwagger { } final class GetGroupsTemplateStaffOptions { - private GetGroupsTemplateStaffOptions() { - } + + private GetGroupsTemplateStaffOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -58,8 +58,8 @@ final class GroupsApiResourceSwagger { } final class GetGroupsTemplateClientOptions { - private GetGroupsTemplateClientOptions() { - } + + private GetGroupsTemplateClientOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -72,16 +72,16 @@ final class GroupsApiResourceSwagger { } final class GetGroupsTemplateDatatables { - private GetGroupsTemplateDatatables() { - } + + private GetGroupsTemplateDatatables() {} final class GetGroupsTemplateColumnHeaderData { - private GetGroupsTemplateColumnHeaderData() { - } + + private GetGroupsTemplateColumnHeaderData() {} final class GetGroupsTemplateColumnValues { - private GetGroupsTemplateColumnValues() { - } + + private GetGroupsTemplateColumnValues() {} } @ApiModelProperty(example = "group_id") @@ -116,16 +116,16 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "GetGroupsResponse") public static final class GetGroupsResponse { - private GetGroupsResponse() { - } + + private GetGroupsResponse() {} final class GetGroupsPageItems { - private GetGroupsPageItems() { - } + + private GetGroupsPageItems() {} final class GetGroupsStatus { - private GetGroupsStatus() { - } + + private GetGroupsStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -157,12 +157,12 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "GetGroupsGroupIdResponse") public final static class GetGroupsGroupIdResponse { - private GetGroupsGroupIdResponse() { - } + + private GetGroupsGroupIdResponse() {} final class GetGroupsGroupIdTimeline { - private GetGroupsGroupIdTimeline() { - } + + private GetGroupsGroupIdTimeline() {} @ApiModelProperty(example = "[2013, 11, 14]") public LocalDate activatedOnDate; @@ -191,8 +191,8 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "PostGroupsRequest") public final static class PostGroupsRequest { - private PostGroupsRequest() { - } + + private PostGroupsRequest() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -204,8 +204,8 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "PostGroupsResponse") public final static class PostGroupsResponse { - private PostGroupsResponse() { - } + + private PostGroupsResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -217,8 +217,8 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "DeleteGroupsGroupIdResponse") public final static class DeleteGroupsGroupIdResponse { - private DeleteGroupsGroupIdResponse() { - } + + private DeleteGroupsGroupIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -230,8 +230,8 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "PostGroupsGroupIdCommandUnassignStaffRequest") public final static class PostGroupsGroupIdCommandUnassignStaffRequest { - private PostGroupsGroupIdCommandUnassignStaffRequest() { - } + + private PostGroupsGroupIdCommandUnassignStaffRequest() {} @ApiModelProperty(example = "1") public Integer staffId; @@ -239,12 +239,12 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "PostGroupsGroupIdCommandUnassignStaffResponse") public final static class PostGroupsGroupIdCommandUnassignStaffResponse { - private PostGroupsGroupIdCommandUnassignStaffResponse() { - } + + private PostGroupsGroupIdCommandUnassignStaffResponse() {} final class PostGroupsGroupIdCommandUnassignStaffChanges { - private PostGroupsGroupIdCommandUnassignStaffChanges() { - } + + private PostGroupsGroupIdCommandUnassignStaffChanges() {} } @ApiModelProperty(example = "1") @@ -258,8 +258,8 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "PutGroupsGroupIdRequest") public final static class PutGroupsGroupIdRequest { - private PutGroupsGroupIdRequest() { - } + + private PutGroupsGroupIdRequest() {} @ApiModelProperty(example = "First Group (changed)") public String name; @@ -267,12 +267,12 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "PutGroupsGroupIdResponse") public final static class PutGroupsGroupIdResponse { - private PutGroupsGroupIdResponse() { - } + + private PutGroupsGroupIdResponse() {} final class PutGroupsGroupIdChanges { - private PutGroupsGroupIdChanges() { - } + + private PutGroupsGroupIdChanges() {} @ApiModelProperty(example = "First Group (changed)") public String name; @@ -289,16 +289,16 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "GetGroupsGroupIdAccountsResponse") public final static class GetGroupsGroupIdAccountsResponse { - private GetGroupsGroupIdAccountsResponse() { - } + + private GetGroupsGroupIdAccountsResponse() {} final class GetGroupsGroupIdAccountsLoanAccounts { - private GetGroupsGroupIdAccountsLoanAccounts() { - } + + private GetGroupsGroupIdAccountsLoanAccounts() {} final class GetGroupsGroupIdAccountsStatus { - private GetGroupsGroupIdAccountsStatus() { - } + + private GetGroupsGroupIdAccountsStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -325,8 +325,8 @@ final class GroupsApiResourceSwagger { } final class GetGroupsGroupIdAccountsLoanType { - private GetGroupsGroupIdAccountsLoanType() { - } + + private GetGroupsGroupIdAccountsLoanType() {} @ApiModelProperty(example = "2") public Integer id; @@ -349,12 +349,12 @@ final class GroupsApiResourceSwagger { } final class GetGroupsGroupIdAccountsSavingAccounts { - private GetGroupsGroupIdAccountsSavingAccounts() { - } + + private GetGroupsGroupIdAccountsSavingAccounts() {} final class GetGroupsGroupIdAccountsSavingStatus { - private GetGroupsGroupIdAccountsSavingStatus() { - } + + private GetGroupsGroupIdAccountsSavingStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -377,8 +377,8 @@ final class GroupsApiResourceSwagger { } final class GetGroupsGroupIdAccountsSavingCurrency { - private GetGroupsGroupIdAccountsSavingCurrency() { - } + + private GetGroupsGroupIdAccountsSavingCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -395,8 +395,8 @@ final class GroupsApiResourceSwagger { } final class GetGroupsGroupIdAccountsSavingAccountType { - private GetGroupsGroupIdAccountsSavingAccountType() { - } + + private GetGroupsGroupIdAccountsSavingAccountType() {} @ApiModelProperty(example = "2") public Integer id; @@ -420,12 +420,12 @@ final class GroupsApiResourceSwagger { } final class GetGroupsGroupIdAccountsMemberLoanAccounts { - private GetGroupsGroupIdAccountsMemberLoanAccounts() { - } + + private GetGroupsGroupIdAccountsMemberLoanAccounts() {} final class GetGroupsGroupIdAccountsMemberLoanStatus { - private GetGroupsGroupIdAccountsMemberLoanStatus() { - } + + private GetGroupsGroupIdAccountsMemberLoanStatus() {} @ApiModelProperty(example = "200") public Integer id; @@ -452,8 +452,8 @@ final class GroupsApiResourceSwagger { } final class GetGroupsGroupIdAccountsMemberLoanType { - private GetGroupsGroupIdAccountsMemberLoanType() { - } + + private GetGroupsGroupIdAccountsMemberLoanType() {} @ApiModelProperty(example = "3") public Integer id; @@ -476,9 +476,8 @@ final class GroupsApiResourceSwagger { } final class GetGroupsGroupIdAccountsMemberSavingsAccounts { - private GetGroupsGroupIdAccountsMemberSavingsAccounts() { - } + private GetGroupsGroupIdAccountsMemberSavingsAccounts() {} @ApiModelProperty(example = "3") public Integer id; @@ -501,12 +500,12 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "PostGroupsGroupIdRequest") public final static class PostGroupsGroupIdRequest { - private PostGroupsGroupIdRequest() { - } + + private PostGroupsGroupIdRequest() {} final class PostGroupsGroupIdClients { - private PostGroupsGroupIdClients() { - } + + private PostGroupsGroupIdClients() {} @ApiModelProperty(example = "1") public Integer id; @@ -519,8 +518,8 @@ final class GroupsApiResourceSwagger { @ApiModel(value = "PostGroupsGroupIdResponse") public final static class PostGroupsGroupIdResponse { - private PostGroupsGroupIdResponse() { - } + + private PostGroupsGroupIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsLevelApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsLevelApiResource.java index ab4e7a359..f0c88892e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsLevelApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/api/GroupsLevelApiResource.java @@ -44,8 +44,8 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class GroupsLevelApiResource { - private static final Set GROUPLEVEL_DATA_PARAMETERS = new HashSet<>(Arrays.asList("levelId", "levelName", - "parentLevelId", "parentLevelName", "childLevelId", "childLevelName", "superParent", "recursable", "canHaveClients")); + private static final Set GROUPLEVEL_DATA_PARAMETERS = new HashSet<>(Arrays.asList("levelId", "levelName", "parentLevelId", + "parentLevelName", "childLevelId", "childLevelName", "superParent", "recursable", "canHaveClients")); private final PlatformSecurityContext context; private final GroupLevelReadPlatformService groupLevelReadPlatformService; @@ -74,4 +74,4 @@ public class GroupsLevelApiResource { return this.toApiJsonSerializer.serialize(settings, groupLevel, GROUPLEVEL_DATA_PARAMETERS); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/CenterData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/CenterData.java index 365a03373..d06a2ff6b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/CenterData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/CenterData.java @@ -68,49 +68,48 @@ public class CenterData implements Serializable { private List datatables = null; - //import fields + // import fields private transient Integer rowIndex; private String dateFormat; private String locale; private LocalDate submittedOnDate; - public static CenterData importInstance(String name,List groupMembers,LocalDate activationDate, - boolean active ,LocalDate submittedOnDate,String externalId, Long officeId, - Long staffId,Integer rowIndex,String dateFormat,String locale){ + public static CenterData importInstance(String name, List groupMembers, LocalDate activationDate, boolean active, + LocalDate submittedOnDate, String externalId, Long officeId, Long staffId, Integer rowIndex, String dateFormat, String locale) { - return new CenterData(name,groupMembers,activationDate, active,submittedOnDate, externalId, officeId, staffId, rowIndex,dateFormat,locale); + return new CenterData(name, groupMembers, activationDate, active, submittedOnDate, externalId, officeId, staffId, rowIndex, + dateFormat, locale); } - private CenterData(String name,List groupMembers,LocalDate activationDate, - boolean active ,LocalDate submittedOnDate,String externalId, Long officeId, - Long staffId,Integer rowIndex,String dateFormat,String locale) { + private CenterData(String name, List groupMembers, LocalDate activationDate, boolean active, + LocalDate submittedOnDate, String externalId, Long officeId, Long staffId, Integer rowIndex, String dateFormat, String locale) { this.name = name; - this.groupMembers=groupMembers; + this.groupMembers = groupMembers; this.externalId = externalId; this.officeId = officeId; this.staffId = staffId; this.active = active; this.activationDate = activationDate; - this.submittedOnDate=submittedOnDate; + this.submittedOnDate = submittedOnDate; this.rowIndex = rowIndex; - this.dateFormat= dateFormat; - this.locale=locale; - this.status=null; - this.id=null; + this.dateFormat = dateFormat; + this.locale = locale; + this.status = null; + this.id = null; this.accountNo = null; this.staffName = null; this.hierarchy = null; this.timeline = null; this.groupMembersOptions = null; this.collectionMeetingCalendar = null; - this.closureReasons =null; + this.closureReasons = null; this.officeOptions = null; this.staffOptions = null; - this.totalCollected =null; + this.totalCollected = null; this.totalOverdue = null; this.totaldue = null; this.installmentDue = null; - this.officeName=null; + this.officeName = null; } public Integer getRowIndex() { @@ -243,7 +242,7 @@ public class CenterData implements Serializable { return this.id; } - public String getAccountNo(){ + public String getAccountNo() { return this.accountNo; } @@ -269,45 +268,30 @@ public class CenterData implements Serializable { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof CenterData)) { - return false; - } + if (this == o) { return true; } + if (!(o instanceof CenterData)) { return false; } CenterData that = (CenterData) o; - return Objects.equals(active, that.active) && - Objects.equals(id, that.id) && - Objects.equals(accountNo, that.accountNo) && - Objects.equals(name, that.name) && - Objects.equals(externalId, that.externalId) && - Objects.equals(officeId, that.officeId) && - Objects.equals(officeName, that.officeName) && - Objects.equals(staffId, that.staffId) && - Objects.equals(staffName, that.staffName) && - Objects.equals(hierarchy, that.hierarchy) && - Objects.equals(status, that.status) && - Objects.equals(activationDate, that.activationDate) && - Objects.equals(timeline, that.timeline) && - Objects.equals(groupMembers, that.groupMembers) && - Objects.equals(groupMembersOptions, that.groupMembersOptions) && - Objects.equals(collectionMeetingCalendar, that.collectionMeetingCalendar) && - Objects.equals(closureReasons, that.closureReasons) && - Objects.equals(officeOptions, that.officeOptions) && - Objects.equals(staffOptions, that.staffOptions) && - Objects.equals(totalCollected, that.totalCollected) && - Objects.equals(totalOverdue, that.totalOverdue) && - Objects.equals(totaldue, that.totaldue) && - Objects.equals(installmentDue, that.installmentDue) && - Objects.equals(datatables, that.datatables) && - Objects.equals(rowIndex, that.rowIndex) && - Objects.equals(dateFormat, that.dateFormat) && - Objects.equals(locale, that.locale) && - Objects.equals(submittedOnDate, that.submittedOnDate); + return Objects.equals(active, that.active) && Objects.equals(id, that.id) && Objects.equals(accountNo, that.accountNo) + && Objects.equals(name, that.name) && Objects.equals(externalId, that.externalId) && Objects.equals(officeId, that.officeId) + && Objects.equals(officeName, that.officeName) && Objects.equals(staffId, that.staffId) + && Objects.equals(staffName, that.staffName) && Objects.equals(hierarchy, that.hierarchy) + && Objects.equals(status, that.status) && Objects.equals(activationDate, that.activationDate) + && Objects.equals(timeline, that.timeline) && Objects.equals(groupMembers, that.groupMembers) + && Objects.equals(groupMembersOptions, that.groupMembersOptions) + && Objects.equals(collectionMeetingCalendar, that.collectionMeetingCalendar) + && Objects.equals(closureReasons, that.closureReasons) && Objects.equals(officeOptions, that.officeOptions) + && Objects.equals(staffOptions, that.staffOptions) && Objects.equals(totalCollected, that.totalCollected) + && Objects.equals(totalOverdue, that.totalOverdue) && Objects.equals(totaldue, that.totaldue) + && Objects.equals(installmentDue, that.installmentDue) && Objects.equals(datatables, that.datatables) + && Objects.equals(rowIndex, that.rowIndex) && Objects.equals(dateFormat, that.dateFormat) + && Objects.equals(locale, that.locale) && Objects.equals(submittedOnDate, that.submittedOnDate); } @Override public int hashCode() { - return Objects.hash(id, accountNo, name, externalId, officeId, officeName, staffId, staffName, hierarchy, status, active, activationDate, timeline, groupMembers, groupMembersOptions, collectionMeetingCalendar, closureReasons, officeOptions, staffOptions, totalCollected, totalOverdue, totaldue, installmentDue, datatables, rowIndex, dateFormat, locale, submittedOnDate); + return Objects.hash(id, accountNo, name, externalId, officeId, officeName, staffId, staffName, hierarchy, status, active, + activationDate, timeline, groupMembers, groupMembersOptions, collectionMeetingCalendar, closureReasons, officeOptions, + staffOptions, totalCollected, totalOverdue, totaldue, installmentDue, datatables, rowIndex, dateFormat, locale, + submittedOnDate); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupGeneralData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupGeneralData.java index aa61316a9..62fdf791d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupGeneralData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupGeneralData.java @@ -75,25 +75,25 @@ public class GroupGeneralData implements Serializable { private List datatables = null; - //import fields + // import fields private transient Integer rowIndex; private String dateFormat; private String locale; private LocalDate submittedOnDate; - public static GroupGeneralData importInstance(String groupName,List clientMembers,LocalDate activationDate, - LocalDate submittedOnDate ,Boolean active,String externalId,Long officeId,Long staffId, - Long centerId, Integer rowIndex,String locale,String dateFormat){ + public static GroupGeneralData importInstance(String groupName, List clientMembers, LocalDate activationDate, + LocalDate submittedOnDate, Boolean active, String externalId, Long officeId, Long staffId, Long centerId, Integer rowIndex, + String locale, String dateFormat) { - return new GroupGeneralData(groupName, clientMembers, activationDate, submittedOnDate,active, externalId, - officeId, staffId, centerId, rowIndex,locale,dateFormat); + return new GroupGeneralData(groupName, clientMembers, activationDate, submittedOnDate, active, externalId, officeId, staffId, + centerId, rowIndex, locale, dateFormat); } - private GroupGeneralData(String name,List clientMembers,LocalDate activationDate, - LocalDate submittedOnDate ,Boolean active,String externalId,Long officeId,Long staffId, - Long centerId, Integer rowIndex,String locale,String dateFormat ){ - this.dateFormat= dateFormat; - this.locale= locale; + private GroupGeneralData(String name, List clientMembers, LocalDate activationDate, LocalDate submittedOnDate, + Boolean active, String externalId, Long officeId, Long staffId, Long centerId, Integer rowIndex, String locale, + String dateFormat) { + this.dateFormat = dateFormat; + this.locale = locale; this.name = name; this.clientMembers = clientMembers; this.officeId = officeId; @@ -102,13 +102,13 @@ public class GroupGeneralData implements Serializable { this.externalId = externalId; this.active = active; this.activationDate = activationDate; - this.submittedOnDate=submittedOnDate; + this.submittedOnDate = submittedOnDate; this.rowIndex = rowIndex; - this.id=null; + this.id = null; this.accountNo = null; this.status = null; this.officeName = null; - this.centerName =null; + this.centerName = null; this.staffName = null; this.hierarchy = null; this.groupLevel = null; @@ -177,46 +177,47 @@ public class GroupGeneralData implements Serializable { final Collection clientMembers = null; final Collection groupRoles = null; final Collection closureReasons = null; - return new GroupGeneralData(groupId, accountNo, groupName, null, null, null, null, null, null, null, null, null, null, null, clientMembers, null, null, - null, null, null, groupRoles, null, null, null, null, closureReasons, null); + return new GroupGeneralData(groupId, accountNo, groupName, null, null, null, null, null, null, null, null, null, null, null, + clientMembers, null, null, null, null, null, groupRoles, null, null, null, null, closureReasons, null); } - public static GroupGeneralData template(final Long officeId, final Long centerId, final String accountNo, final String centerName, final Long staffId, - final String staffName, final Collection centerOptions, final Collection officeOptions, - final Collection staffOptions, final Collection clientOptions, - final Collection availableRoles) { + public static GroupGeneralData template(final Long officeId, final Long centerId, final String accountNo, final String centerName, + final Long staffId, final String staffName, final Collection centerOptions, + final Collection officeOptions, final Collection staffOptions, + final Collection clientOptions, final Collection availableRoles) { final Collection clientMembers = null; final Collection groupRoles = null; final Collection closureReasons = null; - return new GroupGeneralData(null, accountNo , null, null, null, null, officeId, null, centerId, centerName, staffId, staffName, null, null, - clientMembers, null, centerOptions, officeOptions, staffOptions, clientOptions, groupRoles, availableRoles, null, null, null, - closureReasons, null); + return new GroupGeneralData(null, accountNo, null, null, null, null, officeId, null, centerId, centerName, staffId, staffName, null, + null, clientMembers, null, centerOptions, officeOptions, staffOptions, clientOptions, groupRoles, availableRoles, null, + null, null, closureReasons, null); } public static GroupGeneralData withTemplate(final GroupGeneralData templatedGrouping, final GroupGeneralData grouping) { - return new GroupGeneralData(grouping.id, grouping.accountNo, grouping.name, grouping.externalId, grouping.status, grouping.activationDate, - grouping.officeId, grouping.officeName, grouping.centerId, grouping.centerName, grouping.staffId, grouping.staffName, - grouping.hierarchy, grouping.groupLevel, grouping.clientMembers, grouping.activeClientMembers, templatedGrouping.centerOptions, templatedGrouping.officeOptions, - templatedGrouping.staffOptions, templatedGrouping.clientOptions, grouping.groupRoles, templatedGrouping.availableRoles, - grouping.selectedRole, grouping.calendarsData, grouping.collectionMeetingCalendar, grouping.closureReasons, - templatedGrouping.timeline); + return new GroupGeneralData(grouping.id, grouping.accountNo, grouping.name, grouping.externalId, grouping.status, + grouping.activationDate, grouping.officeId, grouping.officeName, grouping.centerId, grouping.centerName, grouping.staffId, + grouping.staffName, grouping.hierarchy, grouping.groupLevel, grouping.clientMembers, grouping.activeClientMembers, + templatedGrouping.centerOptions, templatedGrouping.officeOptions, templatedGrouping.staffOptions, + templatedGrouping.clientOptions, grouping.groupRoles, templatedGrouping.availableRoles, grouping.selectedRole, + grouping.calendarsData, grouping.collectionMeetingCalendar, grouping.closureReasons, templatedGrouping.timeline); } public static GroupGeneralData withAssocations(final GroupGeneralData grouping, final Collection membersOfGroup, - final Collection activeClientMembers, final Collection groupRoles, final Collection calendarsData, - final CalendarData collectionMeetingCalendar) { - return new GroupGeneralData(grouping.id, grouping.accountNo, grouping.name, grouping.externalId, grouping.status, grouping.activationDate, - grouping.officeId, grouping.officeName, grouping.centerId, grouping.centerName, grouping.staffId, grouping.staffName, - grouping.hierarchy, grouping.groupLevel, membersOfGroup, activeClientMembers, grouping.centerOptions, grouping.officeOptions, grouping.staffOptions, - grouping.clientOptions, groupRoles, grouping.availableRoles, grouping.selectedRole, calendarsData, - collectionMeetingCalendar, grouping.closureReasons, grouping.timeline); + final Collection activeClientMembers, final Collection groupRoles, + final Collection calendarsData, final CalendarData collectionMeetingCalendar) { + return new GroupGeneralData(grouping.id, grouping.accountNo, grouping.name, grouping.externalId, grouping.status, + grouping.activationDate, grouping.officeId, grouping.officeName, grouping.centerId, grouping.centerName, grouping.staffId, + grouping.staffName, grouping.hierarchy, grouping.groupLevel, membersOfGroup, activeClientMembers, grouping.centerOptions, + grouping.officeOptions, grouping.staffOptions, grouping.clientOptions, groupRoles, grouping.availableRoles, + grouping.selectedRole, calendarsData, collectionMeetingCalendar, grouping.closureReasons, grouping.timeline); } - public static GroupGeneralData instance(final Long id, final String accountNo, final String name, final String externalId, final EnumOptionData status, - final LocalDate activationDate, final Long officeId, final String officeName, final Long centerId, final String centerName, - final Long staffId, final String staffName, final String hierarchy, final String groupLevel, final GroupTimelineData timeline) { + public static GroupGeneralData instance(final Long id, final String accountNo, final String name, final String externalId, + final EnumOptionData status, final LocalDate activationDate, final Long officeId, final String officeName, final Long centerId, + final String centerName, final Long staffId, final String staffName, final String hierarchy, final String groupLevel, + final GroupTimelineData timeline) { final Collection clientMembers = null; final Collection activeClientMembers = null; @@ -231,18 +232,18 @@ public class GroupGeneralData implements Serializable { final CalendarData collectionMeetingCalendar = null; final Collection closureReasons = null; - return new GroupGeneralData(id, accountNo, name, externalId, status, activationDate, officeId, officeName, centerId, centerName, staffId, - staffName, hierarchy, groupLevel, clientMembers, activeClientMembers, centerOptions, officeOptions, staffOptions, + return new GroupGeneralData(id, accountNo, name, externalId, status, activationDate, officeId, officeName, centerId, centerName, + staffId, staffName, hierarchy, groupLevel, clientMembers, activeClientMembers, centerOptions, officeOptions, staffOptions, clientOptions, groupRoles, availableRoles, role, calendarsData, collectionMeetingCalendar, closureReasons, timeline); } private GroupGeneralData(final Long id, final String accountNo, final String name, final String externalId, final EnumOptionData status, final LocalDate activationDate, final Long officeId, final String officeName, final Long centerId, final String centerName, - final Long staffId, final String staffName, final String hierarchy, final String groupLevel, final Collection clientMembers, - final Collection activeClientMembers, final Collection centerOptions, - final Collection officeOptions, final Collection staffOptions, - final Collection clientOptions, final Collection groupRoles, - final Collection availableRoles, final GroupRoleData role, + final Long staffId, final String staffName, final String hierarchy, final String groupLevel, + final Collection clientMembers, final Collection activeClientMembers, + final Collection centerOptions, final Collection officeOptions, + final Collection staffOptions, final Collection clientOptions, + final Collection groupRoles, final Collection availableRoles, final GroupRoleData role, final Collection calendarsData, final CalendarData collectionMeetingCalendar, final Collection closureReasons, final GroupTimelineData timeline) { this.id = id; @@ -292,7 +293,7 @@ public class GroupGeneralData implements Serializable { return this.id; } - public String getAccountNo(){ + public String getAccountNo() { return this.accountNo; } @@ -317,11 +318,12 @@ public class GroupGeneralData implements Serializable { } public static GroupGeneralData updateSelectedRole(final GroupGeneralData grouping, final GroupRoleData selectedRole) { - return new GroupGeneralData(grouping.id, grouping.accountNo, grouping.name, grouping.externalId, grouping.status, grouping.activationDate, - grouping.officeId, grouping.officeName, grouping.centerId, grouping.centerName, grouping.staffId, grouping.staffName, - grouping.hierarchy, grouping.groupLevel, grouping.clientMembers, grouping.activeClientMembers, grouping.centerOptions, - grouping.officeOptions, grouping.staffOptions, grouping.clientOptions, grouping.groupRoles, grouping.availableRoles, - selectedRole, grouping.calendarsData, grouping.collectionMeetingCalendar, grouping.closureReasons, null); + return new GroupGeneralData(grouping.id, grouping.accountNo, grouping.name, grouping.externalId, grouping.status, + grouping.activationDate, grouping.officeId, grouping.officeName, grouping.centerId, grouping.centerName, grouping.staffId, + grouping.staffName, grouping.hierarchy, grouping.groupLevel, grouping.clientMembers, grouping.activeClientMembers, + grouping.centerOptions, grouping.officeOptions, grouping.staffOptions, grouping.clientOptions, grouping.groupRoles, + grouping.availableRoles, selectedRole, grouping.calendarsData, grouping.collectionMeetingCalendar, grouping.closureReasons, + null); } public static GroupGeneralData withClosureReasons(final Collection closureReasons) { @@ -351,9 +353,9 @@ public class GroupGeneralData implements Serializable { final Collection calendarsData = null; final CalendarData collectionMeetingCalendar = null; - return new GroupGeneralData(id, accountNo, name, externalId, status, activationDate, officeId, officeName, centerId, centerName, staffId, - staffName, hierarchy, groupLevel, clientMembers, activeClientMembers, centerOptions, officeOptions, staffOptions, clientOptions, groupRoles, - availableRoles, role, calendarsData, collectionMeetingCalendar, closureReasons, null); + return new GroupGeneralData(id, accountNo, name, externalId, status, activationDate, officeId, officeName, centerId, centerName, + staffId, staffName, hierarchy, groupLevel, clientMembers, activeClientMembers, centerOptions, officeOptions, staffOptions, + clientOptions, groupRoles, availableRoles, role, calendarsData, collectionMeetingCalendar, closureReasons, null); } public Collection clientMembers() { @@ -361,55 +363,38 @@ public class GroupGeneralData implements Serializable { } public void setDatatables(final List datatables) { - this.datatables = datatables; + this.datatables = datatables; } @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof GroupGeneralData)) { - return false; - } + if (this == o) { return true; } + if (!(o instanceof GroupGeneralData)) { return false; } GroupGeneralData that = (GroupGeneralData) o; - return Objects.equals(id, that.id) && - Objects.equals(accountNo, that.accountNo) && - Objects.equals(name, that.name) && - Objects.equals(externalId, that.externalId) && - Objects.equals(status, that.status) && - Objects.equals(active, that.active) && - Objects.equals(activationDate, that.activationDate) && - Objects.equals(officeId, that.officeId) && - Objects.equals(officeName, that.officeName) && - Objects.equals(centerId, that.centerId) && - Objects.equals(centerName, that.centerName) && - Objects.equals(staffId, that.staffId) && - Objects.equals(staffName, that.staffName) && - Objects.equals(hierarchy, that.hierarchy) && - Objects.equals(groupLevel, that.groupLevel) && - Objects.equals(clientMembers, that.clientMembers) && - Objects.equals(activeClientMembers, that.activeClientMembers) && - Objects.equals(groupRoles, that.groupRoles) && - Objects.equals(calendarsData, that.calendarsData) && - Objects.equals(collectionMeetingCalendar, that.collectionMeetingCalendar) && - Objects.equals(centerOptions, that.centerOptions) && - Objects.equals(officeOptions, that.officeOptions) && - Objects.equals(staffOptions, that.staffOptions) && - Objects.equals(clientOptions, that.clientOptions) && - Objects.equals(availableRoles, that.availableRoles) && - Objects.equals(selectedRole, that.selectedRole) && - Objects.equals(closureReasons, that.closureReasons) && - Objects.equals(timeline, that.timeline) && - Objects.equals(datatables, that.datatables) && - Objects.equals(rowIndex, that.rowIndex) && - Objects.equals(dateFormat, that.dateFormat) && - Objects.equals(locale, that.locale) && - Objects.equals(submittedOnDate, that.submittedOnDate); + return Objects.equals(id, that.id) && Objects.equals(accountNo, that.accountNo) && Objects.equals(name, that.name) + && Objects.equals(externalId, that.externalId) && Objects.equals(status, that.status) && Objects.equals(active, that.active) + && Objects.equals(activationDate, that.activationDate) && Objects.equals(officeId, that.officeId) + && Objects.equals(officeName, that.officeName) && Objects.equals(centerId, that.centerId) + && Objects.equals(centerName, that.centerName) && Objects.equals(staffId, that.staffId) + && Objects.equals(staffName, that.staffName) && Objects.equals(hierarchy, that.hierarchy) + && Objects.equals(groupLevel, that.groupLevel) && Objects.equals(clientMembers, that.clientMembers) + && Objects.equals(activeClientMembers, that.activeClientMembers) && Objects.equals(groupRoles, that.groupRoles) + && Objects.equals(calendarsData, that.calendarsData) + && Objects.equals(collectionMeetingCalendar, that.collectionMeetingCalendar) + && Objects.equals(centerOptions, that.centerOptions) && Objects.equals(officeOptions, that.officeOptions) + && Objects.equals(staffOptions, that.staffOptions) && Objects.equals(clientOptions, that.clientOptions) + && Objects.equals(availableRoles, that.availableRoles) && Objects.equals(selectedRole, that.selectedRole) + && Objects.equals(closureReasons, that.closureReasons) && Objects.equals(timeline, that.timeline) + && Objects.equals(datatables, that.datatables) && Objects.equals(rowIndex, that.rowIndex) + && Objects.equals(dateFormat, that.dateFormat) && Objects.equals(locale, that.locale) + && Objects.equals(submittedOnDate, that.submittedOnDate); } @Override public int hashCode() { - return Objects.hash(id, accountNo, name, externalId, status, active, activationDate, officeId, officeName, centerId, centerName, staffId, staffName, hierarchy, groupLevel, clientMembers, activeClientMembers, groupRoles, calendarsData, collectionMeetingCalendar, centerOptions, officeOptions, staffOptions, clientOptions, availableRoles, selectedRole, closureReasons, timeline, datatables, rowIndex, dateFormat, locale, submittedOnDate); + return Objects.hash(id, accountNo, name, externalId, status, active, activationDate, officeId, officeName, centerId, centerName, + staffId, staffName, hierarchy, groupLevel, clientMembers, activeClientMembers, groupRoles, calendarsData, + collectionMeetingCalendar, centerOptions, officeOptions, staffOptions, clientOptions, availableRoles, selectedRole, + closureReasons, timeline, datatables, rowIndex, dateFormat, locale, submittedOnDate); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupLevelData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupLevelData.java index 769a52543..a595c02be 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupLevelData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupLevelData.java @@ -84,4 +84,4 @@ public class GroupLevelData { return this.canHaveClients; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupRoleData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupRoleData.java index 329e55028..1acc64476 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupRoleData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupRoleData.java @@ -46,17 +46,11 @@ public class GroupRoleData implements Serializable { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof GroupRoleData)) { - return false; - } + if (this == o) { return true; } + if (!(o instanceof GroupRoleData)) { return false; } GroupRoleData that = (GroupRoleData) o; - return Objects.equals(id, that.id) && - Objects.equals(role, that.role) && - Objects.equals(clientId, that.clientId) && - Objects.equals(clientName, that.clientName); + return Objects.equals(id, that.id) && Objects.equals(role, that.role) && Objects.equals(clientId, that.clientId) + && Objects.equals(clientName, that.clientName); } @Override diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupSummary.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupSummary.java index cc31b06a4..7fc58a490 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupSummary.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupSummary.java @@ -52,4 +52,4 @@ public class GroupSummary { return this.totalSavings; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupTimelineData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupTimelineData.java index 0d23f2b1e..f31cdba56 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupTimelineData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/data/GroupTimelineData.java @@ -68,29 +68,23 @@ public class GroupTimelineData implements Serializable { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof GroupTimelineData)) { - return false; - } + if (this == o) { return true; } + if (!(o instanceof GroupTimelineData)) { return false; } GroupTimelineData that = (GroupTimelineData) o; - return Objects.equals(submittedOnDate, that.submittedOnDate) && - Objects.equals(submittedByUsername, that.submittedByUsername) && - Objects.equals(submittedByFirstname, that.submittedByFirstname) && - Objects.equals(submittedByLastname, that.submittedByLastname) && - Objects.equals(activatedOnDate, that.activatedOnDate) && - Objects.equals(activatedByUsername, that.activatedByUsername) && - Objects.equals(activatedByFirstname, that.activatedByFirstname) && - Objects.equals(activatedByLastname, that.activatedByLastname) && - Objects.equals(closedOnDate, that.closedOnDate) && - Objects.equals(closedByUsername, that.closedByUsername) && - Objects.equals(closedByFirstname, that.closedByFirstname) && - Objects.equals(closedByLastname, that.closedByLastname); + return Objects.equals(submittedOnDate, that.submittedOnDate) && Objects.equals(submittedByUsername, that.submittedByUsername) + && Objects.equals(submittedByFirstname, that.submittedByFirstname) + && Objects.equals(submittedByLastname, that.submittedByLastname) && Objects.equals(activatedOnDate, that.activatedOnDate) + && Objects.equals(activatedByUsername, that.activatedByUsername) + && Objects.equals(activatedByFirstname, that.activatedByFirstname) + && Objects.equals(activatedByLastname, that.activatedByLastname) && Objects.equals(closedOnDate, that.closedOnDate) + && Objects.equals(closedByUsername, that.closedByUsername) && Objects.equals(closedByFirstname, that.closedByFirstname) + && Objects.equals(closedByLastname, that.closedByLastname); } @Override public int hashCode() { - return Objects.hash(submittedOnDate, submittedByUsername, submittedByFirstname, submittedByLastname, activatedOnDate, activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, closedByLastname); + return Objects.hash(submittedOnDate, submittedByUsername, submittedByFirstname, submittedByLastname, activatedOnDate, + activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, + closedByLastname); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/Group.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/Group.java index bea4f61da..67ed92993 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/Group.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/Group.java @@ -120,7 +120,7 @@ public final class Group extends AbstractPersistableCustom { @Temporal(TemporalType.DATE) private Date closureDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "closedon_userid", nullable = true) private AppUser closedBy; @@ -128,7 +128,7 @@ public final class Group extends AbstractPersistableCustom { @Temporal(TemporalType.DATE) private Date submittedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "submittedon_userid", nullable = true) private AppUser submittedBy; @@ -141,13 +141,12 @@ public final class Group extends AbstractPersistableCustom { @Transient private boolean accountNumberRequiresAutoGeneration = false; - @OneToMany(mappedBy="group",cascade = CascadeType.REMOVE) + @OneToMany(mappedBy = "group", cascade = CascadeType.REMOVE) private Set groupRole; @OneToMany(mappedBy = "group") private List glimLoan; - // JPA default constructor for entity protected Group() { this.name = null; @@ -155,10 +154,9 @@ public final class Group extends AbstractPersistableCustom { this.clientMembers = new HashSet<>(); } - public static Group newGroup(final Office office, final Staff staff, final Group parent, final GroupLevel groupLevel, - final String name, final String externalId, final boolean active, final LocalDate activationDate, - final Set clientMembers, final Set groupMembers, final LocalDate submittedOnDate, final AppUser currentUser, - final String accountNo) { + public static Group newGroup(final Office office, final Staff staff, final Group parent, final GroupLevel groupLevel, final String name, + final String externalId, final boolean active, final LocalDate activationDate, final Set clientMembers, + final Set groupMembers, final LocalDate submittedOnDate, final AppUser currentUser, final String accountNo) { // By default new group is created in PENDING status, unless explicitly // status is set to active @@ -237,7 +235,8 @@ public final class Group extends AbstractPersistableCustom { } - private void activate(final AppUser currentUser, final LocalDate activationLocalDate, final List dataValidationErrors) { + private void activate(final AppUser currentUser, final LocalDate activationLocalDate, + final List dataValidationErrors) { validateStatusNotEqualToActiveAndLogError(dataValidationErrors); if (dataValidationErrors.isEmpty()) { @@ -415,7 +414,7 @@ public final class Group extends AbstractPersistableCustom { } public void resetHierarchy() { - this.hierarchy = "." + this.getId(); + this.hierarchy = "." + this.getId(); } private String hierarchyOf(final Long id) { @@ -524,7 +523,8 @@ public final class Group extends AbstractPersistableCustom { if (isClosed()) { final String errorMessage = "Group with identifier " + getId() + " is alread closed."; - throw new InvalidGroupStateTransitionException(this.groupLevel.getLevelName(), "close", "already.closed", errorMessage, getId()); + throw new InvalidGroupStateTransitionException(this.groupLevel.getLevelName(), "close", "already.closed", errorMessage, + getId()); } if (isNotPending() && getActivationLocalDate().isAfter(closureDate)) { @@ -578,8 +578,8 @@ public final class Group extends AbstractPersistableCustom { if (group.isChildGroup()) { final String defaultUserMessage = "Group is already associated with a center"; - throw new GeneralPlatformDomainRuleException("error.msg.group.already.associated.with.center", defaultUserMessage, group - .getParent().getId(), group.getId()); + throw new GeneralPlatformDomainRuleException("error.msg.group.already.associated.with.center", defaultUserMessage, + group.getParent().getId(), group.getId()); } this.groupMembers.add(group); @@ -764,5 +764,4 @@ public final class Group extends AbstractPersistableCustom { this.groupMembers = groupMembers; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupLevel.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupLevel.java index 35b9cf0e1..6284c96a7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupLevel.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupLevel.java @@ -94,4 +94,4 @@ public class GroupLevel extends AbstractPersistableCustom { return this.levelName.equalsIgnoreCase("Group"); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRepositoryWrapper.java index 93b4f5693..d24f466b9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRepositoryWrapper.java @@ -42,8 +42,7 @@ public class GroupRepositoryWrapper { } public Group findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new GroupNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new GroupNotFoundException(id)); } public Group findByOfficeWithNotFoundDetection(final Long id, final Office office) { @@ -70,9 +69,7 @@ public class GroupRepositoryWrapper { public LocalDate retrieveSubmittedOndate(final Long groupId) { Date submittedOnDate = this.repository.retrieveGroupTypeSubmitteOndDate(groupId); - if (submittedOnDate != null) { - return new LocalDate(submittedOnDate); - } + if (submittedOnDate != null) { return new LocalDate(submittedOnDate); } return null; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRoleRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRoleRepositoryWrapper.java index d58133291..a9f445751 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRoleRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupRoleRepositoryWrapper.java @@ -33,8 +33,7 @@ public class GroupRoleRepositoryWrapper { } public GroupRole findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new GroupRoleNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new GroupRoleNotFoundException(id)); } public void save(final GroupRole entity) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupingTypeEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupingTypeEnumerations.java index 23729aa16..69bb51bd8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupingTypeEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupingTypeEnumerations.java @@ -58,4 +58,4 @@ public class GroupingTypeEnumerations { return optionData; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupingTypeStatus.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupingTypeStatus.java index a50142e1a..091b19e19 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupingTypeStatus.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/domain/GroupingTypeStatus.java @@ -96,4 +96,4 @@ public enum GroupingTypeStatus { public boolean isUnderTransfer() { return isTransferInProgress() || isTransferOnHold(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/ClientExistInGroupException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/ClientExistInGroupException.java index 9a20a6c3b..92e90b991 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/ClientExistInGroupException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/ClientExistInGroupException.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class ClientExistInGroupException extends AbstractPlatformDomainRuleException { public ClientExistInGroupException(final Long clientId, final Long groupId) { - super("error.msg.group.client.exist.in.group", "Client with identifier " + clientId - + " is already exists in Group with identifier " + groupId, clientId, groupId); + super("error.msg.group.client.exist.in.group", + "Client with identifier " + clientId + " is already exists in Group with identifier " + groupId, clientId, groupId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupExistsInCenterException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupExistsInCenterException.java index 4ba19559b..b5b62e0f8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupExistsInCenterException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupExistsInCenterException.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class GroupExistsInCenterException extends AbstractPlatformDomainRuleException { public GroupExistsInCenterException(final Long centerId, final Long groupId) { - super("error.msg.group.is.already.member.of.center", "Group with identifier " + groupId - + " is already exists in Center with identifier " + centerId, groupId, centerId); + super("error.msg.group.is.already.member.of.center", + "Group with identifier " + groupId + " is already exists in Center with identifier " + centerId, groupId, centerId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMemberCountNotInPermissibleRangeException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMemberCountNotInPermissibleRangeException.java index 39f929c06..30bf5861c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMemberCountNotInPermissibleRangeException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMemberCountNotInPermissibleRangeException.java @@ -23,8 +23,9 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class GroupMemberCountNotInPermissibleRangeException extends AbstractPlatformDomainRuleException { public GroupMemberCountNotInPermissibleRangeException(final Long groupId, final Integer minClients, final Integer maxClients) { - super("error.msg.group.members.count.must.be.in.permissible.range", "Number of members in the group with Id " + groupId - + " should be between " + minClients + " and " + maxClients, groupId, minClients, maxClients); + super("error.msg.group.members.count.must.be.in.permissible.range", + "Number of members in the group with Id " + groupId + " should be between " + minClients + " and " + maxClients, groupId, + minClients, maxClients); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMemberNotFoundInGSIMException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMemberNotFoundInGSIMException.java index 5da7aae1a..23817fbad 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMemberNotFoundInGSIMException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMemberNotFoundInGSIMException.java @@ -21,10 +21,9 @@ package org.apache.fineract.portfolio.group.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; - public class GroupMemberNotFoundInGSIMException extends AbstractPlatformDomainRuleException - { - public GroupMemberNotFoundInGSIMException(final Long clientId) - { - super("error.msg.Group.member.not.found.in.linked.gsim", "The client with id `" + clientId + "` is not present in GSIM", clientId); - } +public class GroupMemberNotFoundInGSIMException extends AbstractPlatformDomainRuleException { + + public GroupMemberNotFoundInGSIMException(final Long clientId) { + super("error.msg.Group.member.not.found.in.linked.gsim", "The client with id `" + clientId + "` is not present in GSIM", clientId); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMustBePendingToBeDeletedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMustBePendingToBeDeletedException.java index 2cf4ec428..430f78459 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMustBePendingToBeDeletedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupMustBePendingToBeDeletedException.java @@ -29,4 +29,4 @@ public class GroupMustBePendingToBeDeletedException extends AbstractPlatformDoma super("error.msg.group.cannot.be.deleted", "Group with identifier " + id + " cannot be deleted as it is not in `Pending` state.", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupNotExistsInCenterException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupNotExistsInCenterException.java index 4eb6ef657..b5e355e52 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupNotExistsInCenterException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/exception/GroupNotExistsInCenterException.java @@ -27,4 +27,4 @@ public class GroupNotExistsInCenterException extends AbstractPlatformDomainRuleE groupId, centerId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/ActivateCenterCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/ActivateCenterCommandHandler.java index c9e95f226..cb9dc5172 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/ActivateCenterCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/ActivateCenterCommandHandler.java @@ -44,4 +44,4 @@ public class ActivateCenterCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.activateGroupOrCenter(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/ActivateGroupCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/ActivateGroupCommandHandler.java index 822ffb0b8..975a82aa8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/ActivateGroupCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/ActivateGroupCommandHandler.java @@ -44,4 +44,4 @@ public class ActivateGroupCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.activateGroupOrCenter(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/AssociateClientsToGroupCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/AssociateClientsToGroupCommandHandler.java index bab2f813c..fe633fbfa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/AssociateClientsToGroupCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/AssociateClientsToGroupCommandHandler.java @@ -44,4 +44,4 @@ public class AssociateClientsToGroupCommandHandler implements NewCommandSourceHa return this.writePlatformService.associateClientsToGroup(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/CreateCenterCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/CreateCenterCommandHandler.java index 4fd986a2f..e0c12b992 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/CreateCenterCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/CreateCenterCommandHandler.java @@ -43,4 +43,4 @@ public class CreateCenterCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.groupWritePlatformService.createCenter(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/CreateGroupCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/CreateGroupCommandHandler.java index aebd6be7a..9cc8400fb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/CreateGroupCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/CreateGroupCommandHandler.java @@ -45,4 +45,4 @@ public class CreateGroupCommandHandler implements NewCommandSourceHandler { final Long centerId = command.longValueOfParameterNamed("centerId"); return this.groupWritePlatformService.createGroup(centerId, command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DeleteCenterCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DeleteCenterCommandHandler.java index 7abcf08bb..4d250ab7e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DeleteCenterCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DeleteCenterCommandHandler.java @@ -43,4 +43,4 @@ public class DeleteCenterCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.groupWritePlatformService.deleteGroup(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DeleteGroupCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DeleteGroupCommandHandler.java index a8f2d02ef..1610021a2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DeleteGroupCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DeleteGroupCommandHandler.java @@ -43,4 +43,4 @@ public class DeleteGroupCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.groupWritePlatformService.deleteGroup(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DisassociateClientsFromGroupCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DisassociateClientsFromGroupCommandHandler.java index e5ab1b080..ce690bd0d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DisassociateClientsFromGroupCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/DisassociateClientsFromGroupCommandHandler.java @@ -43,4 +43,4 @@ public class DisassociateClientsFromGroupCommandHandler implements NewCommandSou public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.disassociateClientsFromGroup(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/SaveCenterCollectionSheetCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/SaveCenterCollectionSheetCommandHandler.java index 389c65d4f..f134a8cfc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/SaveCenterCollectionSheetCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/SaveCenterCollectionSheetCommandHandler.java @@ -44,4 +44,4 @@ public class SaveCenterCollectionSheetCommandHandler implements NewCommandSource return this.writePlatformService.updateCollectionSheet(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/SaveGroupCollectionSheetCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/SaveGroupCollectionSheetCommandHandler.java index efe9c8f00..3eca03069 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/SaveGroupCollectionSheetCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/SaveGroupCollectionSheetCommandHandler.java @@ -44,4 +44,4 @@ public class SaveGroupCollectionSheetCommandHandler implements NewCommandSourceH return this.writePlatformService.updateCollectionSheet(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UnassignGroupStaffCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UnassignGroupStaffCommandHandler.java index 9749a9834..547e26bda 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UnassignGroupStaffCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UnassignGroupStaffCommandHandler.java @@ -43,4 +43,4 @@ public class UnassignGroupStaffCommandHandler implements NewCommandSourceHandler public CommandProcessingResult processCommand(final JsonCommand command) { return this.groupWritePlatformService.unassignGroupOrCenterStaff(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UnassignStaffFromCenterCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UnassignStaffFromCenterCommandHandler.java index 80b0b1dc5..4823dfb08 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UnassignStaffFromCenterCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UnassignStaffFromCenterCommandHandler.java @@ -41,4 +41,4 @@ public class UnassignStaffFromCenterCommandHandler implements NewCommandSourceHa public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.unassignGroupOrCenterStaff(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UpdateCenterCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UpdateCenterCommandHandler.java index 0d20a6e50..3036e8e33 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UpdateCenterCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UpdateCenterCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateCenterCommandHandler implements NewCommandSourceHandler { return this.groupWritePlatformService.updateCenter(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UpdateGroupCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UpdateGroupCommandHandler.java index add0b267b..fee0f90f5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UpdateGroupCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/handler/UpdateGroupCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateGroupCommandHandler implements NewCommandSourceHandler { return this.groupWritePlatformService.updateGroup(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/serialization/GroupRolesDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/serialization/GroupRolesDataValidator.java index 9bba5aaed..b2ced2113 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/serialization/GroupRolesDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/serialization/GroupRolesDataValidator.java @@ -61,8 +61,7 @@ public class GroupRolesDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper - .checkForUnsupportedParameters(typeOfMap, json, GROUP_ROLES_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, GROUP_ROLES_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); @@ -86,8 +85,7 @@ public class GroupRolesDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper - .checkForUnsupportedParameters(typeOfMap, json, GROUP_ROLES_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, GROUP_ROLES_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/serialization/GroupingTypesDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/serialization/GroupingTypesDataValidator.java old mode 100755 new mode 100644 index a9b5e5d4b..31b440d5c --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/serialization/GroupingTypesDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/serialization/GroupingTypesDataValidator.java @@ -48,35 +48,31 @@ public final class GroupingTypesDataValidator { private final FromJsonHelper fromApiJsonHelper; private final GroupRepositoryWrapper groupRepositoryWrapper; - private static final Set CENTER_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(GroupingTypesApiConstants.localeParamName, GroupingTypesApiConstants.dateFormatParamName, - GroupingTypesApiConstants.idParamName, GroupingTypesApiConstants.nameParamName, - GroupingTypesApiConstants.externalIdParamName, GroupingTypesApiConstants.officeIdParamName, - GroupingTypesApiConstants.staffIdParamName, GroupingTypesApiConstants.activeParamName, - GroupingTypesApiConstants.activationDateParamName, GroupingTypesApiConstants.groupMembersParamName, - GroupingTypesApiConstants.submittedOnDateParamName, GroupingTypesApiConstants.datatables)); + private static final Set CENTER_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(GroupingTypesApiConstants.localeParamName, + GroupingTypesApiConstants.dateFormatParamName, GroupingTypesApiConstants.idParamName, GroupingTypesApiConstants.nameParamName, + GroupingTypesApiConstants.externalIdParamName, GroupingTypesApiConstants.officeIdParamName, + GroupingTypesApiConstants.staffIdParamName, GroupingTypesApiConstants.activeParamName, + GroupingTypesApiConstants.activationDateParamName, GroupingTypesApiConstants.groupMembersParamName, + GroupingTypesApiConstants.submittedOnDateParamName, GroupingTypesApiConstants.datatables)); - private static final Set GROUP_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - GroupingTypesApiConstants.localeParamName, GroupingTypesApiConstants.dateFormatParamName, - GroupingTypesApiConstants.idParamName, GroupingTypesApiConstants.nameParamName, + private static final Set GROUP_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(GroupingTypesApiConstants.localeParamName, + GroupingTypesApiConstants.dateFormatParamName, GroupingTypesApiConstants.idParamName, GroupingTypesApiConstants.nameParamName, GroupingTypesApiConstants.externalIdParamName, GroupingTypesApiConstants.centerIdParamName, GroupingTypesApiConstants.officeIdParamName, GroupingTypesApiConstants.staffIdParamName, GroupingTypesApiConstants.activeParamName, GroupingTypesApiConstants.activationDateParamName, GroupingTypesApiConstants.clientMembersParamName, GroupingTypesApiConstants.collectionMeetingCalendar, GroupingTypesApiConstants.submittedOnDateParamName, GroupingTypesApiConstants.datatables)); - private static final Set ACTIVATION_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(GroupingTypesApiConstants.localeParamName, GroupingTypesApiConstants.dateFormatParamName, GroupingTypesApiConstants.activationDateParamName)); - private static final Set GROUP_CLOSE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - GroupingTypesApiConstants.localeParamName, GroupingTypesApiConstants.dateFormatParamName, - GroupingTypesApiConstants.closureDateParamName, GroupingTypesApiConstants.closureReasonIdParamName)); + private static final Set GROUP_CLOSE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(GroupingTypesApiConstants.localeParamName, GroupingTypesApiConstants.dateFormatParamName, + GroupingTypesApiConstants.closureDateParamName, GroupingTypesApiConstants.closureReasonIdParamName)); @Autowired - public GroupingTypesDataValidator(final FromJsonHelper fromApiJsonHelper, - final GroupRepositoryWrapper groupRepositoryWrapper) { + public GroupingTypesDataValidator(final FromJsonHelper fromApiJsonHelper, final GroupRepositoryWrapper groupRepositoryWrapper) { this.fromApiJsonHelper = fromApiJsonHelper; this.groupRepositoryWrapper = groupRepositoryWrapper; } @@ -123,8 +119,8 @@ public final class GroupingTypesDataValidator { final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); if (active != null) { if (active.booleanValue()) { - final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed( - GroupingTypesApiConstants.activationDateParamName, element); + final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, + element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull(); } else { // TODO - KW - not using config for now - just supporting move @@ -140,12 +136,12 @@ public final class GroupingTypesDataValidator { } if (this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.submittedOnDateParamName, element)) { - final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed( - GroupingTypesApiConstants.submittedOnDateParamName, element); + final LocalDate submittedOnDate = this.fromApiJsonHelper + .extractLocalDateNamed(GroupingTypesApiConstants.submittedOnDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.submittedOnDateParamName).value(submittedOnDate).notNull(); } - if(this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.datatables, element)){ + if (this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.datatables, element)) { final JsonArray datatables = this.fromApiJsonHelper.extractJsonArrayNamed(GroupingTypesApiConstants.datatables, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.datatables).value(datatables).notNull().jsonArrayNotEmpty(); } @@ -192,8 +188,8 @@ public final class GroupingTypesDataValidator { final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); if (active != null) { if (active.booleanValue()) { - final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed( - GroupingTypesApiConstants.activationDateParamName, element); + final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, + element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull(); } else { // TODO - KW - not using config for now - just supporting move @@ -209,12 +205,12 @@ public final class GroupingTypesDataValidator { } if (this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.submittedOnDateParamName, element)) { - final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed( - GroupingTypesApiConstants.submittedOnDateParamName, element); + final LocalDate submittedOnDate = this.fromApiJsonHelper + .extractLocalDateNamed(GroupingTypesApiConstants.submittedOnDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.submittedOnDateParamName).value(submittedOnDate).notNull(); } - if(this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.datatables, element)){ + if (this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.datatables, element)) { final JsonArray datatables = this.fromApiJsonHelper.extractJsonArrayNamed(GroupingTypesApiConstants.datatables, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.datatables).value(datatables).notNull().jsonArrayNotEmpty(); } @@ -257,8 +253,8 @@ public final class GroupingTypesDataValidator { final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); if (active != null) { if (active.booleanValue()) { - final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed( - GroupingTypesApiConstants.activationDateParamName, element); + final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, + element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull(); } else { // TODO - KW - not using config for now - just supporting move @@ -274,12 +270,12 @@ public final class GroupingTypesDataValidator { } if (this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.submittedOnDateParamName, element)) { - final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed( - GroupingTypesApiConstants.submittedOnDateParamName, element); + final LocalDate submittedOnDate = this.fromApiJsonHelper + .extractLocalDateNamed(GroupingTypesApiConstants.submittedOnDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.submittedOnDateParamName).value(submittedOnDate).notNull(); } - if(this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.datatables, element)){ + if (this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.datatables, element)) { final JsonArray datatables = this.fromApiJsonHelper.extractJsonArrayNamed(GroupingTypesApiConstants.datatables, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.datatables).value(datatables).notNull().jsonArrayNotEmpty(); } @@ -323,14 +319,13 @@ public final class GroupingTypesDataValidator { LocalDate submittedOnDate = this.groupRepositoryWrapper.retrieveSubmittedOndate(centerId); - final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, - element); + final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); if ((active != null && active) || this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.activationDateParamName, element)) { - final LocalDate joinedDate = this.fromApiJsonHelper - .extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, element); - baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate) - .notNull().validateDateAfter(submittedOnDate); + final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, + element); + baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull() + .validateDateAfter(submittedOnDate); } throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -373,19 +368,17 @@ public final class GroupingTypesDataValidator { LocalDate submittedOnDate = this.groupRepositoryWrapper.retrieveSubmittedOndate(groupId); if (this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.submittedOnDateParamName, element)) { - submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed( - GroupingTypesApiConstants.submittedOnDateParamName, element); + submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.submittedOnDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.submittedOnDateParamName).value(submittedOnDate).notNull(); } - final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, - element); - if ((active != null && active) || this.fromApiJsonHelper - .parameterExists(GroupingTypesApiConstants.activationDateParamName, element)) { - final LocalDate joinedDate = this.fromApiJsonHelper - .extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, element); - baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate) - .notNull().validateDateAfter(submittedOnDate); + final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); + if ((active != null && active) + || this.fromApiJsonHelper.parameterExists(GroupingTypesApiConstants.activationDateParamName, element)) { + final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, + element); + baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull() + .validateDateAfter(submittedOnDate); } throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -437,7 +430,8 @@ public final class GroupingTypesDataValidator { final Type typeOfMap = new TypeToken>() {}.getType(); - final Set supportedParametersAssignStaff = new HashSet<>(Arrays.asList(GroupingTypesApiConstants.staffIdParamName,GroupingTypesApiConstants.inheritStaffForClientAccounts)); + final Set supportedParametersAssignStaff = new HashSet<>( + Arrays.asList(GroupingTypesApiConstants.staffIdParamName, GroupingTypesApiConstants.inheritStaffForClientAccounts)); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParametersAssignStaff); final JsonElement element = this.fromApiJsonHelper.parse(json); @@ -452,9 +446,10 @@ public final class GroupingTypesDataValidator { baseDataValidator.reset().parameter(staffIdParameterName).value(staffId).notNull().longGreaterThanZero(); final String inheritStaffForClientAccountsParamName = GroupingTypesApiConstants.inheritStaffForClientAccounts; - final Boolean inheritStaffForClientAccounts= this.fromApiJsonHelper.extractBooleanNamed(inheritStaffForClientAccountsParamName,element); - baseDataValidator.reset().parameter(inheritStaffForClientAccountsParamName).value(inheritStaffForClientAccounts).ignoreIfNull().notBlank().isOneOfTheseValues(true, false); - + final Boolean inheritStaffForClientAccounts = this.fromApiJsonHelper.extractBooleanNamed(inheritStaffForClientAccountsParamName, + element); + baseDataValidator.reset().parameter(inheritStaffForClientAccountsParamName).value(inheritStaffForClientAccounts).ignoreIfNull() + .notBlank().isOneOfTheseValues(true, false); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } @@ -505,8 +500,7 @@ public final class GroupingTypesDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper - .checkForUnsupportedParameters(typeOfMap, json, GROUP_CLOSE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, GROUP_CLOSE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -531,8 +525,7 @@ public final class GroupingTypesDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper - .checkForUnsupportedParameters(typeOfMap, json, GROUP_CLOSE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, GROUP_CLOSE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/AllGroupTypesDataMapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/AllGroupTypesDataMapper.java index 5468d5938..4cbac8377 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/AllGroupTypesDataMapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/AllGroupTypesDataMapper.java @@ -113,7 +113,7 @@ public final class AllGroupTypesDataMapper implements RowMapper paramList,final SearchParameters searchCriteria) { + private String getCenterExtraCriteria(String schemaSl, List paramList, final SearchParameters searchCriteria) { StringBuilder extraCriteria = new StringBuilder(200); extraCriteria.append(" and g.level_id = " + GroupTypes.CENTER.getId()); - if (searchCriteria!=null) { + if (searchCriteria != null) { String sqlQueryCriteria = searchCriteria.getSqlSearch(); if (StringUtils.isNotBlank(sqlQueryCriteria)) { SQLInjectionValidator.validateSQLInput(sqlQueryCriteria); @@ -181,9 +182,7 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService + "g.closedon_date as closedOnDate, " + "g.submittedon_date as submittedOnDate, " + "sbu.username as submittedByUsername, " + "sbu.firstname as submittedByFirstname, " + "sbu.lastname as submittedByLastname, " + "clu.username as closedByUsername, " + "clu.firstname as closedByFirstname, " + "clu.lastname as closedByLastname, " + "acu.username as activatedByUsername, " - + "acu.firstname as activatedByFirstname, " - + "acu.lastname as activatedByLastname " - + "from m_group g " // + + "acu.firstname as activatedByFirstname, " + "acu.lastname as activatedByLastname " + "from m_group g " // + "join m_office o on o.id = g.office_id " + "left join m_staff s on s.id = g.staff_id " + "left join m_group pg on pg.id = g.parent_id " + "left join m_appuser sbu on sbu.id = g.submittedon_userid " + "left join m_appuser acu on acu.id = g.activatedon_userid " + "left join m_appuser clu on clu.id = g.closedon_userid "; @@ -298,7 +297,7 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService final LocalDate startDate = JdbcSupport.getLocalDate(rs, "startDate"); final LocalDate endDate = JdbcSupport.getLocalDate(rs, "endDate"); final String recurrence = rs.getString("recurrence"); - final LocalTime meetingTime = JdbcSupport.getLocalTime(rs,"meetingTime"); + final LocalTime meetingTime = JdbcSupport.getLocalTime(rs, "meetingTime"); final BigDecimal totalCollected = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "totalCollected"); final BigDecimal totalOverdue = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "totalOverdue"); final BigDecimal totaldue = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "totaldue"); @@ -306,8 +305,8 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService Integer monthOnDay = CalendarUtils.getMonthOnDay(recurrence); CalendarData calendarData = CalendarData.instance(calendarId, calendarInstanceId, entityId, entityType, title, description, - location, startDate, endDate, null, null, false, recurrence, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, meetingTime, monthOnDay); + location, startDate, endDate, null, null, false, recurrence, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, meetingTime, monthOnDay); return CenterData.instance(id, accountNo, name, externalId, status, activationDate, officeId, null, staffId, staffName, hierarchy, null, calendarData, totalCollected, totalOverdue, totaldue, installmentDue); @@ -364,8 +363,8 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService submittedByLastname, activationDate, activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, closedByLastname); - return GroupGeneralData.instance(id, accountNo, name, externalId, status, activationDate, officeId, officeName, null, null, staffId, - staffName, hierarchy, groupLevel, timeline); + return GroupGeneralData.instance(id, accountNo, name, externalId, status, activationDate, officeId, officeName, null, null, + staffId, staffName, hierarchy, groupLevel, timeline); } } @@ -381,8 +380,7 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); sqlBuilder.append(this.centerMapper.schema()); sqlBuilder.append(" where o.hierarchy like ?"); - List paramList = new ArrayList<>( - Arrays.asList(hierarchySearchString)); + List paramList = new ArrayList<>(Arrays.asList(hierarchySearchString)); final String extraCriteria = getCenterExtraCriteria(this.centerMapper.schema(), paramList, searchParameters); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), extraCriteria); if (StringUtils.isNotBlank(extraCriteria)) { @@ -404,13 +402,13 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService } final String sqlCountRows = "SELECT FOUND_ROWS()"; - return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), - paramList.toArray(), this.centerMapper); + return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), paramList.toArray(), + this.centerMapper); } @Override public Collection retrieveAll(SearchParameters searchParameters, PaginationParameters parameters) { - if (parameters!=null) { + if (parameters != null) { this.paginationParametersDataValidator.validateParameterValues(parameters, SUPPORTED_ORDER_BY_VALUES, "audits"); } final AppUser currentUser = this.context.authenticatedUser(); @@ -421,14 +419,13 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService sqlBuilder.append("select "); sqlBuilder.append(this.centerMapper.schema()); sqlBuilder.append(" where o.hierarchy like ?"); - List paramList = new ArrayList<>( - Arrays.asList(hierarchySearchString)); - if (searchParameters!=null) { - final String extraCriteria = getCenterExtraCriteria(this.centerMapper.schema(), paramList, searchParameters); - this.columnValidator.validateSqlInjection(sqlBuilder.toString(), extraCriteria); - if (StringUtils.isNotBlank(extraCriteria)) { - sqlBuilder.append(" and (").append(extraCriteria).append(")"); - } + List paramList = new ArrayList<>(Arrays.asList(hierarchySearchString)); + if (searchParameters != null) { + final String extraCriteria = getCenterExtraCriteria(this.centerMapper.schema(), paramList, searchParameters); + this.columnValidator.validateSqlInjection(sqlBuilder.toString(), extraCriteria); + if (StringUtils.isNotBlank(extraCriteria)) { + sqlBuilder.append(" and (").append(extraCriteria).append(")"); + } if (searchParameters.isOrderByRequested()) { sqlBuilder.append(" order by ").append(searchParameters.getOrderBy()).append(' ').append(searchParameters.getSortOrder()); @@ -545,8 +542,8 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService clientOptions = null; } - return GroupGeneralData.template(centerOfficeId, center.getId(), center.getAccountNo(), center.getName(), staffId, staffName, centerOptions, - officeOptions, staffOptions, clientOptions, null); + return GroupGeneralData.template(centerOfficeId, center.getId(), center.getAccountNo(), center.getName(), staffId, staffName, + centerOptions, officeOptions, staffOptions, clientOptions, null); } @Override @@ -574,11 +571,11 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService sql += " and g.staff_id=? "; sql += "and lrs.duedate<='" + passeddate + "' and l.loan_type_enum=3"; sql += " group by c.id, ci.id, g.account_no, g.external_id, g.status_enum, g.activation_date, g.hierarchy"; - centerDataArray = this.jdbcTemplate.query(sql, centerCalendarMapper, new Object[] { passeddate, passeddate, passeddate, passeddate, - passeddate, passeddate, officeId, staffId }); + centerDataArray = this.jdbcTemplate.query(sql, centerCalendarMapper, + new Object[] { passeddate, passeddate, passeddate, passeddate, passeddate, passeddate, officeId, staffId }); } else { - centerDataArray = this.jdbcTemplate.query(sql, centerCalendarMapper, new Object[] { passeddate, passeddate, passeddate, passeddate, - passeddate, passeddate, officeId }); + centerDataArray = this.jdbcTemplate.query(sql, centerCalendarMapper, + new Object[] { passeddate, passeddate, passeddate, passeddate, passeddate, passeddate, officeId }); } Collection staffCenterDataArray = new ArrayList<>(); @@ -589,7 +586,8 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService numberOfDays = this.configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } for (CenterData centerData : centerDataArray) { - if (centerData.getCollectionMeetingCalendar().isValidRecurringDate(new LocalDate(meetingDate), isSkipRepaymentOnFirstMonthEnabled, numberOfDays)) { + if (centerData.getCollectionMeetingCalendar().isValidRecurringDate(new LocalDate(meetingDate), + isSkipRepaymentOnFirstMonthEnabled, numberOfDays)) { if (staffCenterDataArray.size() <= 0) { Collection meetingFallCenter = new ArrayList<>(); meetingFallCenter.add(centerData); @@ -600,7 +598,6 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService if (staffCenterData.getStaffId().equals(centerData.staffId())) { staffCenterData.getMeetingFallCenters().add(centerData); - flag = true; break; } @@ -608,8 +605,8 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService if (!flag) { Collection meetingFallCenter = new ArrayList<>(); meetingFallCenter.add(centerData); - staffCenterDataArray.add(StaffCenterData.instance(centerData.staffId(), centerData.getStaffName(), - meetingFallCenter)); + staffCenterDataArray + .add(StaffCenterData.instance(centerData.staffId(), centerData.getStaffName(), meetingFallCenter)); } } @@ -624,8 +621,10 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("productivecollectionsheet"); baseDataValidator.reset().parameter("staffId").value(staffId).notNull(); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupReadPlatformService.java index c02815e8c..5cd6432d4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupReadPlatformService.java @@ -37,4 +37,4 @@ public interface GroupReadPlatformService { Collection retrieveGroupsForLookup(Long officeId); GroupGeneralData retrieveGroupWithClosureReasons(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupReadPlatformServiceImpl.java index a3da7cfdf..d5508324d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupReadPlatformServiceImpl.java @@ -77,11 +77,9 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { @Autowired public GroupReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, - final CenterReadPlatformService centerReadPlatformService, - final OfficeReadPlatformService officeReadPlatformService, final StaffReadPlatformService staffReadPlatformService, - final CodeValueReadPlatformService codeValueReadPlatformService, - final PaginationParametersDataValidator paginationParametersDataValidator, - final ColumnValidator columnValidator) { + final CenterReadPlatformService centerReadPlatformService, final OfficeReadPlatformService officeReadPlatformService, + final StaffReadPlatformService staffReadPlatformService, final CodeValueReadPlatformService codeValueReadPlatformService, + final PaginationParametersDataValidator paginationParametersDataValidator, final ColumnValidator columnValidator) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); this.centerReadPlatformService = centerReadPlatformService; @@ -151,8 +149,7 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); sqlBuilder.append(this.allGroupTypesDataMapper.schema()); sqlBuilder.append(" where o.hierarchy like ?"); - List paramList = new ArrayList<>( - Arrays.asList(hierarchySearchString)); + List paramList = new ArrayList<>(Arrays.asList(hierarchySearchString)); final String extraCriteria = getGroupExtraCriteria(this.allGroupTypesDataMapper.schema(), paramList, searchParameters); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), extraCriteria); if (StringUtils.isNotBlank(extraCriteria)) { @@ -173,8 +170,8 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { } final String sqlCountRows = "SELECT FOUND_ROWS()"; - return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), - paramList.toArray(), this.allGroupTypesDataMapper); + return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), paramList.toArray(), + this.allGroupTypesDataMapper); } @Override @@ -187,16 +184,15 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { sqlBuilder.append("select "); sqlBuilder.append(this.allGroupTypesDataMapper.schema()); sqlBuilder.append(" where o.hierarchy like ?"); - List paramList = new ArrayList<>( - Arrays.asList(hierarchySearchString)); - if (searchParameters!=null) { + List paramList = new ArrayList<>(Arrays.asList(hierarchySearchString)); + if (searchParameters != null) { final String extraCriteria = getGroupExtraCriteria(this.allGroupTypesDataMapper.schema(), paramList, searchParameters); if (StringUtils.isNotBlank(extraCriteria)) { sqlBuilder.append(" and (").append(extraCriteria).append(")"); } } - if (parameters!=null) { + if (parameters != null) { if (parameters.isOrderByRequested()) { sqlBuilder.append(parameters.orderBySql()); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), parameters.orderBySql()); @@ -217,26 +213,26 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { StringBuilder extraCriteria = new StringBuilder(200); extraCriteria.append(" and g.level_Id = ").append(GroupTypes.GROUP.getId()); - String sqlSearch = searchCriteria.getSqlSearch(); - if (sqlSearch != null) { - SQLInjectionValidator.validateSQLInput(sqlSearch); - sqlSearch = sqlSearch.replace(" display_name ", " g.display_name "); - sqlSearch = sqlSearch.replace("display_name ", "g.display_name "); - extraCriteria.append(" and ( ").append(sqlSearch).append(") "); - this.columnValidator.validateSqlInjection(schemaSql, sqlSearch); - } + String sqlSearch = searchCriteria.getSqlSearch(); + if (sqlSearch != null) { + SQLInjectionValidator.validateSQLInput(sqlSearch); + sqlSearch = sqlSearch.replace(" display_name ", " g.display_name "); + sqlSearch = sqlSearch.replace("display_name ", "g.display_name "); + extraCriteria.append(" and ( ").append(sqlSearch).append(") "); + this.columnValidator.validateSqlInjection(schemaSql, sqlSearch); + } - final Long officeId = searchCriteria.getOfficeId(); - if (officeId != null) { - paramList.add(officeId); - extraCriteria.append(" and g.office_id = ? "); - } + final Long officeId = searchCriteria.getOfficeId(); + if (officeId != null) { + paramList.add(officeId); + extraCriteria.append(" and g.office_id = ? "); + } - final String externalId = searchCriteria.getExternalId(); - if (externalId != null) { - paramList.add(ApiParameterHelper.sqlEncodeString(externalId)); - extraCriteria.append(" and g.external_id = ? "); - } + final String externalId = searchCriteria.getExternalId(); + if (externalId != null) { + paramList.add(ApiParameterHelper.sqlEncodeString(externalId)); + extraCriteria.append(" and g.external_id = ? "); + } final String name = searchCriteria.getName(); if (name != null) { @@ -244,30 +240,30 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { extraCriteria.append(" and g.display_name like ? "); } - final String hierarchy = searchCriteria.getHierarchy(); - if (hierarchy != null) { - paramList.add(ApiParameterHelper.sqlEncodeString(hierarchy + "%")); - extraCriteria.append(" and o.hierarchy like ? "); - } + final String hierarchy = searchCriteria.getHierarchy(); + if (hierarchy != null) { + paramList.add(ApiParameterHelper.sqlEncodeString(hierarchy + "%")); + extraCriteria.append(" and o.hierarchy like ? "); + } - if (searchCriteria.isStaffIdPassed()) { - paramList.add(searchCriteria.getStaffId()); - extraCriteria.append(" and g.staff_id = ? "); - } + if (searchCriteria.isStaffIdPassed()) { + paramList.add(searchCriteria.getStaffId()); + extraCriteria.append(" and g.staff_id = ? "); + } - if (StringUtils.isNotBlank(extraCriteria.toString())) { - extraCriteria.delete(0, 4); - } + if (StringUtils.isNotBlank(extraCriteria.toString())) { + extraCriteria.delete(0, 4); + } - final Long staffId = searchCriteria.getStaffId(); - if (staffId != null) { - paramList.add(staffId); - extraCriteria.append(" and g.staff_id = ? "); - } + final Long staffId = searchCriteria.getStaffId(); + if (staffId != null) { + paramList.add(staffId); + extraCriteria.append(" and g.staff_id = ? "); + } - if (searchCriteria.isOrphansOnly()) { - extraCriteria.append(" and g.parent_id IS NULL"); - } + if (searchCriteria.isOrphansOnly()) { + extraCriteria.append(" and g.parent_id IS NULL"); + } return extraCriteria.toString(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupingTypesWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupingTypesWritePlatformServiceJpaRepositoryImpl.java index e0c1ffe6b..388449c15 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupingTypesWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/group/service/GroupingTypesWritePlatformServiceJpaRepositoryImpl.java @@ -120,13 +120,13 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group @Autowired public GroupingTypesWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final GroupRepositoryWrapper groupRepository, final ClientRepositoryWrapper clientRepositoryWrapper, - final OfficeRepositoryWrapper officeRepositoryWrapper, final StaffRepositoryWrapper staffRepository, final NoteRepository noteRepository, - final GroupLevelRepository groupLevelRepository, final GroupingTypesDataValidator fromApiJsonDeserializer, - final SavingsAccountRepositoryWrapper savingsAccountRepositoryWrapper, + final OfficeRepositoryWrapper officeRepositoryWrapper, final StaffRepositoryWrapper staffRepository, + final NoteRepository noteRepository, final GroupLevelRepository groupLevelRepository, + final GroupingTypesDataValidator fromApiJsonDeserializer, final SavingsAccountRepositoryWrapper savingsAccountRepositoryWrapper, final CodeValueRepositoryWrapper codeValueRepository, final CommandProcessingService commandProcessingService, final CalendarInstanceRepository calendarInstanceRepository, final ConfigurationDomainService configurationDomainService, - final LoanRepositoryWrapper loanRepositoryWrapper, - final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository, final AccountNumberGenerator accountNumberGenerator, + final LoanRepositoryWrapper loanRepositoryWrapper, final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository, + final AccountNumberGenerator accountNumberGenerator, final EntityDatatableChecksWritePlatformService entityDatatableChecksWritePlatformService, final BusinessEventNotifierService businessEventNotifierService) { this.context = context; @@ -254,31 +254,30 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group } catch (final DataIntegrityViolationException dve) { handleGroupDataIntegrityIssues(command, dve.getMostSpecificCause(), dve, groupingType); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleGroupDataIntegrityIssues(command, throwable, dve, groupingType); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } - private void generateAccountNumberIfRequired(Group newGroup){ + private void generateAccountNumberIfRequired(Group newGroup) { if (newGroup.isAccountNumberRequiresAutoGeneration()) { EntityAccountType entityAccountType = null; AccountNumberFormat accountNumberFormat = null; - if(newGroup.isCenter()){ + if (newGroup.isCenter()) { entityAccountType = EntityAccountType.CENTER; - accountNumberFormat = this.accountNumberFormatRepository - .findByAccountType(entityAccountType); + accountNumberFormat = this.accountNumberFormatRepository.findByAccountType(entityAccountType); newGroup.updateAccountNo(this.accountNumberGenerator.generateCenterAccountNumber(newGroup, accountNumberFormat)); - }else { + } else { entityAccountType = EntityAccountType.GROUP; - accountNumberFormat = this.accountNumberFormatRepository - .findByAccountType(entityAccountType); + accountNumberFormat = this.accountNumberFormatRepository.findByAccountType(entityAccountType); newGroup.updateAccountNo(this.accountNumberGenerator.generateGroupAccountNumber(newGroup, accountNumberFormat)); } } } + @Transactional @Override public CommandProcessingResult createCenter(final JsonCommand command) { @@ -345,10 +344,10 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group } catch (final DataIntegrityViolationException dve) { handleGroupDataIntegrityIssues(command, dve.getMostSpecificCause(), dve, GroupTypes.GROUP); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleGroupDataIntegrityIssues(command, throwable, dve, GroupTypes.GROUP); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -485,10 +484,10 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group } catch (final DataIntegrityViolationException dve) { handleGroupDataIntegrityIssues(command, dve.getMostSpecificCause(), dve, groupingType); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleGroupDataIntegrityIssues(command, throwable, dve, groupingType); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -618,8 +617,8 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group final AppUser currentUser = this.context.authenticatedUser(); - final CodeValue closureReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( - GroupingTypesApiConstants.GROUP_CLOSURE_REASON, closureReasonId); + final CodeValue closureReason = this.codeValueRepository + .findOneByCodeNameAndIdWithNotFoundDetection(GroupingTypesApiConstants.GROUP_CLOSURE_REASON, closureReasonId); if (group.hasActiveClients()) { final String errorMessage = group.getGroupLevel().getLevelName() @@ -630,8 +629,8 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group validateLoansAndSavingsForGroupOrCenterClose(group, closureDate); - entityDatatableChecksWritePlatformService.runTheCheck(groupId, EntityTables.GROUP.getName(), - StatusEnum.CLOSE.getCode().longValue(),EntityTables.GROUP.getForeignKeyColumnNameOnDatatable()); + entityDatatableChecksWritePlatformService.runTheCheck(groupId, EntityTables.GROUP.getName(), StatusEnum.CLOSE.getCode().longValue(), + EntityTables.GROUP.getForeignKeyColumnNameOnDatatable()); group.close(currentUser, closureReason, closureDate); @@ -691,8 +690,8 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group final LocalDate closureDate = command.localDateValueOfParameterNamed(GroupingTypesApiConstants.closureDateParamName); final Long closureReasonId = command.longValueOfParameterNamed(GroupingTypesApiConstants.closureReasonIdParamName); - final CodeValue closureReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( - GroupingTypesApiConstants.CENTER_CLOSURE_REASON, closureReasonId); + final CodeValue closureReason = this.codeValueRepository + .findOneByCodeNameAndIdWithNotFoundDetection(GroupingTypesApiConstants.CENTER_CLOSURE_REASON, closureReasonId); final AppUser currentUser = this.context.authenticatedUser(); @@ -708,7 +707,6 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group entityDatatableChecksWritePlatformService.runTheCheck(centerId, EntityTables.GROUP.getName(), StatusEnum.ACTIVATE.getCode().longValue(), EntityTables.GROUP.getForeignKeyColumnNameOnDatatable()); - center.close(currentUser, closureReason, closureDate); this.groupRepository.saveAndFlush(center); @@ -930,7 +928,8 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group @Transactional private void validateForJLGSavings(final Long groupId, final Set clientMembers) { for (final Client client : clientMembers) { - final Collection savings = this.savingsAccountRepositoryWrapper.findByClientIdAndGroupId(client.getId(), groupId); + final Collection savings = this.savingsAccountRepositoryWrapper.findByClientIdAndGroupId(client.getId(), + groupId); if (!CollectionUtils.isEmpty(savings)) { final String defaultUserMessage = "Client with identifier " + client.getId() + " cannot be disassociated it has group savings."; @@ -944,8 +943,8 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group final LocalDate activationDate) { if (activationDate != null && groupOffice.getOpeningLocalDate().isAfter(activationDate)) { final String levelName = groupLevel.getLevelName(); - final String errorMessage = levelName - + " activation date should be greater than or equal to the parent Office's creation date " + activationDate.toString(); + final String errorMessage = levelName + " activation date should be greater than or equal to the parent Office's creation date " + + activationDate.toString(); throw new InvalidGroupStateTransitionException(levelName.toLowerCase(), "activate.date", "cannot.be.before.office.activation.date", errorMessage, activationDate, groupOffice.getOpeningLocalDate()); } @@ -980,8 +979,8 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group */ if (ceneterCalendar == null && groupCalendar != null) { throw new GeneralPlatformDomainRuleException( - "error.msg.center.associating.group.not.allowed.with.meeting.attached.to.group", "Group with id " + group.getId() - + " is already associated with meeting", group.getId()); + "error.msg.center.associating.group.not.allowed.with.meeting.attached.to.group", + "Group with id " + group.getId() + " is already associated with meeting", group.getId()); } /** * Group meeting recurrence should match with center meeting @@ -989,14 +988,17 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group */ else if (ceneterCalendar != null && groupCalendar != null) { - if (!ceneterCalendar.getRecurrence().equalsIgnoreCase(groupCalendar.getRecurrence())) { throw new GeneralPlatformDomainRuleException( - "error.msg.center.associating.group.not.allowed.with.different.meeting", "Group with id " + group.getId() - + " meeting recurrence doesnot matched with center meeting recurrence", group.getId()); } + if (!ceneterCalendar.getRecurrence().equalsIgnoreCase(groupCalendar.getRecurrence())) { + throw new GeneralPlatformDomainRuleException("error.msg.center.associating.group.not.allowed.with.different.meeting", + "Group with id " + group.getId() + " meeting recurrence doesnot matched with center meeting recurrence", + group.getId()); + } } } } - private Map constructEntityMap(final BusinessEntity entityEvent, Object entity) { + private Map constructEntityMap(final BusinessEntity entityEvent, + Object entity) { Map map = new HashMap<>(1); map.put(entityEvent, entity); return map; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestIncentiveApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestIncentiveApiConstants.java old mode 100755 new mode 100644 index a87506b4a..a04934a88 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestIncentiveApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestIncentiveApiConstants.java @@ -35,8 +35,8 @@ public interface InterestIncentiveApiConstants { public static final String INCENTIVE_RESOURCE_NAME = "interest.rate.incentives"; - public static final Set INTERESTRATE_INCENTIVE_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, - entityTypeParamName, attributeNameParamName, conditionTypeParamName, attributeValueParamName, incentiveTypeparamName, - amountParamName)); + public static final Set INTERESTRATE_INCENTIVE_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(idParamName, entityTypeParamName, attributeNameParamName, conditionTypeParamName, attributeValueParamName, + incentiveTypeparamName, amountParamName)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestRateChartApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestRateChartApiConstants.java index 2dcb5a0fc..ed5583f95 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestRateChartApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestRateChartApiConstants.java @@ -43,19 +43,23 @@ public class InterestRateChartApiConstants { public static final String isPrimaryGroupingByAmountParamName = "isPrimaryGroupingByAmount"; // interest rate chart Slabs parameters -// public static final String periodTypeParamName = "periodType"; -// public static final String fromPeriodParamName = "fromPeriod"; -// public static final String toPeriodParamName = "toPeriod"; -// public static final String amountRangeFromParamName = "amountRangeFrom"; -// public static final String amountRangeToParamName = "amountRangeTo"; -// public static final String annualInterestRateParamName = "annualInterestRate"; -// public static final String interestRateForFemaleParamName = "interestRateForFemale"; -// public static final String interestRateForChildrenParamName = "interestRateForChildren"; -// public static final String interestRateForSeniorCitizenParamName = "interestRateForSeniorCitizen"; + // public static final String periodTypeParamName = "periodType"; + // public static final String fromPeriodParamName = "fromPeriod"; + // public static final String toPeriodParamName = "toPeriod"; + // public static final String amountRangeFromParamName = "amountRangeFrom"; + // public static final String amountRangeToParamName = "amountRangeTo"; + // public static final String annualInterestRateParamName = + // "annualInterestRate"; + // public static final String interestRateForFemaleParamName = + // "interestRateForFemale"; + // public static final String interestRateForChildrenParamName = + // "interestRateForChildren"; + // public static final String interestRateForSeniorCitizenParamName = + // "interestRateForSeniorCitizen"; // associations public static final String chartSlabs = "chartSlabs"; // to delete chart Slabs from chart public static final String deleteParamName = "delete"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestRateChartSlabApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestRateChartSlabApiConstants.java index 63b0cf989..3fb2627c7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestRateChartSlabApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/InterestRateChartSlabApiConstants.java @@ -41,4 +41,4 @@ public class InterestRateChartSlabApiConstants { public static final String annualInterestRateParamName = "annualInterestRate"; public static final String currencyCodeParamName = "currencyCode"; public static final String incentivesParamName = "incentives"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartSlabsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartSlabsApiResource.java index b7d71ab3d..3c545d961 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartSlabsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartSlabsApiResource.java @@ -71,10 +71,9 @@ import org.springframework.stereotype.Component; @Path("/interestratecharts/{chartId}/chartslabs") @Component @Scope("singleton") -@Api(tags = {"Interest Rate Slab (A.K.A interest bands)"}) +@Api(tags = { "Interest Rate Slab (A.K.A interest bands)" }) @SwaggerDefinition(tags = { - @Tag(name = "Interest Rate Slab (A.K.A interest bands)", description = "The slabs a.k.a interest bands are associated with Interest Rate Chart. These bands allow to define different interest rates for different deposit term periods.") -}) + @Tag(name = "Interest Rate Slab (A.K.A interest bands)", description = "The slabs a.k.a interest bands are associated with Interest Rate Chart. These bands allow to define different interest rates for different deposit term periods.") }) public class InterestRateChartSlabsApiResource { private final InterestRateChartSlabReadPlatformService interestRateChartSlabReadPlatformService; @@ -82,11 +81,10 @@ public class InterestRateChartSlabsApiResource { private final DefaultToApiJsonSerializer toApiJsonSerializer; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final ApiRequestParameterHelper apiRequestParameterHelper; - private static final Set INTERESTRATE_CHART_SLAB_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - InterestRateChartSlabApiConstants.localeParamName, InterestRateChartSlabApiConstants.idParamName, - descriptionParamName, periodTypeParamName, fromPeriodParamName, toPeriodParamName, amountRangeFromParamName, - amountRangeToParamName, annualInterestRateParamName, currencyCodeParamName, incentivesParamName)); - + private static final Set INTERESTRATE_CHART_SLAB_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(InterestRateChartSlabApiConstants.localeParamName, InterestRateChartSlabApiConstants.idParamName, + descriptionParamName, periodTypeParamName, fromPeriodParamName, toPeriodParamName, amountRangeFromParamName, + amountRangeToParamName, annualInterestRateParamName, currencyCodeParamName, incentivesParamName)); @Autowired public InterestRateChartSlabsApiResource(final InterestRateChartSlabReadPlatformService interestRateChartSlabReadPlatformService, @@ -114,8 +112,10 @@ public class InterestRateChartSlabsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve all Slabs", httpMethod = "GET", notes = "Retrieve list of slabs associated with a chart\n" + "\n" + "Example Requests:\n" + "\n" + "interestratecharts/1/chartslabs") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InterestRateChartSlabsApiResourceSwagger.GetInterestRateChartsChartIdChartSlabsResponse.class, responseContainer = "List")}) + @ApiOperation(value = "Retrieve all Slabs", httpMethod = "GET", notes = "Retrieve list of slabs associated with a chart\n" + "\n" + + "Example Requests:\n" + "\n" + "interestratecharts/1/chartslabs") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = InterestRateChartSlabsApiResourceSwagger.GetInterestRateChartsChartIdChartSlabsResponse.class, responseContainer = "List") }) public String retrieveAll(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(INTERESTRATE_CHART_SLAB_RESOURCE_NAME); @@ -129,10 +129,12 @@ public class InterestRateChartSlabsApiResource { @Path("{chartSlabId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Slab", httpMethod = "GET", notes = "Retrieve a slab associated with an Interest rate chart\n" + "\n" + "Example Requests:\n" + "\n" + "interestratecharts/1/chartslabs/1\n") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InterestRateChartSlabsApiResourceSwagger.GetInterestRateChartsChartIdChartSlabsResponse.class)}) - public String retrieveOne(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, @PathParam("chartSlabId") @ApiParam(value = "chartSlabId") final Long chartSlabId, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Slab", httpMethod = "GET", notes = "Retrieve a slab associated with an Interest rate chart\n" + "\n" + + "Example Requests:\n" + "\n" + "interestratecharts/1/chartslabs/1\n") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = InterestRateChartSlabsApiResourceSwagger.GetInterestRateChartsChartIdChartSlabsResponse.class) }) + public String retrieveOne(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, + @PathParam("chartSlabId") @ApiParam(value = "chartSlabId") final Long chartSlabId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(INTERESTRATE_CHART_SLAB_RESOURCE_NAME); @@ -148,10 +150,15 @@ public class InterestRateChartSlabsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Slab", httpMethod = "POST", notes = "Creates a new interest rate slab for an interest rate chart.\n" + "Mandatory Fields\n" + "periodType, fromPeriod, annualInterestRate\n" + "Optional Fields\n" + "toPeriod and description\n" +"Example Requests:\n" + "\n" + "interestratecharts/1/chartslabs") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InterestRateChartSlabsApiResourceSwagger.PostInterestRateChartsChartIdChartSlabsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InterestRateChartSlabsApiResourceSwagger.PostInterestRateChartsChartIdChartSlabsResponse.class)}) - public String create(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Create a Slab", httpMethod = "POST", notes = "Creates a new interest rate slab for an interest rate chart.\n" + + "Mandatory Fields\n" + "periodType, fromPeriod, annualInterestRate\n" + "Optional Fields\n" + "toPeriod and description\n" + + "Example Requests:\n" + "\n" + "interestratecharts/1/chartslabs") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InterestRateChartSlabsApiResourceSwagger.PostInterestRateChartsChartIdChartSlabsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = InterestRateChartSlabsApiResourceSwagger.PostInterestRateChartsChartIdChartSlabsResponse.class) }) + public String create(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createInterestRateChartSlab(chartId) .withJson(apiRequestBodyAsJson).build(); @@ -166,9 +173,12 @@ public class InterestRateChartSlabsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Slab", httpMethod = "PUT", notes = "It updates the Slab from chart") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InterestRateChartSlabsApiResourceSwagger.PutInterestRateChartsChartIdChartSlabsChartSlabIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InterestRateChartSlabsApiResourceSwagger.PutInterestRateChartsChartIdChartSlabsChartSlabIdResponse.class)}) - public String update(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, @PathParam("chartSlabId") @ApiParam(value = "chartSlabId") final Long chartSlabId, + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InterestRateChartSlabsApiResourceSwagger.PutInterestRateChartsChartIdChartSlabsChartSlabIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = InterestRateChartSlabsApiResourceSwagger.PutInterestRateChartsChartIdChartSlabsChartSlabIdResponse.class) }) + public String update(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, + @PathParam("chartSlabId") @ApiParam(value = "chartSlabId") final Long chartSlabId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateInterestRateChartSlab(chartId, chartSlabId) @@ -184,10 +194,12 @@ public class InterestRateChartSlabsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Slab", httpMethod = "DELETE", notes = "Delete a Slab from a chart") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InterestRateChartSlabsApiResourceSwagger.DeleteInterestRateChartsChartIdChartSlabsResponse.class)}) - public String delete(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, @PathParam("chartSlabId") @ApiParam(value = "chartSlabId") final Long chartSlabId) { + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = InterestRateChartSlabsApiResourceSwagger.DeleteInterestRateChartsChartIdChartSlabsResponse.class) }) + public String delete(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, + @PathParam("chartSlabId") @ApiParam(value = "chartSlabId") final Long chartSlabId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteInterestRateChartSlab(chartId, chartSlabId).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartSlabsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartSlabsApiResourceSwagger.java index 6884bbbe1..239866d03 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartSlabsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartSlabsApiResourceSwagger.java @@ -26,21 +26,21 @@ import java.util.Set; * Created by Chirag Gupta on 08/12/17. */ final class InterestRateChartSlabsApiResourceSwagger { - private InterestRateChartSlabsApiResourceSwagger() { - } + + private InterestRateChartSlabsApiResourceSwagger() {} @ApiModel(value = "GetInterestRateChartsChartIdChartSlabsResponse") public final static class GetInterestRateChartsChartIdChartSlabsResponse { - private GetInterestRateChartsChartIdChartSlabsResponse() { - } + + private GetInterestRateChartsChartIdChartSlabsResponse() {} final class GetInterestRateChartsChartIdChartSlabsIncentives { - private GetInterestRateChartsChartIdChartSlabsIncentives() { - } + + private GetInterestRateChartsChartIdChartSlabsIncentives() {} final class GetInterestRateChartsChartIdChartSlabsEntityType { - private GetInterestRateChartsChartIdChartSlabsEntityType() { - } + + private GetInterestRateChartsChartIdChartSlabsEntityType() {} @ApiModelProperty(example = "2") public Integer id; @@ -51,8 +51,8 @@ final class InterestRateChartSlabsApiResourceSwagger { } final class GetInterestRateChartsChartIdChartSlabsAttributeName { - private GetInterestRateChartsChartIdChartSlabsAttributeName() { - } + + private GetInterestRateChartsChartIdChartSlabsAttributeName() {} @ApiModelProperty(example = "2") public Integer id; @@ -63,8 +63,8 @@ final class InterestRateChartSlabsApiResourceSwagger { } final class GetInterestRateChartsChartIdChartSlabsConditionType { - private GetInterestRateChartsChartIdChartSlabsConditionType() { - } + + private GetInterestRateChartsChartIdChartSlabsConditionType() {} @ApiModelProperty(example = "2") public Integer id; @@ -75,8 +75,8 @@ final class InterestRateChartSlabsApiResourceSwagger { } final class GetInterestRateChartsChartIdChartSlabsIncentiveType { - private GetInterestRateChartsChartIdChartSlabsIncentiveType() { - } + + private GetInterestRateChartsChartIdChartSlabsIncentiveType() {} @ApiModelProperty(example = "3") public Integer id; @@ -117,12 +117,12 @@ final class InterestRateChartSlabsApiResourceSwagger { @ApiModel(value = "PostInterestRateChartsChartIdChartSlabsRequest") public static final class PostInterestRateChartsChartIdChartSlabsRequest { - private PostInterestRateChartsChartIdChartSlabsRequest() { - } + + private PostInterestRateChartsChartIdChartSlabsRequest() {} final class PostInterestRateChartsChartIdChartSlabsIncentives { - private PostInterestRateChartsChartIdChartSlabsIncentives() { - } + + private PostInterestRateChartsChartIdChartSlabsIncentives() {} @ApiModelProperty(example = "2") public Integer entityType; @@ -155,8 +155,8 @@ final class InterestRateChartSlabsApiResourceSwagger { @ApiModel(value = "PostInterestRateChartsChartIdChartSlabsResponse") public final static class PostInterestRateChartsChartIdChartSlabsResponse { - private PostInterestRateChartsChartIdChartSlabsResponse() { - } + + private PostInterestRateChartsChartIdChartSlabsResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -164,8 +164,8 @@ final class InterestRateChartSlabsApiResourceSwagger { @ApiModel(value = "PutInterestRateChartsChartIdChartSlabsChartSlabIdRequest") public static final class PutInterestRateChartsChartIdChartSlabsChartSlabIdRequest { - private PutInterestRateChartsChartIdChartSlabsChartSlabIdRequest() { - } + + private PutInterestRateChartsChartIdChartSlabsChartSlabIdRequest() {} @ApiModelProperty(example = "6") public Double annualInterestRate; @@ -175,8 +175,8 @@ final class InterestRateChartSlabsApiResourceSwagger { @ApiModel(value = "PutInterestRateChartsChartIdChartSlabsChartSlabIdResponse") public static final class PutInterestRateChartsChartIdChartSlabsChartSlabIdResponse { - private PutInterestRateChartsChartIdChartSlabsChartSlabIdResponse() { - } + + private PutInterestRateChartsChartIdChartSlabsChartSlabIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -185,8 +185,8 @@ final class InterestRateChartSlabsApiResourceSwagger { @ApiModel(value = "DeleteInterestRateChartsChartIdChartSlabsResponse") public final static class DeleteInterestRateChartsChartIdChartSlabsResponse { - private DeleteInterestRateChartsChartIdChartSlabsResponse() { - } + + private DeleteInterestRateChartsChartIdChartSlabsResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartsApiResource.java index a064f948f..5927459c7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartsApiResource.java @@ -70,10 +70,9 @@ import org.springframework.stereotype.Component; @Path("/interestratecharts") @Component @Scope("singleton") -@Api(tags = {"Interest Rate Chart"}) +@Api(tags = { "Interest Rate Chart" }) @SwaggerDefinition(tags = { - @Tag(name = "Interest Rate Chart", description = "This defines an interest rate scheme that can be associated to a term deposit product. This will have a slab (band or range) of deposit periods and the associated interest rates applicable along with incentives for each band.") -}) + @Tag(name = "Interest Rate Chart", description = "This defines an interest rate scheme that can be associated to a term deposit product. This will have a slab (band or range) of deposit periods and the associated interest rates applicable along with incentives for each band.") }) public class InterestRateChartsApiResource { private final InterestRateChartReadPlatformService chartReadPlatformService; @@ -81,10 +80,9 @@ public class InterestRateChartsApiResource { private final DefaultToApiJsonSerializer toApiJsonSerializer; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final ApiRequestParameterHelper apiRequestParameterHelper; - private static final Set INTERESTRATE_CHART_RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(InterestRateChartApiConstants.localeParamName, - InterestRateChartApiConstants.dateFormatParamName, idParamName, nameParamName, descriptionParamName, - fromDateParamName, endDateParamName, chartSlabs, isPrimaryGroupingByAmountParamName)); + private static final Set INTERESTRATE_CHART_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList( + InterestRateChartApiConstants.localeParamName, InterestRateChartApiConstants.dateFormatParamName, idParamName, nameParamName, + descriptionParamName, fromDateParamName, endDateParamName, chartSlabs, isPrimaryGroupingByAmountParamName)); @Autowired public InterestRateChartsApiResource(final InterestRateChartReadPlatformService chartReadPlatformService, @@ -103,8 +101,10 @@ public class InterestRateChartsApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Chart Details Template", httpMethod = "GET", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for creating a chart. The template data returned consists of any or all of:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "interestratecharts/template") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InterestRateChartsApiResourceSwagger.GetInterestRateChartsTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Chart Details Template", httpMethod = "GET", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for creating a chart. The template data returned consists of any or all of:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "interestratecharts/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = InterestRateChartsApiResourceSwagger.GetInterestRateChartsTemplateResponse.class) }) public String template(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(InterestRateChartApiConstants.INTERESTRATE_CHART_RESOURCE_NAME); @@ -117,9 +117,12 @@ public class InterestRateChartsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve all Charts", httpMethod = "GET", notes = "Retrieve list of charts associated with a term deposit product(FD or RD).\n" + "Example Requests:\n" + "\n" + "interestratecharts?productId=1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = InterestRateChartsApiResourceSwagger.GetInterestRateChartsResponse.class)}) - public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("productId") @ApiParam(value = "productId") final Long productId) { + @ApiOperation(value = "Retrieve all Charts", httpMethod = "GET", notes = "Retrieve list of charts associated with a term deposit product(FD or RD).\n" + + "Example Requests:\n" + "\n" + "interestratecharts?productId=1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = InterestRateChartsApiResourceSwagger.GetInterestRateChartsResponse.class) }) + public String retrieveAll(@Context final UriInfo uriInfo, + @QueryParam("productId") @ApiParam(value = "productId") final Long productId) { this.context.authenticatedUser().validateHasReadPermission(InterestRateChartApiConstants.INTERESTRATE_CHART_RESOURCE_NAME); @@ -133,8 +136,10 @@ public class InterestRateChartsApiResource { @Path("{chartId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Chart", httpMethod = "GET", notes = "It retrieves the Interest Rate Chart\n" + "Example Requests:\n" + "\n" + "interestratecharts/1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InterestRateChartsApiResourceSwagger.GetInterestRateChartsResponse.class)}) + @ApiOperation(value = "Retrieve a Chart", httpMethod = "GET", notes = "It retrieves the Interest Rate Chart\n" + "Example Requests:\n" + + "\n" + "interestratecharts/1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = InterestRateChartsApiResourceSwagger.GetInterestRateChartsResponse.class) }) public String retrieveOne(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(InterestRateChartApiConstants.INTERESTRATE_CHART_RESOURCE_NAME); @@ -143,7 +148,7 @@ public class InterestRateChartsApiResource { final Set associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); if (!associationParameters.isEmpty() && associationParameters.contains(InterestRateChartApiConstants.chartSlabs)) { chartData = this.chartReadPlatformService.retrieveOneWithSlabs(chartId); - }else { + } else { chartData = this.chartReadPlatformService.retrieveOne(chartId); } @@ -159,8 +164,10 @@ public class InterestRateChartsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create a Chart", httpMethod = "POST", notes = "Creates a new chart which can be attached to a term deposit products (FD or RD).") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InterestRateChartsApiResourceSwagger.PostInterestRateChartsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InterestRateChartsApiResourceSwagger.PostInterestRateChartsResponse.class)}) + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InterestRateChartsApiResourceSwagger.PostInterestRateChartsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = InterestRateChartsApiResourceSwagger.PostInterestRateChartsResponse.class) }) public String create(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createInterestRateChart().withJson(apiRequestBodyAsJson).build(); @@ -175,12 +182,15 @@ public class InterestRateChartsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Chart", notes = "It updates the Chart.", httpMethod = "PUT") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InterestRateChartsApiResourceSwagger.PutInterestRateChartsChartIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InterestRateChartsApiResourceSwagger.PutInterestRateChartsChartIdResponse.class)}) - public String update(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = InterestRateChartsApiResourceSwagger.PutInterestRateChartsChartIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = InterestRateChartsApiResourceSwagger.PutInterestRateChartsChartIdResponse.class) }) + public String update(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateInterestRateChart(chartId) - .withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateInterestRateChart(chartId).withJson(apiRequestBodyAsJson) + .build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -192,10 +202,11 @@ public class InterestRateChartsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Chart", notes = "It deletes the chart", httpMethod = "DELETE") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = InterestRateChartsApiResourceSwagger.DeleteInterestRateChartsChartIdResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = InterestRateChartsApiResourceSwagger.DeleteInterestRateChartsChartIdResponse.class) }) public String delete(@PathParam("chartId") @ApiParam(value = "chartId") final Long chartId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteInterestRateChart(chartId).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartsApiResourceSwagger.java index e97b58c1e..f1a0ca1af 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/api/InterestRateChartsApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/04/17. */ final class InterestRateChartsApiResourceSwagger { - private InterestRateChartsApiResourceSwagger() { - } + + private InterestRateChartsApiResourceSwagger() {} @ApiModel(value = "GetInterestRateChartsTemplateResponse") public final static class GetInterestRateChartsTemplateResponse { - private GetInterestRateChartsTemplateResponse() { - } + + private GetInterestRateChartsTemplateResponse() {} final class GetInterestRateChartsTemplatePeriodTypes { - private GetInterestRateChartsTemplatePeriodTypes() { - } + + private GetInterestRateChartsTemplatePeriodTypes() {} @ApiModelProperty(example = "0") public Integer id; @@ -52,12 +52,12 @@ final class InterestRateChartsApiResourceSwagger { @ApiModel(value = "GetInterestRateChartsResponse") public static final class GetInterestRateChartsResponse { - private GetInterestRateChartsResponse() { - } + + private GetInterestRateChartsResponse() {} final class GetInterestRateChartsChartSlabs { - private GetInterestRateChartsChartSlabs() { - } + + private GetInterestRateChartsChartSlabs() {} @ApiModelProperty(example = "1") public Integer id; @@ -70,8 +70,8 @@ final class InterestRateChartsApiResourceSwagger { } final class GetInterestRateChartsCurrency { - private GetInterestRateChartsCurrency() { - } + + private GetInterestRateChartsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -100,8 +100,8 @@ final class InterestRateChartsApiResourceSwagger { @ApiModel(value = "PostInterestRateChartsRequest") public static final class PostInterestRateChartsRequest { - private PostInterestRateChartsRequest() { - } + + private PostInterestRateChartsRequest() {} @ApiModelProperty(example = "Chart - 2014") public String name; @@ -119,8 +119,8 @@ final class InterestRateChartsApiResourceSwagger { @ApiModel(value = "PostInterestRateChartsResponse") public static final class PostInterestRateChartsResponse { - private PostInterestRateChartsResponse() { - } + + private PostInterestRateChartsResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -128,8 +128,9 @@ final class InterestRateChartsApiResourceSwagger { @ApiModel(value = "PutInterestRateChartsChartIdRequest") public static final class PutInterestRateChartsChartIdRequest { - private PutInterestRateChartsChartIdRequest() { - } + + private PutInterestRateChartsChartIdRequest() {} + @ApiModelProperty(example = "Interest rate chart for 2014") public String name; @ApiModelProperty(example = "Interest rate chart for 2014") @@ -138,8 +139,8 @@ final class InterestRateChartsApiResourceSwagger { @ApiModel(value = "PutInterestRateChartsChartIdResponse") public static final class PutInterestRateChartsChartIdResponse { - private PutInterestRateChartsChartIdResponse() { - } + + private PutInterestRateChartsChartIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -147,8 +148,8 @@ final class InterestRateChartsApiResourceSwagger { @ApiModel(value = "DeleteInterestRateChartsChartIdResponse") public static final class DeleteInterestRateChartsChartIdResponse { - private DeleteInterestRateChartsChartIdResponse() { - } + + private DeleteInterestRateChartsChartIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestIncentiveDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestIncentiveDataValidator.java old mode 100755 new mode 100644 index 7fb557321..f05fcd484 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestIncentiveDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestIncentiveDataValidator.java @@ -59,12 +59,12 @@ public class InterestIncentiveDataValidator { private final FromJsonHelper fromApiJsonHelper; private static final Set INTERESTRATE_INCENTIVE_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(InterestIncentiveApiConstants.idParamName, entityTypeParamName, attributeNameParamName, - conditionTypeParamName, attributeValueParamName, incentiveTypeparamName, amountParamName)); + Arrays.asList(InterestIncentiveApiConstants.idParamName, entityTypeParamName, attributeNameParamName, conditionTypeParamName, + attributeValueParamName, incentiveTypeparamName, amountParamName)); private static final Set INTERESTRATE_INCENTIVE_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(InterestIncentiveApiConstants.idParamName, entityTypeParamName, attributeNameParamName, - conditionTypeParamName, attributeValueParamName, incentiveTypeparamName, amountParamName)); + Arrays.asList(InterestIncentiveApiConstants.idParamName, entityTypeParamName, attributeNameParamName, conditionTypeParamName, + attributeValueParamName, incentiveTypeparamName, amountParamName)); @Autowired public InterestIncentiveDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -178,4 +178,4 @@ public class InterestIncentiveDataValidator { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartData.java index 8da097ade..b0a2910d7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartData.java @@ -67,14 +67,14 @@ public class InterestRateChartData { incentiveTypeOptions, genderOptions, clientTypeOptions, clientClassificationOptions); } - public static InterestRateChartData withSlabs(InterestRateChartData interestRateChartData, Collection chartSlabs) { + public static InterestRateChartData withSlabs(InterestRateChartData interestRateChartData, + Collection chartSlabs) { return new InterestRateChartData(interestRateChartData.id, interestRateChartData.name, interestRateChartData.description, interestRateChartData.fromDate, interestRateChartData.endDate, interestRateChartData.isPrimaryGroupingByAmount, interestRateChartData.productId, interestRateChartData.productName, chartSlabs, interestRateChartData.periodTypes, interestRateChartData.entityTypeOptions, interestRateChartData.attributeNameOptions, - interestRateChartData.conditionTypeOptions, interestRateChartData.incentiveTypeOptions, - interestRateChartData.genderOptions, interestRateChartData.clientTypeOptions, - interestRateChartData.clientClassificationOptions); + interestRateChartData.conditionTypeOptions, interestRateChartData.incentiveTypeOptions, interestRateChartData.genderOptions, + interestRateChartData.clientTypeOptions, interestRateChartData.clientClassificationOptions); } public static InterestRateChartData withTemplate(InterestRateChartData interestRateChartData, Collection periodTypes, @@ -89,11 +89,10 @@ public class InterestRateChartData { clientClassificationOptions); } - public static InterestRateChartData template(Collection periodTypes, - final Collection entityTypeOptions, final Collection attributeNameOptions, - final Collection conditionTypeOptions, final Collection incentiveTypeOptions, - final Collection genderOptions, final Collection clientTypeOptions, - final Collection clientClassificationOptions) { + public static InterestRateChartData template(Collection periodTypes, final Collection entityTypeOptions, + final Collection attributeNameOptions, final Collection conditionTypeOptions, + final Collection incentiveTypeOptions, final Collection genderOptions, + final Collection clientTypeOptions, final Collection clientClassificationOptions) { final Long id = null; final String name = null; final String description = null; @@ -110,11 +109,12 @@ public class InterestRateChartData { } private InterestRateChartData(Long id, String name, String description, LocalDate fromDate, LocalDate endDate, - boolean isPrimaryGroupingByAmount, Long savingsProductId, String savingsProductName, Collection chartSlabs, - Collection periodTypes, final Collection entityTypeOptions, - final Collection attributeNameOptions, final Collection conditionTypeOptions, - final Collection incentiveTypeOptions, final Collection genderOptions, - final Collection clientTypeOptions, final Collection clientClassificationOptions) { + boolean isPrimaryGroupingByAmount, Long savingsProductId, String savingsProductName, + Collection chartSlabs, Collection periodTypes, + final Collection entityTypeOptions, final Collection attributeNameOptions, + final Collection conditionTypeOptions, final Collection incentiveTypeOptions, + final Collection genderOptions, final Collection clientTypeOptions, + final Collection clientClassificationOptions) { this.id = id; this.name = name; this.description = description; @@ -198,9 +198,8 @@ public class InterestRateChartData { return this.clientClassificationOptions; } - public boolean isPrimaryGroupingByAmount() { return this.isPrimaryGroupingByAmount; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartDataValidator.java index 84f1ea32c..add6ed49b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartDataValidator.java @@ -57,14 +57,13 @@ public class InterestRateChartDataValidator { private final FromJsonHelper fromApiJsonHelper; private final InterestRateChartSlabDataValidator chartSlabDataValidator; private static final Set INTERESTRATE_CHART_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - InterestRateChartApiConstants.localeParamName, InterestRateChartApiConstants.dateFormatParamName, - nameParamName, descriptionParamName, fromDateParamName, endDateParamName, productIdParamName, chartSlabs, - isPrimaryGroupingByAmountParamName)); + InterestRateChartApiConstants.localeParamName, InterestRateChartApiConstants.dateFormatParamName, nameParamName, + descriptionParamName, fromDateParamName, endDateParamName, productIdParamName, chartSlabs, isPrimaryGroupingByAmountParamName)); - private static final Set INTERESTRATE_CHART_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - InterestRateChartApiConstants.localeParamName, InterestRateChartApiConstants.dateFormatParamName, - idParamName, nameParamName, descriptionParamName, fromDateParamName, endDateParamName, chartSlabs, - InterestRateChartApiConstants.deleteParamName, isPrimaryGroupingByAmountParamName)); + private static final Set INTERESTRATE_CHART_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(InterestRateChartApiConstants.localeParamName, InterestRateChartApiConstants.dateFormatParamName, idParamName, + nameParamName, descriptionParamName, fromDateParamName, endDateParamName, chartSlabs, + InterestRateChartApiConstants.deleteParamName, isPrimaryGroupingByAmountParamName)); @Autowired public InterestRateChartDataValidator(final FromJsonHelper fromApiJsonHelper, @@ -186,7 +185,7 @@ public class InterestRateChartDataValidator { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - private void validateChartSlabs(JsonElement element, DataValidatorBuilder baseDataValidator,final boolean isPrimaryGroupingByAmount) { + private void validateChartSlabs(JsonElement element, DataValidatorBuilder baseDataValidator, final boolean isPrimaryGroupingByAmount) { if (element.isJsonObject()) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); @@ -198,12 +197,14 @@ public class InterestRateChartDataValidator { if (this.fromApiJsonHelper.parameterExists(idParamName, interstRateChartElement)) { final Long id = this.fromApiJsonHelper.extractLongNamed(idParamName, interstRateChartElement); baseDataValidator.reset().parameter(idParamName).value(id).notNull().integerGreaterThanZero(); - this.chartSlabDataValidator.validateChartSlabsUpdate(interstRateChartElement, baseDataValidator, locale, isPrimaryGroupingByAmount); + this.chartSlabDataValidator.validateChartSlabsUpdate(interstRateChartElement, baseDataValidator, locale, + isPrimaryGroupingByAmount); } else { - this.chartSlabDataValidator.validateChartSlabsCreate(interstRateChartElement, baseDataValidator, locale, isPrimaryGroupingByAmount); + this.chartSlabDataValidator.validateChartSlabsCreate(interstRateChartElement, baseDataValidator, locale, + isPrimaryGroupingByAmount); } } } } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartRepository.java index 293f33eba..7c1a8aa35 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartRepository.java @@ -24,4 +24,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface InterestRateChartRepository extends JpaRepository, JpaSpecificationExecutor { -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartRepositoryWrapper.java index 7306c89d2..e2bca6efd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartRepositoryWrapper.java @@ -47,8 +47,7 @@ public class InterestRateChartRepositoryWrapper { } public InterestRateChart findOneWithNotFoundDetection(final Long intrestRateChartId) { - return this.repository.findById(intrestRateChartId) - .orElseThrow(() -> new InterestRateChartNotFoundException(intrestRateChartId)); + return this.repository.findById(intrestRateChartId).orElseThrow(() -> new InterestRateChartNotFoundException(intrestRateChartId)); } public void save(final InterestRateChart interestRateChart) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabData.java index 40c774f64..950a64d8b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabData.java @@ -205,4 +205,4 @@ public class InterestRateChartSlabData { return this.clientClassificationOptions; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabDataValidator.java index 7961dcee8..81105e3bf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabDataValidator.java @@ -60,16 +60,14 @@ public class InterestRateChartSlabDataValidator { private final FromJsonHelper fromApiJsonHelper; private final InterestIncentiveDataValidator interestIncentiveDataValidator; private static final Set INTERESTRATE_CHART_SLAB_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(InterestRateChartSlabApiConstants.localeParamName, - InterestRateChartSlabApiConstants.idParamName, descriptionParamName, periodTypeParamName, - fromPeriodParamName, toPeriodParamName, amountRangeFromParamName, amountRangeToParamName, - annualInterestRateParamName, currencyCodeParamName, incentivesParamName)); + Arrays.asList(InterestRateChartSlabApiConstants.localeParamName, InterestRateChartSlabApiConstants.idParamName, + descriptionParamName, periodTypeParamName, fromPeriodParamName, toPeriodParamName, amountRangeFromParamName, + amountRangeToParamName, annualInterestRateParamName, currencyCodeParamName, incentivesParamName)); private static final Set INTERESTRATE_CHART_SLAB_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(InterestRateChartSlabApiConstants.localeParamName, - InterestRateChartSlabApiConstants.idParamName, descriptionParamName, periodTypeParamName, - fromPeriodParamName, toPeriodParamName, amountRangeFromParamName, amountRangeToParamName, - annualInterestRateParamName, currencyCodeParamName, incentivesParamName)); + Arrays.asList(InterestRateChartSlabApiConstants.localeParamName, InterestRateChartSlabApiConstants.idParamName, + descriptionParamName, periodTypeParamName, fromPeriodParamName, toPeriodParamName, amountRangeFromParamName, + amountRangeToParamName, annualInterestRateParamName, currencyCodeParamName, incentivesParamName)); @Autowired public InterestRateChartSlabDataValidator(final FromJsonHelper fromApiJsonHelper, @@ -270,8 +268,8 @@ public class InterestRateChartSlabDataValidator { for (int i = 0; i < array.size(); i++) { final JsonObject incentiveElement = array.get(i).getAsJsonObject(); if (this.fromApiJsonHelper.parameterExists(InterestIncentiveApiConstants.idParamName, incentiveElement)) { - final Long id = this.fromApiJsonHelper - .extractLongNamed(InterestIncentiveApiConstants.idParamName, incentiveElement); + final Long id = this.fromApiJsonHelper.extractLongNamed(InterestIncentiveApiConstants.idParamName, + incentiveElement); baseDataValidator.reset().parameter(InterestIncentiveApiConstants.idParamName).value(id).notNull() .integerGreaterThanZero(); this.interestIncentiveDataValidator.validateIncentiveUpdate(incentiveElement, baseDataValidator, locale); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabRepository.java index 38d794594..ec9ffce34 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabRepository.java @@ -22,6 +22,7 @@ import org.apache.fineract.portfolio.interestratechart.domain.InterestRateChartS import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface InterestRateChartSlabRepository extends JpaRepository, JpaSpecificationExecutor { +public interface InterestRateChartSlabRepository + extends JpaRepository, JpaSpecificationExecutor { -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabRepositoryWrapper.java index a3e7ea51a..7cbea3024 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/data/InterestRateChartSlabRepositoryWrapper.java @@ -25,9 +25,10 @@ import org.springframework.stereotype.Service; /** *

- * Wrapper for {@link InterestRateChartSlabRepository} that is responsible for checking - * if {@link InterestRateChartSlab} is returned when using findOne - * repository method and throwing an appropriate not found exception. + * Wrapper for {@link InterestRateChartSlabRepository} that is responsible for + * checking if {@link InterestRateChartSlab} is returned when using + * findOne repository method and throwing an appropriate not found + * exception. *

* *

@@ -46,8 +47,7 @@ public class InterestRateChartSlabRepositoryWrapper { } public InterestRateChartSlab findOneWithNotFoundDetection(final Long chartSlabId) { - return this.repository.findById(chartSlabId) - .orElseThrow(() -> new InterestRateChartSlabNotFoundException(chartSlabId)); + return this.repository.findById(chartSlabId).orElseThrow(() -> new InterestRateChartSlabNotFoundException(chartSlabId)); } public void save(final InterestRateChartSlab chartSlab) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestIncentivesFields.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestIncentivesFields.java old mode 100755 new mode 100644 index d9de8f76d..104516bd2 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestIncentivesFields.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestIncentivesFields.java @@ -63,13 +63,15 @@ public class InterestIncentivesFields { } public static InterestIncentivesFields createNew(final Integer entityType, final Integer attributeName, final Integer conditionType, - final String attributeValue, final Integer incentiveType, final BigDecimal amount, final DataValidatorBuilder baseDataValidator) { + final String attributeValue, final Integer incentiveType, final BigDecimal amount, + final DataValidatorBuilder baseDataValidator) { return new InterestIncentivesFields(entityType, attributeName, conditionType, attributeValue, incentiveType, amount, baseDataValidator); } private InterestIncentivesFields(final Integer entityType, final Integer attributeName, final Integer conditionType, - final String attributeValue, final Integer incentiveType, final BigDecimal amount, final DataValidatorBuilder baseDataValidator) { + final String attributeValue, final Integer incentiveType, final BigDecimal amount, + final DataValidatorBuilder baseDataValidator) { this.entityType = entityType; this.attributeName = attributeName; this.attributeValue = attributeValue; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChart.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChart.java index 970f8478e..b1c6d4281 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChart.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChart.java @@ -70,7 +70,8 @@ public class InterestRateChart extends AbstractPersistableCustom { // } - public static InterestRateChart createNew(InterestRateChartFields chartFields, Collection interestRateChartSlabs) { + public static InterestRateChart createNew(InterestRateChartFields chartFields, + Collection interestRateChartSlabs) { return new InterestRateChart(chartFields, new HashSet<>(interestRateChartSlabs)); } @@ -122,8 +123,8 @@ public class InterestRateChart extends AbstractPersistableCustom { if (i == 0) { tmpPeriodType = iSlabs.slabFields().periodType(); if (iSlabs.slabFields().isNotProperChartStart()) { - baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.range.start.incorrect", iSlabs.slabFields() - .fromPeriod(), iSlabs.slabFields().getAmountRangeFrom()); + baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.range.start.incorrect", + iSlabs.slabFields().fromPeriod(), iSlabs.slabFields().getAmountRangeFrom()); } isAmountChart = isAmountChart || iSlabs.slabFields().getAmountRangeFrom() != null; isPeriodChart = isPeriodChart || iSlabs.slabFields().fromPeriod() != null; @@ -136,15 +137,17 @@ public class InterestRateChart extends AbstractPersistableCustom { if (iSlabs.slabFields().isValidChart(isPrimaryGroupingByAmount) && nextSlabs.slabFields().isValidChart(isPrimaryGroupingByAmount)) { if (iSlabs.slabFields().isRateChartOverlapping(nextSlabs.slabFields(), isPrimaryGroupingByAmount)) { - baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.range.overlapping", iSlabs.slabFields() - .fromPeriod(), iSlabs.slabFields().toPeriod(), nextSlabs.slabFields().fromPeriod(), nextSlabs.slabFields() - .toPeriod(), iSlabs.slabFields().getAmountRangeFrom(), iSlabs.slabFields().getAmountRangeTo(), nextSlabs - .slabFields().getAmountRangeFrom(), nextSlabs.slabFields().getAmountRangeTo()); + baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.range.overlapping", + iSlabs.slabFields().fromPeriod(), iSlabs.slabFields().toPeriod(), nextSlabs.slabFields().fromPeriod(), + nextSlabs.slabFields().toPeriod(), iSlabs.slabFields().getAmountRangeFrom(), + iSlabs.slabFields().getAmountRangeTo(), nextSlabs.slabFields().getAmountRangeFrom(), + nextSlabs.slabFields().getAmountRangeTo()); } else if (iSlabs.slabFields().isRateChartHasGap(nextSlabs.slabFields(), isPrimaryGroupingByAmount)) { - baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.range.has.gap", iSlabs.slabFields() - .fromPeriod(), iSlabs.slabFields().toPeriod(), nextSlabs.slabFields().fromPeriod(), nextSlabs.slabFields() - .toPeriod(), iSlabs.slabFields().getAmountRangeFrom(), iSlabs.slabFields().getAmountRangeTo(), nextSlabs - .slabFields().getAmountRangeFrom(), nextSlabs.slabFields().getAmountRangeTo()); + baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.range.has.gap", + iSlabs.slabFields().fromPeriod(), iSlabs.slabFields().toPeriod(), nextSlabs.slabFields().fromPeriod(), + nextSlabs.slabFields().toPeriod(), iSlabs.slabFields().getAmountRangeFrom(), + iSlabs.slabFields().getAmountRangeTo(), nextSlabs.slabFields().getAmountRangeFrom(), + nextSlabs.slabFields().getAmountRangeTo()); } if (isPrimaryGroupingByAmount) { if (!iSlabs.slabFields().isAmountSame(nextSlabs.slabFields())) { @@ -153,26 +156,26 @@ public class InterestRateChart extends AbstractPersistableCustom { nextSlabs.slabFields().toPeriod()); } if (iSlabs.slabFields().toPeriod() != null) { - baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.period.range.end.incorrect", iSlabs - .slabFields().toPeriod()); + baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.period.range.end.incorrect", + iSlabs.slabFields().toPeriod()); } } } else if (!iSlabs.slabFields().isPeriodsSame(nextSlabs.slabFields())) { if (InterestRateChartSlabFields.isNotProperAmountStart(nextSlabs.slabFields())) { - baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.amount.range.start.incorrect", nextSlabs - .slabFields().getAmountRangeFrom()); + baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.amount.range.start.incorrect", + nextSlabs.slabFields().getAmountRangeFrom()); } if (iSlabs.slabFields().getAmountRangeTo() != null) { - baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.amount.range.end.incorrect", iSlabs - .slabFields().getAmountRangeTo()); + baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.amount.range.end.incorrect", + iSlabs.slabFields().getAmountRangeTo()); } } } } else if (iSlabs.slabFields().isNotProperPriodEnd()) { - baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.range.end.incorrect", - iSlabs.slabFields().toPeriod(), iSlabs.slabFields().getAmountRangeTo()); + baseDataValidator.failWithCodeNoParameterAddedToErrorCode("chart.slabs.range.end.incorrect", iSlabs.slabFields().toPeriod(), + iSlabs.slabFields().getAmountRangeTo()); } } } @@ -234,8 +237,8 @@ public class InterestRateChart extends AbstractPersistableCustom { } } - public void updateChartSlabs(JsonCommand command, final Map actualChanges, - final DataValidatorBuilder baseDataValidator, String currencyCode) { + public void updateChartSlabs(JsonCommand command, final Map actualChanges, final DataValidatorBuilder baseDataValidator, + String currencyCode) { final Map deleteChartSlabs = new HashMap<>(); final Map chartSlabsChanges = new HashMap<>(); @@ -272,12 +275,12 @@ public class InterestRateChart extends AbstractPersistableCustom { final BigDecimal amountRangeFrom = chartSlabsCommand.bigDecimalValueOfParameterNamed(amountRangeFromParamName, locale); final BigDecimal amountRangeTo = chartSlabsCommand.bigDecimalValueOfParameterNamed(amountRangeToParamName, locale); - final BigDecimal annualInterestRate = chartSlabsCommand.bigDecimalValueOfParameterNamed( - annualInterestRateParamName, locale); + final BigDecimal annualInterestRate = chartSlabsCommand.bigDecimalValueOfParameterNamed(annualInterestRateParamName, + locale); - final InterestRateChartSlabFields slabFields = InterestRateChartSlabFields - .createNew(description, periodFrequencyType, fromPeriod, toPeriod, amountRangeFrom, amountRangeTo, - annualInterestRate, currencyCode); + final InterestRateChartSlabFields slabFields = InterestRateChartSlabFields.createNew(description, + periodFrequencyType, fromPeriod, toPeriod, amountRangeFrom, amountRangeTo, annualInterestRate, + currencyCode); final InterestRateChartSlab chartSlab = InterestRateChartSlab.createNew(slabFields, this); chartSlab.slabFields().validateChartSlabPlatformRules(chartSlabsCommand, baseDataValidator, locale); chartSlab.updateIncentives(chartSlabsCommand, actualChanges, baseDataValidator, chartSlab, locale); @@ -333,4 +336,4 @@ public class InterestRateChart extends AbstractPersistableCustom { public boolean isApplicableChartFor(final LocalDate target) { return this.chartFields.isApplicableChartFor(target); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartFields.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartFields.java index 47f83d07b..31820362e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartFields.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartFields.java @@ -67,7 +67,8 @@ public class InterestRateChartFields { return new InterestRateChartFields(name, description, fromDate, toDate, isPrimaryGroupingByAmount); } - private InterestRateChartFields(String name, String description, LocalDate fromDate, LocalDate toDate, boolean isPrimaryGroupingByAmount) { + private InterestRateChartFields(String name, String description, LocalDate fromDate, LocalDate toDate, + boolean isPrimaryGroupingByAmount) { this.name = name; this.description = description; this.fromDate = fromDate.toDate(); @@ -172,4 +173,4 @@ public class InterestRateChartFields { return this.isPrimaryGroupingByAmount; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartSlab.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartSlab.java index 2632adba1..d49886779 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartSlab.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartSlab.java @@ -138,8 +138,8 @@ public class InterestRateChartSlab extends AbstractPersistableCustom { return incentives.remove(incentive); } - public void updateIncentives(JsonCommand command, final Map actualChanges, - final DataValidatorBuilder baseDataValidator, final InterestRateChartSlab chartSlab, final Locale locale) { + public void updateIncentives(JsonCommand command, final Map actualChanges, final DataValidatorBuilder baseDataValidator, + final InterestRateChartSlab chartSlab, final Locale locale) { final Map deleteIncentives = new HashMap<>(); final Map IncentiveChanges = new HashMap<>(); if (command.hasParameter(InterestRateChartSlabApiConstants.incentivesParamName)) { @@ -189,4 +189,4 @@ public class InterestRateChartSlab extends AbstractPersistableCustom { } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartSlabFields.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartSlabFields.java index 16b8a9f10..443f9289a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartSlabFields.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/domain/InterestRateChartSlabFields.java @@ -228,8 +228,8 @@ public class InterestRateChartSlabFields { public static boolean isNotProperAmountStart(final InterestRateChartSlabFields interestRateChartSlabFields) { return interestRateChartSlabFields.amountRangeFrom != null - && (interestRateChartSlabFields.amountRangeFrom.compareTo(BigDecimal.ONE) != 0 && interestRateChartSlabFields.amountRangeFrom - .compareTo(BigDecimal.ZERO) != 0); + && (interestRateChartSlabFields.amountRangeFrom.compareTo(BigDecimal.ONE) != 0 + && interestRateChartSlabFields.amountRangeFrom.compareTo(BigDecimal.ZERO) != 0); } private boolean isNotProperAmountStart(final BigDecimal amount) { @@ -305,7 +305,9 @@ public class InterestRateChartSlabFields { public boolean isBigDecimalSame(final BigDecimal obj1, final BigDecimal obj2) { if (obj1 == null || obj2 == null) { - if (Objects.compare(obj1,obj2, Comparator.nullsFirst(Comparator.naturalOrder())) == 0 ? Boolean.TRUE:Boolean.FALSE){ return true; } + if (Objects.compare(obj1, obj2, Comparator.nullsFirst(Comparator.naturalOrder())) == 0 ? Boolean.TRUE : Boolean.FALSE) { + return true; + } return false; } return obj1.compareTo(obj2) == 0; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/exception/InterestRateChartNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/exception/InterestRateChartNotFoundException.java index 664454359..16f8950be 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/exception/InterestRateChartNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/exception/InterestRateChartNotFoundException.java @@ -25,4 +25,4 @@ public class InterestRateChartNotFoundException extends AbstractPlatformResource public InterestRateChartNotFoundException(final Long id) { super("error.msg.interest.rate.chart.id.invalid", "Interest rate chart with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/exception/InterestRateChartSlabNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/exception/InterestRateChartSlabNotFoundException.java index 79b561608..7deb51d89 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/exception/InterestRateChartSlabNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/exception/InterestRateChartSlabNotFoundException.java @@ -27,6 +27,8 @@ public class InterestRateChartSlabNotFoundException extends AbstractPlatformReso } public InterestRateChartSlabNotFoundException(final Long id, final Long chartId) { - super("error.msg.interest.rate.chart.slab.id.invalid", "Interest rate chart slab with identifier " + id + " does not exist in interest chart with identifier " + chartId , id, chartId); + super("error.msg.interest.rate.chart.slab.id.invalid", + "Interest rate chart slab with identifier " + id + " does not exist in interest chart with identifier " + chartId, id, + chartId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/CreateInterestRateChartCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/CreateInterestRateChartCommandHandler.java index 06cb22bae..8d9472fda 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/CreateInterestRateChartCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/CreateInterestRateChartCommandHandler.java @@ -41,4 +41,4 @@ public class CreateInterestRateChartCommandHandler implements NewCommandSourceHa public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.create(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/CreateInterestRateChartSlabCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/CreateInterestRateChartSlabCommandHandler.java index ef01f0322..f3d772390 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/CreateInterestRateChartSlabCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/CreateInterestRateChartSlabCommandHandler.java @@ -41,4 +41,4 @@ public class CreateInterestRateChartSlabCommandHandler implements NewCommandSour public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.create(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/DeleteInterestRateChartCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/DeleteInterestRateChartCommandHandler.java index 6f83f812a..bb5566020 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/DeleteInterestRateChartCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/DeleteInterestRateChartCommandHandler.java @@ -41,4 +41,4 @@ public class DeleteInterestRateChartCommandHandler implements NewCommandSourceHa public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.deleteChart(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/DeleteInterestRateChartSlabCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/DeleteInterestRateChartSlabCommandHandler.java index c9debde7f..d58610982 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/DeleteInterestRateChartSlabCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/DeleteInterestRateChartSlabCommandHandler.java @@ -39,7 +39,7 @@ public class DeleteInterestRateChartSlabCommandHandler implements NewCommandSour @Override public CommandProcessingResult processCommand(final JsonCommand command) { - //command.subentityId(); //returns chart id + // command.subentityId(); //returns chart id return this.writePlatformService.deleteChartSlab(command.entityId(), command.subentityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/UpdateInterestRateChartCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/UpdateInterestRateChartCommandHandler.java index 3d20956a2..c1bba0abf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/UpdateInterestRateChartCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/UpdateInterestRateChartCommandHandler.java @@ -41,4 +41,4 @@ public class UpdateInterestRateChartCommandHandler implements NewCommandSourceHa public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.update(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/UpdateInterestRateChartSlabCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/UpdateInterestRateChartSlabCommandHandler.java index 3f6e79d7b..b24427a1c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/UpdateInterestRateChartSlabCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/handler/UpdateInterestRateChartSlabCommandHandler.java @@ -39,7 +39,7 @@ public class UpdateInterestRateChartSlabCommandHandler implements NewCommandSour @Override public CommandProcessingResult processCommand(final JsonCommand command) { - //command.subentityId();//returns chart id + // command.subentityId();//returns chart id return this.writePlatformService.update(command.entityId(), command.subentityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveAttributeName.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveAttributeName.java old mode 100755 new mode 100644 index 35d57388a..e5648363b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveAttributeName.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveAttributeName.java @@ -109,4 +109,4 @@ public enum InterestIncentiveAttributeName { return values.toArray(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveEntityType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveEntityType.java old mode 100755 new mode 100644 index deb0fffd9..36e329729 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveEntityType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveEntityType.java @@ -80,4 +80,4 @@ public enum InterestIncentiveEntityType { return values.toArray(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveType.java old mode 100755 new mode 100644 index 1e656547e..75b41757a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/incentive/InterestIncentiveType.java @@ -85,4 +85,4 @@ public enum InterestIncentiveType { return values.toArray(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestIncentiveDropdownReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestIncentiveDropdownReadPlatformService.java old mode 100755 new mode 100644 index 2501ac6be..5315b4d37 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestIncentiveDropdownReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestIncentiveDropdownReadPlatformService.java @@ -30,4 +30,4 @@ public interface InterestIncentiveDropdownReadPlatformService { Collection retrieveConditionTypeOptions(); Collection retrieveIncentiveTypeOptions(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestIncentivesEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestIncentivesEnumerations.java old mode 100755 new mode 100644 index 9f2a02108..28932af76 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestIncentivesEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestIncentivesEnumerations.java @@ -137,4 +137,4 @@ public class InterestIncentivesEnumerations { return optionDatas; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartAssembler.java index e19bbedb0..16fe6716f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartAssembler.java @@ -78,7 +78,8 @@ public class InterestRateChartAssembler { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - public InterestRateChart assembleFrom(final JsonElement element, final String currencyCode, final DataValidatorBuilder baseDataValidator) { + public InterestRateChart assembleFrom(final JsonElement element, final String currencyCode, + final DataValidatorBuilder baseDataValidator) { final String name = this.fromApiJsonHelper.extractStringNamed(nameParamName, element); final String description = this.fromApiJsonHelper.extractStringNamed(descriptionParamName, element); @@ -104,4 +105,4 @@ public class InterestRateChartAssembler { .findOneWithNotFoundDetection(interestRateChartId); return interestRateChart; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartDropdownReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartDropdownReadPlatformService.java index f3adc786e..dfaea1fe4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartDropdownReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartDropdownReadPlatformService.java @@ -24,4 +24,4 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; public interface InterestRateChartDropdownReadPlatformService { Collection retrievePeriodTypeOptions(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartDropdownReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartDropdownReadPlatformServiceImpl.java index 3517e9493..bcbc72ea1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartDropdownReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartDropdownReadPlatformServiceImpl.java @@ -31,4 +31,4 @@ public class InterestRateChartDropdownReadPlatformServiceImpl implements Interes return InterestRateChartEnumerations.periodType(PeriodFrequencyType.values()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartEnumerations.java index 983f02287..3228093d3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartEnumerations.java @@ -37,20 +37,20 @@ public class InterestRateChartEnumerations { case INVALID: break; case DAYS: - optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), - PeriodFrequencyType.DAYS.getCode(), "Days"); + optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), PeriodFrequencyType.DAYS.getCode(), + "Days"); break; case WEEKS: - optionData = new EnumOptionData(PeriodFrequencyType.WEEKS.getValue().longValue(), - PeriodFrequencyType.WEEKS.getCode(), "Weeks"); + optionData = new EnumOptionData(PeriodFrequencyType.WEEKS.getValue().longValue(), PeriodFrequencyType.WEEKS.getCode(), + "Weeks"); break; case MONTHS: - optionData = new EnumOptionData(PeriodFrequencyType.MONTHS.getValue().longValue(), - PeriodFrequencyType.MONTHS.getCode(), "Months"); + optionData = new EnumOptionData(PeriodFrequencyType.MONTHS.getValue().longValue(), PeriodFrequencyType.MONTHS.getCode(), + "Months"); break; case YEARS: - optionData = new EnumOptionData(PeriodFrequencyType.YEARS.getValue().longValue(), - PeriodFrequencyType.YEARS.getCode(), "Years"); + optionData = new EnumOptionData(PeriodFrequencyType.YEARS.getValue().longValue(), PeriodFrequencyType.YEARS.getCode(), + "Years"); break; default: } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartReadPlatformService.java index 016a13392..764be19f2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartReadPlatformService.java @@ -23,11 +23,11 @@ import org.apache.fineract.portfolio.interestratechart.data.InterestRateChartDat public interface InterestRateChartReadPlatformService { - //Collection retrieveAll(Long savingsProductId); + // Collection retrieveAll(Long savingsProductId); InterestRateChartData retrieveOne(Long interestChartId); - //Collection retrieveAllWithSlabs(); + // Collection retrieveAllWithSlabs(); Collection retrieveAllWithSlabs(Long savingsProductId); @@ -42,4 +42,4 @@ public interface InterestRateChartReadPlatformService { InterestRateChartData template(); InterestRateChartData retrieveActiveChartWithTemplate(Long productId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartReadPlatformServiceImpl.java index 4995a9176..10f7d967f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartReadPlatformServiceImpl.java @@ -186,8 +186,7 @@ public class InterestRateChartReadPlatformServiceImpl implements InterestRateCha private InterestRateChartExtractor() { final StringBuilder sqlBuilder = new StringBuilder(400); - sqlBuilder - .append("irc.id as ircId, irc.name as ircName, irc.description as ircDescription,") + sqlBuilder.append("irc.id as ircId, irc.name as ircName, irc.description as ircDescription,") .append("irc.from_date as ircFromDate, irc.end_date as ircEndDate, ") .append("irc.is_primary_grouping_by_amount as isPrimaryGroupingByAmount, ") .append("ircd.id as ircdId, ircd.description as ircdDescription, ircd.period_type_enum ircdPeriodTypeId, ") @@ -198,8 +197,8 @@ public class InterestRateChartReadPlatformServiceImpl implements InterestRateCha .append("sp.id as savingsProductId, sp.name as savingsProductName, ").append("iri.id as iriId, ") .append(" iri.entiry_type as entityType, iri.attribute_name as attributeName ,") .append(" iri.condition_type as conditionType, iri.attribute_value as attributeValue, ") - .append(" iri.incentive_type as incentiveType, iri.amount as amount, ") - .append("code.code_value as attributeValueDesc ").append("from ") + .append(" iri.incentive_type as incentiveType, iri.amount as amount, ").append("code.code_value as attributeValueDesc ") + .append("from ") .append("m_interest_rate_chart irc left join m_interest_rate_slab ircd on irc.id=ircd.interest_rate_chart_id ") .append(" left join m_interest_incentives iri on iri.interest_rate_slab_id = ircd.id ") .append(" left join m_code_value code on code.id = iri.attribute_value ") @@ -271,7 +270,8 @@ public class InterestRateChartReadPlatformServiceImpl implements InterestRateCha final Long savingsProductId = JdbcSupport.getLongDefaultToNullIfZero(rs, "savingsProductId"); final String savingsProductName = rs.getString("savingsProductName"); - return InterestRateChartData.instance(id, name, description, fromDate, endDate, isPrimaryGroupingByAmount, savingsProductId, savingsProductName); + return InterestRateChartData.instance(id, name, description, fromDate, endDate, isPrimaryGroupingByAmount, savingsProductId, + savingsProductName); } } @@ -287,16 +287,15 @@ public class InterestRateChartReadPlatformServiceImpl implements InterestRateCha private InterestRateChartSlabsMapper() { final StringBuilder sqlBuilder = new StringBuilder(400); - sqlBuilder - .append("ircd.id as ircdId, ircd.description as ircdDescription, ircd.period_type_enum ircdPeriodTypeId, ") - .append("ircd.from_period as ircdFromPeriod, ircd.to_period as ircdToPeriod, ircd.amount_range_from as ircdAmountRangeFrom, ") + sqlBuilder.append("ircd.id as ircdId, ircd.description as ircdDescription, ircd.period_type_enum ircdPeriodTypeId, ").append( + "ircd.from_period as ircdFromPeriod, ircd.to_period as ircdToPeriod, ircd.amount_range_from as ircdAmountRangeFrom, ") .append("ircd.amount_range_to as ircdAmountRangeTo, ircd.annual_interest_rate as ircdAnnualInterestRate, ") .append("curr.code as currencyCode, curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ") .append("curr.display_symbol as currencyDisplaySymbol, curr.decimal_places as currencyDigits, curr.currency_multiplesof as inMultiplesOf, ") .append("iri.id as iriId, ").append(" iri.entiry_type as entityType, iri.attribute_name as attributeName ,") .append(" iri.condition_type as conditionType, iri.attribute_value as attributeValue, ") - .append(" iri.incentive_type as incentiveType, iri.amount as amount, ") - .append("code.code_value as attributeValueDesc ").append("from ").append("m_interest_rate_slab ircd ") + .append(" iri.incentive_type as incentiveType, iri.amount as amount, ").append("code.code_value as attributeValueDesc ") + .append("from ").append("m_interest_rate_slab ircd ") .append(" left join m_interest_incentives iri on iri.interest_rate_slab_id = ircd.id ") .append(" left join m_code_value code on code.id = iri.attribute_value ") .append("left join m_currency curr on ircd.currency_code= curr.code "); @@ -330,8 +329,8 @@ public class InterestRateChartReadPlatformServiceImpl implements InterestRateCha final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); // currency - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); return InterestRateChartSlabData.instance(id, description, periodType, fromPeriod, toPeriod, amountRangeFrom, amountRangeTo, annualInterestRate, currency); @@ -416,4 +415,4 @@ public class InterestRateChartReadPlatformServiceImpl implements InterestRateCha } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabAssembler.java index 457e4f4e2..0fcae7887 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabAssembler.java @@ -61,7 +61,8 @@ public class InterestRateChartSlabAssembler { @Autowired public InterestRateChartSlabAssembler(final FromJsonHelper fromApiJsonHelper, - final InterestRateChartRepositoryWrapper interestRateChartRepositoryWrapper, final InterestIncentiveAssembler incentiveAssembler) { + final InterestRateChartRepositoryWrapper interestRateChartRepositoryWrapper, + final InterestIncentiveAssembler incentiveAssembler) { this.fromApiJsonHelper = fromApiJsonHelper; this.interestRateChartRepositoryWrapper = interestRateChartRepositoryWrapper; this.incentiveAssembler = incentiveAssembler; @@ -118,9 +119,7 @@ public class InterestRateChartSlabAssembler { final InterestRateChart chart = this.interestRateChartRepositoryWrapper.findOneWithNotFoundDetection(chartId); final InterestRateChartSlab interestRateChartSlab = chart.findChartSlab(chartSlabId); - if (interestRateChartSlab == null) { - throw new InterestRateChartSlabNotFoundException(chartSlabId, chartId); - } + if (interestRateChartSlab == null) { throw new InterestRateChartSlabNotFoundException(chartSlabId, chartId); } return interestRateChartSlab; } @@ -147,4 +146,4 @@ public class InterestRateChartSlabAssembler { private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabReadPlatformService.java index 71596c3fb..8092377af 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabReadPlatformService.java @@ -31,4 +31,4 @@ public interface InterestRateChartSlabReadPlatformService { InterestRateChartSlabData retrieveTemplate(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabReadPlatformServiceImpl.java index 545ab87cc..9ddc40461 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabReadPlatformServiceImpl.java @@ -77,8 +77,8 @@ public class InterestRateChartSlabReadPlatformServiceImpl implements InterestRat public InterestRateChartSlabData retrieveOne(Long chartId, Long chartSlabId) { this.context.authenticatedUser(); final String sql = "select " + this.chartSlabExtractor.schema() + " where irc.id = ? order by ircd.id asc"; - Collection chartDatas = this.jdbcTemplate.query(sql, this.chartSlabExtractor, new Object[] { - chartSlabId, chartId }); + Collection chartDatas = this.jdbcTemplate.query(sql, this.chartSlabExtractor, + new Object[] { chartSlabId, chartId }); if (chartDatas == null || chartDatas.isEmpty()) { throw new InterestRateChartSlabNotFoundException(chartSlabId, chartId); } return chartDatas.iterator().next(); @@ -132,16 +132,15 @@ public class InterestRateChartSlabReadPlatformServiceImpl implements InterestRat private InterestRateChartSlabsMapper() { final StringBuilder sqlBuilder = new StringBuilder(400); - sqlBuilder - .append("ircd.id as ircdId, ircd.description as ircdDescription, ircd.period_type_enum ircdPeriodTypeId, ") - .append("ircd.from_period as ircdFromPeriod, ircd.to_period as ircdToPeriod, ircd.amount_range_from as ircdAmountRangeFrom, ") + sqlBuilder.append("ircd.id as ircdId, ircd.description as ircdDescription, ircd.period_type_enum ircdPeriodTypeId, ").append( + "ircd.from_period as ircdFromPeriod, ircd.to_period as ircdToPeriod, ircd.amount_range_from as ircdAmountRangeFrom, ") .append("ircd.amount_range_to as ircdAmountRangeTo, ircd.annual_interest_rate as ircdAnnualInterestRate, ") .append("curr.code as currencyCode, curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ") .append("curr.display_symbol as currencyDisplaySymbol, curr.decimal_places as currencyDigits, curr.currency_multiplesof as inMultiplesOf, ") .append("iri.id as iriId, ").append(" iri.entiry_type as entityType, iri.attribute_name as attributeName ,") .append(" iri.condition_type as conditionType, iri.attribute_value as attributeValue, ") - .append(" iri.incentive_type as incentiveType, iri.amount as amount, ") - .append("code.code_value as attributeValueDesc ").append("from ").append("m_interest_rate_slab ircd ") + .append(" iri.incentive_type as incentiveType, iri.amount as amount, ").append("code.code_value as attributeValueDesc ") + .append("from ").append("m_interest_rate_slab ircd ") .append(" left join m_interest_incentives iri on iri.interest_rate_slab_id = ircd.id ") .append(" left join m_code_value code on code.id = iri.attribute_value ") .append("left join m_currency curr on ircd.currency_code= curr.code "); @@ -172,8 +171,8 @@ public class InterestRateChartSlabReadPlatformServiceImpl implements InterestRat final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); // currency - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); return InterestRateChartSlabData.instance(id, description, periodType, fromPeriod, toPeriod, amountRangeFrom, amountRangeTo, annualInterestRate, currency); @@ -254,4 +253,4 @@ public class InterestRateChartSlabReadPlatformServiceImpl implements InterestRat } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabWritePlatformService.java index 372e03c5e..caeb69bba 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabWritePlatformService.java @@ -28,4 +28,4 @@ public interface InterestRateChartSlabWritePlatformService { CommandProcessingResult update(Long chartSlabId, Long interestChartId, JsonCommand command); CommandProcessingResult deleteChartSlab(Long chartSlabId, Long interestRateChartId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabWritePlatformServiceJpaRepositoryImpl.java index ada128c97..6edd54895 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartSlabWritePlatformServiceJpaRepositoryImpl.java @@ -91,10 +91,9 @@ public class InterestRateChartSlabWritePlatformServiceJpaRepositoryImpl implemen public CommandProcessingResult update(Long chartSlabId, Long interestRateChartId, JsonCommand command) { this.interestRateChartSlabDataValidator.validateUpdate(command.json()); final Map changes = new LinkedHashMap<>(20); - final InterestRateChartSlab updateChartSlabs = this.interestRateChartSlabAssembler.assembleFrom(chartSlabId, - interestRateChartId); + final InterestRateChartSlab updateChartSlabs = this.interestRateChartSlabAssembler.assembleFrom(chartSlabId, interestRateChartId); final Locale locale = command.extractLocale(); - updateChartSlabs.update(command, changes,locale); + updateChartSlabs.update(command, changes, locale); this.chartSlabRepository.saveAndFlush(updateChartSlabs); @@ -107,12 +106,11 @@ public class InterestRateChartSlabWritePlatformServiceJpaRepositoryImpl implemen @Override @Transactional public CommandProcessingResult deleteChartSlab(Long chartSlabId, Long interestRateChartId) { - final InterestRateChartSlab deleteChartSlabs = this.interestRateChartSlabAssembler.assembleFrom(chartSlabId, - interestRateChartId); + final InterestRateChartSlab deleteChartSlabs = this.interestRateChartSlabAssembler.assembleFrom(chartSlabId, interestRateChartId); this.chartSlabRepository.delete(deleteChartSlabs); return new CommandProcessingResultBuilder() // .withEntityId(chartSlabId) // .build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartWritePlatformService.java index bb401d81c..401731666 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartWritePlatformService.java @@ -28,4 +28,4 @@ public interface InterestRateChartWritePlatformService { CommandProcessingResult update(Long interestChartId, JsonCommand command); CommandProcessingResult deleteChart(Long interestChartId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartWritePlatformServiceJpaRepositoryImpl.java index a8990c146..fa7e15152 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/interestratechart/service/InterestRateChartWritePlatformServiceJpaRepositoryImpl.java @@ -101,4 +101,4 @@ public class InterestRateChartWritePlatformServiceJpaRepositoryImpl implements I .build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/BulkLoansApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/BulkLoansApiResource.java index 0ab27e584..ee865e04f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/BulkLoansApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/BulkLoansApiResource.java @@ -56,8 +56,8 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class BulkLoansApiResource { - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("officeId", "fromLoanOfficerId", - "assignmentDate", "officeOptions", "loanOfficerOptions", "accountSummaryCollection")); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("officeId", "fromLoanOfficerId", "assignmentDate", + "officeOptions", "loanOfficerOptions", "accountSummaryCollection")); private final String resourceNameForPermissions = "LOAN"; @@ -124,4 +124,4 @@ public class BulkLoansApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanApiConstants.java index 6edee4895..bbc359f33 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanApiConstants.java @@ -31,7 +31,7 @@ public interface LoanApiConstants { public static final String loanChargeIdParameterName = "loanChargeId"; public static final String principalDisbursedParameterName = "transactionAmount"; public static final String chargesParameterName = "charges"; - public static final String loanIdTobeApproved="loanId"; + public static final String loanIdTobeApproved = "loanId"; public static final String approvedLoanAmountParameterName = "approvedLoanAmount"; public static final String approvedOnDateParameterName = "approvedOnDate"; @@ -110,10 +110,10 @@ public interface LoanApiConstants { public static final String dueDateParamName = "dueDate"; public static final String modifiedDueDateParamName = "modifiedDueDate"; public static final String principalParamName = "principal"; - public static final String parentAccountParamName="isParentAccount"; - public static final String totalLoanParamName="totalLoan"; + public static final String parentAccountParamName = "isParentAccount"; + public static final String totalLoanParamName = "totalLoan"; public static final String installmentAmountParamName = "installmentAmount"; - //loan write off + // loan write off public static final String WRITEOFFREASONS = "WriteOffReasons"; // fore closure constants diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanChargesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanChargesApiResource.java index 663d31e94..4a7a86ded 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanChargesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanChargesApiResource.java @@ -66,10 +66,11 @@ import org.springframework.stereotype.Component; @Path("/loans/{loanId}/charges") @Component @Scope("singleton") -@Api(tags = {"Loan Charges"}) +@Api(tags = { "Loan Charges" }) @SwaggerDefinition(tags = { - @Tag(name = "Loan Charges", description = "Its typical for MFIs to add extra costs for their loan products. They can be either Fees or Penalties.\n" + "\n" + "Loan Charges are instances of Charges and represent either fees and penalties for loan products. Refer Charges for documentation of the various properties of a charge, Only additional properties ( specific to the context of a Charge being associated with a Loan) are described here") -}) + @Tag(name = "Loan Charges", description = "Its typical for MFIs to add extra costs for their loan products. They can be either Fees or Penalties.\n" + + "\n" + + "Loan Charges are instances of Charges and represent either fees and penalties for loan products. Refer Charges for documentation of the various properties of a charge, Only additional properties ( specific to the context of a Charge being associated with a Loan) are described here") }) public class LoanChargesApiResource { private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( @@ -89,8 +90,7 @@ public class LoanChargesApiResource { @Autowired public LoanChargesApiResource(final PlatformSecurityContext context, final ChargeReadPlatformService chargeReadPlatformService, final LoanChargeReadPlatformService loanChargeReadPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, + final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.context = context; this.chargeReadPlatformService = chargeReadPlatformService; @@ -107,9 +107,12 @@ public class LoanChargesApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Loan Charges", httpMethod = "GET", notes = "It lists all the Loan Charges specific to a Loan \n\n" + "Example Requests:\n" + "\n" + "loans/1/charges\n" + "\n" + "\n" + "loans/1/charges?fields=name,amountOrPercentage") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = LoanChargesApiResourceSwagger.GetLoansLoanIdChargesChargeIdResponse.class)}) - public String retrieveAllLoanCharges(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @Context final UriInfo uriInfo){ + @ApiOperation(value = "List Loan Charges", httpMethod = "GET", notes = "It lists all the Loan Charges specific to a Loan \n\n" + + "Example Requests:\n" + "\n" + "loans/1/charges\n" + "\n" + "\n" + "loans/1/charges?fields=name,amountOrPercentage") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = LoanChargesApiResourceSwagger.GetLoansLoanIdChargesChargeIdResponse.class) }) + public String retrieveAllLoanCharges(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -121,10 +124,12 @@ public class LoanChargesApiResource { @GET @Path("template") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @ApiOperation(value = "Retrieve Loan Charges Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "loans/1/charges/template\n" + "\n") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.GetLoansLoanIdChargesTemplateResponse.class)}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Retrieve Loan Charges Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "loans/1/charges/template\n" + "\n") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.GetLoansLoanIdChargesTemplateResponse.class) }) public String retrieveTemplate(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -139,12 +144,14 @@ public class LoanChargesApiResource { @GET @Path("{chargeId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @ApiOperation(value = "Retrieve a Loan Charge", httpMethod = "GET", notes = "Retrieves Loan Charge according to the Loan ID and Charge ID" + "Example Requests:\n" + "\n" + "/loans/1/charges/1\n" + "\n" + "\n" + "/loans/1/charges/1?fields=name,amountOrPercentage") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.GetLoansLoanIdChargesChargeIdResponse.class)}) - public String retrieveLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId, - @Context final UriInfo uriInfo) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Retrieve a Loan Charge", httpMethod = "GET", notes = "Retrieves Loan Charge according to the Loan ID and Charge ID" + + "Example Requests:\n" + "\n" + "/loans/1/charges/1\n" + "\n" + "\n" + "/loans/1/charges/1?fields=name,amountOrPercentage") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.GetLoansLoanIdChargesChargeIdResponse.class) }) + public String retrieveLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -160,13 +167,16 @@ public class LoanChargesApiResource { } @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Create a Loan Charge", httpMethod = "POST", notes = "It Creates a Loan Charge") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanChargesApiResourceSwagger.PostLoansLoanIdChargesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.PostLoansLoanIdChargesResponse.class)}) - public String executeLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanChargesApiResourceSwagger.PostLoansLoanIdChargesRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.PostLoansLoanIdChargesResponse.class) }) + public String executeLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { CommandProcessingResult result = null; if (is(commandParam, "pay")) { @@ -184,13 +194,16 @@ public class LoanChargesApiResource { @PUT @Path("{chargeId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Loan Charge", httpMethod = "PUT", notes = "Currently Loan Charges may be updated only if the Loan is not yet approved") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanChargesApiResourceSwagger.PutLoansLoanIdChargesChargeIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.PutLoansLoanIdChargesChargeIdResponse.class)}) - public String updateLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanChargesApiResourceSwagger.PutLoansLoanIdChargesChargeIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.PutLoansLoanIdChargesChargeIdResponse.class) }) + public String updateLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateLoanCharge(loanId, loanChargeId) .withJson(apiRequestBodyAsJson).build(); @@ -202,13 +215,17 @@ public class LoanChargesApiResource { @POST @Path("{chargeId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Pay Loan Charge", httpMethod = "POST", notes = "Loan Charge will be paid if the loan is linked with a savings account") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanChargesApiResourceSwagger.PostLoansLoanIdChargesChargeIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.PostLoansLoanIdChargesChargeIdResponse.class)}) - public String executeLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId, - @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanChargesApiResourceSwagger.PostLoansLoanIdChargesChargeIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.PostLoansLoanIdChargesChargeIdResponse.class) }) + public String executeLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); CommandProcessingResult result = null; @@ -227,11 +244,13 @@ public class LoanChargesApiResource { @DELETE @Path("{chargeId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Loan Charge", httpMethod = "DELETE", notes = "Note: Currently, A Loan Charge may only be removed from Loans that are not yet approved.") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.DeleteLoansLoanIdChargesChargeIdResponse.class)}) - public String deleteLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId) { + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanChargesApiResourceSwagger.DeleteLoansLoanIdChargesChargeIdResponse.class) }) + public String deleteLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteLoanCharge(loanId, loanChargeId).build(); @@ -239,4 +258,4 @@ public class LoanChargesApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanChargesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanChargesApiResourceSwagger.java index a3b95257d..6571cc434 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanChargesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanChargesApiResourceSwagger.java @@ -26,17 +26,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/02/17. */ final class LoanChargesApiResourceSwagger { - private LoanChargesApiResourceSwagger() { - } + + private LoanChargesApiResourceSwagger() {} @ApiModel(value = "GetLoansLoanIdChargesChargeIdResponse") public static final class GetLoansLoanIdChargesChargeIdResponse { - private GetLoansLoanIdChargesChargeIdResponse() { - } + + private GetLoansLoanIdChargesChargeIdResponse() {} final class GetLoanChargeTimeType { - private GetLoanChargeTimeType() { - } + + private GetLoanChargeTimeType() {} @ApiModelProperty(example = "1") public Integer id; @@ -47,8 +47,8 @@ final class LoanChargesApiResourceSwagger { } final class GetLoanChargeCalculationType { - private GetLoanChargeCalculationType() { - } + + private GetLoanChargeCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -59,8 +59,8 @@ final class LoanChargesApiResourceSwagger { } final class GetLoanChargeCurrency { - private GetLoanChargeCurrency() { - } + + private GetLoanChargeCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -107,16 +107,16 @@ final class LoanChargesApiResourceSwagger { @ApiModel(value = "GetLoansLoanIdChargesTemplateResponse") public static final class GetLoansLoanIdChargesTemplateResponse { - private GetLoansLoanIdChargesTemplateResponse() { - } + + private GetLoansLoanIdChargesTemplateResponse() {} final class GetLoanChargeTemplateChargeOptions { - private GetLoanChargeTemplateChargeOptions() { - } + + private GetLoanChargeTemplateChargeOptions() {} final class GetLoanChargeTemplateChargeTimeType { - private GetLoanChargeTemplateChargeTimeType() { - } + + private GetLoanChargeTemplateChargeTimeType() {} @ApiModelProperty(example = "2") public Integer id; @@ -127,8 +127,8 @@ final class LoanChargesApiResourceSwagger { } final class GetLoanChargeTemplateChargeAppliesTo { - private GetLoanChargeTemplateChargeAppliesTo() { - } + + private GetLoanChargeTemplateChargeAppliesTo() {} @ApiModelProperty(example = "1 ") public Integer id; @@ -167,8 +167,8 @@ final class LoanChargesApiResourceSwagger { @ApiModel(value = " PostLoansLoanIdChargesRequest") public static final class PostLoansLoanIdChargesRequest { - private PostLoansLoanIdChargesRequest() { - } + + private PostLoansLoanIdChargesRequest() {} @ApiModelProperty(example = "2") public Integer chargeId; @@ -184,8 +184,8 @@ final class LoanChargesApiResourceSwagger { @ApiModel(value = " PostLoansLoanIdChargesResponse") public static final class PostLoansLoanIdChargesResponse { - private PostLoansLoanIdChargesResponse() { - } + + private PostLoansLoanIdChargesResponse() {} @ApiModelProperty(example = "1") public Long officeId; @@ -199,8 +199,8 @@ final class LoanChargesApiResourceSwagger { @ApiModel(value = " PutLoansLoanIdChargesChargeIdRequest") public static final class PutLoansLoanIdChargesChargeIdRequest { - private PutLoansLoanIdChargesChargeIdRequest() { - } + + private PutLoansLoanIdChargesChargeIdRequest() {} @ApiModelProperty(example = "dd MMMM yyyy") public String dateFormat; @@ -214,8 +214,8 @@ final class LoanChargesApiResourceSwagger { @ApiModel(value = "PutLoansLoanIdChargesChargeIdResponse") public static final class PutLoansLoanIdChargesChargeIdResponse { - private PutLoansLoanIdChargesChargeIdResponse() { - } + + private PutLoansLoanIdChargesChargeIdResponse() {} @ApiModelProperty(example = "1") public Long officeId; @@ -230,8 +230,8 @@ final class LoanChargesApiResourceSwagger { @ApiModel(value = "PostLoansLoanIdChargesChargeIdRequest") public static final class PostLoansLoanIdChargesChargeIdRequest { - private PostLoansLoanIdChargesChargeIdRequest() { - } + + private PostLoansLoanIdChargesChargeIdRequest() {} @ApiModelProperty(example = "dd MMMM yyyy") public String dateFormat; @@ -243,8 +243,8 @@ final class LoanChargesApiResourceSwagger { @ApiModel(value = "PostLoansLoanIdChargesChargeIdResponse") public static final class PostLoansLoanIdChargesChargeIdResponse { - private PostLoansLoanIdChargesChargeIdResponse() { - } + + private PostLoansLoanIdChargesChargeIdResponse() {} @ApiModelProperty(example = "1") public Long officeId; @@ -260,8 +260,8 @@ final class LoanChargesApiResourceSwagger { @ApiModel(value = "DeleteLoansLoanIdChargesChargeIdResponse") public static final class DeleteLoansLoanIdChargesChargeIdResponse { - private DeleteLoansLoanIdChargesChargeIdResponse() { - } + + private DeleteLoansLoanIdChargesChargeIdResponse() {} @ApiModelProperty(example = "1") public Long officeId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanDisbursementDetailApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanDisbursementDetailApiResource.java index 9eb6e25d6..754e9cb29 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanDisbursementDetailApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanDisbursementDetailApiResource.java @@ -49,8 +49,8 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class LoanDisbursementDetailApiResource { - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "expectedDisbursementDate", - "actualDisbursementDate", "principal", "approvedPrincipal")); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "expectedDisbursementDate", "actualDisbursementDate", "principal", "approvedPrincipal")); private final String resourceNameForPermissions = "LOAN"; @@ -79,7 +79,7 @@ public class LoanDisbursementDetailApiResource { final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateDisbusementDate(loanId, disbursementId) - .withJson(apiRequestBodyAsJson).build(); + .withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -92,8 +92,8 @@ public class LoanDisbursementDetailApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String addAndDeleteDisbursementDetail(@PathParam("loanId") final Long loanId, final String apiRequestBodyAsJson) { - CommandWrapper commandRequest = new CommandWrapperBuilder().addAndDeleteDisbursementDetails(loanId) - .withJson(apiRequestBodyAsJson).build(); + CommandWrapper commandRequest = new CommandWrapperBuilder().addAndDeleteDisbursementDetails(loanId).withJson(apiRequestBodyAsJson) + .build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -115,4 +115,4 @@ public class LoanDisbursementDetailApiResource { return this.toApiJsonSerializer.serialize(settings, disbursementData, this.RESPONSE_DATA_PARAMETERS); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanScheduleApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanScheduleApiResource.java index e6ee78c69..425d67ec9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanScheduleApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanScheduleApiResource.java @@ -55,10 +55,9 @@ import org.springframework.stereotype.Component; @Path("/loans/{loanId}/schedule") @Component @Scope("singleton") -@Api(tags = {"Loan Rescheduling"}) +@Api(tags = { "Loan Rescheduling" }) @SwaggerDefinition(tags = { - @Tag(name = "Loan Rescheduling", description = "Loan Term Variations provides the ability to change due dates, amounts and number of instalments before loan approval.") -}) + @Tag(name = "Loan Rescheduling", description = "Loan Term Variations provides the ability to change due dates, amounts and number of instalments before loan approval.") }) public class LoanScheduleApiResource { private final String resourceNameForPermissions = "LOAN"; @@ -84,11 +83,18 @@ public class LoanScheduleApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Calculate loan repayment schedule based on Loan term variations | Updates loan repayment schedule based on Loan term variations | Updates loan repayment schedule by removing Loan term variations", httpMethod = "POST", notes = "Calculate loan repayment schedule based on Loan term variations:\n\n" + "Mandatory Fields: exceptions,locale,dateFormat\n\n" + "Updates loan repayment schedule based on Loan term variations:\n\n" + "Mandatory Fields: exceptions,locale,dateFormat\n\n" + "Updates loan repayment schedule by removing Loan term variations:\n\n" + "It updates the loan repayment schedule by removing Loan term variations\n\n" + "Showing request/response for 'Updates loan repayment schedule by removing Loan term variations'") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanScheduleApiResourceSwagger.PostLoansLoanIdScheduleRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanScheduleApiResourceSwagger.PostLoansLoanIdScheduleResponse.class)}) + @ApiOperation(value = "Calculate loan repayment schedule based on Loan term variations | Updates loan repayment schedule based on Loan term variations | Updates loan repayment schedule by removing Loan term variations", httpMethod = "POST", notes = "Calculate loan repayment schedule based on Loan term variations:\n\n" + + "Mandatory Fields: exceptions,locale,dateFormat\n\n" + "Updates loan repayment schedule based on Loan term variations:\n\n" + + "Mandatory Fields: exceptions,locale,dateFormat\n\n" + "Updates loan repayment schedule by removing Loan term variations:\n\n" + + "It updates the loan repayment schedule by removing Loan term variations\n\n" + + "Showing request/response for 'Updates loan repayment schedule by removing Loan term variations'") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanScheduleApiResourceSwagger.PostLoansLoanIdScheduleRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanScheduleApiResourceSwagger.PostLoansLoanIdScheduleResponse.class) }) public String calculateLoanScheduleOrSubmitVariableSchedule(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, - @QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { CommandWrapper commandRequest = null; if (is(commandParam, "calculateLoanSchedule")) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanScheduleApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanScheduleApiResourceSwagger.java index 42cea8684..13e6d66a7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanScheduleApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanScheduleApiResourceSwagger.java @@ -26,23 +26,23 @@ import java.util.List; * Created by Chirag Gupta on 12/30/17. */ final class LoanScheduleApiResourceSwagger { - private LoanScheduleApiResourceSwagger() { - } + + private LoanScheduleApiResourceSwagger() {} @ApiModel(value = "PostLoansLoanIdScheduleRequest") public final static class PostLoansLoanIdScheduleRequest { - private PostLoansLoanIdScheduleRequest() { - } + + private PostLoansLoanIdScheduleRequest() {} } @ApiModel(value = "PostLoansLoanIdScheduleResponse") public final static class PostLoansLoanIdScheduleResponse { - private PostLoansLoanIdScheduleResponse() { - } + + private PostLoansLoanIdScheduleResponse() {} final class PostLoanChanges { - private PostLoanChanges() { - } + + private PostLoanChanges() {} @ApiModelProperty(example = "[21, 22]") public List removedEntityIds; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanTransactionsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanTransactionsApiResource.java old mode 100755 new mode 100644 index 6a4c6fcbf..f910452a9 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanTransactionsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanTransactionsApiResource.java @@ -66,14 +66,13 @@ import org.springframework.stereotype.Component; @Path("/loans/{loanId}/transactions") @Component @Scope("singleton") -@Api(tags = {"Loan Transactions"}) +@Api(tags = { "Loan Transactions" }) @SwaggerDefinition(tags = { - @Tag(name = "Loan Transactions", description = "Capabilities include loan repayment's, interest waivers and the ability to 'adjust' an existing transaction. An 'adjustment' of a transaction is really a 'reversal' of existing transaction followed by creation of a new transaction with the provided details.") -}) + @Tag(name = "Loan Transactions", description = "Capabilities include loan repayment's, interest waivers and the ability to 'adjust' an existing transaction. An 'adjustment' of a transaction is really a 'reversal' of existing transaction followed by creation of a new transaction with the provided details.") }) public class LoanTransactionsApiResource { - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "type", "date", "currency", "amount", - "externalId")); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "type", "date", "currency", "amount", "externalId")); private final String resourceNameForPermissions = "LOAN"; @@ -90,7 +89,8 @@ public class LoanTransactionsApiResource { final ApiRequestParameterHelper apiRequestParameterHelper, final DefaultToApiJsonSerializer toApiJsonSerializer, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - PaymentTypeReadPlatformService paymentTypeReadPlatformService, LoanChargePaidByReadPlatformService loanChargePaidByReadPlatformService) { + PaymentTypeReadPlatformService paymentTypeReadPlatformService, + LoanChargePaidByReadPlatformService loanChargePaidByReadPlatformService) { this.context = context; this.loanReadPlatformService = loanReadPlatformService; this.apiRequestParameterHelper = apiRequestParameterHelper; @@ -108,11 +108,16 @@ public class LoanTransactionsApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Loan Transaction Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Request:\n" + "\n" + "loans/1/transactions/template?command=repayment") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanTransactionsApiResourceSwagger.GetLoansLoanIdTransactionsTemplateResponse.class)}) - public String retrieveTransactionTemplate(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, - @Context final UriInfo uriInfo, @QueryParam("dateFormat") @ApiParam(value = "dateFormat") final String dateFormat, - @QueryParam("transactionDate") @ApiParam(value = "transactionDate") final DateParam transactionDateParam, @QueryParam("locale") @ApiParam(value = "locale") final String locale) { + @ApiOperation(value = "Retrieve Loan Transaction Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Request:\n" + "\n" + + "loans/1/transactions/template?command=repayment") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanTransactionsApiResourceSwagger.GetLoansLoanIdTransactionsTemplateResponse.class) }) + public String retrieveTransactionTemplate(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo, + @QueryParam("dateFormat") @ApiParam(value = "dateFormat") final String dateFormat, + @QueryParam("transactionDate") @ApiParam(value = "transactionDate") final DateParam transactionDateParam, + @QueryParam("locale") @ApiParam(value = "locale") final String locale) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -165,10 +170,12 @@ public class LoanTransactionsApiResource { @Path("{transactionId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Transaction Details", httpMethod = "GET", notes = "Retrieves a Transaction Details\n\n" + "Example Request:\n" + "\n" + "loans/5/transactions/3") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanTransactionsApiResourceSwagger.GetLoansLoanIdTransactionsTransactionIdResponse.class)}) - public String retrieveTransaction(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Transaction Details", httpMethod = "GET", notes = "Retrieves a Transaction Details\n\n" + + "Example Request:\n" + "\n" + "loans/5/transactions/3") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanTransactionsApiResourceSwagger.GetLoansLoanIdTransactionsTransactionIdResponse.class) }) + public String retrieveTransaction(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -186,10 +193,14 @@ public class LoanTransactionsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Make a Repayment | Make a Refund of an Active Loan by Cash | Foreclosure of an Active Loan | Waive Interest | Write-off Loan | Make Recovery Payment | Undo Loan Write-off Transaction", httpMethod = "POST", notes = "Make Recovery Payment:\n\n" + "This API allows collecting recovery payments for written-off loans") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanTransactionsApiResourceSwagger.PostLoansLoanIdTransactionsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanTransactionsApiResourceSwagger.PostLoansLoanIdTransactionsResponse.class)}) - public String executeLoanTransaction(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiOperation(value = "Make a Repayment | Make a Refund of an Active Loan by Cash | Foreclosure of an Active Loan | Waive Interest | Write-off Loan | Make Recovery Payment | Undo Loan Write-off Transaction", httpMethod = "POST", notes = "Make Recovery Payment:\n\n" + + "This API allows collecting recovery payments for written-off loans") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanTransactionsApiResourceSwagger.PostLoansLoanIdTransactionsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanTransactionsApiResourceSwagger.PostLoansLoanIdTransactionsResponse.class) }) + public String executeLoanTransaction(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); @@ -233,10 +244,14 @@ public class LoanTransactionsApiResource { @Path("{transactionId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Adjust a Transaction", httpMethod = "POST", notes = "Note: there is no need to specify command={transactionType} parameter.\n\n" + "Mandatory Fields: transactionDate, transactionAmount") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanTransactionsApiResourceSwagger.PostLoansLoanIdTransactionsTransactionIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanTransactionsApiResourceSwagger.PostLoansLoanIdTransactionsTransactionIdResponse.class)}) - public String adjustLoanTransaction(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, + @ApiOperation(value = "Adjust a Transaction", httpMethod = "POST", notes = "Note: there is no need to specify command={transactionType} parameter.\n\n" + + "Mandatory Fields: transactionDate, transactionAmount") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanTransactionsApiResourceSwagger.PostLoansLoanIdTransactionsTransactionIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanTransactionsApiResourceSwagger.PostLoansLoanIdTransactionsTransactionIdResponse.class) }) + public String adjustLoanTransaction(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); @@ -247,4 +262,4 @@ public class LoanTransactionsApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanTransactionsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanTransactionsApiResourceSwagger.java index 950d5ff80..22cade254 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanTransactionsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoanTransactionsApiResourceSwagger.java @@ -26,17 +26,17 @@ import java.time.LocalDate; * Created by Chirag Gupta on 12/30/17. */ final class LoanTransactionsApiResourceSwagger { - private LoanTransactionsApiResourceSwagger() { - } + + private LoanTransactionsApiResourceSwagger() {} @ApiModel(value = "GetLoansLoanIdTransactionsTemplateResponse") public final static class GetLoansLoanIdTransactionsTemplateResponse { - private GetLoansLoanIdTransactionsTemplateResponse() { - } + + private GetLoansLoanIdTransactionsTemplateResponse() {} final class GetLoansTransactionType { - private GetLoansTransactionType() { - } + + private GetLoansTransactionType() {} @ApiModelProperty(example = "2") public Integer id; @@ -47,8 +47,8 @@ final class LoanTransactionsApiResourceSwagger { } final class GetLoansTotal { - private GetLoansTotal() { - } + + private GetLoansTotal() {} @ApiModelProperty(example = "XOF") public String currencyCode; @@ -80,12 +80,12 @@ final class LoanTransactionsApiResourceSwagger { @ApiModel(value = "GetLoansLoanIdTransactionsTransactionIdResponse") public final static class GetLoansLoanIdTransactionsTransactionIdResponse { - private GetLoansLoanIdTransactionsTransactionIdResponse() { - } + + private GetLoansLoanIdTransactionsTransactionIdResponse() {} final class GetLoansType { - private GetLoansType() { - } + + private GetLoansType() {} @ApiModelProperty(example = "2") public Integer id; @@ -112,8 +112,8 @@ final class LoanTransactionsApiResourceSwagger { } final class GetLoansCurrency { - private GetLoansCurrency() { - } + + private GetLoansCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -145,14 +145,14 @@ final class LoanTransactionsApiResourceSwagger { @ApiModel(value = "PostLoansLoanIdTransactionsRequest") public final static class PostLoansLoanIdTransactionsRequest { - private PostLoansLoanIdTransactionsRequest() { - } + + private PostLoansLoanIdTransactionsRequest() {} } @ApiModel(value = "PostLoansLoanIdTransactionsResponse") public final static class PostLoansLoanIdTransactionsResponse { - private PostLoansLoanIdTransactionsResponse() { - } + + private PostLoansLoanIdTransactionsResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -164,8 +164,8 @@ final class LoanTransactionsApiResourceSwagger { @ApiModel(value = "PostLoansLoanIdTransactionsTransactionIdRequest") public final static class PostLoansLoanIdTransactionsTransactionIdRequest { - private PostLoansLoanIdTransactionsTransactionIdRequest() { - } + + private PostLoansLoanIdTransactionsTransactionIdRequest() {} @ApiModelProperty(example = "en_GB") public String locale; @@ -181,8 +181,8 @@ final class LoanTransactionsApiResourceSwagger { @ApiModel(value = "PostLoansLoanIdTransactionsTransactionIdResponse") public final static class PostLoansLoanIdTransactionsTransactionIdResponse { - private PostLoansLoanIdTransactionsTransactionIdResponse() { - } + + private PostLoansLoanIdTransactionsTransactionIdResponse() {} @ApiModelProperty(example = "16") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoansApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoansApiResource.java index 28c115d82..1c81283e6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoansApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoansApiResource.java @@ -143,109 +143,70 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; - @Path("/loans") @Component @Scope("singleton") -@Api(tags = {"Loans"}) +@Api(tags = { "Loans" }) @SwaggerDefinition(tags = { - @Tag(name = "Loans", description = "The API concept of loans models the loan application process and the loan contract/monitoring process.\n" + - "\n" + - "Field Descriptions\n" + - "accountNo\n" + - "The account no. associated with this loan. Is auto generated if not provided at loan application creation time.\n" + - "externalId\n" + - "A place to put an external reference for this loan e.g. The ID another system uses.\n" + - "If provided, it must be unique.\n" + - "fundId\n" + - "Optional: For associating a loan with a given fund.\n" + - "loanOfficerId\n" + - "Optional: For associating a loan with a given staff member who is a loan officer.\n" + - "loanPurposeId\n" + - "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.\n" + - "principal\n" + - "The loan amount to be disbursed to through loan.\n" + - "loanTermFrequency\n" + - "The length of loan term\n" + - "Used like: loanTermFrequency loanTermFrequencyType\n" + - "e.g. 12 Months\n" + - "loanTermFrequencyType\n" + - "The loan term period to use. Used like: loanTermFrequency loanTermFrequencyType\n" + - "e.g. 12 Months Example Values: 0=Days, 1=Weeks, 2=Months, 3=Years\n" + - "numberOfRepayments\n" + - "Number of installments to repay.\n" + - "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + - "e.g. 10 (repayments) Every 12 Weeks\n" + - "repaymentEvery\n" + - "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + - "e.g. 10 (repayments) Every 12 Weeks\n" + - "repaymentFrequencyType\n" + - "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + - "e.g. 10 (repayments) Every 12 Weeks \n" + - "Example Values: 0=Days, 1=Weeks, 2=Months\n" + - "interestRatePerPeriod\n" + - "Interest Rate.\n" + - "Used like: interestRatePerPeriod % interestRateFrequencyType - interestType\n" + - "e.g. 12.0000% Per year - Declining Balance\n" + - "interestRateFrequencyType\n" + - "Used like: interestRatePerPeriod% interestRateFrequencyType - interestType\n" + - "e.g. 12.0000% Per year - Declining Balance \n" + - "Example Values: 2=Per month, 3=Per year\n" + - "graceOnPrincipalPayment\n" + - "Optional: Integer - represents the number of repayment periods that grace should apply to the principal component of a repayment period.\n" + - "graceOnInterestPayment\n" + - "Optional: Integer - represents the number of repayment periods that grace should apply to the interest component of a repayment period. Interest is still calculated but offset to later repayment periods.\n" + - "graceOnInterestCharged\n" + - "Optional: Integer - represents the number of repayment periods that should be interest-free.\n" + - "graceOnArrearsAgeing\n" + - "Optional: Integer - Used in Arrears calculation to only take into account loans that are more than graceOnArrearsAgeing days overdue.\n" + - "interestChargedFromDate\n" + - "Optional: Date - The date from with interest is to start being charged.\n" + - "expectedDisbursementDate\n" + - "The proposed disbursement date of the loan so a proposed repayment schedule can be provided.\n" + - "submittedOnDate\n" + - "The date the loan application was submitted by applicant.\n" + - "linkAccountId\n" + - "The Savings Account id for linking with loan account for payments.\n" + - "amortizationType\n" + - "Example Values: 0=Equal principle payments, 1=Equal installments\n" + - "interestType\n" + - "Used like: interestRatePerPeriod% interestRateFrequencyType - interestType\n" + - "e.g. 12.0000% Per year - Declining Balance \n" + - "Example Values: 0=Declining Balance, 1=Flat\n" + - "interestCalculationPeriodType\n" + - "Example Values: 0=Daily, 1=Same as repayment period\n" + - "allowPartialPeriodInterestCalcualtion\n" + - "This value will be supported along with interestCalculationPeriodType as Same as repayment period to calculate interest for partial periods. Example: Interest charged from is 5th of April , Principal is 10000 and interest is 1% per month then the interest will be (10000 * 1%)* (25/30) , it calculates for the month first then calculates exact periods between start date and end date(can be a decimal)\n" + - "inArrearsTolerance\n" + - "The amount that can be 'waived' at end of all loan payments because it is too small to worry about.\n" + - "This is also the tolerance amount assessed when determining if a loan is in arrears.\n" + - "transactionProcessingStrategyId\n" + - "An enumeration that indicates the type of transaction processing strategy to be used. This relates to functionality that is also known as Payment Application Logic.\n" + - "A number of out of the box approaches exist, some are custom to specific MFIs, some are more general and indicate the order in which payments are processed.\n" + - "\n" + - "Refer to the Payment Application Logic / Transaction Processing Strategy section in the appendix for more detailed overview of each available payment application logic provided out of the box.\n" + - "\n" + - "List of current approaches:\n" + - "1 = Mifos style (Similar to Old Mifos)\n" + - "2 = Heavensfamily (Custom MFI approach)\n" + - "3 = Creocore (Custom MFI approach)\n" + - "4 = RBI (India)\n" + - "5 = Principal Interest Penalties Fees Order\n" + - "6 = Interest Principal Penalties Fees Order\n" + - "7 = Early Payment Strategy\n" + - "loanType\n" + - "To represent different type of loans.\n" + - "At present there are three type of loans are supported. \n" + - "Available loan types:\n" + - "individual: Loan given to individual member\n" + - "group: Loan given to group as a whole\n" + - "jlg: Joint liability group loan given to members in a group on individual basis. JLG loan can be given to one or more members in a group.\n" + - "recalculationRestFrequencyDate\n" + - "Specifies rest frequency start date for interest recalculation. This date must be before or equal to disbursement date\n" + - "recalculationCompoundingFrequencyDate\n" + - "Specifies compounding frequency start date for interest recalculation. This date must be equal to disbursement date") -}) + @Tag(name = "Loans", description = "The API concept of loans models the loan application process and the loan contract/monitoring process.\n" + + "\n" + "Field Descriptions\n" + "accountNo\n" + + "The account no. associated with this loan. Is auto generated if not provided at loan application creation time.\n" + + "externalId\n" + "A place to put an external reference for this loan e.g. The ID another system uses.\n" + + "If provided, it must be unique.\n" + "fundId\n" + "Optional: For associating a loan with a given fund.\n" + + "loanOfficerId\n" + "Optional: For associating a loan with a given staff member who is a loan officer.\n" + + "loanPurposeId\n" + + "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.\n" + + "principal\n" + "The loan amount to be disbursed to through loan.\n" + "loanTermFrequency\n" + "The length of loan term\n" + + "Used like: loanTermFrequency loanTermFrequencyType\n" + "e.g. 12 Months\n" + "loanTermFrequencyType\n" + + "The loan term period to use. Used like: loanTermFrequency loanTermFrequencyType\n" + + "e.g. 12 Months Example Values: 0=Days, 1=Weeks, 2=Months, 3=Years\n" + "numberOfRepayments\n" + + "Number of installments to repay.\n" + "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + + "e.g. 10 (repayments) Every 12 Weeks\n" + "repaymentEvery\n" + + "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + "e.g. 10 (repayments) Every 12 Weeks\n" + + "repaymentFrequencyType\n" + "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + + "e.g. 10 (repayments) Every 12 Weeks \n" + "Example Values: 0=Days, 1=Weeks, 2=Months\n" + "interestRatePerPeriod\n" + + "Interest Rate.\n" + "Used like: interestRatePerPeriod % interestRateFrequencyType - interestType\n" + + "e.g. 12.0000% Per year - Declining Balance\n" + "interestRateFrequencyType\n" + + "Used like: interestRatePerPeriod% interestRateFrequencyType - interestType\n" + + "e.g. 12.0000% Per year - Declining Balance \n" + "Example Values: 2=Per month, 3=Per year\n" + + "graceOnPrincipalPayment\n" + + "Optional: Integer - represents the number of repayment periods that grace should apply to the principal component of a repayment period.\n" + + "graceOnInterestPayment\n" + + "Optional: Integer - represents the number of repayment periods that grace should apply to the interest component of a repayment period. Interest is still calculated but offset to later repayment periods.\n" + + "graceOnInterestCharged\n" + + "Optional: Integer - represents the number of repayment periods that should be interest-free.\n" + + "graceOnArrearsAgeing\n" + + "Optional: Integer - Used in Arrears calculation to only take into account loans that are more than graceOnArrearsAgeing days overdue.\n" + + "interestChargedFromDate\n" + "Optional: Date - The date from with interest is to start being charged.\n" + + "expectedDisbursementDate\n" + + "The proposed disbursement date of the loan so a proposed repayment schedule can be provided.\n" + "submittedOnDate\n" + + "The date the loan application was submitted by applicant.\n" + "linkAccountId\n" + + "The Savings Account id for linking with loan account for payments.\n" + "amortizationType\n" + + "Example Values: 0=Equal principle payments, 1=Equal installments\n" + "interestType\n" + + "Used like: interestRatePerPeriod% interestRateFrequencyType - interestType\n" + + "e.g. 12.0000% Per year - Declining Balance \n" + "Example Values: 0=Declining Balance, 1=Flat\n" + + "interestCalculationPeriodType\n" + "Example Values: 0=Daily, 1=Same as repayment period\n" + + "allowPartialPeriodInterestCalcualtion\n" + + "This value will be supported along with interestCalculationPeriodType as Same as repayment period to calculate interest for partial periods. Example: Interest charged from is 5th of April , Principal is 10000 and interest is 1% per month then the interest will be (10000 * 1%)* (25/30) , it calculates for the month first then calculates exact periods between start date and end date(can be a decimal)\n" + + "inArrearsTolerance\n" + + "The amount that can be 'waived' at end of all loan payments because it is too small to worry about.\n" + + "This is also the tolerance amount assessed when determining if a loan is in arrears.\n" + + "transactionProcessingStrategyId\n" + + "An enumeration that indicates the type of transaction processing strategy to be used. This relates to functionality that is also known as Payment Application Logic.\n" + + "A number of out of the box approaches exist, some are custom to specific MFIs, some are more general and indicate the order in which payments are processed.\n" + + "\n" + + "Refer to the Payment Application Logic / Transaction Processing Strategy section in the appendix for more detailed overview of each available payment application logic provided out of the box.\n" + + "\n" + "List of current approaches:\n" + "1 = Mifos style (Similar to Old Mifos)\n" + + "2 = Heavensfamily (Custom MFI approach)\n" + "3 = Creocore (Custom MFI approach)\n" + "4 = RBI (India)\n" + + "5 = Principal Interest Penalties Fees Order\n" + "6 = Interest Principal Penalties Fees Order\n" + + "7 = Early Payment Strategy\n" + "loanType\n" + "To represent different type of loans.\n" + + "At present there are three type of loans are supported. \n" + "Available loan types:\n" + + "individual: Loan given to individual member\n" + "group: Loan given to group as a whole\n" + + "jlg: Joint liability group loan given to members in a group on individual basis. JLG loan can be given to one or more members in a group.\n" + + "recalculationRestFrequencyDate\n" + + "Specifies rest frequency start date for interest recalculation. This date must be before or equal to disbursement date\n" + + "recalculationCompoundingFrequencyDate\n" + + "Specifies compounding frequency start date for interest recalculation. This date must be equal to disbursement date") }) public class LoansApiResource { private final Set LOAN_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "accountNo", "status", "externalId", "clientId", @@ -254,21 +215,22 @@ public class LoansApiResource { "inArrearsTolerance", "termFrequency", "termPeriodFrequencyType", "numberOfRepayments", "repaymentEvery", "interestRatePerPeriod", "annualInterestRate", "repaymentFrequencyType", "transactionProcessingStrategyId", "transactionProcessingStrategyName", "interestRateFrequencyType", "amortizationType", "interestType", - "interestCalculationPeriodType", LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, "expectedFirstRepaymentOnDate", - "graceOnPrincipalPayment", "recurringMoratoriumOnPrincipalPeriods", "graceOnInterestPayment", "graceOnInterestCharged", "interestChargedFromDate", "timeline", - "totalFeeChargesAtDisbursement", "summary", "repaymentSchedule", "transactions", "charges", "collateral", "guarantors", - "meeting", "productOptions", "amortizationTypeOptions", "interestTypeOptions", "interestCalculationPeriodTypeOptions", - "repaymentFrequencyTypeOptions", "repaymentFrequencyNthDayTypeOptions", "repaymentFrequencyDaysOfWeekTypeOptions", - "termFrequencyTypeOptions", "interestRateFrequencyTypeOptions", "fundOptions", "repaymentStrategyOptions", "chargeOptions", - "loanOfficerOptions", "loanPurposeOptions", "loanCollateralOptions", "chargeTemplate", "calendarOptions", - "syncDisbursementWithMeeting", "loanCounter", "loanProductCounter", "notes", "accountLinkingOptions", "linkedAccount", - "interestRateDifferential", "isFloatingInterestRate", "interestRatesPeriods", LoanApiConstants.canUseForTopup, - LoanApiConstants.isTopup, LoanApiConstants.loanIdToClose, LoanApiConstants.topupAmount, LoanApiConstants.clientActiveLoanOptions, + "interestCalculationPeriodType", LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, + "expectedFirstRepaymentOnDate", "graceOnPrincipalPayment", "recurringMoratoriumOnPrincipalPeriods", "graceOnInterestPayment", + "graceOnInterestCharged", "interestChargedFromDate", "timeline", "totalFeeChargesAtDisbursement", "summary", + "repaymentSchedule", "transactions", "charges", "collateral", "guarantors", "meeting", "productOptions", + "amortizationTypeOptions", "interestTypeOptions", "interestCalculationPeriodTypeOptions", "repaymentFrequencyTypeOptions", + "repaymentFrequencyNthDayTypeOptions", "repaymentFrequencyDaysOfWeekTypeOptions", "termFrequencyTypeOptions", + "interestRateFrequencyTypeOptions", "fundOptions", "repaymentStrategyOptions", "chargeOptions", "loanOfficerOptions", + "loanPurposeOptions", "loanCollateralOptions", "chargeTemplate", "calendarOptions", "syncDisbursementWithMeeting", + "loanCounter", "loanProductCounter", "notes", "accountLinkingOptions", "linkedAccount", "interestRateDifferential", + "isFloatingInterestRate", "interestRatesPeriods", LoanApiConstants.canUseForTopup, LoanApiConstants.isTopup, + LoanApiConstants.loanIdToClose, LoanApiConstants.topupAmount, LoanApiConstants.clientActiveLoanOptions, LoanApiConstants.datatables, LoanProductConstants.RATES_PARAM_NAME)); private final Set LOAN_APPROVAL_DATA_PARAMETERS = new HashSet<>(Arrays.asList("approvalDate", "approvalAmount")); - final Set GLIM_ACCOUNTS_DATA_PARAMETERS = new HashSet<>(Arrays.asList("glimId","groupId", "clientId","parentLoanAccountNo","parentPrincipalAmount", - "childLoanAccountNo", "childPrincipalAmount","clientName")); + final Set GLIM_ACCOUNTS_DATA_PARAMETERS = new HashSet<>(Arrays.asList("glimId", "groupId", "clientId", "parentLoanAccountNo", + "parentPrincipalAmount", "childLoanAccountNo", "childPrincipalAmount", "clientName")); private final String resourceNameForPermissions = "LOAN"; private final PlatformSecurityContext context; @@ -325,7 +287,8 @@ public class LoansApiResource { final EntityDatatableChecksReadService entityDatatableChecksReadService, final BulkImportWorkbookService bulkImportWorkbookService, final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService, final RateReadService rateReadService, - final ConfigurationDomainService configurationDomainService, final DefaultToApiJsonSerializer glimTemplateToApiJsonSerializer, + final ConfigurationDomainService configurationDomainService, + final DefaultToApiJsonSerializer glimTemplateToApiJsonSerializer, final GLIMAccountInfoReadPlatformService glimAccountInfoReadPlatformService) { this.context = context; this.loanReadPlatformService = loanReadPlatformService; @@ -353,11 +316,11 @@ public class LoansApiResource { this.accountDetailsReadPlatformService = accountDetailsReadPlatformService; this.entityDatatableChecksReadService = entityDatatableChecksReadService; this.rateReadService = rateReadService; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; this.configurationDomainService = configurationDomainService; - this.glimTemplateToApiJsonSerializer=glimTemplateToApiJsonSerializer; - this.glimAccountInfoReadPlatformService=glimAccountInfoReadPlatformService; + this.glimTemplateToApiJsonSerializer = glimTemplateToApiJsonSerializer; + this.glimAccountInfoReadPlatformService = glimAccountInfoReadPlatformService; } /* @@ -371,8 +334,8 @@ public class LoansApiResource { @Path("{loanId}/template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveApprovalTemplate(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @QueryParam("templateType") @ApiParam(value = "templateType") final String templateType, - @Context final UriInfo uriInfo) { + public String retrieveApprovalTemplate(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @QueryParam("templateType") @ApiParam(value = "templateType") final String templateType, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -394,12 +357,18 @@ public class LoansApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Loan Details Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Requests:\n" + "\n" + "loans/template?templateType=individual&clientId=1\n" + "\n" + "\n" + "loans/template?templateType=individual&clientId=1&productId=1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.GetLoansTemplateResponse.class)}) - public String template(@QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, @QueryParam("groupId") @ApiParam(value = "groupId") final Long groupId, - @QueryParam("productId")@ApiParam(value = "productId") final Long productId, @QueryParam("templateType") @ApiParam(value = "templateType") final String templateType, + @ApiOperation(value = "Retrieve Loan Details Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Requests:\n" + "\n" + + "loans/template?templateType=individual&clientId=1\n" + "\n" + "\n" + + "loans/template?templateType=individual&clientId=1&productId=1") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.GetLoansTemplateResponse.class) }) + public String template(@QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @QueryParam("groupId") @ApiParam(value = "groupId") final Long groupId, + @QueryParam("productId") @ApiParam(value = "productId") final Long productId, + @QueryParam("templateType") @ApiParam(value = "templateType") final String templateType, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, - @DefaultValue("false") @QueryParam("activeOnly") @ApiParam(value = "activeOnly") final boolean onlyActive, @Context final UriInfo uriInfo) { + @DefaultValue("false") @QueryParam("activeOnly") @ApiParam(value = "activeOnly") final boolean onlyActive, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -429,14 +398,14 @@ public class LoansApiResource { // for JLG loan both client and group details are required if (templateType.equals("individual") || templateType.equals("jlg")) { - if(clientId == null) { + if (clientId == null) { newLoanAccount = newLoanAccount == null ? LoanAccountData.emptyTemplate() : newLoanAccount; } else { final LoanAccountData loanAccountClientDetails = this.loanReadPlatformService.retrieveClientDetailsTemplate(clientId); officeId = loanAccountClientDetails.officeId(); - newLoanAccount = newLoanAccount == null ? loanAccountClientDetails : LoanAccountData.populateClientDefaults(newLoanAccount, - loanAccountClientDetails); + newLoanAccount = newLoanAccount == null ? loanAccountClientDetails + : LoanAccountData.populateClientDefaults(newLoanAccount, loanAccountClientDetails); } // if it's JLG loan add group details @@ -451,8 +420,8 @@ public class LoansApiResource { final LoanAccountData loanAccountGroupData = this.loanReadPlatformService.retrieveGroupDetailsTemplate(groupId); officeId = loanAccountGroupData.groupOfficeId(); calendarOptions = this.loanReadPlatformService.retrieveCalendars(groupId); - newLoanAccount = newLoanAccount == null ? loanAccountGroupData : LoanAccountData.populateGroupDefaults(newLoanAccount, - loanAccountGroupData); + newLoanAccount = newLoanAccount == null ? loanAccountGroupData + : LoanAccountData.populateGroupDefaults(newLoanAccount, loanAccountGroupData); accountLinkingOptions = getaccountLinkingOptions(newLoanAccount, clientId, groupId); } else if (templateType.equals("jlgbulk")) { @@ -460,13 +429,13 @@ public class LoansApiResource { final LoanAccountData loanAccountGroupData = this.loanReadPlatformService.retrieveGroupAndMembersDetailsTemplate(groupId); officeId = loanAccountGroupData.groupOfficeId(); calendarOptions = this.loanReadPlatformService.retrieveCalendars(groupId); - newLoanAccount = newLoanAccount == null ? loanAccountGroupData : LoanAccountData.populateGroupDefaults(newLoanAccount, - loanAccountGroupData); + newLoanAccount = newLoanAccount == null ? loanAccountGroupData + : LoanAccountData.populateGroupDefaults(newLoanAccount, loanAccountGroupData); if (productId != null) { Map memberLoanCycle = new HashMap<>(); Collection members = loanAccountGroupData.groupData().clientMembers(); accountLinkingOptions = new ArrayList<>(); - if(members != null){ + if (members != null) { for (ClientData clientData : members) { Integer loanCounter = this.loanReadPlatformService.retriveLoanCounter(clientData.id(), productId); memberLoanCycle.put(clientData.id(), loanCounter); @@ -509,8 +478,8 @@ public class LoansApiResource { currencyCode = currencyData.code(); } final long[] accountStatus = { SavingsAccountStatusType.ACTIVE.getValue() }; - final PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO(PortfolioAccountType.SAVINGS.getValue(), clientId, currencyCode, - accountStatus, DepositAccountType.SAVINGS_DEPOSIT.getValue()); + final PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO(PortfolioAccountType.SAVINGS.getValue(), clientId, + currencyCode, accountStatus, DepositAccountType.SAVINGS_DEPOSIT.getValue()); if (groupId != null) { portfolioAccountDTO.setGroupId(groupId); } @@ -521,19 +490,22 @@ public class LoansApiResource { @Path("{loanId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Loan", httpMethod = "GET", notes = "Note: template=true parameter doesn't apply to this resource." + "Example Requests:\n" + "\n" + "loans/1\n" + "\n" + "\n" + "loans/1?fields=id,principal,annualInterestRate\n" + "\n" + "\n" + "loans/1?associations=all\n" + "\n" + "loans/1?associations=all&exclude=guarantors\n" + "\n" + "\n" + "loans/1?fields=id,principal,annualInterestRate&associations=repaymentSchedule,transactions") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.GetLoansLoanIdResponse.class)}) + @ApiOperation(value = "Retrieve a Loan", httpMethod = "GET", notes = "Note: template=true parameter doesn't apply to this resource." + + "Example Requests:\n" + "\n" + "loans/1\n" + "\n" + "\n" + "loans/1?fields=id,principal,annualInterestRate\n" + "\n" + "\n" + + "loans/1?associations=all\n" + "\n" + "loans/1?associations=all&exclude=guarantors\n" + "\n" + "\n" + + "loans/1?fields=id,principal,annualInterestRate&associations=repaymentSchedule,transactions") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.GetLoansLoanIdResponse.class) }) public String retrieveLoan(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, @Context final UriInfo uriInfo) { - long start = System.currentTimeMillis() ; + long start = System.currentTimeMillis(); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); LoanAccountData loanBasicDetails = this.loanReadPlatformService.retrieveOne(loanId); if (loanBasicDetails.isInterestRecalculationEnabled()) { - Collection interestRecalculationCalendarDatas = this.calendarReadPlatformService - .retrieveCalendarsByEntity(loanBasicDetails.getInterestRecalculationDetailId(), - CalendarEntityType.LOAN_RECALCULATION_REST_DETAIL.getValue(), null); + Collection interestRecalculationCalendarDatas = this.calendarReadPlatformService.retrieveCalendarsByEntity( + loanBasicDetails.getInterestRecalculationDetailId(), CalendarEntityType.LOAN_RECALCULATION_REST_DETAIL.getValue(), + null); CalendarData calendarData = null; if (!CollectionUtils.isEmpty(interestRecalculationCalendarDatas)) { calendarData = interestRecalculationCalendarDatas.iterator().next(); @@ -550,18 +522,18 @@ public class LoansApiResource { compoundingCalendarData); } if (loanBasicDetails.isMonthlyRepaymentFrequencyType()) { - Collection loanCalendarDatas = this.calendarReadPlatformService - .retrieveCalendarsByEntity(loanId, - CalendarEntityType.LOANS.getValue(), null); + Collection loanCalendarDatas = this.calendarReadPlatformService.retrieveCalendarsByEntity(loanId, + CalendarEntityType.LOANS.getValue(), null); CalendarData calendarData = null; if (!CollectionUtils.isEmpty(loanCalendarDatas)) { calendarData = loanCalendarDatas.iterator().next(); } - if(calendarData != null) { + if (calendarData != null) { loanBasicDetails = LoanAccountData.withLoanCalendarData(loanBasicDetails, calendarData); } } - Collection interestRatesPeriods = this.loanReadPlatformService.retrieveLoanInterestRatePeriodData(loanBasicDetails); + Collection interestRatesPeriods = this.loanReadPlatformService + .retrieveLoanInterestRatePeriodData(loanBasicDetails); Collection loanRepayments = null; LoanScheduleData repaymentSchedule = null; Collection charges = null; @@ -625,8 +597,8 @@ public class LoansApiResource { if (associationParameters.contains("originalSchedule") && loanBasicDetails.isInterestRecalculationEnabled() && loanBasicDetails.isActive()) { mandatoryResponseParameters.add("originalSchedule"); - LoanScheduleData loanScheduleData = this.loanScheduleHistoryReadPlatformService.retrieveRepaymentArchiveSchedule( - loanId, repaymentScheduleRelatedData, disbursementData); + LoanScheduleData loanScheduleData = this.loanScheduleHistoryReadPlatformService.retrieveRepaymentArchiveSchedule(loanId, + repaymentScheduleRelatedData, disbursementData); loanBasicDetails = LoanAccountData.withOriginalSchedule(loanBasicDetails, loanScheduleData); } } @@ -714,8 +686,8 @@ public class LoansApiResource { chargeOptions = this.chargeReadPlatformService.retrieveLoanAccountApplicableCharges(loanId, new ChargeTimeType[] { ChargeTimeType.OVERDUE_INSTALLMENT }); } else { - chargeOptions = this.chargeReadPlatformService.retrieveLoanAccountApplicableCharges(loanId, new ChargeTimeType[] { - ChargeTimeType.OVERDUE_INSTALLMENT, ChargeTimeType.TRANCHE_DISBURSEMENT }); + chargeOptions = this.chargeReadPlatformService.retrieveLoanAccountApplicableCharges(loanId, + new ChargeTimeType[] { ChargeTimeType.OVERDUE_INSTALLMENT, ChargeTimeType.TRANCHE_DISBURSEMENT }); } chargeTemplate = this.loanChargeReadPlatformService.retrieveLoanChargeTemplate(); @@ -742,11 +714,11 @@ public class LoansApiResource { calendarOptions = this.loanReadPlatformService.retrieveCalendars(loanBasicDetails.groupId()); } - if(loanBasicDetails.product().canUseForTopup() && loanBasicDetails.clientId() != null){ - clientActiveLoanOptions = this.accountDetailsReadPlatformService.retrieveClientActiveLoanAccountSummary(loanBasicDetails.clientId()); + if (loanBasicDetails.product().canUseForTopup() && loanBasicDetails.clientId() != null) { + clientActiveLoanOptions = this.accountDetailsReadPlatformService + .retrieveClientActiveLoanAccountSummary(loanBasicDetails.clientId()); } - } Collection overdueCharges = this.chargeReadPlatformService.retrieveLoanProductCharges(loanBasicDetails.loanProductId(), @@ -754,38 +726,42 @@ public class LoansApiResource { paidInAdvanceTemplate = this.loanReadPlatformService.retrieveTotalPaidInAdvance(loanId); - //Get rates from Loan + // Get rates from Loan boolean isRatesEnabled = this.configurationDomainService.isSubRatesEnabled(); List rates = null; - if (isRatesEnabled){ - rates = this.rateReadService.retrieveLoanRates(loanId); + if (isRatesEnabled) { + rates = this.rateReadService.retrieveLoanRates(loanId); } final LoanAccountData loanAccount = LoanAccountData.associationsAndTemplate(loanBasicDetails, repaymentSchedule, loanRepayments, charges, collateral, guarantors, meeting, productOptions, loanTermFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, repaymentFrequencyDayOfWeekTypeOptions, repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, - fundOptions, chargeOptions, chargeTemplate, allowedLoanOfficers, loanPurposeOptions, loanCollateralOptions, - calendarOptions, notes, accountLinkingOptions, linkedAccount, disbursementData, emiAmountVariations, - overdueCharges, paidInAdvanceTemplate, interestRatesPeriods, clientActiveLoanOptions, rates, isRatesEnabled); + fundOptions, chargeOptions, chargeTemplate, allowedLoanOfficers, loanPurposeOptions, loanCollateralOptions, calendarOptions, + notes, accountLinkingOptions, linkedAccount, disbursementData, emiAmountVariations, overdueCharges, paidInAdvanceTemplate, + interestRatesPeriods, clientActiveLoanOptions, rates, isRatesEnabled); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters(), mandatoryResponseParameters); String toReturn = this.toApiJsonSerializer.serialize(settings, loanAccount, this.LOAN_DATA_PARAMETERS); - return toReturn ; + return toReturn; } @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Loans", httpMethod = "GET", notes = "The list capability of loans can support pagination and sorting.\n" + "Example Requests:\n" + "\n" + "loans\n" + "\n" + "loans?fields=accountNo\n" + "\n" + "loans?offset=10&limit=50\n" + "\n" + "loans?orderBy=accountNo&sortOrder=DESC") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.GetLoansResponse.class)}) + @ApiOperation(value = "List Loans", httpMethod = "GET", notes = "The list capability of loans can support pagination and sorting.\n" + + "Example Requests:\n" + "\n" + "loans\n" + "\n" + "loans?fields=accountNo\n" + "\n" + "loans?offset=10&limit=50\n" + "\n" + + "loans?orderBy=accountNo&sortOrder=DESC") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.GetLoansResponse.class) }) public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, // @QueryParam("underHierarchy") final String hierarchy, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder")final String sortOrder, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder, @QueryParam("accountNo") @ApiParam(value = "accountNo") final String accountNo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -802,11 +778,19 @@ public class LoansApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Calculate loan repayment schedule | Submit a new Loan Application", httpMethod = "POST", notes = "It calculates the loan repayment Schedule\n" + "Submits a new loan application\n" + "Mandatory Fields: clientId, productId, principal, loanTermFrequency, loanTermFrequencyType, loanType, numberOfRepayments, repaymentEvery, repaymentFrequencyType, interestRatePerPeriod, amortizationType, interestType, interestCalculationPeriodType, transactionProcessingStrategyId, expectedDisbursementDate, submittedOnDate, loanType\n" + "Optional Fields: graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, linkAccountId, allowPartialPeriodInterestCalcualtion, fixedEmiAmount, maxOutstandingLoanBalance, disbursementData, graceOnArrearsAgeing, createStandingInstructionAtDisbursement (requires linkedAccountId if set to true)\n" + "Additional Mandatory Fields if interest recalculation is enabled for product and Rest frequency not same as repayment period: recalculationRestFrequencyDate\n" + "Additional Mandatory Fields if interest recalculation with interest/fee compounding is enabled for product and compounding frequency not same as repayment period: recalculationCompoundingFrequencyDate\n" + "Additional Mandatory Field if Entity-Datatable Check is enabled for the entity of type loan: datatables") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoansApiResourceSwagger.PostLoansRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.PostLoansResponse.class)}) - public String calculateLoanScheduleOrSubmitLoanApplication(@QueryParam("command") @ApiParam(value = "command") final String commandParam, - @Context final UriInfo uriInfo, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Calculate loan repayment schedule | Submit a new Loan Application", httpMethod = "POST", notes = "It calculates the loan repayment Schedule\n" + + "Submits a new loan application\n" + + "Mandatory Fields: clientId, productId, principal, loanTermFrequency, loanTermFrequencyType, loanType, numberOfRepayments, repaymentEvery, repaymentFrequencyType, interestRatePerPeriod, amortizationType, interestType, interestCalculationPeriodType, transactionProcessingStrategyId, expectedDisbursementDate, submittedOnDate, loanType\n" + + "Optional Fields: graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, linkAccountId, allowPartialPeriodInterestCalcualtion, fixedEmiAmount, maxOutstandingLoanBalance, disbursementData, graceOnArrearsAgeing, createStandingInstructionAtDisbursement (requires linkedAccountId if set to true)\n" + + "Additional Mandatory Fields if interest recalculation is enabled for product and Rest frequency not same as repayment period: recalculationRestFrequencyDate\n" + + "Additional Mandatory Fields if interest recalculation with interest/fee compounding is enabled for product and compounding frequency not same as repayment period: recalculationCompoundingFrequencyDate\n" + + "Additional Mandatory Field if Entity-Datatable Check is enabled for the entity of type loan: datatables") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoansApiResourceSwagger.PostLoansRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.PostLoansResponse.class) }) + public String calculateLoanScheduleOrSubmitLoanApplication( + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { if (is(commandParam, "calculateLoanSchedule")) { @@ -831,9 +815,11 @@ public class LoansApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Modify a loan application", httpMethod = "PUT", notes = "Loan application can only be modified when in 'Submitted and pending approval' state. Once the application is approved, the details cannot be changed using this method.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoansApiResourceSwagger.PutLoansLoanIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.PutLoansLoanIdResponse.class)}) - public String modifyLoanApplication(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoansApiResourceSwagger.PutLoansLoanIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.PutLoansLoanIdResponse.class) }) + public String modifyLoanApplication(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateLoanApplication(loanId).withJson(apiRequestBodyAsJson) .build(); @@ -848,7 +834,7 @@ public class LoansApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Loan Application", httpMethod = "DELETE", notes = "Note: Only loans in \"Submitted and awaiting approval\" status can be deleted.") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.DeleteLoansLoanIdResponse.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.DeleteLoansLoanIdResponse.class) }) public String deleteLoanApplication(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteLoanApplication(loanId).build(); @@ -862,11 +848,24 @@ public class LoansApiResource { @Path("{loanId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Approve Loan Application | Recover Loan Guarantee | Undo Loan Application Approval | Assign a Loan Officer | Unassign a Loan Officer | Reject Loan Application | Applicant Withdraws from Loan Application | Disburse Loan Disburse Loan To Savings Account | Undo Loan Disbursal", httpMethod = "POST", notes = "Approve Loan Application:\n" + "Mandatory Fields: approvedOnDate\n" + "Optional Fields: approvedLoanAmount and expectedDisbursementDate\n" + "Approves the loan application\n\n" + "Recover Loan Guarantee:\n" + "Recovers the loan guarantee\n\n" + "Undo Loan Application Approval:\n" + "Undoes the Loan Application Approval\n\n" + "Assign a Loan Officer:\n" + "Allows you to assign Loan Officer for existing Loan.\n\n" + "Unassign a Loan Officer:\n" + "Allows you to unassign the Loan Officer.\n\n" + "Reject Loan Application:\n" + "Mandatory Fields: rejectedOnDate\n" + "Allows you to reject the loan application\n\n" + "Applicant Withdraws from Loan Application:\n" + "Mandatory Fields: withdrawnOnDate\n" + "Allows the applicant to withdraw the loan application\n\n" + "Disburse Loan:\n" + "Mandatory Fields: actualDisbursementDate\n" + "Optional Fields: transactionAmount and fixedEmiAmount\n" + "Disburses the Loan\n\n" + "Disburse Loan To Savings Account:\n" + "Mandatory Fields: actualDisbursementDate\n" + "Optional Fields: transactionAmount and fixedEmiAmount\n" + "Disburses the loan to Saving Account\n\n" + "Undo Loan Disbursal:\n" + "Undoes the Loan Disbursal\n" + "Showing request and response for Assign a Loan Officer") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoansApiResourceSwagger.PostLoansLoanIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.PostLoansLoanIdResponse.class)}) - public String stateTransitions(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Approve Loan Application | Recover Loan Guarantee | Undo Loan Application Approval | Assign a Loan Officer | Unassign a Loan Officer | Reject Loan Application | Applicant Withdraws from Loan Application | Disburse Loan Disburse Loan To Savings Account | Undo Loan Disbursal", httpMethod = "POST", notes = "Approve Loan Application:\n" + + "Mandatory Fields: approvedOnDate\n" + "Optional Fields: approvedLoanAmount and expectedDisbursementDate\n" + + "Approves the loan application\n\n" + "Recover Loan Guarantee:\n" + "Recovers the loan guarantee\n\n" + + "Undo Loan Application Approval:\n" + "Undoes the Loan Application Approval\n\n" + "Assign a Loan Officer:\n" + + "Allows you to assign Loan Officer for existing Loan.\n\n" + "Unassign a Loan Officer:\n" + + "Allows you to unassign the Loan Officer.\n\n" + "Reject Loan Application:\n" + "Mandatory Fields: rejectedOnDate\n" + + "Allows you to reject the loan application\n\n" + "Applicant Withdraws from Loan Application:\n" + + "Mandatory Fields: withdrawnOnDate\n" + "Allows the applicant to withdraw the loan application\n\n" + "Disburse Loan:\n" + + "Mandatory Fields: actualDisbursementDate\n" + "Optional Fields: transactionAmount and fixedEmiAmount\n" + + "Disburses the Loan\n\n" + "Disburse Loan To Savings Account:\n" + "Mandatory Fields: actualDisbursementDate\n" + + "Optional Fields: transactionAmount and fixedEmiAmount\n" + "Disburses the loan to Saving Account\n\n" + + "Undo Loan Disbursal:\n" + "Undoes the Loan Disbursal\n" + "Showing request and response for Assign a Loan Officer") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoansApiResourceSwagger.PostLoansLoanIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.PostLoansLoanIdResponse.class) }) + public String stateTransitions(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); @@ -895,7 +894,7 @@ public class LoansApiResource { } else if (is(commandParam, "undodisbursal")) { final CommandWrapper commandRequest = builder.undoLoanApplicationDisbursal(loanId).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - }else if (is(commandParam, "undolastdisbursal")) { + } else if (is(commandParam, "undolastdisbursal")) { final CommandWrapper commandRequest = builder.undoLastDisbursalLoanApplication(loanId).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); } @@ -923,32 +922,39 @@ public class LoansApiResource { @GET @Path("downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getLoansTemplate(@QueryParam("officeId") final Long officeId, - @QueryParam("staffId") final Long staffId,@QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.LOANS.toString(), officeId, staffId,dateFormat); + public Response getLoansTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("staffId") final Long staffId, + @QueryParam("dateFormat") final String dateFormat) { + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.LOANS.toString(), officeId, staffId, dateFormat); } @GET @Path("glimAccount/{glimId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String getGlimRepaymentTemplate(@PathParam("glimId") final Long glimId,@Context final UriInfo uriInfo) - { - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - Collection glimRepaymentTemplate=this.glimAccountInfoReadPlatformService.findglimRepaymentTemplate(glimId); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.glimTemplateToApiJsonSerializer.serialize(settings, glimRepaymentTemplate, this.GLIM_ACCOUNTS_DATA_PARAMETERS); + public String getGlimRepaymentTemplate(@PathParam("glimId") final Long glimId, @Context final UriInfo uriInfo) { + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + Collection glimRepaymentTemplate = this.glimAccountInfoReadPlatformService.findglimRepaymentTemplate(glimId); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.glimTemplateToApiJsonSerializer.serialize(settings, glimRepaymentTemplate, this.GLIM_ACCOUNTS_DATA_PARAMETERS); } @POST @Path("glimAccount/{glimId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Approve GLIM Application | Undo GLIM Application Approval | Reject GLIM Application | Disburse Loan Disburse Loan To Savings Account | Undo Loan Disbursal", httpMethod = "POST", notes = "Approve GLIM Application:\n" + "Mandatory Fields: approvedOnDate\n" + "Optional Fields: approvedLoanAmount and expectedDisbursementDate\n" + "Approves the GLIM application\n\n" + "Undo GLIM Application Approval:\n" + "Undoes the GLIM Application Approval\n\n" + "Reject GLIM Application:\n" + "Mandatory Fields: rejectedOnDate\n" + "Allows you to reject the GLIM application\n\n" + "Disburse Loan:\n" + "Mandatory Fields: actualDisbursementDate\n" + "Optional Fields: transactionAmount and fixedEmiAmount\n" + "Disburses the Loan\n\n" + "Disburse Loan To Savings Account:\n" + "Mandatory Fields: actualDisbursementDate\n" + "Optional Fields: transactionAmount and fixedEmiAmount\n" + "Disburses the loan to Saving Account\n\n" + "Undo Loan Disbursal:\n" + "Undoes the Loan Disbursal\n") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoansApiResourceSwagger.PostLoansLoanIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.PostLoansLoanIdResponse.class)}) + @ApiOperation(value = "Approve GLIM Application | Undo GLIM Application Approval | Reject GLIM Application | Disburse Loan Disburse Loan To Savings Account | Undo Loan Disbursal", httpMethod = "POST", notes = "Approve GLIM Application:\n" + + "Mandatory Fields: approvedOnDate\n" + "Optional Fields: approvedLoanAmount and expectedDisbursementDate\n" + + "Approves the GLIM application\n\n" + "Undo GLIM Application Approval:\n" + "Undoes the GLIM Application Approval\n\n" + + "Reject GLIM Application:\n" + "Mandatory Fields: rejectedOnDate\n" + "Allows you to reject the GLIM application\n\n" + + "Disburse Loan:\n" + "Mandatory Fields: actualDisbursementDate\n" + "Optional Fields: transactionAmount and fixedEmiAmount\n" + + "Disburses the Loan\n\n" + "Disburse Loan To Savings Account:\n" + "Mandatory Fields: actualDisbursementDate\n" + + "Optional Fields: transactionAmount and fixedEmiAmount\n" + "Disburses the loan to Saving Account\n\n" + + "Undo Loan Disbursal:\n" + "Undoes the Loan Disbursal\n") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoansApiResourceSwagger.PostLoansLoanIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = LoansApiResourceSwagger.PostLoansLoanIdResponse.class) }) public String glimStateTransitions(@PathParam("glimId") final Long glimId, @QueryParam("command") final String commandParam, - final String apiRequestBodyAsJson) { + final String apiRequestBodyAsJson) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); @@ -984,16 +990,17 @@ public class LoansApiResource { @Produces("application/vnd.ms-excel") public Response getLoanRepaymentTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.LOAN_TRANSACTIONS.toString(), officeId, null,dateFormat); + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.LOAN_TRANSACTIONS.toString(), officeId, null, dateFormat); } @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postLoanTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId = this. bulkImportWorkbookService.importWorkbook(GlobalEntityType.LOANS.toString(), uploadedInputStream,fileDetail,locale,dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.LOANS.toString(), uploadedInputStream, + fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } @@ -1001,10 +1008,10 @@ public class LoansApiResource { @Path("repayments/uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postLoanRepaymentTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail,@FormDataParam("locale") final String locale, - @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.LOAN_TRANSACTIONS.toString(), uploadedInputStream,fileDetail, - locale,dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.LOAN_TRANSACTIONS.toString(), + uploadedInputStream, fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoansApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoansApiResourceSwagger.java index a01d79baf..d1a035a91 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoansApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/LoansApiResourceSwagger.java @@ -27,25 +27,25 @@ import java.util.Set; * Created by Chirag Gupta on 12/09/17. */ final class LoansApiResourceSwagger { - private LoansApiResourceSwagger() { - } + + private LoansApiResourceSwagger() {} @ApiModel(value = "GetLoansTemplateResponse") public final static class GetLoansTemplateResponse { - private GetLoansTemplateResponse() { - } + + private GetLoansTemplateResponse() {} final class GetLoansTemplateTimeline { - private GetLoansTemplateTimeline() { - } + + private GetLoansTemplateTimeline() {} @ApiModelProperty(example = "[2013, 3, 8]") public LocalDate expectedDisbursementDate; } final class GetLoansTemplateProductOptions { - private GetLoansTemplateProductOptions() { - } + + private GetLoansTemplateProductOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -65,12 +65,12 @@ final class LoansApiResourceSwagger { @ApiModel(value = "GetLoansLoanIdResponse") public final static class GetLoansLoanIdResponse { - private GetLoansLoanIdResponse() { - } + + private GetLoansLoanIdResponse() {} final class GetLoansLoanIdStatus { - private GetLoansLoanIdStatus() { - } + + private GetLoansLoanIdStatus() {} @ApiModelProperty(example = "300") public Integer id; @@ -97,8 +97,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdLoanType { - private GetLoansLoanIdLoanType() { - } + + private GetLoansLoanIdLoanType() {} @ApiModelProperty(example = "1") public Integer id; @@ -109,8 +109,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdCurrency { - private GetLoansLoanIdCurrency() { - } + + private GetLoansLoanIdCurrency() {} @ApiModelProperty(example = "UGX") public String code; @@ -127,8 +127,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdTermPeriodFrequencyType { - private GetLoansLoanIdTermPeriodFrequencyType() { - } + + private GetLoansLoanIdTermPeriodFrequencyType() {} @ApiModelProperty(example = "2") public Integer id; @@ -139,8 +139,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdRepaymentFrequencyType { - private GetLoansLoanIdRepaymentFrequencyType() { - } + + private GetLoansLoanIdRepaymentFrequencyType() {} @ApiModelProperty(example = "2") public Integer id; @@ -151,8 +151,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdInterestRateFrequencyType { - private GetLoansLoanIdInterestRateFrequencyType() { - } + + private GetLoansLoanIdInterestRateFrequencyType() {} @ApiModelProperty(example = "3") public Integer id; @@ -163,8 +163,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdAmortizationType { - private GetLoansLoanIdAmortizationType() { - } + + private GetLoansLoanIdAmortizationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -175,8 +175,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdInterestType { - private GetLoansLoanIdInterestType() { - } + + private GetLoansLoanIdInterestType() {} @ApiModelProperty(example = "1") public Integer id; @@ -187,8 +187,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdInterestCalculationPeriodType { - private GetLoansLoanIdInterestCalculationPeriodType() { - } + + private GetLoansLoanIdInterestCalculationPeriodType() {} @ApiModelProperty(example = "1") public Integer id; @@ -199,8 +199,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdTimeline { - private GetLoansLoanIdTimeline() { - } + + private GetLoansLoanIdTimeline() {} @ApiModelProperty(example = "[2012, 4, 3]") public LocalDate submittedOnDate; @@ -233,17 +233,17 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdSummary { - private GetLoansLoanIdSummary() { - } + + private GetLoansLoanIdSummary() {} final class GetLoansLoanIdEmiVariations { - private GetLoansLoanIdEmiVariations() { - } + + private GetLoansLoanIdEmiVariations() {} } final class GetLoansLoanIdLinkedAccount { - private GetLoansLoanIdLinkedAccount() { - } + + private GetLoansLoanIdLinkedAccount() {} @ApiModelProperty(example = "1") public Integer id; @@ -252,8 +252,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdDisbursementDetails { - private GetLoansLoanIdDisbursementDetails() { - } + + private GetLoansLoanIdDisbursementDetails() {} @ApiModelProperty(example = "71") public Integer id; @@ -266,12 +266,12 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdOverdueCharges { - private GetLoansLoanIdOverdueCharges() { - } + + private GetLoansLoanIdOverdueCharges() {} final class GetLoansLoanIdChargeTimeType { - private GetLoansLoanIdChargeTimeType() { - } + + private GetLoansLoanIdChargeTimeType() {} @ApiModelProperty(example = "9") public Integer id; @@ -282,8 +282,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdChargeCalculationType { - private GetLoansLoanIdChargeCalculationType() { - } + + private GetLoansLoanIdChargeCalculationType() {} @ApiModelProperty(example = "2") public Integer id; @@ -294,8 +294,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdChargePaymentMode { - private GetLoansLoanIdChargePaymentMode() { - } + + private GetLoansLoanIdChargePaymentMode() {} @ApiModelProperty(example = "0") public Integer id; @@ -306,8 +306,8 @@ final class LoansApiResourceSwagger { } final class GetLoansLoanIdFeeFrequency { - private GetLoansLoanIdFeeFrequency() { - } + + private GetLoansLoanIdFeeFrequency() {} @ApiModelProperty(example = "1") public Integer id; @@ -473,8 +473,8 @@ final class LoansApiResourceSwagger { @ApiModel(value = "GetLoansResponse") public final static class GetLoansResponse { - private GetLoansResponse() { - } + + private GetLoansResponse() {} @ApiModelProperty(example = "1") public Integer totalFilteredRecords; @@ -483,8 +483,8 @@ final class LoansApiResourceSwagger { @ApiModel(value = "PostLoansRequest") public static final class PostLoansRequest { - private PostLoansRequest() { - } + + private PostLoansRequest() {} @ApiModelProperty(example = "dd MMMM yyyy") public String dateFormat; @@ -520,12 +520,12 @@ final class LoansApiResourceSwagger { @ApiModel(value = "PostLoansResponse") public static final class PostLoansResponse { - private PostLoansResponse() { - } + + private PostLoansResponse() {} final class PostLoansRepaymentSchedulePeriods { - private PostLoansRepaymentSchedulePeriods() { - } + + private PostLoansRepaymentSchedulePeriods() {} @ApiModelProperty(example = "0") public Integer period; @@ -581,8 +581,8 @@ final class LoansApiResourceSwagger { @ApiModel(value = "PutLoansLoanIdRequest") public final static class PutLoansLoanIdRequest { - private PutLoansLoanIdRequest() { - } + + private PutLoansLoanIdRequest() {} @ApiModelProperty(example = "en") public String locale; @@ -618,12 +618,12 @@ final class LoansApiResourceSwagger { @ApiModel(value = "PutLoansLoanIdResponse") public final static class PutLoansLoanIdResponse { - private PutLoansLoanIdResponse() { - } + + private PutLoansLoanIdResponse() {} final class PutLoansLoanIdChanges { - private PutLoansLoanIdChanges() { - } + + private PutLoansLoanIdChanges() {} @ApiModelProperty(example = "5000") public Long principal; @@ -644,8 +644,8 @@ final class LoansApiResourceSwagger { @ApiModel(value = "DeleteLoansLoanIdResponse") public static final class DeleteLoansLoanIdResponse { - private DeleteLoansLoanIdResponse() { - } + + private DeleteLoansLoanIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -659,8 +659,8 @@ final class LoansApiResourceSwagger { @ApiModel(value = "PostLoansLoanIdRequest") public final static class PostLoansLoanIdRequest { - private PostLoansLoanIdRequest() { - } + + private PostLoansLoanIdRequest() {} @ApiModelProperty(example = "2") public Integer toLoanOfficerId; @@ -676,8 +676,8 @@ final class LoansApiResourceSwagger { @ApiModel(value = "PostLoansLoanIdResponse") public static final class PostLoansLoanIdResponse { - private PostLoansLoanIdResponse() { - } + + private PostLoansLoanIdResponse() {} @ApiModelProperty(example = "2") public Integer officeId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/LoanChargeCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/LoanChargeCommand.java index dc925e47e..87e7b2a4e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/LoanChargeCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/LoanChargeCommand.java @@ -56,4 +56,4 @@ public class LoanChargeCommand implements Comparable { } return comparison; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/LoanUpdateCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/LoanUpdateCommand.java index eace59a1b..9ec3fee2c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/LoanUpdateCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/LoanUpdateCommand.java @@ -44,7 +44,9 @@ public class LoanUpdateCommand { baseDataValidator.reset().parameter("unassignedDate").value(this.unassignedDate).notNull(); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/UndoStateTransitionCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/UndoStateTransitionCommand.java index 9dd2fbb5d..3362c6c39 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/UndoStateTransitionCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/UndoStateTransitionCommand.java @@ -38,4 +38,4 @@ public class UndoStateTransitionCommand { public String getNote() { return this.note; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/UpdateLoanOfficerCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/UpdateLoanOfficerCommand.java index 3accada8d..bbbb87115 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/UpdateLoanOfficerCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/command/UpdateLoanOfficerCommand.java @@ -65,8 +65,10 @@ public class UpdateLoanOfficerCommand { baseDataValidator.reset().parameter("loans").value(this.loans).arrayNotEmpty(); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForLoanReassignment() { @@ -79,7 +81,9 @@ public class UpdateLoanOfficerCommand { baseDataValidator.reset().parameter("assignmentDate").value(this.assignmentDate).notNull(); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/DisbursementData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/DisbursementData.java index 520711803..512bb0a2f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/DisbursementData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/DisbursementData.java @@ -36,31 +36,31 @@ public class DisbursementData implements Comparable { private final BigDecimal chargeAmount; private final BigDecimal waivedChargeAmount; - //import fields + // import fields private transient Integer rowIndex; private String dateFormat; private String locale; private String note; private transient String linkAccountId; - public static DisbursementData importInstance(LocalDate actualDisbursementDate,String linkAccountId, - Integer rowIndex,String locale,String dateFormat){ - return new DisbursementData(actualDisbursementDate,linkAccountId,rowIndex,locale,dateFormat); + public static DisbursementData importInstance(LocalDate actualDisbursementDate, String linkAccountId, Integer rowIndex, String locale, + String dateFormat) { + return new DisbursementData(actualDisbursementDate, linkAccountId, rowIndex, locale, dateFormat); } - private DisbursementData(LocalDate actualDisbursementDate,String linkAccountId, - Integer rowIndex,String locale,String dateFormat) { - this.dateFormat= dateFormat; - this.locale= locale; + + private DisbursementData(LocalDate actualDisbursementDate, String linkAccountId, Integer rowIndex, String locale, String dateFormat) { + this.dateFormat = dateFormat; + this.locale = locale; this.actualDisbursementDate = actualDisbursementDate; this.rowIndex = rowIndex; - this.note=""; - this.linkAccountId=linkAccountId; - this.id=null; - this.expectedDisbursementDate=null; - this.principal=null; - this.loanChargeId=null; - this.chargeAmount=null; - this.waivedChargeAmount=null; + this.note = ""; + this.linkAccountId = linkAccountId; + this.id = null; + this.expectedDisbursementDate = null; + this.principal = null; + this.loanChargeId = null; + this.chargeAmount = null; + this.waivedChargeAmount = null; } @@ -116,12 +116,9 @@ public class DisbursementData implements Comparable { return target != null && target.isAfter(fromNotInclusive) && !target.isAfter(upToAndInclusive); } - public BigDecimal getWaivedChargeAmount() { - if(this.waivedChargeAmount == null){ - return BigDecimal.ZERO; - } + if (this.waivedChargeAmount == null) { return BigDecimal.ZERO; } return this.waivedChargeAmount; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GLIMContainer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GLIMContainer.java index 82aea12aa..9a9e31c40 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GLIMContainer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GLIMContainer.java @@ -24,50 +24,50 @@ import org.apache.fineract.portfolio.accountdetails.data.LoanAccountSummaryData; public class GLIMContainer { - private final BigDecimal glimId; + private final BigDecimal glimId; - private final BigDecimal groupId; + private final BigDecimal groupId; - private final String accountNumber; + private final String accountNumber; - private final List childGLIMAccounts; + private final List childGLIMAccounts; - private final BigDecimal parentPrincipalAmount; + private final BigDecimal parentPrincipalAmount; - private final String loanStatus; + private final String loanStatus; - public GLIMContainer(final BigDecimal glimId,final BigDecimal groupId,final String accountNumber,final List childGLIMAccounts, - final BigDecimal parentPrincipalAmount,final String loanStatus) { - this.glimId=glimId; - this.groupId=groupId; - this.accountNumber = accountNumber; - this.childGLIMAccounts=childGLIMAccounts; - this.parentPrincipalAmount = parentPrincipalAmount; - this.loanStatus=loanStatus; + public GLIMContainer(final BigDecimal glimId, final BigDecimal groupId, final String accountNumber, + final List childGLIMAccounts, final BigDecimal parentPrincipalAmount, final String loanStatus) { + this.glimId = glimId; + this.groupId = groupId; + this.accountNumber = accountNumber; + this.childGLIMAccounts = childGLIMAccounts; + this.parentPrincipalAmount = parentPrincipalAmount; + this.loanStatus = loanStatus; - } + } - public BigDecimal getGlimId() { - return glimId; - } + public BigDecimal getGlimId() { + return glimId; + } - public BigDecimal getGroupId() { - return groupId; - } + public BigDecimal getGroupId() { + return groupId; + } - public String getAccountNumber() { - return accountNumber; - } + public String getAccountNumber() { + return accountNumber; + } - public List getChildGLIMAccounts() { - return childGLIMAccounts; - } + public List getChildGLIMAccounts() { + return childGLIMAccounts; + } - public BigDecimal getParentPrincipalAmount() { - return parentPrincipalAmount; - } + public BigDecimal getParentPrincipalAmount() { + return parentPrincipalAmount; + } - public String getLoanStatus() { - return loanStatus; - } -} \ No newline at end of file + public String getLoanStatus() { + return loanStatus; + } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GlimRepaymentTemplate.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GlimRepaymentTemplate.java index 7176a13c7..abec34c1d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GlimRepaymentTemplate.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GlimRepaymentTemplate.java @@ -17,89 +17,85 @@ * under the License. */ - package org.apache.fineract.portfolio.loanaccount.data; import java.math.BigDecimal; -public class GlimRepaymentTemplate -{ +public class GlimRepaymentTemplate { - private final BigDecimal glimId; + private final BigDecimal glimId; - private final BigDecimal groupId; + private final BigDecimal groupId; - private final BigDecimal clientId; + private final BigDecimal clientId; - private final String clientName; + private final String clientName; - private final BigDecimal childLoanId; + private final BigDecimal childLoanId; - private final String parentAccountNo; + private final String parentAccountNo; - private final BigDecimal parentPrincipalAmount; + private final BigDecimal parentPrincipalAmount; - private final String childLoanAccountNo; + private final String childLoanAccountNo; - private final BigDecimal childPrincipalAmount ; + private final BigDecimal childPrincipalAmount; - private GlimRepaymentTemplate(final BigDecimal glimId,final BigDecimal groupId,final BigDecimal clientId, - final String clientName,final BigDecimal childLoanId,final String parentAccountNo,final BigDecimal parentPrincipalAmount, - final String childLoanAccountNo,final BigDecimal childPrincipalAmount) - { - this.glimId=glimId; - this.groupId=groupId; - this.clientId=clientId; - this.clientName=clientName; - this.childLoanId=childLoanId; - this.parentAccountNo=parentAccountNo; - this.parentPrincipalAmount=parentPrincipalAmount; - this.childLoanAccountNo=childLoanAccountNo; - this.childPrincipalAmount=childPrincipalAmount; - } + private GlimRepaymentTemplate(final BigDecimal glimId, final BigDecimal groupId, final BigDecimal clientId, final String clientName, + final BigDecimal childLoanId, final String parentAccountNo, final BigDecimal parentPrincipalAmount, + final String childLoanAccountNo, final BigDecimal childPrincipalAmount) { + this.glimId = glimId; + this.groupId = groupId; + this.clientId = clientId; + this.clientName = clientName; + this.childLoanId = childLoanId; + this.parentAccountNo = parentAccountNo; + this.parentPrincipalAmount = parentPrincipalAmount; + this.childLoanAccountNo = childLoanAccountNo; + this.childPrincipalAmount = childPrincipalAmount; + } - public static GlimRepaymentTemplate getInstance(final BigDecimal glimId,final BigDecimal groupId,final BigDecimal clientId, - final String clientName,final BigDecimal childLoanId,final String parentAccountNo,final BigDecimal parentPrincipalAmount, - final String childLoanAccountNo,final BigDecimal childPrincipalAmount) - { - return new GlimRepaymentTemplate(glimId,groupId,clientId,clientName,childLoanId,parentAccountNo, - parentPrincipalAmount,childLoanAccountNo,childPrincipalAmount); - } + public static GlimRepaymentTemplate getInstance(final BigDecimal glimId, final BigDecimal groupId, final BigDecimal clientId, + final String clientName, final BigDecimal childLoanId, final String parentAccountNo, final BigDecimal parentPrincipalAmount, + final String childLoanAccountNo, final BigDecimal childPrincipalAmount) { + return new GlimRepaymentTemplate(glimId, groupId, clientId, clientName, childLoanId, parentAccountNo, parentPrincipalAmount, + childLoanAccountNo, childPrincipalAmount); + } - public BigDecimal getGlimId() { - return glimId; - } + public BigDecimal getGlimId() { + return glimId; + } - public BigDecimal getGroupId() { - return groupId; - } + public BigDecimal getGroupId() { + return groupId; + } - public BigDecimal getClientId() { - return clientId; - } + public BigDecimal getClientId() { + return clientId; + } - public String getClientName() { - return clientName; - } + public String getClientName() { + return clientName; + } - public BigDecimal getChildLoanId() { - return childLoanId; - } + public BigDecimal getChildLoanId() { + return childLoanId; + } - public String getParentAccountNo() { - return parentAccountNo; - } + public String getParentAccountNo() { + return parentAccountNo; + } - public BigDecimal getParentPrincipalAmount() { - return parentPrincipalAmount; - } + public BigDecimal getParentPrincipalAmount() { + return parentPrincipalAmount; + } - public String getChildLoanAccountNo() { - return childLoanAccountNo; - } + public String getChildLoanAccountNo() { + return childLoanAccountNo; + } - public BigDecimal getChildPrincipalAmount() { - return childPrincipalAmount; - } + public BigDecimal getChildPrincipalAmount() { + return childPrincipalAmount; + } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GroupLoanIndividualMonitoringAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GroupLoanIndividualMonitoringAccountData.java index 319cbbb21..5eabd0a71 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GroupLoanIndividualMonitoringAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/GroupLoanIndividualMonitoringAccountData.java @@ -21,8 +21,8 @@ package org.apache.fineract.portfolio.loanaccount.data; import java.math.BigDecimal; -public class GroupLoanIndividualMonitoringAccountData -{ +public class GroupLoanIndividualMonitoringAccountData { + private final BigDecimal glimId; private final BigDecimal groupId; @@ -39,35 +39,32 @@ public class GroupLoanIndividualMonitoringAccountData private final String loanStatus; - private GroupLoanIndividualMonitoringAccountData(final BigDecimal glimId,final BigDecimal groupId,final String accountNumber, final String childAccountNumber, - final BigDecimal childPrincipalAmount, final BigDecimal parentPrincipalAmount, - final Long childAccountsCount,final String loanStatus) { - this.glimId=glimId; - this.groupId=groupId; + private GroupLoanIndividualMonitoringAccountData(final BigDecimal glimId, final BigDecimal groupId, final String accountNumber, + final String childAccountNumber, final BigDecimal childPrincipalAmount, final BigDecimal parentPrincipalAmount, + final Long childAccountsCount, final String loanStatus) { + this.glimId = glimId; + this.groupId = groupId; this.accountNumber = accountNumber; this.childAccountNumber = childAccountNumber; this.childPrincipalAmount = childPrincipalAmount; this.parentPrincipalAmount = parentPrincipalAmount; this.childAccountsCount = childAccountsCount; - this.loanStatus=loanStatus; + this.loanStatus = loanStatus; } - public static GroupLoanIndividualMonitoringAccountData getInstance(final BigDecimal glimId, final BigDecimal groupId,final String accountNumber, final String childAccountNumber, - final BigDecimal childPrincipalAmount, final BigDecimal parentPrincipalAmount, - final Long childAccountsCount,final String loanStatus) - { - return new GroupLoanIndividualMonitoringAccountData(glimId,groupId,accountNumber,childAccountNumber, - childPrincipalAmount,parentPrincipalAmount,childAccountsCount,loanStatus); + public static GroupLoanIndividualMonitoringAccountData getInstance(final BigDecimal glimId, final BigDecimal groupId, + final String accountNumber, final String childAccountNumber, final BigDecimal childPrincipalAmount, + final BigDecimal parentPrincipalAmount, final Long childAccountsCount, final String loanStatus) { + return new GroupLoanIndividualMonitoringAccountData(glimId, groupId, accountNumber, childAccountNumber, childPrincipalAmount, + parentPrincipalAmount, childAccountsCount, loanStatus); } - public static GroupLoanIndividualMonitoringAccountData getInstance1(final BigDecimal glimId,final BigDecimal groupId,final String accountNumber, - final BigDecimal parentPrincipalAmount,final String loanStatus) - { - return new GroupLoanIndividualMonitoringAccountData(glimId,groupId,accountNumber,null,null,parentPrincipalAmount,null,loanStatus); + public static GroupLoanIndividualMonitoringAccountData getInstance1(final BigDecimal glimId, final BigDecimal groupId, + final String accountNumber, final BigDecimal parentPrincipalAmount, final String loanStatus) { + return new GroupLoanIndividualMonitoringAccountData(glimId, groupId, accountNumber, null, null, parentPrincipalAmount, null, + loanStatus); } - - public BigDecimal getGlimId() { return glimId; } @@ -76,7 +73,6 @@ public class GroupLoanIndividualMonitoringAccountData return groupId; } - public String getAccountNumber() { return accountNumber; } @@ -100,4 +96,4 @@ public class GroupLoanIndividualMonitoringAccountData public String getLoanStatus() { return loanStatus; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanAccountData.java index a402e4d50..3b04618bd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanAccountData.java @@ -220,11 +220,11 @@ public class LoanAccountData { private List datatables = null; private final Boolean isEqualAmortization; - //Rate + // Rate private final List rates; private final Boolean isRatesEnabled; - //import fields + // import fields private String dateFormat; private String locale; private transient Integer rowIndex; @@ -237,63 +237,57 @@ public class LoanAccountData { private Long groupId; private LocalDate expectedDisbursementDate; - public static LoanAccountData importInstanceIndividual(EnumOptionData loanTypeEnumOption,Long clientId,Long productId, - Long loanOfficerId,LocalDate submittedOnDate, - Long fundId,BigDecimal principal, Integer numberOfRepayments,Integer repaymentEvery, - EnumOptionData repaidEveryFrequencyEnums, Integer loanTermFrequency,EnumOptionData loanTermFrequencyTypeEnum, - BigDecimal nominalInterestRate,LocalDate expectedDisbursementDate ,EnumOptionData amortizationEnumOption, - EnumOptionData interestMethodEnum, EnumOptionData interestCalculationPeriodTypeEnum,BigDecimal inArrearsTolerance,Long transactionProcessingStrategyId, - Integer graceOnPrincipalPayment,Integer graceOnInterestPayment,Integer graceOnInterestCharged, - LocalDate interestChargedFromDate,LocalDate repaymentsStartingFromDate,Integer rowIndex , - String externalId,Long groupId,Collection charges,String linkAccountId, - String locale,String dateFormat){ + public static LoanAccountData importInstanceIndividual(EnumOptionData loanTypeEnumOption, Long clientId, Long productId, + Long loanOfficerId, LocalDate submittedOnDate, Long fundId, BigDecimal principal, Integer numberOfRepayments, + Integer repaymentEvery, EnumOptionData repaidEveryFrequencyEnums, Integer loanTermFrequency, + EnumOptionData loanTermFrequencyTypeEnum, BigDecimal nominalInterestRate, LocalDate expectedDisbursementDate, + EnumOptionData amortizationEnumOption, EnumOptionData interestMethodEnum, EnumOptionData interestCalculationPeriodTypeEnum, + BigDecimal inArrearsTolerance, Long transactionProcessingStrategyId, Integer graceOnPrincipalPayment, + Integer graceOnInterestPayment, Integer graceOnInterestCharged, LocalDate interestChargedFromDate, + LocalDate repaymentsStartingFromDate, Integer rowIndex, String externalId, Long groupId, Collection charges, + String linkAccountId, String locale, String dateFormat) { - return new LoanAccountData(loanTypeEnumOption, clientId, productId, loanOfficerId, submittedOnDate, fundId, - principal, numberOfRepayments, - repaymentEvery, repaidEveryFrequencyEnums, loanTermFrequency, loanTermFrequencyTypeEnum, nominalInterestRate, expectedDisbursementDate, - amortizationEnumOption, interestMethodEnum, interestCalculationPeriodTypeEnum, inArrearsTolerance, transactionProcessingStrategyId, - graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, repaymentsStartingFromDate, - rowIndex, externalId, null, charges, linkAccountId,locale,dateFormat); + return new LoanAccountData(loanTypeEnumOption, clientId, productId, loanOfficerId, submittedOnDate, fundId, principal, + numberOfRepayments, repaymentEvery, repaidEveryFrequencyEnums, loanTermFrequency, loanTermFrequencyTypeEnum, + nominalInterestRate, expectedDisbursementDate, amortizationEnumOption, interestMethodEnum, + interestCalculationPeriodTypeEnum, inArrearsTolerance, transactionProcessingStrategyId, graceOnPrincipalPayment, + graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, repaymentsStartingFromDate, rowIndex, externalId, + null, charges, linkAccountId, locale, dateFormat); } + public static LoanAccountData importInstanceGroup(EnumOptionData loanTypeEnumOption, Long groupIdforGroupLoan, Long productId, + Long loanOfficerId, LocalDate submittedOnDate, Long fundId, BigDecimal principal, Integer numberOfRepayments, + Integer repaidEvery, EnumOptionData repaidEveryFrequencyEnums, Integer loanTermFrequency, + EnumOptionData loanTermFrequencyTypeEnum, BigDecimal nominalInterestRate, EnumOptionData amortizationEnumOption, + EnumOptionData interestMethodEnum, EnumOptionData interestCalculationPeriodEnum, BigDecimal arrearsTolerance, + Long transactionProcessingStrategyId, Integer graceOnPrincipalPayment, Integer graceOnInterestPayment, + Integer graceOnInterestCharged, LocalDate interestChargedFromDate, LocalDate repaymentsStartingFromDate, Integer rowIndex, + String externalId, String linkAccountId, String locale, String dateFormat) { - public static LoanAccountData importInstanceGroup(EnumOptionData loanTypeEnumOption,Long groupIdforGroupLoan,Long productId, - Long loanOfficerId,LocalDate submittedOnDate, - Long fundId,BigDecimal principal, Integer numberOfRepayments,Integer repaidEvery, - EnumOptionData repaidEveryFrequencyEnums, Integer loanTermFrequency,EnumOptionData loanTermFrequencyTypeEnum, - BigDecimal nominalInterestRate, EnumOptionData amortizationEnumOption,EnumOptionData interestMethodEnum, - EnumOptionData interestCalculationPeriodEnum,BigDecimal arrearsTolerance, - Long transactionProcessingStrategyId, - Integer graceOnPrincipalPayment,Integer graceOnInterestPayment,Integer graceOnInterestCharged, - LocalDate interestChargedFromDate,LocalDate repaymentsStartingFromDate, - Integer rowIndex ,String externalId,String linkAccountId,String locale,String dateFormat){ - - return new LoanAccountData(loanTypeEnumOption, groupIdforGroupLoan, productId, loanOfficerId, submittedOnDate, fundId, - principal, numberOfRepayments, - repaidEvery, repaidEveryFrequencyEnums, loanTermFrequency, loanTermFrequencyTypeEnum, nominalInterestRate, null, - amortizationEnumOption, interestMethodEnum, interestCalculationPeriodEnum, arrearsTolerance, + return new LoanAccountData(loanTypeEnumOption, groupIdforGroupLoan, productId, loanOfficerId, submittedOnDate, fundId, principal, + numberOfRepayments, repaidEvery, repaidEveryFrequencyEnums, loanTermFrequency, loanTermFrequencyTypeEnum, + nominalInterestRate, null, amortizationEnumOption, interestMethodEnum, interestCalculationPeriodEnum, arrearsTolerance, transactionProcessingStrategyId, graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, - interestChargedFromDate, repaymentsStartingFromDate, rowIndex, externalId, null, null, linkAccountId,locale,dateFormat); + interestChargedFromDate, repaymentsStartingFromDate, rowIndex, externalId, null, null, linkAccountId, locale, dateFormat); } - private LoanAccountData(EnumOptionData loanType,Long clientId,Long productId,Long loanOfficerId,LocalDate submittedOnDate, - Long fundId,BigDecimal principal, Integer numberOfRepayments,Integer repaymentEvery, - EnumOptionData repaymentFrequencyType, Integer loanTermFrequency,EnumOptionData loanTermFrequencyType, - BigDecimal interestRatePerPeriod,LocalDate expectedDisbursementDate ,EnumOptionData amortizationType, - EnumOptionData interestType, EnumOptionData interestCalculationPeriodType,BigDecimal inArrearsTolerance,Long transactionProcessingStrategyId, - Integer graceOnPrincipalPayment,Integer graceOnInterestPayment,Integer graceOnInterestCharged, - LocalDate interestChargedFromDate,LocalDate repaymentsStartingFromDate,Integer rowIndex , - String externalId,Long groupId,Collection charges,String linkAccountId, - String locale,String dateFormat) { - this.dateFormat=dateFormat; - this.locale= locale; - this.rowIndex=rowIndex; - this.submittedOnDate=submittedOnDate; - this.productId=productId; - this.loanTermFrequency=loanTermFrequency; - this.loanTermFrequencyType=loanTermFrequencyType; - this.repaymentsStartingFromDate=repaymentsStartingFromDate; - this.linkAccountId=linkAccountId; + private LoanAccountData(EnumOptionData loanType, Long clientId, Long productId, Long loanOfficerId, LocalDate submittedOnDate, + Long fundId, BigDecimal principal, Integer numberOfRepayments, Integer repaymentEvery, EnumOptionData repaymentFrequencyType, + Integer loanTermFrequency, EnumOptionData loanTermFrequencyType, BigDecimal interestRatePerPeriod, + LocalDate expectedDisbursementDate, EnumOptionData amortizationType, EnumOptionData interestType, + EnumOptionData interestCalculationPeriodType, BigDecimal inArrearsTolerance, Long transactionProcessingStrategyId, + Integer graceOnPrincipalPayment, Integer graceOnInterestPayment, Integer graceOnInterestCharged, + LocalDate interestChargedFromDate, LocalDate repaymentsStartingFromDate, Integer rowIndex, String externalId, Long groupId, + Collection charges, String linkAccountId, String locale, String dateFormat) { + this.dateFormat = dateFormat; + this.locale = locale; + this.rowIndex = rowIndex; + this.submittedOnDate = submittedOnDate; + this.productId = productId; + this.loanTermFrequency = loanTermFrequency; + this.loanTermFrequencyType = loanTermFrequencyType; + this.repaymentsStartingFromDate = repaymentsStartingFromDate; + this.linkAccountId = linkAccountId; this.externalId = externalId; this.clientId = clientId; this.fundId = fundId; @@ -313,10 +307,10 @@ public class LoanAccountData { this.graceOnInterestCharged = graceOnInterestCharged; this.graceOnPrincipalPayment = graceOnPrincipalPayment; this.interestChargedFromDate = interestChargedFromDate; - this.groupId=groupId; - this.expectedDisbursementDate=expectedDisbursementDate; + this.groupId = groupId; + this.expectedDisbursementDate = expectedDisbursementDate; this.charges = charges; - this.rates=null; + this.rates = null; this.id = null; this.accountNo = null; @@ -345,7 +339,6 @@ public class LoanAccountData { this.termFrequency = null; this.termPeriodFrequencyType = null; - this.repaymentFrequencyNthDayType = null; this.repaymentFrequencyDayOfWeekType = null; @@ -427,7 +420,6 @@ public class LoanAccountData { this.isRatesEnabled = false; } - public Integer getRowIndex() { return rowIndex; } @@ -469,6 +461,7 @@ public class LoanAccountData { public String getClientAccountNo() { return clientAccountNo; } + /** * Used to produce a {@link LoanAccountData} with only collateral options * for now. @@ -597,18 +590,19 @@ public class LoanAccountData { repaymentFrequencyType, repaymentFrequencyNthDayType, repaymentFrequencyDayOfWeekType, transactionProcessingStrategyId, transactionProcessingStrategyName, amortizationType, interestRatePerPeriod, interestRateFrequencyType, annualInterestRate, interestType, isFloatingInterestRate, interestRateDifferential, interestCalculationPeriodType, - allowPartialPeriodInterestCalcualtion, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, - graceOnInterestCharged, interestChargedFromDate, timeline, summary, feeChargesDueAtDisbursementCharged, repaymentSchedule, - transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, - repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, repaymentFrequencyDayOfWeekTypeOptions, - transactionProcessingStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, - interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, - loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, notes, - accountLinkingOptions, linkedAccount, disbursementData, multiDisburseLoan, canDefineInstallmentAmount, fixedEmiAmount, - maxOutstandingLoanBalance, emiAmountVariations, memberVariations, product, inArrears, graceOnArrearsAgeing, overdueCharges, - isNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, interestRecalculationData, originalSchedule, - createStandingInstructionAtDisbursement, paidInAdvance, interestRatesPeriods, isVariableInstallmentsAllowed, minimumGap, - maximumGap, subStatus, canUseForTopup, clientActiveLoanOptions, isTopup, closureLoanId, closureLoanAccountNo, topupAmount, isEqualAmortization, rates, isRatesEnabled); + allowPartialPeriodInterestCalcualtion, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, timeline, + summary, feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, + productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, + repaymentFrequencyDayOfWeekTypeOptions, transactionProcessingStrategyOptions, interestRateFrequencyTypeOptions, + amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, + chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, + loancounter, loanProductCounter, notes, accountLinkingOptions, linkedAccount, disbursementData, multiDisburseLoan, + canDefineInstallmentAmount, fixedEmiAmount, maxOutstandingLoanBalance, emiAmountVariations, memberVariations, product, + inArrears, graceOnArrearsAgeing, overdueCharges, isNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, + interestRecalculationData, originalSchedule, createStandingInstructionAtDisbursement, paidInAdvance, interestRatesPeriods, + isVariableInstallmentsAllowed, minimumGap, maximumGap, subStatus, canUseForTopup, clientActiveLoanOptions, isTopup, + closureLoanId, closureLoanAccountNo, topupAmount, isEqualAmortization, rates, isRatesEnabled); } @@ -740,19 +734,19 @@ public class LoanAccountData { repaymentFrequencyType, repaymentFrequencyNthDayType, repaymentFrequencyDayOfWeekType, transactionProcessingStrategyId, transactionProcessingStrategyName, amortizationType, interestRatePerPeriod, interestRateFrequencyType, annualInterestRate, interestType, isFloatingInterestRate, interestRateDifferential, interestCalculationPeriodType, - allowPartialPeriodInterestCalcualtion, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, - graceOnInterestCharged, interestChargedFromDate, timeline, summary, feeChargesDueAtDisbursementCharged, repaymentSchedule, - transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, - repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, repaymentFrequencyDayOfWeekTypeOptions, - repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, - interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, - loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, notes, - accountLinkingOptions, linkedAccount, disbursementData, multiDisburseLoan, canDefineInstallmentAmount, fixedEmiAmount, - maxOutstandingLoanBalance, emiAmountVariations, memberVariations, product, inArrears, graceOnArrearsAgeing, overdueCharges, - isNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, interestRecalculationData, originalSchedule, - createStandingInstructionAtDisbursement, paidInAdvance, interestRatesPeriods, isVariableInstallmentsAllowed, minimumGap, - maximumGap, subStatus, canUseForTopup, clientActiveLoanOptions, isTopup, closureLoanId, closureLoanAccountNo, topupAmount, isEqualAmortization, - rates, isRatesEnabled); + allowPartialPeriodInterestCalcualtion, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, timeline, + summary, feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, + productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, + repaymentFrequencyDayOfWeekTypeOptions, repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, + interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, + loanPurposeOptions, loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, + notes, accountLinkingOptions, linkedAccount, disbursementData, multiDisburseLoan, canDefineInstallmentAmount, + fixedEmiAmount, maxOutstandingLoanBalance, emiAmountVariations, memberVariations, product, inArrears, graceOnArrearsAgeing, + overdueCharges, isNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, interestRecalculationData, + originalSchedule, createStandingInstructionAtDisbursement, paidInAdvance, interestRatesPeriods, + isVariableInstallmentsAllowed, minimumGap, maximumGap, subStatus, canUseForTopup, clientActiveLoanOptions, isTopup, + closureLoanId, closureLoanAccountNo, topupAmount, isEqualAmortization, rates, isRatesEnabled); } @@ -767,23 +761,22 @@ public class LoanAccountData { acc.repaymentFrequencyDayOfWeekType, acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.isFloatingInterestRate, acc.interestRateDifferential, acc.interestCalculationPeriodType, - acc.allowPartialPeriodInterestCalcualtion, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, - acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, clientAcc.timeline, acc.summary, - acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, - acc.meeting, acc.productOptions, acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, - acc.repaymentFrequencyNthDayTypeOptions, acc.repaymentFrequencyDaysOfWeekTypeOptions, - acc.transactionProcessingStrategyOptions, acc.interestRateFrequencyTypeOptions, acc.amortizationTypeOptions, - acc.interestTypeOptions, acc.interestCalculationPeriodTypeOptions, acc.fundOptions, acc.chargeOptions, null, - acc.loanOfficerOptions, acc.loanPurposeOptions, acc.loanCollateralOptions, acc.calendarOptions, + acc.allowPartialPeriodInterestCalcualtion, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, + acc.recurringMoratoriumOnPrincipalPeriods, acc.graceOnInterestPayment, acc.graceOnInterestCharged, + acc.interestChargedFromDate, clientAcc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, + acc.transactions, acc.charges, acc.collateral, acc.guarantors, acc.meeting, acc.productOptions, + acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, acc.repaymentFrequencyNthDayTypeOptions, + acc.repaymentFrequencyDaysOfWeekTypeOptions, acc.transactionProcessingStrategyOptions, acc.interestRateFrequencyTypeOptions, + acc.amortizationTypeOptions, acc.interestTypeOptions, acc.interestCalculationPeriodTypeOptions, acc.fundOptions, + acc.chargeOptions, null, acc.loanOfficerOptions, acc.loanPurposeOptions, acc.loanCollateralOptions, acc.calendarOptions, acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, acc.notes, acc.accountLinkingOptions, acc.linkedAccount, acc.disbursementDetails, acc.multiDisburseLoan, acc.canDefineInstallmentAmount, acc.fixedEmiAmount, acc.maxOutstandingLoanBalance, acc.emiAmountVariations, acc.memberVariations, acc.product, acc.inArrears, acc.graceOnArrearsAgeing, acc.overdueCharges, acc.isNPA, acc.daysInMonthType, acc.daysInYearType, acc.isInterestRecalculationEnabled, acc.interestRecalculationData, acc.originalSchedule, - acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, - acc.isVariableInstallmentsAllowed, acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, - acc.clientActiveLoanOptions, acc.isTopup, acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, - acc.rates, acc.isRatesEnabled); + acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, acc.isVariableInstallmentsAllowed, + acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, acc.clientActiveLoanOptions, acc.isTopup, + acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, acc.rates, acc.isRatesEnabled); } /** @@ -916,19 +909,19 @@ public class LoanAccountData { repaymentFrequencyType, repaymentFrequencyNthDayType, repaymentFrequencyDayOfWeekType, transactionProcessingStrategyId, transactionProcessingStrategyName, amortizationType, interestRatePerPeriod, interestRateFrequencyType, annualInterestRate, interestType, isFloatingInterestRate, interestRateDifferential, interestCalculationPeriodType, - allowPartialPeriodInterestCalcualtion, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, - graceOnInterestCharged, interestChargedFromDate, timeline, summary, feeChargesDueAtDisbursementCharged, repaymentSchedule, - transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, - repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, repaymentFrequencyDayOfWeekTypeOptions, - repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, - interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, - loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, notes, - accountLinkingOptions, linkedAccount, disbursementData, multiDisburseLoan, canDefineInstallmentAmount, fixedEmiAmount, - maxOutstandingBalance, emiAmountVariations, memberVariations, product, inArrears, graceOnArrearsAgeing, overdueCharges, - isNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, interestRecalculationData, originalSchedule, - createStandingInstructionAtDisbursement, paidInAdvance, interestRatesPeriods, isVariableInstallmentsAllowed, minimumGap, - maximumGap, subStatus, canUseForTopup, clientActiveLoanOptions, isTopup, closureLoanId, closureLoanAccountNo, topupAmount, isEqualAmortization, - rates, isRatesEnabled); + allowPartialPeriodInterestCalcualtion, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, timeline, + summary, feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, + productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, + repaymentFrequencyDayOfWeekTypeOptions, repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, + interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, + loanPurposeOptions, loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, + notes, accountLinkingOptions, linkedAccount, disbursementData, multiDisburseLoan, canDefineInstallmentAmount, + fixedEmiAmount, maxOutstandingBalance, emiAmountVariations, memberVariations, product, inArrears, graceOnArrearsAgeing, + overdueCharges, isNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, interestRecalculationData, + originalSchedule, createStandingInstructionAtDisbursement, paidInAdvance, interestRatesPeriods, + isVariableInstallmentsAllowed, minimumGap, maximumGap, subStatus, canUseForTopup, clientActiveLoanOptions, isTopup, + closureLoanId, closureLoanAccountNo, topupAmount, isEqualAmortization, rates, isRatesEnabled); } @@ -940,10 +933,10 @@ public class LoanAccountData { acc.loanOfficerName, acc.currency, acc.proposedPrincipal, acc.principal, acc.approvedPrincipal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, acc.numberOfRepayments, acc.repaymentEvery, acc.repaymentFrequencyType, acc.repaymentFrequencyNthDayType, acc.repaymentFrequencyDayOfWeekType, - acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, - acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, - acc.isFloatingInterestRate, acc.interestRateDifferential, acc.interestCalculationPeriodType, - acc.allowPartialPeriodInterestCalcualtion, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, + acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, acc.interestRatePerPeriod, + acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.isFloatingInterestRate, + acc.interestRateDifferential, acc.interestCalculationPeriodType, acc.allowPartialPeriodInterestCalcualtion, + acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, groupAcc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, acc.meeting, acc.productOptions, acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, @@ -956,10 +949,9 @@ public class LoanAccountData { acc.maxOutstandingLoanBalance, acc.emiAmountVariations, acc.memberVariations, acc.product, acc.inArrears, acc.graceOnArrearsAgeing, acc.overdueCharges, acc.isNPA, acc.daysInMonthType, acc.daysInYearType, acc.isInterestRecalculationEnabled, acc.interestRecalculationData, acc.originalSchedule, - acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, - acc.isVariableInstallmentsAllowed, acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, - acc.clientActiveLoanOptions, acc.isTopup, acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, - acc.rates, acc.isRatesEnabled); + acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, acc.isVariableInstallmentsAllowed, + acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, acc.clientActiveLoanOptions, acc.isTopup, + acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, acc.rates, acc.isRatesEnabled); } @@ -1102,21 +1094,21 @@ public class LoanAccountData { product.getInterestRateFrequencyType(), product.getAnnualInterestRate(), product.getInterestType(), product.isFloatingInterestRateCalculationAllowed(), product.getDefaultDifferentialLendingRate(), product.getInterestCalculationPeriodType(), product.getAllowPartialPeriodInterestCalcualtion(), - expectedFirstRepaymentOnDate, product.getGraceOnPrincipalPayment(), product.getRecurringMoratoriumOnPrincipalPeriods(), product.getGraceOnInterestPayment(), - product.getGraceOnInterestCharged(), interestChargedFromDate, timeline, summary, feeChargesDueAtDisbursementCharged, - repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, - repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, repaymentFrequencyDayOfWeekTypeOptions, - repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, - interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, - loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, notes, - accountLinkingOptions, linkedAccount, disbursementData, product.getMultiDisburseLoan(), + expectedFirstRepaymentOnDate, product.getGraceOnPrincipalPayment(), product.getRecurringMoratoriumOnPrincipalPeriods(), + product.getGraceOnInterestPayment(), product.getGraceOnInterestCharged(), interestChargedFromDate, timeline, summary, + feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, + productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, + repaymentFrequencyDayOfWeekTypeOptions, repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, + interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, + loanPurposeOptions, loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, + notes, accountLinkingOptions, linkedAccount, disbursementData, product.getMultiDisburseLoan(), product.canDefineInstallmentAmount(), fixedEmi, product.getOutstandingLoanBalance(), emiAmountVariations, memberVariations, product, inArrears, product.getGraceOnArrearsAgeing(), product.overdueFeeCharges(), isNPA, product.getDaysInMonthType(), product.getDaysInYearType(), product.isInterestRecalculationEnabled(), product.toLoanInterestRecalculationData(), originalSchedule, createStandingInstructionAtDisbursement, paidInAdvance, interestRatesPeriods, product.isVariableInstallmentsAllowed(), product.getMinimumGapBetweenInstallments(), product.getMaximumGapBetweenInstallments(), subStatus, canUseForTopup, clientActiveLoanOptions, isTopup, closureLoanId, - closureLoanAccountNo, topupAmount, product.isEqualAmortization(),rates, isRatesEnabled); + closureLoanAccountNo, topupAmount, product.isEqualAmortization(), rates, isRatesEnabled); } public static LoanAccountData populateLoanProductDefaults(final LoanAccountData acc, final LoanProductData product) { @@ -1162,22 +1154,22 @@ public class LoanAccountData { product.getAmortizationType(), product.getInterestRatePerPeriod(), product.getInterestRateFrequencyType(), product.getAnnualInterestRate(), product.getInterestType(), product.isFloatingInterestRateCalculationAllowed(), product.getDefaultDifferentialLendingRate(), product.getInterestCalculationPeriodType(), - product.getAllowPartialPeriodInterestCalcualtion(), acc.expectedFirstRepaymentOnDate, product.getGraceOnPrincipalPayment(), product.getRecurringMoratoriumOnPrincipalPeriods(), - product.getGraceOnInterestPayment(), product.getGraceOnInterestCharged(), acc.interestChargedFromDate, acc.timeline, - acc.summary, acc.feeChargesAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, - calendarData, productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, null, null, - repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, - interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, - loanCollateralOptions, calendarOptions, acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, notes, - acc.accountLinkingOptions, acc.linkedAccount, acc.disbursementDetails, product.getMultiDisburseLoan(), - product.canDefineInstallmentAmount(), acc.fixedEmiAmount, product.getOutstandingLoanBalance(), acc.emiAmountVariations, - acc.memberVariations, product, acc.inArrears, product.getGraceOnArrearsAgeing(), product.overdueFeeCharges(), acc.isNPA, - product.getDaysInMonthType(), product.getDaysInYearType(), product.isInterestRecalculationEnabled(), - product.toLoanInterestRecalculationData(), acc.originalSchedule, acc.createStandingInstructionAtDisbursement, - paidInAdvance, acc.interestRatesPeriods, product.isVariableInstallmentsAllowed(), - product.getMinimumGapBetweenInstallments(), product.getMaximumGapBetweenInstallments(), acc.subStatus, acc.canUseForTopup, - acc.clientActiveLoanOptions, acc.isTopup, acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, product.isEqualAmortization(), acc.rates, - acc.isRatesEnabled); + product.getAllowPartialPeriodInterestCalcualtion(), acc.expectedFirstRepaymentOnDate, product.getGraceOnPrincipalPayment(), + product.getRecurringMoratoriumOnPrincipalPeriods(), product.getGraceOnInterestPayment(), + product.getGraceOnInterestCharged(), acc.interestChargedFromDate, acc.timeline, acc.summary, + acc.feeChargesAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, + productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, null, null, repaymentStrategyOptions, + interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, + fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, + acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, notes, acc.accountLinkingOptions, + acc.linkedAccount, acc.disbursementDetails, product.getMultiDisburseLoan(), product.canDefineInstallmentAmount(), + acc.fixedEmiAmount, product.getOutstandingLoanBalance(), acc.emiAmountVariations, acc.memberVariations, product, + acc.inArrears, product.getGraceOnArrearsAgeing(), product.overdueFeeCharges(), acc.isNPA, product.getDaysInMonthType(), + product.getDaysInYearType(), product.isInterestRecalculationEnabled(), product.toLoanInterestRecalculationData(), + acc.originalSchedule, acc.createStandingInstructionAtDisbursement, paidInAdvance, acc.interestRatesPeriods, + product.isVariableInstallmentsAllowed(), product.getMinimumGapBetweenInstallments(), + product.getMaximumGapBetweenInstallments(), acc.subStatus, acc.canUseForTopup, acc.clientActiveLoanOptions, acc.isTopup, + acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, product.isEqualAmortization(), acc.rates, acc.isRatesEnabled); } @@ -1199,8 +1191,9 @@ public class LoanAccountData { final BigDecimal annualInterestRate, final EnumOptionData interestType, final boolean isFloatingInterestRate, final BigDecimal interestRateDifferential, final EnumOptionData interestCalculationPeriodType, Boolean allowPartialPeriodInterestCalcualtion, final LocalDate expectedFirstRepaymentOnDate, - final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, - final LocalDate interestChargedFromDate, final LoanApplicationTimelineData timeline, final LoanSummaryData loanSummary, + final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, + final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, final LocalDate interestChargedFromDate, + final LoanApplicationTimelineData timeline, final LoanSummaryData loanSummary, final BigDecimal feeChargesDueAtDisbursementCharged, final Boolean syncDisbursementWithMeeting, final Integer loanCounter, final Integer loanProductCounter, final Boolean multiDisburseLoan, Boolean canDefineInstallmentAmount, final BigDecimal fixedEmiAmont, final BigDecimal outstandingLoanBalance, final Boolean inArrears, @@ -1256,19 +1249,19 @@ public class LoanAccountData { repaymentEvery, repaymentFrequencyType, repaymentFrequencyNthDayType, repaymentFrequencyDayOfWeekType, transactionStrategyId, transactionStrategyName, amortizationType, interestRatePerPeriod, interestRateFrequencyType, annualInterestRate, interestType, isFloatingInterestRate, interestRateDifferential, interestCalculationPeriodType, - allowPartialPeriodInterestCalcualtion, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, - graceOnInterestCharged, interestChargedFromDate, timeline, loanSummary, feeChargesDueAtDisbursementCharged, - repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, - repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, repaymentFrequencyDayOfWeekTypeOptions, - repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, - interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, - loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loanCounter, loanProductCounter, notes, - accountLinkingOptions, linkedAccount, disbursementData, multiDisburseLoan, canDefineInstallmentAmount, fixedEmiAmont, + allowPartialPeriodInterestCalcualtion, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, timeline, + loanSummary, feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, + calendarData, productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, + repaymentFrequencyDayOfWeekTypeOptions, repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, + interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, + loanPurposeOptions, loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loanCounter, loanProductCounter, + notes, accountLinkingOptions, linkedAccount, disbursementData, multiDisburseLoan, canDefineInstallmentAmount, fixedEmiAmont, outstandingLoanBalance, emiAmountVariations, memberVariations, product, inArrears, graceOnArrearsAgeing, overdueCharges, isNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, interestRecalculationData, originalSchedule, createStandingInstructionAtDisbursement, paidInAdvance, interestRatesPeriods, isVariableInstallmentsAllowed, minimumGap, - maximumGap, subStatus, canUseForTopup, clientActiveLoanOptions, isTopup, closureLoanId, closureLoanAccountNo, topupAmount, isEqualAmortization, - rates, isRatesEnabled); + maximumGap, subStatus, canUseForTopup, clientActiveLoanOptions, isTopup, closureLoanId, closureLoanAccountNo, topupAmount, + isEqualAmortization, rates, isRatesEnabled); } /* @@ -1292,7 +1285,7 @@ public class LoanAccountData { final PortfolioAccountData linkedAccount, final Collection disbursementDetails, final Collection emiAmountVariations, final Collection overdueCharges, final PaidInAdvanceData paidInAdvance, Collection interestRatesPeriods, - final Collection clientActiveLoanOptions,final List rates, final Boolean isRatesEnabled) { + final Collection clientActiveLoanOptions, final List rates, final Boolean isRatesEnabled) { LoanProductConfigurableAttributes loanProductConfigurableAttributes = null; if (acc.product != null) { loanProductConfigurableAttributes = acc.product.getloanProductConfigurableAttributes(); @@ -1304,10 +1297,10 @@ public class LoanAccountData { acc.loanOfficerName, acc.currency, acc.proposedPrincipal, acc.principal, acc.approvedPrincipal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, acc.numberOfRepayments, acc.repaymentEvery, acc.repaymentFrequencyType, acc.repaymentFrequencyNthDayType, acc.repaymentFrequencyDayOfWeekType, - acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, - acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, - acc.isFloatingInterestRate, acc.interestRateDifferential, acc.interestCalculationPeriodType, - acc.allowPartialPeriodInterestCalcualtion, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, + acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, acc.interestRatePerPeriod, + acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.isFloatingInterestRate, + acc.interestRateDifferential, acc.interestCalculationPeriodType, acc.allowPartialPeriodInterestCalcualtion, + acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, acc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentFrequencyNthDayTypeOptions, @@ -1320,8 +1313,8 @@ public class LoanAccountData { acc.graceOnArrearsAgeing, overdueCharges, acc.isNPA, acc.daysInMonthType, acc.daysInYearType, acc.isInterestRecalculationEnabled, acc.interestRecalculationData, acc.originalSchedule, acc.createStandingInstructionAtDisbursement, paidInAdvance, interestRatesPeriods, acc.isVariableInstallmentsAllowed, - acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, clientActiveLoanOptions, acc.isTopup, - acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, rates, isRatesEnabled); + acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, clientActiveLoanOptions, acc.isTopup, acc.closureLoanId, + acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, rates, isRatesEnabled); } public static LoanAccountData associationsAndTemplate(final LoanAccountData acc, final Collection productOptions, @@ -1334,7 +1327,7 @@ public class LoanAccountData { acc.interestTypeOptions, acc.interestCalculationPeriodTypeOptions, acc.fundOptions, acc.chargeOptions, null, allowedLoanOfficers, acc.loanPurposeOptions, acc.loanCollateralOptions, calendarOptions, acc.notes, accountLinkingOptions, acc.linkedAccount, acc.disbursementDetails, acc.emiAmountVariations, acc.overdueCharges, acc.paidInAdvance, - acc.interestRatesPeriods, acc.clientActiveLoanOptions,acc.rates, isRatesEnabled); + acc.interestRatesPeriods, acc.clientActiveLoanOptions, acc.rates, isRatesEnabled); } public static LoanAccountData associateGroup(final LoanAccountData acc, final GroupGeneralData group) { @@ -1345,10 +1338,10 @@ public class LoanAccountData { acc.loanOfficerName, acc.currency, acc.proposedPrincipal, acc.principal, acc.approvedPrincipal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, acc.numberOfRepayments, acc.repaymentEvery, acc.repaymentFrequencyType, acc.repaymentFrequencyNthDayType, acc.repaymentFrequencyDayOfWeekType, - acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, - acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, - acc.isFloatingInterestRate, acc.interestRateDifferential, acc.interestCalculationPeriodType, - acc.allowPartialPeriodInterestCalcualtion, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, + acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, acc.interestRatePerPeriod, + acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.isFloatingInterestRate, + acc.interestRateDifferential, acc.interestCalculationPeriodType, acc.allowPartialPeriodInterestCalcualtion, + acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, acc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, acc.meeting, acc.productOptions, acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, @@ -1361,10 +1354,9 @@ public class LoanAccountData { acc.maxOutstandingLoanBalance, acc.emiAmountVariations, acc.memberVariations, acc.product, acc.inArrears, acc.graceOnArrearsAgeing, acc.overdueCharges, acc.isNPA, acc.daysInMonthType, acc.daysInYearType, acc.isInterestRecalculationEnabled, acc.interestRecalculationData, acc.originalSchedule, - acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, - acc.isVariableInstallmentsAllowed, acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, - acc.clientActiveLoanOptions, acc.isTopup, acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, acc.rates, - acc.isRatesEnabled); + acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, acc.isVariableInstallmentsAllowed, + acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, acc.clientActiveLoanOptions, acc.isTopup, + acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, acc.rates, acc.isRatesEnabled); } public static LoanAccountData associateMemberVariations(final LoanAccountData acc, final Map memberLoanCycle) { @@ -1411,10 +1403,10 @@ public class LoanAccountData { acc.loanOfficerName, acc.currency, acc.proposedPrincipal, acc.principal, acc.approvedPrincipal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, acc.numberOfRepayments, acc.repaymentEvery, acc.repaymentFrequencyType, acc.repaymentFrequencyNthDayType, acc.repaymentFrequencyDayOfWeekType, - acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, - acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, - acc.isFloatingInterestRate, acc.interestRateDifferential, acc.interestCalculationPeriodType, - acc.allowPartialPeriodInterestCalcualtion, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, + acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, acc.interestRatePerPeriod, + acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.isFloatingInterestRate, + acc.interestRateDifferential, acc.interestCalculationPeriodType, acc.allowPartialPeriodInterestCalcualtion, + acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, acc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, acc.meeting, acc.productOptions, acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, @@ -1427,18 +1419,17 @@ public class LoanAccountData { acc.maxOutstandingLoanBalance, acc.emiAmountVariations, memberVariations, acc.product, acc.inArrears, acc.graceOnArrearsAgeing, acc.overdueCharges, acc.isNPA, acc.daysInMonthType, acc.daysInYearType, acc.isInterestRecalculationEnabled, acc.interestRecalculationData, acc.originalSchedule, - acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, - acc.isVariableInstallmentsAllowed, acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, - acc.clientActiveLoanOptions, acc.isTopup, acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, acc.rates, - acc.isRatesEnabled); + acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, acc.isVariableInstallmentsAllowed, + acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, acc.clientActiveLoanOptions, acc.isTopup, + acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, acc.rates, acc.isRatesEnabled); } public static LoanAccountData withInterestRecalculationCalendarData(final LoanAccountData acc, final CalendarData calendarData, final CalendarData compoundingCalendarData) { - final LoanInterestRecalculationData interestRecalculationData = LoanInterestRecalculationData.withCalendarData( - acc.interestRecalculationData, calendarData, compoundingCalendarData); + final LoanInterestRecalculationData interestRecalculationData = LoanInterestRecalculationData + .withCalendarData(acc.interestRecalculationData, calendarData, compoundingCalendarData); return new LoanAccountData(acc.id, acc.accountNo, acc.status, acc.externalId, acc.clientId, acc.clientAccountNo, acc.clientName, acc.clientOfficeId, acc.group, acc.loanType, acc.loanProductId, acc.loanProductName, acc.loanProductDescription, @@ -1446,10 +1437,10 @@ public class LoanAccountData { acc.loanOfficerName, acc.currency, acc.proposedPrincipal, acc.principal, acc.approvedPrincipal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, acc.numberOfRepayments, acc.repaymentEvery, acc.repaymentFrequencyType, acc.repaymentFrequencyNthDayType, acc.repaymentFrequencyDayOfWeekType, - acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, - acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, - acc.isFloatingInterestRate, acc.interestRateDifferential, acc.interestCalculationPeriodType, - acc.allowPartialPeriodInterestCalcualtion, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, + acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, acc.interestRatePerPeriod, + acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.isFloatingInterestRate, + acc.interestRateDifferential, acc.interestCalculationPeriodType, acc.allowPartialPeriodInterestCalcualtion, + acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, acc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, acc.meeting, acc.productOptions, acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, @@ -1462,10 +1453,9 @@ public class LoanAccountData { acc.maxOutstandingLoanBalance, acc.emiAmountVariations, acc.memberVariations, acc.product, acc.inArrears, acc.graceOnArrearsAgeing, acc.overdueCharges, acc.isNPA, acc.daysInMonthType, acc.daysInYearType, acc.isInterestRecalculationEnabled, interestRecalculationData, acc.originalSchedule, - acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, - acc.isVariableInstallmentsAllowed, acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, - acc.clientActiveLoanOptions, acc.isTopup, acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, acc.rates, - acc.isRatesEnabled); + acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, acc.isVariableInstallmentsAllowed, + acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, acc.clientActiveLoanOptions, acc.isTopup, + acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, acc.rates, acc.isRatesEnabled); } public static LoanAccountData withLoanCalendarData(final LoanAccountData acc, final CalendarData calendarData) { @@ -1475,26 +1465,25 @@ public class LoanAccountData { acc.loanOfficerName, acc.currency, acc.proposedPrincipal, acc.principal, acc.approvedPrincipal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, acc.numberOfRepayments, acc.repaymentEvery, acc.repaymentFrequencyType, calendarData.getRepeatsOnNthDayOfMonth(), calendarData.getRepeatsOnDay(), - acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, - acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, - acc.isFloatingInterestRate, acc.interestRateDifferential, acc.interestCalculationPeriodType, - acc.allowPartialPeriodInterestCalcualtion, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, - acc.recurringMoratoriumOnPrincipalPeriods, acc.graceOnInterestPayment, acc.graceOnInterestCharged, - acc.interestChargedFromDate, acc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, - acc.transactions, acc.charges, acc.collateral, acc.guarantors, acc.meeting, acc.productOptions, - acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, acc.repaymentFrequencyNthDayTypeOptions, - acc.repaymentFrequencyDaysOfWeekTypeOptions, acc.transactionProcessingStrategyOptions, - acc.interestRateFrequencyTypeOptions, acc.amortizationTypeOptions, acc.interestTypeOptions, - acc.interestCalculationPeriodTypeOptions, acc.fundOptions, acc.chargeOptions, null, acc.loanOfficerOptions, - acc.loanPurposeOptions, acc.loanCollateralOptions, acc.calendarOptions, acc.syncDisbursementWithMeeting, acc.loanCounter, - acc.loanProductCounter, acc.notes, acc.accountLinkingOptions, acc.linkedAccount, acc.disbursementDetails, - acc.multiDisburseLoan, acc.canDefineInstallmentAmount, acc.fixedEmiAmount, acc.maxOutstandingLoanBalance, - acc.emiAmountVariations, acc.memberVariations, acc.product, acc.inArrears, acc.graceOnArrearsAgeing, acc.overdueCharges, - acc.isNPA, acc.daysInMonthType, acc.daysInYearType, acc.isInterestRecalculationEnabled, acc.interestRecalculationData, - acc.originalSchedule, acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, - acc.isVariableInstallmentsAllowed, acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, - acc.clientActiveLoanOptions, acc.isTopup, acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, - acc.rates, acc.isRatesEnabled); + acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, acc.interestRatePerPeriod, + acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.isFloatingInterestRate, + acc.interestRateDifferential, acc.interestCalculationPeriodType, acc.allowPartialPeriodInterestCalcualtion, + acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, + acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, acc.timeline, acc.summary, + acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, + acc.meeting, acc.productOptions, acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, + acc.repaymentFrequencyNthDayTypeOptions, acc.repaymentFrequencyDaysOfWeekTypeOptions, + acc.transactionProcessingStrategyOptions, acc.interestRateFrequencyTypeOptions, acc.amortizationTypeOptions, + acc.interestTypeOptions, acc.interestCalculationPeriodTypeOptions, acc.fundOptions, acc.chargeOptions, null, + acc.loanOfficerOptions, acc.loanPurposeOptions, acc.loanCollateralOptions, acc.calendarOptions, + acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, acc.notes, acc.accountLinkingOptions, + acc.linkedAccount, acc.disbursementDetails, acc.multiDisburseLoan, acc.canDefineInstallmentAmount, acc.fixedEmiAmount, + acc.maxOutstandingLoanBalance, acc.emiAmountVariations, acc.memberVariations, acc.product, acc.inArrears, + acc.graceOnArrearsAgeing, acc.overdueCharges, acc.isNPA, acc.daysInMonthType, acc.daysInYearType, + acc.isInterestRecalculationEnabled, acc.interestRecalculationData, acc.originalSchedule, + acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, acc.isVariableInstallmentsAllowed, + acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, acc.clientActiveLoanOptions, acc.isTopup, + acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, acc.rates, acc.isRatesEnabled); } public static LoanAccountData withOriginalSchedule(final LoanAccountData acc, final LoanScheduleData originalSchedule) { @@ -1505,10 +1494,10 @@ public class LoanAccountData { acc.loanOfficerName, acc.currency, acc.proposedPrincipal, acc.principal, acc.approvedPrincipal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, acc.numberOfRepayments, acc.repaymentEvery, acc.repaymentFrequencyType, acc.repaymentFrequencyNthDayType, acc.repaymentFrequencyDayOfWeekType, - acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, - acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, - acc.isFloatingInterestRate, acc.interestRateDifferential, acc.interestCalculationPeriodType, - acc.allowPartialPeriodInterestCalcualtion, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, + acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, acc.interestRatePerPeriod, + acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.isFloatingInterestRate, + acc.interestRateDifferential, acc.interestCalculationPeriodType, acc.allowPartialPeriodInterestCalcualtion, + acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.recurringMoratoriumOnPrincipalPeriods, acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, acc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, acc.meeting, acc.productOptions, acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, @@ -1521,10 +1510,9 @@ public class LoanAccountData { acc.maxOutstandingLoanBalance, acc.emiAmountVariations, acc.memberVariations, acc.product, acc.inArrears, acc.graceOnArrearsAgeing, acc.overdueCharges, acc.isNPA, acc.daysInMonthType, acc.daysInYearType, acc.isInterestRecalculationEnabled, acc.interestRecalculationData, originalSchedule, - acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, - acc.isVariableInstallmentsAllowed, acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, - acc.clientActiveLoanOptions, acc.isTopup, acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, - acc.rates, acc.isRatesEnabled); + acc.createStandingInstructionAtDisbursement, acc.paidInAdvance, acc.interestRatesPeriods, acc.isVariableInstallmentsAllowed, + acc.minimumGap, acc.maximumGap, acc.subStatus, acc.canUseForTopup, acc.clientActiveLoanOptions, acc.isTopup, + acc.closureLoanId, acc.closureLoanAccountNo, acc.topupAmount, acc.isEqualAmortization, acc.rates, acc.isRatesEnabled); } private LoanAccountData(final Long id, // @@ -1548,10 +1536,12 @@ public class LoanAccountData { final BigDecimal annualInterestRate, final EnumOptionData interestType, final boolean isFloatingInterestRate, final BigDecimal interestRateDifferential, final EnumOptionData interestCalculationPeriodType, final Boolean allowPartialPeriodInterestCalcualtion, final LocalDate expectedFirstRepaymentOnDate, - final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, - final LocalDate interestChargedFromDate, final LoanApplicationTimelineData timeline, final LoanSummaryData summary, final BigDecimal feeChargesDueAtDisbursementCharged, - final LoanScheduleData repaymentSchedule, final Collection transactions, final Collection charges, - final Collection collateral, final Collection guarantors, final CalendarData meeting, final Collection productOptions, + final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, + final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, final LocalDate interestChargedFromDate, + final LoanApplicationTimelineData timeline, final LoanSummaryData summary, final BigDecimal feeChargesDueAtDisbursementCharged, + final LoanScheduleData repaymentSchedule, final Collection transactions, + final Collection charges, final Collection collateral, + final Collection guarantors, final CalendarData meeting, final Collection productOptions, final Collection termFrequencyTypeOptions, final Collection repaymentFrequencyTypeOptions, final Collection repaymentFrequencyNthDayTypeOptions, final Collection repaymentFrequencyDaysOfWeekTypeOptions, @@ -1573,9 +1563,9 @@ public class LoanAccountData { final Boolean createStandingInstructionAtDisbursement, final PaidInAdvanceData paidInAdvance, final Collection interestRatesPeriods, final Boolean isVariableInstallmentsAllowed, final Integer minimumGap, final Integer maximumGap, final EnumOptionData subStatus, final Boolean canUseForTopup, - final Collection clientActiveLoanOptions, final boolean isTopup, - final Long closureLoanId, final String closureLoanAccountNo, final BigDecimal topupAmount, final boolean isEqualAmortization, - final List rates, final Boolean isRatesEnabled) { + final Collection clientActiveLoanOptions, final boolean isTopup, final Long closureLoanId, + final String closureLoanAccountNo, final BigDecimal topupAmount, final boolean isEqualAmortization, final List rates, + final Boolean isRatesEnabled) { this.id = id; this.accountNo = accountNo; @@ -1844,7 +1834,7 @@ public class LoanAccountData { } public BigDecimal getTotalOutstandingAmount() { - if(this.summary!=null) { + if (this.summary != null) { return this.summary.getTotalOutstanding(); } else { return null; @@ -1869,9 +1859,7 @@ public class LoanAccountData { } public BigDecimal getTotalPaidFeeCharges() { - if (this.summary != null) { - return this.summary.getTotalPaidFeeCharges(); - } + if (this.summary != null) { return this.summary.getTotalPaidFeeCharges(); } return BigDecimal.ZERO; } @@ -1880,7 +1868,8 @@ public class LoanAccountData { } /** - * Used to produce a {@link LoanAccountData} with only collateral options for now. + * Used to produce a {@link LoanAccountData} with only collateral options + * for now. * * @return {@link LoanAccountData} object */ @@ -1894,25 +1883,23 @@ public class LoanAccountData { return this.isLoanProductLinkedToFloatingRate; } - public LocalDate getDisbursementDate(){ + public LocalDate getDisbursementDate() { return this.timeline.getDisbursementDate(); } - public boolean isFloatingInterestRate() { return this.isFloatingInterestRate; } - public BigDecimal getInterestRateDifferential() { return this.interestRateDifferential; } public void setDatatables(final List datatables) { - this.datatables = datatables; + this.datatables = datatables; } - public String getStatusStringValue(){ + public String getStatusStringValue() { return this.status.value(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanApplicationTimelineData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanApplicationTimelineData.java index b3d45b3af..e587605a8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanApplicationTimelineData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanApplicationTimelineData.java @@ -100,16 +100,16 @@ public class LoanApplicationTimelineData { writeOffByUsername, writeOffByFirstname, writeOffByLastname); } - public LoanApplicationTimelineData(final LocalDate submittedOnDate, final String submittedByUsername, - final String submittedByFirstname, final String submittedByLastname, final LocalDate rejectedOnDate, - final String rejectedByUsername, final String rejectedByFirstname, final String rejectedByLastname, - final LocalDate withdrawnOnDate, final String withdrawnByUsername, final String withdrawnByFirstname, - final String withdrawnByLastname, final LocalDate approvedOnDate, final String approvedByUsername, - final String approvedByFirstname, final String approvedByLastname, final LocalDate expectedDisbursementDate, - final LocalDate actualDisbursementDate, final String disbursedByUsername, final String disbursedByFirstname, - final String disbursedByLastname, final LocalDate closedOnDate, final String closedByUsername, final String closedByFirstname, - final String closedByLastname, final LocalDate expectedMaturityDate, final LocalDate writeOffOnDate, - final String writeOffByUsername, final String writeOffByFirstname, final String writeOffByLastname) { + public LoanApplicationTimelineData(final LocalDate submittedOnDate, final String submittedByUsername, final String submittedByFirstname, + final String submittedByLastname, final LocalDate rejectedOnDate, final String rejectedByUsername, + final String rejectedByFirstname, final String rejectedByLastname, final LocalDate withdrawnOnDate, + final String withdrawnByUsername, final String withdrawnByFirstname, final String withdrawnByLastname, + final LocalDate approvedOnDate, final String approvedByUsername, final String approvedByFirstname, + final String approvedByLastname, final LocalDate expectedDisbursementDate, final LocalDate actualDisbursementDate, + final String disbursedByUsername, final String disbursedByFirstname, final String disbursedByLastname, + final LocalDate closedOnDate, final String closedByUsername, final String closedByFirstname, final String closedByLastname, + final LocalDate expectedMaturityDate, final LocalDate writeOffOnDate, final String writeOffByUsername, + final String writeOffByFirstname, final String writeOffByLastname) { this.submittedOnDate = submittedOnDate; this.submittedByUsername = submittedByUsername; this.submittedByFirstname = submittedByFirstname; @@ -145,14 +145,14 @@ public class LoanApplicationTimelineData { public RepaymentScheduleRelatedLoanData repaymentScheduleRelatedData(final CurrencyData currency, final BigDecimal principal, final BigDecimal approvedPrincipal, final BigDecimal inArrearsTolerance, final BigDecimal totalFeeChargesAtDisbursement) { return new RepaymentScheduleRelatedLoanData(this.expectedDisbursementDate, this.actualDisbursementDate, currency, principal, - inArrearsTolerance, totalFeeChargesAtDisbursement); + inArrearsTolerance, totalFeeChargesAtDisbursement); } - public LocalDate getDisbursementDate(){ + public LocalDate getDisbursementDate() { LocalDate disbursementDate = this.expectedDisbursementDate; - if(this.actualDisbursementDate != null){ + if (this.actualDisbursementDate != null) { disbursementDate = this.actualDisbursementDate; } return disbursementDate; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanApprovalData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanApprovalData.java index 35e380156..f8f167d6f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanApprovalData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanApprovalData.java @@ -29,25 +29,25 @@ public class LoanApprovalData { private final LocalDate approvalDate; private final BigDecimal approvalAmount; - //import fields + // import fields private LocalDate approvedOnDate; private String note; private String dateFormat; private String locale; private transient Integer rowIndex; - public static LoanApprovalData importInstance(LocalDate approvedOnDate, Integer rowIndex, - String locale,String dateFormat){ - return new LoanApprovalData(approvedOnDate,rowIndex,locale,dateFormat); + public static LoanApprovalData importInstance(LocalDate approvedOnDate, Integer rowIndex, String locale, String dateFormat) { + return new LoanApprovalData(approvedOnDate, rowIndex, locale, dateFormat); } - private LoanApprovalData(LocalDate approvedOnDate, Integer rowIndex,String locale,String dateFormat) { + + private LoanApprovalData(LocalDate approvedOnDate, Integer rowIndex, String locale, String dateFormat) { this.approvedOnDate = approvedOnDate; this.rowIndex = rowIndex; - this.dateFormat=dateFormat; - this.locale= locale; - this.note=""; - this.approvalAmount=null; - this.approvalDate=null; + this.dateFormat = dateFormat; + this.locale = locale; + this.note = ""; + this.approvalAmount = null; + this.approvalDate = null; } public LoanApprovalData(final BigDecimal approvalAmount, final LocalDate approvalDate) { @@ -63,4 +63,4 @@ public class LoanApprovalData { return this.approvalAmount; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargeData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargeData.java old mode 100755 new mode 100644 index c1235fceb..dfaba085f --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargeData.java @@ -81,7 +81,6 @@ public class LoanChargeData { private BigDecimal amountUnrecognized; - public static LoanChargeData template(final Collection chargeOptions) { return new LoanChargeData(null, null, null, null, null, null, null, null, chargeOptions, false, null, false, false, null, null, null, null, null); @@ -407,4 +406,4 @@ public class LoanChargeData { public BigDecimal getAmountUnrecognized() { return this.amountUnrecognized; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargePaidByData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargePaidByData.java old mode 100755 new mode 100644 index 3545b6cfb..085ca5ad4 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargePaidByData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargePaidByData.java @@ -30,13 +30,13 @@ public class LoanChargePaidByData { private final String name; public LoanChargePaidByData(final Long id, final BigDecimal amount, final Integer installmentNumber, final Long chargeId, - final Long transactionId, String name) { + final Long transactionId, String name) { this.id = id; this.amount = amount; this.installmentNumber = installmentNumber; this.chargeId = chargeId; this.transactionId = transactionId; - this.name=name; + this.name = name; } public LoanChargePaidByData(final Long id, final BigDecimal amount, final Integer installmentNumber, final Long chargeId, @@ -46,7 +46,7 @@ public class LoanChargePaidByData { this.installmentNumber = installmentNumber; this.chargeId = chargeId; this.transactionId = transactionId; - this.name=null; + this.name = null; } public Long getId() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargePaidDetail.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargePaidDetail.java old mode 100755 new mode 100644 index 927810887..5b75fa9f1 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargePaidDetail.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanChargePaidDetail.java @@ -21,30 +21,26 @@ package org.apache.fineract.portfolio.loanaccount.data; import org.apache.fineract.organisation.monetary.domain.Money; import org.apache.fineract.portfolio.loanaccount.domain.LoanRepaymentScheduleInstallment; - public class LoanChargePaidDetail { private final Money amount; private final LoanRepaymentScheduleInstallment installment; private final boolean isFeeCharge; - public LoanChargePaidDetail( Money amount,LoanRepaymentScheduleInstallment installment,boolean isFeeCharge){ + public LoanChargePaidDetail(Money amount, LoanRepaymentScheduleInstallment installment, boolean isFeeCharge) { this.amount = amount; this.installment = installment; this.isFeeCharge = isFeeCharge; } - public Money getAmount() { return this.amount; } - public LoanRepaymentScheduleInstallment getInstallment() { return this.installment; } - public boolean isFeeCharge() { return this.isFeeCharge; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanConvenienceData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanConvenienceData.java index 765735f35..ac2408c3c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanConvenienceData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanConvenienceData.java @@ -67,4 +67,4 @@ public class LoanConvenienceData { public int getActualLoanTermInMonths() { return this.actualLoanTermInMonths; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanInterestRecalculationData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanInterestRecalculationData.java index 2af6cbafc..105e87f10 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanInterestRecalculationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanInterestRecalculationData.java @@ -53,7 +53,8 @@ public class LoanInterestRecalculationData { final Integer recalculationRestFrequencyOnDay, final CalendarData compoundingCalendarData, final EnumOptionData recalculationCompoundingFrequencyType, final Integer recalculationCompoundingFrequencyInterval, final EnumOptionData recalculationCompoundingFrequencyNthDay, final EnumOptionData recalculationCompoundingFrequencyWeekday, - final Integer recalculationCompoundingFrequencyOnDay, final Boolean isCompoundingToBePostedAsTransaction, final Boolean allowCompoundingOnEod) { + final Integer recalculationCompoundingFrequencyOnDay, final Boolean isCompoundingToBePostedAsTransaction, + final Boolean allowCompoundingOnEod) { this.id = id; this.loanId = loanId; this.interestRecalculationCompoundingType = interestRecalculationCompoundingType; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanScheduleAccrualData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanScheduleAccrualData.java old mode 100755 new mode 100644 index b419e0218..0e4b4a7ca --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanScheduleAccrualData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanScheduleAccrualData.java @@ -174,20 +174,16 @@ public class LoanScheduleAccrualData { this.dueDatePenaltyIncome = dueDatePenaltyIncome; } - public BigDecimal getWaivedInterestIncome() { return this.waivedInterestIncome; } - - public BigDecimal getAccruableIncome () { + public BigDecimal getAccruableIncome() { return this.accruableIncome; } - - public void updateAccruableIncome (BigDecimal accruableIncome ) { - this.accruableIncome = accruableIncome ; + public void updateAccruableIncome(BigDecimal accruableIncome) { + this.accruableIncome = accruableIncome; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanStatusEnumData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanStatusEnumData.java index 1409a470c..1edfcbe9a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanStatusEnumData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanStatusEnumData.java @@ -61,4 +61,4 @@ public class LoanStatusEnumData { public String value() { return this.value; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanSummaryData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanSummaryData.java index b423de5e2..337cc0c1b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanSummaryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanSummaryData.java @@ -76,7 +76,7 @@ public class LoanSummaryData { final BigDecimal penaltyChargesOverdue, final BigDecimal totalExpectedRepayment, final BigDecimal totalRepayment, final BigDecimal totalExpectedCostOfLoan, final BigDecimal totalCostOfLoan, final BigDecimal totalWaived, final BigDecimal totalWrittenOff, final BigDecimal totalOutstanding, final BigDecimal totalOverdue, - final LocalDate overdueSinceDate,final Long writeoffReasonId,final String writeoffReason) { + final LocalDate overdueSinceDate, final Long writeoffReasonId, final String writeoffReason) { this.currency = currency; this.principalDisbursed = principalDisbursed; this.principalPaid = principalPaid; @@ -120,6 +120,6 @@ public class LoanSummaryData { } public BigDecimal getTotalPaidFeeCharges() { - return feeChargesPaid ; + return feeChargesPaid; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTermVariationsData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTermVariationsData.java index 716708384..ab1bf3973 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTermVariationsData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTermVariationsData.java @@ -44,8 +44,8 @@ public class LoanTermVariationsData implements Comparable exceptionData){ - if(this.exceptionData != null && exceptionData != null && exceptionData.size() > 0){ + public void updateLoanTermVariationsData(final List exceptionData) { + if (this.exceptionData != null && exceptionData != null && exceptionData.size() > 0) { this.exceptionData.addAll(exceptionData); deriveLoanTermVariations(); } @@ -162,7 +162,7 @@ public class LoanTermVariationsDataWrapper { this.dueDateIterator = this.dueDateVariation.listIterator(); } - public void resetVariations(){ + public void resetVariations() { for (LoanTermVariationsData loanTermVariationsData : this.exceptionData) { loanTermVariationsData.setProcessed(false); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTransactionData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTransactionData.java index f9759a0f1..04c74630b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTransactionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTransactionData.java @@ -64,9 +64,9 @@ public class LoanTransactionData { // templates final Collection paymentTypeOptions; - private Collection writeOffReasonOptions = null; + private Collection writeOffReasonOptions = null; - //import fields + // import fields private transient Integer rowIndex; private String dateFormat; private String locale; @@ -81,22 +81,23 @@ public class LoanTransactionData { private transient Long accountId; private transient String transactionType; - public static LoanTransactionData importInstance(BigDecimal repaymentAmount,LocalDate lastRepaymentDate, - Long repaymentTypeId,Integer rowIndex,String locale,String dateFormat){ - return new LoanTransactionData(repaymentAmount, lastRepaymentDate, repaymentTypeId, rowIndex,locale,dateFormat); + public static LoanTransactionData importInstance(BigDecimal repaymentAmount, LocalDate lastRepaymentDate, Long repaymentTypeId, + Integer rowIndex, String locale, String dateFormat) { + return new LoanTransactionData(repaymentAmount, lastRepaymentDate, repaymentTypeId, rowIndex, locale, dateFormat); } - private LoanTransactionData(BigDecimal transactionAmount,LocalDate transactionDate, - Long paymentTypeId,Integer rowIndex,String locale,String dateFormat) { - this.transactionAmount=transactionAmount; - this.transactionDate=transactionDate; - this.paymentTypeId=paymentTypeId; + + private LoanTransactionData(BigDecimal transactionAmount, LocalDate transactionDate, Long paymentTypeId, Integer rowIndex, + String locale, String dateFormat) { + this.transactionAmount = transactionAmount; + this.transactionDate = transactionDate; + this.paymentTypeId = paymentTypeId; this.rowIndex = rowIndex; - this.dateFormat= dateFormat; - this.locale= locale; + this.dateFormat = dateFormat; + this.locale = locale; this.amount = null; this.date = null; this.type = null; - this.id =null; + this.id = null; this.officeId = null; this.officeName = null; this.currency = null; @@ -117,32 +118,30 @@ public class LoanTransactionData { this.paymentTypeOptions = null; this.writeOffReasonOptions = null; } - public static LoanTransactionData importInstance(BigDecimal repaymentAmount,LocalDate repaymentDate, - Long repaymentTypeId, String accountNumber,Integer checkNumber,Integer routingCode, - Integer receiptNumber, Integer bankNumber,Long loanAccountId,String transactionType, - Integer rowIndex,String locale, String dateFormat){ - return new LoanTransactionData(repaymentAmount, repaymentDate, repaymentTypeId, accountNumber, - checkNumber, routingCode, receiptNumber, bankNumber, loanAccountId, "", - rowIndex,locale,dateFormat); + + public static LoanTransactionData importInstance(BigDecimal repaymentAmount, LocalDate repaymentDate, Long repaymentTypeId, + String accountNumber, Integer checkNumber, Integer routingCode, Integer receiptNumber, Integer bankNumber, Long loanAccountId, + String transactionType, Integer rowIndex, String locale, String dateFormat) { + return new LoanTransactionData(repaymentAmount, repaymentDate, repaymentTypeId, accountNumber, checkNumber, routingCode, + receiptNumber, bankNumber, loanAccountId, "", rowIndex, locale, dateFormat); } - private LoanTransactionData(BigDecimal transactionAmount,LocalDate transactionDate, Long paymentTypeId, - String accountNumber,Integer checkNumber,Integer routingCode,Integer receiptNumber, - Integer bankNumber,Long accountId,String transactionType,Integer rowIndex,String locale, - String dateFormat) { + private LoanTransactionData(BigDecimal transactionAmount, LocalDate transactionDate, Long paymentTypeId, String accountNumber, + Integer checkNumber, Integer routingCode, Integer receiptNumber, Integer bankNumber, Long accountId, String transactionType, + Integer rowIndex, String locale, String dateFormat) { this.transactionAmount = transactionAmount; this.transactionDate = transactionDate; this.paymentTypeId = paymentTypeId; - this.accountNumber=accountNumber; - this.checkNumber=checkNumber; - this.routingCode=routingCode; - this.receiptNumber=receiptNumber; - this.bankNumber=bankNumber; - this.accountId=accountId; - this.transactionType=transactionType; - this.rowIndex=rowIndex; - this.dateFormat=dateFormat; - this.locale= locale; + this.accountNumber = accountNumber; + this.checkNumber = checkNumber; + this.routingCode = routingCode; + this.receiptNumber = receiptNumber; + this.bankNumber = bankNumber; + this.accountId = accountId; + this.transactionType = transactionType; + this.rowIndex = rowIndex; + this.dateFormat = dateFormat; + this.locale = locale; this.id = null; this.officeId = null; this.officeName = null; @@ -193,10 +192,10 @@ public class LoanTransactionData { final BigDecimal principalPortion, final BigDecimal interestPortion, final BigDecimal feeChargesPortion, final BigDecimal penaltyChargesPortion, final BigDecimal overpaymentPortion, final String externalId, final AccountTransferData transfer, BigDecimal fixedEmiAmount, BigDecimal outstandingLoanBalance, - final BigDecimal unrecognizedIncomePortion,final boolean manuallyReversed) { + final BigDecimal unrecognizedIncomePortion, final boolean manuallyReversed) { this(id, officeId, officeName, transactionType, paymentDetailData, currency, date, amount, principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion, overpaymentPortion, unrecognizedIncomePortion, null, externalId, transfer, - fixedEmiAmount, outstandingLoanBalance,manuallyReversed); + fixedEmiAmount, outstandingLoanBalance, manuallyReversed); } public LoanTransactionData(final Long id, final Long officeId, final String officeName, final LoanTransactionEnumData transactionType, @@ -204,10 +203,10 @@ public class LoanTransactionData { final BigDecimal principalPortion, final BigDecimal interestPortion, final BigDecimal feeChargesPortion, final BigDecimal penaltyChargesPortion, final BigDecimal overpaymentPortion, BigDecimal unrecognizedIncomePortion, final Collection paymentTypeOptions, final String externalId, final AccountTransferData transfer, - final BigDecimal fixedEmiAmount, BigDecimal outstandingLoanBalance,boolean manuallyReversed) { + final BigDecimal fixedEmiAmount, BigDecimal outstandingLoanBalance, boolean manuallyReversed) { this(id, officeId, officeName, transactionType, paymentDetailData, currency, date, amount, principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion, overpaymentPortion, unrecognizedIncomePortion, paymentTypeOptions, externalId, - transfer, fixedEmiAmount, outstandingLoanBalance, null,manuallyReversed); + transfer, fixedEmiAmount, outstandingLoanBalance, null, manuallyReversed); } public LoanTransactionData(final Long id, final Long officeId, final String officeName, final LoanTransactionEnumData transactionType, @@ -215,10 +214,10 @@ public class LoanTransactionData { final BigDecimal principalPortion, final BigDecimal interestPortion, final BigDecimal feeChargesPortion, final BigDecimal penaltyChargesPortion, final BigDecimal overpaymentPortion, final BigDecimal unrecognizedIncomePortion, final String externalId, final AccountTransferData transfer, BigDecimal fixedEmiAmount, BigDecimal outstandingLoanBalance, - LocalDate submittedOnDate,final boolean manuallyReversed) { + LocalDate submittedOnDate, final boolean manuallyReversed) { this(id, officeId, officeName, transactionType, paymentDetailData, currency, date, amount, principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion, overpaymentPortion, unrecognizedIncomePortion, null, externalId, transfer, - fixedEmiAmount, outstandingLoanBalance, submittedOnDate,manuallyReversed); + fixedEmiAmount, outstandingLoanBalance, submittedOnDate, manuallyReversed); } public LoanTransactionData(final Long id, final Long officeId, final String officeName, final LoanTransactionEnumData transactionType, @@ -226,7 +225,8 @@ public class LoanTransactionData { final BigDecimal principalPortion, final BigDecimal interestPortion, final BigDecimal feeChargesPortion, final BigDecimal penaltyChargesPortion, final BigDecimal overpaymentPortion, final BigDecimal unrecognizedIncomePortion, final Collection paymentTypeOptions, final String externalId, final AccountTransferData transfer, - final BigDecimal fixedEmiAmount, BigDecimal outstandingLoanBalance, final LocalDate submittedOnDate,final boolean manuallyReversed) { + final BigDecimal fixedEmiAmount, BigDecimal outstandingLoanBalance, final LocalDate submittedOnDate, + final boolean manuallyReversed) { this.id = id; this.officeId = officeId; this.officeName = officeName; @@ -253,68 +253,71 @@ public class LoanTransactionData { public LoanTransactionData(Long id, LoanTransactionEnumData transactionType, LocalDate date, BigDecimal totalAmount, BigDecimal principalPortion, BigDecimal interestPortion, BigDecimal feeChargesPortion, BigDecimal penaltyChargesPortion, - BigDecimal overpaymentPortion, BigDecimal unrecognizedIncomePortion, BigDecimal outstandingLoanBalance,final boolean manuallyReversed) { + BigDecimal overpaymentPortion, BigDecimal unrecognizedIncomePortion, BigDecimal outstandingLoanBalance, + final boolean manuallyReversed) { this(id, null, null, transactionType, null, null, date, totalAmount, principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion, overpaymentPortion, unrecognizedIncomePortion, null, null, null, null, outstandingLoanBalance, null, manuallyReversed); } - public static LoanTransactionData loanTransactionDataForDisbursalTemplate(final LoanTransactionEnumData transactionType, final LocalDate expectedDisbursedOnLocalDateForTemplate, - final BigDecimal disburseAmountForTemplate, final Collection paymentOptions, - final BigDecimal retriveLastEmiAmount, final LocalDate possibleNextRepaymentDate) { - final Long id = null; - final Long officeId = null; - final String officeName = null; - final PaymentDetailData paymentDetailData = null; - final CurrencyData currency = null; - final BigDecimal unrecognizedIncomePortion = null; - final BigDecimal principalPortion = null; - final BigDecimal interestPortion = null; - final BigDecimal feeChargesPortion = null; - final BigDecimal penaltyChargesPortion = null; - final BigDecimal overpaymentPortion = null; - final String externalId = null; - final BigDecimal outstandingLoanBalance = null; - final AccountTransferData transfer = null; - final LocalDate submittedOnDate = null; - final boolean manuallyReversed = false; - return new LoanTransactionData(id, officeId, officeName, transactionType, paymentDetailData, currency, expectedDisbursedOnLocalDateForTemplate, - disburseAmountForTemplate, principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion, overpaymentPortion, unrecognizedIncomePortion, - paymentOptions, transfer, externalId, retriveLastEmiAmount, outstandingLoanBalance, submittedOnDate, manuallyReversed, possibleNextRepaymentDate); + public static LoanTransactionData loanTransactionDataForDisbursalTemplate(final LoanTransactionEnumData transactionType, + final LocalDate expectedDisbursedOnLocalDateForTemplate, final BigDecimal disburseAmountForTemplate, + final Collection paymentOptions, final BigDecimal retriveLastEmiAmount, + final LocalDate possibleNextRepaymentDate) { + final Long id = null; + final Long officeId = null; + final String officeName = null; + final PaymentDetailData paymentDetailData = null; + final CurrencyData currency = null; + final BigDecimal unrecognizedIncomePortion = null; + final BigDecimal principalPortion = null; + final BigDecimal interestPortion = null; + final BigDecimal feeChargesPortion = null; + final BigDecimal penaltyChargesPortion = null; + final BigDecimal overpaymentPortion = null; + final String externalId = null; + final BigDecimal outstandingLoanBalance = null; + final AccountTransferData transfer = null; + final LocalDate submittedOnDate = null; + final boolean manuallyReversed = false; + return new LoanTransactionData(id, officeId, officeName, transactionType, paymentDetailData, currency, + expectedDisbursedOnLocalDateForTemplate, disburseAmountForTemplate, principalPortion, interestPortion, feeChargesPortion, + penaltyChargesPortion, overpaymentPortion, unrecognizedIncomePortion, paymentOptions, transfer, externalId, + retriveLastEmiAmount, outstandingLoanBalance, submittedOnDate, manuallyReversed, possibleNextRepaymentDate); } - private LoanTransactionData(Long id , final Long officeId, final String officeName, LoanTransactionEnumData transactionType, final PaymentDetailData paymentDetailData, - final CurrencyData currency, final LocalDate date, BigDecimal amount, final BigDecimal principalPortion, final BigDecimal interestPortion, - final BigDecimal feeChargesPortion, final BigDecimal penaltyChargesPortion, final BigDecimal overpaymentPortion, BigDecimal unrecognizedIncomePortion, Collection paymentOptions, - final AccountTransferData transfer, final String externalId, final BigDecimal fixedEmiAmount, BigDecimal outstandingLoanBalance, - final LocalDate submittedOnDate, final boolean manuallyReversed, final LocalDate possibleNextRepaymentDate) { - this.id = id; - this.officeId = officeId; - this.officeName = officeName; - this.type = transactionType; - this.paymentDetailData = paymentDetailData; - this.currency = currency; - this.date = date; - this.amount = amount; - this.principalPortion = principalPortion; - this.interestPortion = interestPortion; - this.feeChargesPortion = feeChargesPortion; - this.penaltyChargesPortion = penaltyChargesPortion; - this.unrecognizedIncomePortion = unrecognizedIncomePortion; - this.paymentTypeOptions = paymentOptions; - this.externalId = externalId; - this.transfer = transfer; - this.overpaymentPortion = overpaymentPortion; - this.fixedEmiAmount = fixedEmiAmount; - this.outstandingLoanBalance = outstandingLoanBalance; - this.submittedOnDate = submittedOnDate; - this.manuallyReversed = manuallyReversed; - this.possibleNextRepaymentDate = possibleNextRepaymentDate; + private LoanTransactionData(Long id, final Long officeId, final String officeName, LoanTransactionEnumData transactionType, + final PaymentDetailData paymentDetailData, final CurrencyData currency, final LocalDate date, BigDecimal amount, + final BigDecimal principalPortion, final BigDecimal interestPortion, final BigDecimal feeChargesPortion, + final BigDecimal penaltyChargesPortion, final BigDecimal overpaymentPortion, BigDecimal unrecognizedIncomePortion, + Collection paymentOptions, final AccountTransferData transfer, final String externalId, + final BigDecimal fixedEmiAmount, BigDecimal outstandingLoanBalance, final LocalDate submittedOnDate, + final boolean manuallyReversed, final LocalDate possibleNextRepaymentDate) { + this.id = id; + this.officeId = officeId; + this.officeName = officeName; + this.type = transactionType; + this.paymentDetailData = paymentDetailData; + this.currency = currency; + this.date = date; + this.amount = amount; + this.principalPortion = principalPortion; + this.interestPortion = interestPortion; + this.feeChargesPortion = feeChargesPortion; + this.penaltyChargesPortion = penaltyChargesPortion; + this.unrecognizedIncomePortion = unrecognizedIncomePortion; + this.paymentTypeOptions = paymentOptions; + this.externalId = externalId; + this.transfer = transfer; + this.overpaymentPortion = overpaymentPortion; + this.fixedEmiAmount = fixedEmiAmount; + this.outstandingLoanBalance = outstandingLoanBalance; + this.submittedOnDate = submittedOnDate; + this.manuallyReversed = manuallyReversed; + this.possibleNextRepaymentDate = possibleNextRepaymentDate; } - - public LocalDate dateOf() { return this.date; } @@ -323,23 +326,20 @@ public class LoanTransactionData { return type.id() == 1; } - public BigDecimal getAmount() { return this.amount; } - public BigDecimal getUnrecognizedIncomePortion() { return this.unrecognizedIncomePortion; } - public BigDecimal getInterestPortion() { return this.interestPortion; } - public void setWriteOffReasonOptions(Collection writeOffReasonOptions){ - this.writeOffReasonOptions =writeOffReasonOptions; + public void setWriteOffReasonOptions(Collection writeOffReasonOptions) { + this.writeOffReasonOptions = writeOffReasonOptions; } public Collection getLoanChargePaidByList() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTransactionEnumData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTransactionEnumData.java index 05585d9e8..ad981301f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTransactionEnumData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/LoanTransactionEnumData.java @@ -150,4 +150,4 @@ public class LoanTransactionEnumData { return this.refundForActiveLoans; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/PaidInAdvanceData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/PaidInAdvanceData.java index aff6ea278..0af2382e3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/PaidInAdvanceData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/PaidInAdvanceData.java @@ -22,15 +22,14 @@ import java.math.BigDecimal; public class PaidInAdvanceData { - private final BigDecimal paidInAdvance; + private final BigDecimal paidInAdvance; - public PaidInAdvanceData(final BigDecimal paidInAdvance) { - this.paidInAdvance = paidInAdvance; - } - - public BigDecimal getPaidInAdvance() { - return paidInAdvance; - } + public PaidInAdvanceData(final BigDecimal paidInAdvance) { + this.paidInAdvance = paidInAdvance; + } + public BigDecimal getPaidInAdvance() { + return paidInAdvance; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/RepaymentScheduleRelatedLoanData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/RepaymentScheduleRelatedLoanData.java index a5e1cecc0..bbd1b8c7f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/RepaymentScheduleRelatedLoanData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/RepaymentScheduleRelatedLoanData.java @@ -35,8 +35,8 @@ public class RepaymentScheduleRelatedLoanData { private final BigDecimal totalFeeChargesAtDisbursement; public RepaymentScheduleRelatedLoanData(final LocalDate expectedDisbursementDate, final LocalDate actualDisbursementDate, - final CurrencyData currency, final BigDecimal principal, - final BigDecimal inArrearsTolerance, final BigDecimal totalFeeChargesAtDisbursement) { + final CurrencyData currency, final BigDecimal principal, final BigDecimal inArrearsTolerance, + final BigDecimal totalFeeChargesAtDisbursement) { this.expectedDisbursementDate = expectedDisbursementDate; this.actualDisbursementDate = actualDisbursementDate; this.currency = currency; @@ -75,6 +75,7 @@ public class RepaymentScheduleRelatedLoanData { public DisbursementData disbursementData() { BigDecimal waivedChargeAmount = null; - return new DisbursementData(null, this.expectedDisbursementDate, this.actualDisbursementDate, this.principal, null, null, waivedChargeAmount); + return new DisbursementData(null, this.expectedDisbursementDate, this.actualDisbursementDate, this.principal, null, null, + waivedChargeAmount); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/ScheduleGeneratorDTO.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/ScheduleGeneratorDTO.java old mode 100755 new mode 100644 index 05bfad2ee..8855ad03b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/ScheduleGeneratorDTO.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/data/ScheduleGeneratorDTO.java @@ -44,14 +44,13 @@ public class ScheduleGeneratorDTO { final boolean isSkipRepaymentOnFirstDayofMonth; final Boolean isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled; - public ScheduleGeneratorDTO(final LoanScheduleGeneratorFactory loanScheduleFactory, final ApplicationCurrency applicationCurrency, final LocalDate calculatedRepaymentsStartingFromDate, final HolidayDetailDTO holidayDetailDTO, final CalendarInstance calendarInstanceForInterestRecalculation, final CalendarInstance compoundingCalendarInstance, final LocalDate recalculateFrom, final Long overdurPenaltyWaitPeriod, final FloatingRateDTO floatingRateDTO, final Calendar calendar, final CalendarHistoryDataWrapper calendarHistoryDataWrapper, - final Boolean isInterestChargedFromDateAsDisbursementDateEnabled, final Integer numberOfdays, final boolean isSkipRepaymentOnFirstDayofMonth, - final Boolean isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled) { + final Boolean isInterestChargedFromDateAsDisbursementDateEnabled, final Integer numberOfdays, + final boolean isSkipRepaymentOnFirstDayofMonth, final Boolean isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled) { this.loanScheduleFactory = loanScheduleFactory; this.applicationCurrency = applicationCurrency; @@ -63,7 +62,7 @@ public class ScheduleGeneratorDTO { this.holidayDetailDTO = holidayDetailDTO; this.floatingRateDTO = floatingRateDTO; this.calendar = calendar; - this.calendarHistoryDataWrapper = calendarHistoryDataWrapper; + this.calendarHistoryDataWrapper = calendarHistoryDataWrapper; this.isInterestChargedFromDateAsDisbursementDateEnabled = isInterestChargedFromDateAsDisbursementDateEnabled; this.numberOfdays = numberOfdays; this.isSkipRepaymentOnFirstDayofMonth = isSkipRepaymentOnFirstDayofMonth; @@ -118,15 +117,15 @@ public class ScheduleGeneratorDTO { return this.floatingRateDTO; } - public Calendar getCalendar(){ + public Calendar getCalendar() { return this.calendar; } - public CalendarHistoryDataWrapper getCalendarHistoryDataWrapper(){ + public CalendarHistoryDataWrapper getCalendarHistoryDataWrapper() { return this.calendarHistoryDataWrapper; } - public Boolean isInterestChargedFromDateAsDisbursementDateEnabled(){ + public Boolean isInterestChargedFromDateAsDisbursementDateEnabled() { return this.isInterestChargedFromDateAsDisbursementDateEnabled; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/DefaultLoanLifecycleStateMachine.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/DefaultLoanLifecycleStateMachine.java index 6dfc60cc7..0189dd4fb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/DefaultLoanLifecycleStateMachine.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/DefaultLoanLifecycleStateMachine.java @@ -136,4 +136,4 @@ public class DefaultLoanLifecycleStateMachine implements LoanLifecycleStateMachi return allowed; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/GLIMAccountInfoRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/GLIMAccountInfoRepository.java index ab6ba39b5..ba9979811 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/GLIMAccountInfoRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/GLIMAccountInfoRepository.java @@ -22,13 +22,12 @@ import java.math.BigDecimal; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface GLIMAccountInfoRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface GLIMAccountInfoRepository + extends JpaRepository, JpaSpecificationExecutor { GroupLoanIndividualMonitoringAccount findOneByIsAcceptingChild(boolean acceptingChild); - GroupLoanIndividualMonitoringAccount findOneByIsAcceptingChildAndApplicationId(boolean acceptingChild, - BigDecimal applicationId); + GroupLoanIndividualMonitoringAccount findOneByIsAcceptingChildAndApplicationId(boolean acceptingChild, BigDecimal applicationId); GroupLoanIndividualMonitoringAccount findOneByAccountNumber(String accountNumber); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/GroupLoanIndividualMonitoringAccount.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/GroupLoanIndividualMonitoringAccount.java index b90321d0b..22d50e0df 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/GroupLoanIndividualMonitoringAccount.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/GroupLoanIndividualMonitoringAccount.java @@ -32,117 +32,114 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; import org.apache.fineract.portfolio.group.domain.Group; @Entity -@Table(name = "glim_accounts", uniqueConstraints = { @UniqueConstraint(columnNames = { "account_number" }, name = "FK_glim_id")}) +@Table(name = "glim_accounts", uniqueConstraints = { @UniqueConstraint(columnNames = { "account_number" }, name = "FK_glim_id") }) public class GroupLoanIndividualMonitoringAccount extends AbstractPersistableCustom { - @ManyToOne - @JoinColumn(name = "group_id", nullable = false) - private Group group; + @ManyToOne + @JoinColumn(name = "group_id", nullable = false) + private Group group; - @Column(name = "account_number", nullable = false) - private String accountNumber; + @Column(name = "account_number", nullable = false) + private String accountNumber; - @Column(name = "principal_amount") - private BigDecimal principalAmount; + @Column(name = "principal_amount") + private BigDecimal principalAmount; + @Column(name = "child_accounts_count") + private Long childAccountsCount; - @Column(name = "child_accounts_count") - private Long childAccountsCount; + @Column(name = "accepting_child") + private Boolean isAcceptingChild; - @Column(name = "accepting_child") - private Boolean isAcceptingChild; + @OneToMany + private Set childLoan; - @OneToMany - private Set childLoan; + @Column(name = "loan_status_id", nullable = false) + private Integer loanStatus; - @Column(name = "loan_status_id", nullable = false) - private Integer loanStatus; + @Column(name = "application_id", nullable = true) + private BigDecimal applicationId; - @Column(name = "application_id", nullable = true) - private BigDecimal applicationId; + private GroupLoanIndividualMonitoringAccount() {} - private GroupLoanIndividualMonitoringAccount() {} + private GroupLoanIndividualMonitoringAccount(String accountNumber, Group group, BigDecimal principalAmount, Long childAccountsCount, + Boolean isAcceptingChild, Integer loanStatus, BigDecimal applicationId) { + this.accountNumber = accountNumber; + this.group = group; + this.principalAmount = principalAmount; + this.childAccountsCount = childAccountsCount; + this.isAcceptingChild = isAcceptingChild; + this.loanStatus = loanStatus; + this.applicationId = applicationId; + } - private GroupLoanIndividualMonitoringAccount(String accountNumber,Group group,BigDecimal principalAmount,Long childAccountsCount, - Boolean isAcceptingChild,Integer loanStatus,BigDecimal applicationId) - { - this.accountNumber=accountNumber; - this.group=group; - this.principalAmount=principalAmount; - this.childAccountsCount=childAccountsCount; - this.isAcceptingChild=isAcceptingChild; - this.loanStatus=loanStatus; - this.applicationId=applicationId; - } + public static GroupLoanIndividualMonitoringAccount getInstance(String accountNumber, Group group, BigDecimal principalAmount, + Long childAccountsCount, Boolean isAcceptingChild, Integer loanStatus, BigDecimal applicationId) { + return new GroupLoanIndividualMonitoringAccount(accountNumber, group, principalAmount, childAccountsCount, isAcceptingChild, + loanStatus, applicationId); + } - public static GroupLoanIndividualMonitoringAccount getInstance(String accountNumber,Group group,BigDecimal principalAmount,Long childAccountsCount, - Boolean isAcceptingChild,Integer loanStatus,BigDecimal applicationId) - { - return new GroupLoanIndividualMonitoringAccount(accountNumber,group,principalAmount,childAccountsCount, - isAcceptingChild,loanStatus,applicationId); - } + public String getAccountNumber() { + return accountNumber; + } - public String getAccountNumber() { - return accountNumber; - } + public Group getGroup() { + return group; + } - public Group getGroup() { - return group; - } + public void setGroup(Group group) { + this.group = group; + } - public void setGroup(Group group) { - this.group = group; - } + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } - public void setAccountNumber(String accountNumber) { - this.accountNumber = accountNumber; - } + public Set getChildLoan() { + return childLoan; + } - public Set getChildLoan() { - return childLoan; - } + public void setChildLoan(Set childLoan) { + this.childLoan = childLoan; + } - public void setChildLoan(Set childLoan) { - this.childLoan = childLoan; - } + public BigDecimal getPrincipalAmount() { + return principalAmount; + } - public BigDecimal getPrincipalAmount() { - return principalAmount; - } + public void setPrincipalAmount(BigDecimal principalAmount) { + this.principalAmount = principalAmount; + } - public void setPrincipalAmount(BigDecimal principalAmount) { - this.principalAmount = principalAmount; - } + public Long getChildAccountsCount() { + return childAccountsCount; + } - public Long getChildAccountsCount() { - return childAccountsCount; - } + public void setChildAccountsCount(Long childAccountsCount) { + this.childAccountsCount = childAccountsCount; + } - public void setChildAccountsCount(Long childAccountsCount) { - this.childAccountsCount = childAccountsCount; - } + public Boolean getIsAcceptingChild() { + return isAcceptingChild; + } - public Boolean getIsAcceptingChild() { - return isAcceptingChild; - } + public void setIsAcceptingChild(Boolean isAcceptingChild) { + this.isAcceptingChild = isAcceptingChild; + } - public void setIsAcceptingChild(Boolean isAcceptingChild) { - this.isAcceptingChild = isAcceptingChild; - } + public Integer getLoanStatus() { + return loanStatus; + } - public Integer getLoanStatus() { - return loanStatus; - } + public void setLoanStatus(Integer loanStatus) { + this.loanStatus = loanStatus; + } - public void setLoanStatus(Integer loanStatus) { - this.loanStatus = loanStatus; - } + public BigDecimal getApplicationId() { + return applicationId; + } - public BigDecimal getApplicationId() { - return applicationId; - } - - public void setApplicationId(BigDecimal applicationId) { - this.applicationId = applicationId; - } -} \ No newline at end of file + public void setApplicationId(BigDecimal applicationId) { + this.applicationId = applicationId; + } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/Loan.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/Loan.java old mode 100755 new mode 100644 index 3a150015c..b151046b5 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/Loan.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/Loan.java @@ -174,23 +174,23 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "loan_type_enum", nullable = false) private Integer loanType; - @ManyToOne(fetch=FetchType.EAGER) + @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "product_id", nullable = false) private LoanProduct loanProduct; - @ManyToOne(optional = true, fetch=FetchType.EAGER) + @ManyToOne(optional = true, fetch = FetchType.EAGER) @JoinColumn(name = "fund_id", nullable = true) private Fund fund; - @ManyToOne(fetch=FetchType.EAGER) + @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "loan_officer_id", nullable = true) private Staff loanOfficer; - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "loanpurpose_cv_id", nullable = true) private CodeValue loanPurpose; - @ManyToOne(fetch=FetchType.EAGER) + @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "loan_transaction_strategy_id", nullable = true) private LoanTransactionProcessingStrategy transactionProcessingStrategy; @@ -214,7 +214,7 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "submittedon_date") private Date submittedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "submittedon_userid", nullable = true) private AppUser submittedBy; @@ -222,7 +222,7 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "rejectedon_date") private Date rejectedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "rejectedon_userid", nullable = true) private AppUser rejectedBy; @@ -230,7 +230,7 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "withdrawnon_date") private Date withdrawnOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "withdrawnon_userid", nullable = true) private AppUser withdrawnBy; @@ -238,7 +238,7 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "approvedon_date") private Date approvedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "approvedon_userid", nullable = true) private AppUser approvedBy; @@ -250,7 +250,7 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "disbursedon_date") private Date actualDisbursementDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "disbursedon_userid", nullable = true) private AppUser disbursedBy; @@ -258,7 +258,7 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "closedon_date") private Date closedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "closedon_userid", nullable = true) private AppUser closedBy; @@ -270,7 +270,7 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "rescheduledon_date") private Date rescheduledOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "rescheduledon_userid", nullable = true) private AppUser rescheduledByUser; @@ -299,24 +299,24 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "loan_product_counter") private Integer loanProductCounter; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch = FetchType.LAZY) private Set charges = new HashSet<>(); - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch = FetchType.LAZY) private Set trancheCharges = new HashSet<>(); - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch = FetchType.LAZY) private Set collateral = null; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch = FetchType.LAZY) private Set loanOfficerHistory; @OrderBy(value = "installmentNumber") - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch = FetchType.LAZY) private List repaymentScheduleInstallments = new ArrayList<>(); @OrderBy(value = "dateOf, id") - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch = FetchType.LAZY) private List loanTransactions = new ArrayList<>(); @Embedded @@ -344,18 +344,18 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "max_outstanding_loan_balance", scale = 6, precision = 19, nullable = true) private BigDecimal maxOutstandingLoanBalance; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch = FetchType.LAZY) @OrderBy(value = "expectedDisbursementDate, id") private List disbursementDetails = new ArrayList<>(); @OrderBy(value = "termApplicableFrom, id") - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan", orphanRemoval = true, fetch = FetchType.LAZY) private List loanTermVariations = new ArrayList<>(); @Column(name = "total_recovered_derived", scale = 6, precision = 19) private BigDecimal totalRecovered; - @OneToOne(cascade = CascadeType.ALL, mappedBy = "loan", optional = true, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToOne(cascade = CascadeType.ALL, mappedBy = "loan", optional = true, orphanRemoval = true, fetch = FetchType.EAGER) private LoanInterestRecalculationDetails loanInterestRecalculationDetails; @Column(name = "is_npa", nullable = false) @@ -381,7 +381,7 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "interest_rate_differential", scale = 6, precision = 19, nullable = true) private BigDecimal interestRateDifferential; - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "writeoff_reason_cv_id", nullable = true) private CodeValue writeOffReason; @@ -391,7 +391,7 @@ public class Loan extends AbstractPersistableCustom { @Column(name = "is_topup", nullable = false) private boolean isTopup = false; - @OneToOne(cascade = CascadeType.ALL, mappedBy = "loan", optional = true, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToOne(cascade = CascadeType.ALL, mappedBy = "loan", optional = true, orphanRemoval = true, fetch = FetchType.EAGER) private LoanTopupDetails loanTopupDetails; @OneToMany(fetch = FetchType.LAZY) @@ -442,7 +442,7 @@ public class Loan extends AbstractPersistableCustom { return new Loan(accountNo, client, group, loanType, fund, officer, loanPurpose, transactionProcessingStrategy, loanProduct, loanRepaymentScheduleDetail, status, loanCharges, collateral, syncDisbursementWithMeeting, fixedEmiAmount, disbursementDetails, maxOutstandingLoanBalance, createStandingInstructionAtDisbursement, isFloatingInterestRate, - interestRateDifferential,rates); + interestRateDifferential, rates); } protected Loan() { @@ -513,7 +513,7 @@ public class Loan extends AbstractPersistableCustom { this.proposedPrincipal = this.loanRepaymentScheduleDetail.getPrincipal().getAmount(); - //rates added here + // rates added here this.rates = rates; } @@ -682,8 +682,8 @@ public class Loan extends AbstractPersistableCustom { transactionDate, feeCharges, penaltyCharges, DateUtils.getLocalDateTimeOfTenant(), currentUser); Integer installmentNumber = null; - final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(applyLoanChargeTransaction, loanCharge, loanCharge.getAmount( - getCurrency()).getAmount(), installmentNumber); + final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(applyLoanChargeTransaction, loanCharge, + loanCharge.getAmount(getCurrency()).getAmount(), installmentNumber); applyLoanChargeTransaction.getLoanChargesPaid().add(loanChargePaidBy); addLoanTransaction(applyLoanChargeTransaction); return applyLoanChargeTransaction; @@ -692,8 +692,8 @@ public class Loan extends AbstractPersistableCustom { private void handleChargePaidTransaction(final LoanCharge charge, final LoanTransaction chargesPayment, final LoanLifecycleStateMachine loanLifecycleStateMachine, final Integer installmentNumber) { chargesPayment.updateLoan(this); - final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(chargesPayment, charge, chargesPayment.getAmount(getCurrency()) - .getAmount(), installmentNumber); + final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(chargesPayment, charge, + chargesPayment.getAmount(getCurrency()).getAmount(), installmentNumber); chargesPayment.getLoanChargesPaid().add(loanChargePaidBy); addLoanTransaction(chargesPayment); final LoanStatus statusEnum = loanLifecycleStateMachine.transition(LoanEvent.LOAN_CHARGE_PAYMENT, @@ -704,7 +704,7 @@ public class Loan extends AbstractPersistableCustom { .determineProcessor(this.transactionProcessingStrategy); final List chargePaymentInstallments = new ArrayList<>(); LocalDate startDate = getDisbursementDate(); - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment installment : installments) { if (installmentNumber == null && charge.isDueForCollectionFromAndUpToAndIncluding(startDate, installment.getDueDate())) { @@ -735,7 +735,8 @@ public class Loan extends AbstractPersistableCustom { private void validateLoanChargeIsNotWaived(final LoanCharge loanCharge) { if (loanCharge.isWaived()) { final String defaultUserMessage = "This loan charge cannot be removed as the charge as already been waived."; - throw new LoanChargeCannotBeAddedException("loanCharge", "loanCharge.is.waived", defaultUserMessage, getId(), loanCharge.name()); + throw new LoanChargeCannotBeAddedException("loanCharge", "loanCharge.is.waived", defaultUserMessage, getId(), + loanCharge.name()); } } @@ -752,7 +753,7 @@ public class Loan extends AbstractPersistableCustom { private LocalDate getLastRepaymentPeriodDueDate(final boolean includeRecalculatedInterestComponent) { LocalDate lastRepaymentDate = getDisbursementDate(); - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (LoanRepaymentScheduleInstallment installment : installments) { if ((includeRecalculatedInterestComponent || !installment.isRecalculatedInterestComponent()) && installment.getDueDate().isAfter(lastRepaymentDate)) { @@ -803,23 +804,24 @@ public class Loan extends AbstractPersistableCustom { private void removeOrModifyTransactionAssociatedWithLoanChargeIfDueAtDisbursement(final LoanCharge loanCharge) { if (loanCharge.isDueAtDisbursement()) { LoanTransaction transactionToRemove = null; - List transactions = getLoanTransactions() ; + List transactions = getLoanTransactions(); for (final LoanTransaction transaction : transactions) { - if (transaction.isRepaymentAtDisbursement() && doesLoanChargePaidByContainLoanCharge(transaction.getLoanChargesPaid(), loanCharge)) { + if (transaction.isRepaymentAtDisbursement() + && doesLoanChargePaidByContainLoanCharge(transaction.getLoanChargesPaid(), loanCharge)) { - final MonetaryCurrency currency = loanCurrency(); - final Money chargeAmount = Money.of(currency, loanCharge.amount()); - if (transaction.isGreaterThan(chargeAmount)) { - final Money principalPortion = Money.zero(currency); - final Money interestPortion = Money.zero(currency); - final Money penaltychargesPortion = Money.zero(currency); + final MonetaryCurrency currency = loanCurrency(); + final Money chargeAmount = Money.of(currency, loanCharge.amount()); + if (transaction.isGreaterThan(chargeAmount)) { + final Money principalPortion = Money.zero(currency); + final Money interestPortion = Money.zero(currency); + final Money penaltychargesPortion = Money.zero(currency); - transaction.updateComponentsAndTotal(principalPortion, interestPortion, chargeAmount, penaltychargesPortion); + transaction.updateComponentsAndTotal(principalPortion, interestPortion, chargeAmount, penaltychargesPortion); - } else { - transactionToRemove = transaction; - } + } else { + transactionToRemove = transaction; } + } } if (transactionToRemove != null) { @@ -829,12 +831,10 @@ public class Loan extends AbstractPersistableCustom { } private boolean doesLoanChargePaidByContainLoanCharge(Set loanChargePaidBys, LoanCharge loanCharge) { - for (LoanChargePaidBy loanChargePaidBy : loanChargePaidBys) { - if (loanChargePaidBy.getLoanCharge().equals(loanCharge)) { - return true; - } - } - return false; + for (LoanChargePaidBy loanChargePaidBy : loanChargePaidBys) { + if (loanChargePaidBy.getLoanCharge().equals(loanCharge)) { return true; } + } + return false; } public Map updateLoanCharge(final LoanCharge loanCharge, final JsonCommand command) { @@ -889,7 +889,7 @@ public class Loan extends AbstractPersistableCustom { final BigDecimal totalInterestCharged = getTotalInterest(); if (isMultiDisburmentLoan() && loanCharge.isDisbursementCharge()) { amount = getTotalAllTrancheDisbursementAmount().getAmount().add(totalInterestCharged); - }else{ + } else { amount = getPrincpal().getAmount().add(totalInterestCharged); } break; @@ -923,13 +923,11 @@ public class Loan extends AbstractPersistableCustom { if (isMultiDisburmentLoan()) { int totalTranchDisbursementCount = 0; for (final LoanDisbursementDetails loanDisbursementDetail : this.disbursementDetails) { - if(loanDisbursementDetail.actualDisbursementDate() != null){ + if (loanDisbursementDetail.actualDisbursementDate() != null) { totalTranchDisbursementCount++; } } - if(totalTranchDisbursementCount < 2){ - return true; - } + if (totalTranchDisbursementCount < 2) { return true; } } return false; } @@ -947,7 +945,7 @@ public class Loan extends AbstractPersistableCustom { public BigDecimal calculatePerInstallmentChargeAmount(final ChargeCalculationType calculationType, final BigDecimal percentage) { Money amount = Money.zero(getCurrency()); - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment installment : installments) { amount = amount.plus(calculateInstallmentChargeAmount(calculationType, percentage, installment)); } @@ -1001,8 +999,8 @@ public class Loan extends AbstractPersistableCustom { if (isPeriodicAccrualAccountingEnabledOnLoanProduct()) { Money receivableCharge = Money.zero(getCurrency()); if (loanInstallmentNumber != null) { - receivableCharge = accruedCharge.minus(loanCharge.getInstallmentLoanCharge(loanInstallmentNumber).getAmountPaid( - getCurrency())); + receivableCharge = accruedCharge + .minus(loanCharge.getInstallmentLoanCharge(loanInstallmentNumber).getAmountPaid(getCurrency())); } else { receivableCharge = accruedCharge.minus(loanCharge.getAmountPaid(getCurrency())); } @@ -1028,7 +1026,7 @@ public class Loan extends AbstractPersistableCustom { } else { transactionDate = loanCharge.getDueLocalDate(); } - }else if(loanCharge.isInstalmentFee()){ + } else if (loanCharge.isInstalmentFee()) { transactionDate = loanCharge.getInstallmentLoanCharge(loanInstallmentNumber).getRepaymentInstallment().getDueDate(); } @@ -1039,13 +1037,12 @@ public class Loan extends AbstractPersistableCustom { existingTransactionIds.addAll(findExistingTransactionIds()); existingReversedTransactionIds.addAll(findExistingReversedTransactionIds()); - final LoanTransaction waiveLoanChargeTransaction = LoanTransaction.waiveLoanCharge(this, getOffice(), amountWaived, - transactionDate, feeChargesWaived, penaltyChargesWaived, unrecognizedIncome, DateUtils.getLocalDateTimeOfTenant(), - currentUser); - final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(waiveLoanChargeTransaction, loanCharge, waiveLoanChargeTransaction - .getAmount(getCurrency()).getAmount(), loanInstallmentNumber); + final LoanTransaction waiveLoanChargeTransaction = LoanTransaction.waiveLoanCharge(this, getOffice(), amountWaived, transactionDate, + feeChargesWaived, penaltyChargesWaived, unrecognizedIncome, DateUtils.getLocalDateTimeOfTenant(), currentUser); + final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(waiveLoanChargeTransaction, loanCharge, + waiveLoanChargeTransaction.getAmount(getCurrency()).getAmount(), loanInstallmentNumber); waiveLoanChargeTransaction.getLoanChargesPaid().add(loanChargePaidBy); - addLoanTransaction(waiveLoanChargeTransaction) ; + addLoanTransaction(waiveLoanChargeTransaction); if (this.repaymentScheduleDetail().isInterestRecalculationEnabled() && (loanCharge.getDueLocalDate() == null || LocalDate.now().isAfter(loanCharge.getDueLocalDate()))) { regenerateRepaymentScheduleWithInterestRecalculation(scheduleGeneratorDTO, currentUser); @@ -1085,11 +1082,11 @@ public class Loan extends AbstractPersistableCustom { public GroupLoanIndividualMonitoringAccount getGlim() { return glim; - } + } - public void setGlim(GroupLoanIndividualMonitoringAccount glim) { + public void setGlim(GroupLoanIndividualMonitoringAccount glim) { this.glim = glim; - } + } public LoanProduct loanProduct() { return this.loanProduct; @@ -1177,8 +1174,7 @@ public class Loan extends AbstractPersistableCustom { chargeAmt = loanCharge.amountOrPercentage(); } if (charge != null) { - charge.update(chargeAmt, loanCharge.getDueLocalDate(), amount, - fetchNumberOfInstallmensAfterExceptions(), totalChargeAmt); + charge.update(chargeAmt, loanCharge.getDueLocalDate(), amount, fetchNumberOfInstallmensAfterExceptions(), totalChargeAmt); } } @@ -1252,7 +1248,7 @@ public class Loan extends AbstractPersistableCustom { } private void applyPeriodicAccruals(final Collection accruals) { - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (LoanRepaymentScheduleInstallment installment : installments) { Money interest = Money.zero(getCurrency()); Money fee = Money.zero(getCurrency()); @@ -1266,8 +1262,8 @@ public class Loan extends AbstractPersistableCustom { if (installment.getFeeChargesCharged(getCurrency()).isLessThan(fee) || installment.getInterestCharged(getCurrency()).isLessThan(interest) || installment.getPenaltyChargesCharged(getCurrency()).isLessThan(penality) - || (getAccruedTill().isEqual(loanTransaction.getTransactionDate()) && !installment.getDueDate().isEqual( - getAccruedTill()))) { + || (getAccruedTill().isEqual(loanTransaction.getTransactionDate()) + && !installment.getDueDate().isEqual(getAccruedTill()))) { interest = interest.minus(loanTransaction.getInterestPortion(getCurrency())); fee = fee.minus(loanTransaction.getFeeChargesPortion(getCurrency())); penality = penality.minus(loanTransaction.getPenaltyChargesPortion(getCurrency())); @@ -1296,7 +1292,7 @@ public class Loan extends AbstractPersistableCustom { final LocalDateTime currentDateTime = DateUtils.getLocalDateTimeOfTenant(); final LoanTransaction interestAppliedTransaction = LoanTransaction.accrueInterest(getOffice(), this, interestApplied, getDisbursementDate(), currentDateTime, currentUser); - addLoanTransaction(interestAppliedTransaction) ; + addLoanTransaction(interestAppliedTransaction); } } else { Set chargePaidBies = loanTransaction.getLoanChargesPaid(); @@ -1348,8 +1344,8 @@ public class Loan extends AbstractPersistableCustom { final LoanProduct loanProduct) { final Map actualChanges = this.loanRepaymentScheduleDetail.updateLoanApplicationAttributes(command, aprCalculator); - final MonetaryCurrency currency = new MonetaryCurrency(loanProduct.getCurrency().getCode(), loanProduct.getCurrency().getDigitsAfterDecimal(), - loanProduct.getCurrency().getCurrencyInMultiplesOf()); + final MonetaryCurrency currency = new MonetaryCurrency(loanProduct.getCurrency().getCode(), + loanProduct.getCurrency().getDigitsAfterDecimal(), loanProduct.getCurrency().getCurrencyInMultiplesOf()); this.loanRepaymentScheduleDetail.updateCurrency(currency); if (!actualChanges.isEmpty()) { @@ -1726,7 +1722,8 @@ public class Loan extends AbstractPersistableCustom { final JsonPrimitive primitive = topLevel.get(LoanApiConstants.dateFormatParameterName).getAsJsonPrimitive(); returnObject.put(LoanApiConstants.dateFormatParameterName, primitive.getAsString()); } - if (topLevel.has(LoanApiConstants.localeParameterName) && topLevel.get(LoanApiConstants.localeParameterName).isJsonPrimitive()) { + if (topLevel.has(LoanApiConstants.localeParameterName) + && topLevel.get(LoanApiConstants.localeParameterName).isJsonPrimitive()) { final JsonPrimitive primitive = topLevel.get(LoanApiConstants.localeParameterName).getAsJsonPrimitive(); String localeString = primitive.getAsString(); returnObject.put(LoanApiConstants.localeParameterName, localeString); @@ -1875,8 +1872,8 @@ public class Loan extends AbstractPersistableCustom { this.disbursementDetails.add(disbursementDetails); for (LoanTrancheCharge trancheCharge : trancheCharges) { Charge chargeDefinition = trancheCharge.getCharge(); - final LoanCharge loanCharge = LoanCharge.createNewWithoutLoan(chargeDefinition, principal, null, null, null, new LocalDate( - expectedDisbursementDate), null, null); + final LoanCharge loanCharge = LoanCharge.createNewWithoutLoan(chargeDefinition, principal, null, null, null, + new LocalDate(expectedDisbursementDate), null, null); loanCharge.update(this); LoanTrancheDisbursementCharge loanTrancheDisbursementCharge = new LoanTrancheDisbursementCharge(loanCharge, disbursementDetails); @@ -1962,7 +1959,7 @@ public class Loan extends AbstractPersistableCustom { } private void removeFirstDisbursementTransaction() { - List transactions = getLoanTransactions() ; + List transactions = getLoanTransactions(); for (final LoanTransaction loanTransaction : transactions) { if (loanTransaction.isDisbursement()) { removeLoanTransaction(loanTransaction); @@ -2004,7 +2001,8 @@ public class Loan extends AbstractPersistableCustom { if (this.client != null && this.client.isActivatedAfter(submittedOn)) { final String errorMessage = "The date on which a loan is submitted cannot be earlier than client's activation date."; - throw new InvalidLoanStateTransitionException("submittal", "cannot.be.before.client.activation.date", errorMessage, submittedOn); + throw new InvalidLoanStateTransitionException("submittal", "cannot.be.before.client.activation.date", errorMessage, + submittedOn); } validateActivityNotBeforeClientOrGroupTransferDate(LoanEvent.LOAN_CREATED, submittedOn); @@ -2039,8 +2037,8 @@ public class Loan extends AbstractPersistableCustom { */ if (this.loanRepaymentScheduleDetail.isInterestRecalculationEnabled()) { - this.loanInterestRecalculationDetails = LoanInterestRecalculationDetails.createFrom(this.loanProduct - .getProductInterestRecalculationDetails()); + this.loanInterestRecalculationDetails = LoanInterestRecalculationDetails + .createFrom(this.loanProduct.getProductInterestRecalculationDetails()); this.loanInterestRecalculationDetails.updateLoan(this); } @@ -2048,12 +2046,12 @@ public class Loan extends AbstractPersistableCustom { private LocalDate determineExpectedMaturityDate() { final int numberOfInstallments = this.repaymentScheduleInstallments.size(); - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); LocalDate maturityDate = installments.get(numberOfInstallments - 1).getDueDate(); ListIterator iterator = installments.listIterator(numberOfInstallments); - while(iterator.hasPrevious()){ + while (iterator.hasPrevious()) { LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment = iterator.previous(); - if(!loanRepaymentScheduleInstallment.isRecalculatedInterestComponent()){ + if (!loanRepaymentScheduleInstallment.isRecalculatedInterestComponent()) { maturityDate = loanRepaymentScheduleInstallment.getDueDate(); break; } @@ -2320,7 +2318,7 @@ public class Loan extends AbstractPersistableCustom { public Collection findExistingTransactionIds() { final Collection ids = new ArrayList<>(); - List transactions = getLoanTransactions() ; + List transactions = getLoanTransactions(); for (final LoanTransaction transaction : transactions) { ids.add(transaction.getId()); } @@ -2331,7 +2329,7 @@ public class Loan extends AbstractPersistableCustom { public Collection findExistingReversedTransactionIds() { final Collection ids = new ArrayList<>(); - List transactions = getLoanTransactions() ; + List transactions = getLoanTransactions(); for (final LoanTransaction transaction : transactions) { if (transaction.isReversed()) { ids.add(transaction.getId()); @@ -2383,11 +2381,11 @@ public class Loan extends AbstractPersistableCustom { * selected **/ - if ((isNoneOrCashOrUpfrontAccrualAccountingEnabledOnLoanProduct() - && isMultiDisburmentLoan() && getDisbursedLoanDisbursementDetails().size() == 1) || !isMultiDisburmentLoan()) { + if ((isNoneOrCashOrUpfrontAccrualAccountingEnabledOnLoanProduct() && isMultiDisburmentLoan() + && getDisbursedLoanDisbursementDetails().size() == 1) || !isMultiDisburmentLoan()) { final LoanTransaction interestAppliedTransaction = LoanTransaction.accrueInterest(getOffice(), this, interestApplied, actualDisbursementDate, createdDate, currentUser); - addLoanTransaction(interestAppliedTransaction) ; + addLoanTransaction(interestAppliedTransaction); } return reprocessTransactionForDisbursement(); @@ -2396,17 +2394,17 @@ public class Loan extends AbstractPersistableCustom { private List getDisbursedLoanDisbursementDetails() { List ret = new ArrayList<>(); - if(this.disbursementDetails != null && this.disbursementDetails.size() > 0){ + if (this.disbursementDetails != null && this.disbursementDetails.size() > 0) { for (LoanDisbursementDetails disbursementDetail : this.disbursementDetails) { if (disbursementDetail.actualDisbursementDate() != null) { ret.add(disbursementDetail); } } } - return ret; - } + return ret; + } - public void regenerateScheduleOnDisbursement(final ScheduleGeneratorDTO scheduleGeneratorDTO, final boolean recalculateSchedule, + public void regenerateScheduleOnDisbursement(final ScheduleGeneratorDTO scheduleGeneratorDTO, final boolean recalculateSchedule, final LocalDate actualDisbursementDate, BigDecimal emiAmount, final AppUser currentUser, LocalDate nextPossibleRepaymentDate, Date rescheduledRepaymentDate) { boolean isEmiAmountChanged = false; @@ -2415,9 +2413,10 @@ public class Loan extends AbstractPersistableCustom { if (this.loanProduct.isMultiDisburseLoan()) { final Date dateValue = null; final boolean isSpecificToInstallment = false; - final Boolean isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled = scheduleGeneratorDTO.isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled(); + final Boolean isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled = scheduleGeneratorDTO + .isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled(); Date effectiveDateFrom = actualDisbursementDate.toDate(); - if(!isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled && actualDisbursementDate.equals(nextPossibleRepaymentDate)){ + if (!isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled && actualDisbursementDate.equals(nextPossibleRepaymentDate)) { effectiveDateFrom = nextPossibleRepaymentDate.plusDays(1).toDate(); } LoanTermVariations loanVariationTerms = new LoanTermVariations(LoanTermVariationType.EMI_AMOUNT.getValue(), @@ -2572,7 +2571,8 @@ public class Loan extends AbstractPersistableCustom { if (date != null) { for (LoanDisbursementDetails disbursementDetail : this.disbursementDetails) { if (disbursementDetail.actualDisbursementDate() != null) { - if (disbursementDetail.actualDisbursementDate().after(date) || disbursementDetail.actualDisbursementDate().equals(date)) { + if (disbursementDetail.actualDisbursementDate().after(date) + || disbursementDetail.actualDisbursementDate().equals(date)) { date = disbursementDetail.actualDisbursementDate(); details = disbursementDetail; } @@ -2636,7 +2636,7 @@ public class Loan extends AbstractPersistableCustom { } private void updateLoanRepaymentPeriodsDerivedFields(final LocalDate actualDisbursementDate) { - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment repaymentPeriod : installments) { repaymentPeriod.updateDerivedFields(loanCurrency(), actualDisbursementDate); } @@ -2667,13 +2667,14 @@ public class Loan extends AbstractPersistableCustom { LoanScheduleGenerator loanScheduleGenerator = null; if (loanApplicationTerms.isEqualAmortization()) { if (loanApplicationTerms.getInterestMethod().isDecliningBalnce()) { - final LoanScheduleGenerator decliningLoanScheduleGenerator = scheduleGeneratorDTO.getLoanScheduleFactory().create( - InterestMethod.DECLINING_BALANCE); + final LoanScheduleGenerator decliningLoanScheduleGenerator = scheduleGeneratorDTO.getLoanScheduleFactory() + .create(InterestMethod.DECLINING_BALANCE); Set loanCharges = charges(); - LoanScheduleModel loanSchedule = decliningLoanScheduleGenerator.generate(mc, loanApplicationTerms, loanCharges, scheduleGeneratorDTO.getHolidayDetailDTO()); - - loanApplicationTerms.updateTotalInterestDue(Money.of(loanApplicationTerms.getCurrency(), loanSchedule.getTotalInterestCharged())); + LoanScheduleModel loanSchedule = decliningLoanScheduleGenerator.generate(mc, loanApplicationTerms, loanCharges, + scheduleGeneratorDTO.getHolidayDetailDTO()); + loanApplicationTerms + .updateTotalInterestDue(Money.of(loanApplicationTerms.getCurrency(), loanSchedule.getTotalInterestCharged())); } loanScheduleGenerator = scheduleGeneratorDTO.getLoanScheduleFactory().create(InterestMethod.FLAT); @@ -2722,9 +2723,9 @@ public class Loan extends AbstractPersistableCustom { final Money totalFeeChargesDueAtDisbursement = this.summary.getTotalFeeChargesDueAtDisbursement(loanCurrency()); /** - * all Charges repaid at disbursal is marked as repaid and - * "APPLY Charge" transactions are created for all other fees ( which - * are created during disbursal but not repaid) + * all Charges repaid at disbursal is marked as repaid and "APPLY + * Charge" transactions are created for all other fees ( which are + * created during disbursal but not repaid) **/ Money disbursentMoney = Money.zero(getCurrency()); @@ -2734,11 +2735,11 @@ public class Loan extends AbstractPersistableCustom { for (final LoanCharge charge : charges()) { Date actualDisbursementDate = getActualDisbursementDate(charge); if ((charge.getCharge().getChargeTimeType().equals(ChargeTimeType.DISBURSEMENT.getValue()) - && disbursedOn.equals(new LocalDate(actualDisbursementDate)) && (actualDisbursementDate != null) && !charge.isWaived() && !charge - .isFullyPaid()) + && disbursedOn.equals(new LocalDate(actualDisbursementDate)) && (actualDisbursementDate != null) && !charge.isWaived() + && !charge.isFullyPaid()) || (charge.getCharge().getChargeTimeType().equals(ChargeTimeType.TRANCHE_DISBURSEMENT.getValue()) - && disbursedOn.equals(new LocalDate(actualDisbursementDate)) && (actualDisbursementDate != null) - && !charge.isWaived() && !charge.isFullyPaid())) { + && disbursedOn.equals(new LocalDate(actualDisbursementDate)) && (actualDisbursementDate != null) + && !charge.isWaived() && !charge.isFullyPaid())) { if (totalFeeChargesDueAtDisbursement.isGreaterThanZero() && !charge.getChargePaymentMode().isPaymentModeAccountTransfer()) { charge.markAsFullyPaid(); // Add "Loan Charge Paid By" details to this transaction @@ -2762,7 +2763,7 @@ public class Loan extends AbstractPersistableCustom { final Money zero = Money.zero(getCurrency()); chargesPayment.updateComponentsAndTotal(zero, zero, disbursentMoney, zero); chargesPayment.updateLoan(this); - addLoanTransaction(chargesPayment) ; + addLoanTransaction(chargesPayment); updateLoanOutstandingBalaces(); } @@ -2774,8 +2775,9 @@ public class Loan extends AbstractPersistableCustom { } if (getExpectedFirstRepaymentOnDate() != null - && (disbursedOn.isAfter(this.fetchRepaymentScheduleInstallment(1).getDueDate()) || disbursedOn - .isAfter(getExpectedFirstRepaymentOnDate())) && disbursedOn.toDate().equals(this.actualDisbursementDate)) { + && (disbursedOn.isAfter(this.fetchRepaymentScheduleInstallment(1).getDueDate()) + || disbursedOn.isAfter(getExpectedFirstRepaymentOnDate())) + && disbursedOn.toDate().equals(this.actualDisbursementDate)) { final String errorMessage = "submittedOnDate cannot be after the loans expectedFirstRepaymentOnDate: " + getExpectedFirstRepaymentOnDate().toString(); throw new InvalidLoanStateTransitionException("disbursal", "cannot.be.after.expected.first.repayment.date", errorMessage, @@ -2808,7 +2810,7 @@ public class Loan extends AbstractPersistableCustom { final Money zero = Money.zero(getCurrency()); chargesPayment.updateComponents(zero, zero, charge.getAmount(getCurrency()), zero); chargesPayment.updateLoan(this); - addLoanTransaction(chargesPayment) ; + addLoanTransaction(chargesPayment); updateLoanOutstandingBalaces(); charge.markAsFullyPaid(); return chargesPayment; @@ -2833,8 +2835,9 @@ public class Loan extends AbstractPersistableCustom { final boolean isScheduleRegenerateRequired = isRepaymentScheduleRegenerationRequiredForDisbursement(actualDisbursementDate); this.actualDisbursementDate = null; this.disbursedBy = null; - boolean isDisbursedAmountChanged = - approvedPrincipal.compareTo(this.loanRepaymentScheduleDetail.getPrincipal().getAmount()) == 0 ? Boolean.FALSE:Boolean.TRUE; + boolean isDisbursedAmountChanged = approvedPrincipal.compareTo(this.loanRepaymentScheduleDetail.getPrincipal().getAmount()) == 0 + ? Boolean.FALSE + : Boolean.TRUE; this.loanRepaymentScheduleDetail.setPrincipal(this.approvedPrincipal); if (this.loanProduct.isMultiDisburseLoan()) { for (final LoanDisbursementDetails details : this.disbursementDetails) { @@ -2853,13 +2856,13 @@ public class Loan extends AbstractPersistableCustom { if (isDisbursedAmountChanged) { updateSummaryWithTotalFeeChargesDueAtDisbursement(deriveSumTotalOfChargesDueAtDisbursement()); } - }else if(isPeriodicAccrualAccountingEnabledOnLoanProduct()){ + } else if (isPeriodicAccrualAccountingEnabledOnLoanProduct()) { for (final LoanRepaymentScheduleInstallment period : getRepaymentScheduleInstallments()) { period.resetAccrualComponents(); } } - if(this.isTopup){ + if (this.isTopup) { this.loanTopupDetails.setAccountTransferDetails(null); this.loanTopupDetails.setTopupAmount(null); } @@ -2877,7 +2880,7 @@ public class Loan extends AbstractPersistableCustom { Collection retainTransactions = new ArrayList<>(); for (final LoanTransaction transaction : this.loanTransactions) { transaction.reverse(); - if(transaction.getId() != null){ + if (transaction.getId() != null) { retainTransactions.add(transaction); } } @@ -2897,7 +2900,7 @@ public class Loan extends AbstractPersistableCustom { charge.resetToOriginal(loanCurrency()); } } - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment currentInstallment : installments) { currentInstallment.resetDerivedComponents(); } @@ -3019,7 +3022,7 @@ public class Loan extends AbstractPersistableCustom { loanTransaction.updateLoan(this); if (loanTransaction.isNotZero(loanCurrency())) { - addLoanTransaction(loanTransaction) ; + addLoanTransaction(loanTransaction); } updateLoanSummaryDerivedFields(); doPostLoanTransactionChecks(loanTransaction.getTransactionDate(), loanLifecycleStateMachine); @@ -3051,7 +3054,7 @@ public class Loan extends AbstractPersistableCustom { final boolean isTransactionChronologicallyLatest = isChronologicallyLatestRepaymentOrWaiver(loanTransaction, getLoanTransactions()); if (loanTransaction.isNotZero(loanCurrency())) { - addLoanTransaction(loanTransaction) ; + addLoanTransaction(loanTransaction); } if (loanTransaction.isNotRepayment() && loanTransaction.isNotWaiver() && loanTransaction.isNotRecoveryRepayment()) { @@ -3097,8 +3100,8 @@ public class Loan extends AbstractPersistableCustom { final LoanRepaymentScheduleTransactionProcessor loanRepaymentScheduleTransactionProcessor = this.transactionProcessorFactory .determineProcessor(this.transactionProcessingStrategy); - final LoanRepaymentScheduleInstallment currentInstallment = fetchLoanRepaymentScheduleInstallment(loanTransaction - .getTransactionDate()); + final LoanRepaymentScheduleInstallment currentInstallment = fetchLoanRepaymentScheduleInstallment( + loanTransaction.getTransactionDate()); boolean reprocess = true; if (!isForeclosure() && isTransactionChronologicallyLatest && adjustedTransaction == null @@ -3116,8 +3119,8 @@ public class Loan extends AbstractPersistableCustom { if (currentInstallment == null || currentInstallment.isNotFullyPaidOff()) { reprocess = true; } else { - final LoanRepaymentScheduleInstallment nextInstallment = fetchRepaymentScheduleInstallment(currentInstallment - .getInstallmentNumber() + 1); + final LoanRepaymentScheduleInstallment nextInstallment = fetchRepaymentScheduleInstallment( + currentInstallment.getInstallmentNumber() + 1); if (nextInstallment != null && nextInstallment.getTotalPaidInAdvance(getCurrency()).isGreaterThanZero()) { reprocess = true; } @@ -3170,7 +3173,7 @@ public class Loan extends AbstractPersistableCustom { private LoanRepaymentScheduleInstallment fetchLoanRepaymentScheduleInstallment(LocalDate dueDate) { LoanRepaymentScheduleInstallment installment = null; - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : installments) { if (dueDate.equals(loanRepaymentScheduleInstallment.getDueDate())) { installment = loanRepaymentScheduleInstallment; @@ -3182,7 +3185,7 @@ public class Loan extends AbstractPersistableCustom { private List retreiveListOfIncomePostingTransactions() { final List incomePostTransactions = new ArrayList<>(); - List trans = getLoanTransactions() ; + List trans = getLoanTransactions(); for (final LoanTransaction transaction : trans) { if (transaction.isNotReversed() && transaction.isIncomePosting()) { incomePostTransactions.add(transaction); @@ -3195,7 +3198,7 @@ public class Loan extends AbstractPersistableCustom { private List retreiveListOfTransactionsPostDisbursement() { final List repaymentsOrWaivers = new ArrayList<>(); - List trans = getLoanTransactions() ; + List trans = getLoanTransactions(); for (final LoanTransaction transaction : trans) { if (transaction.isNotReversed() && !(transaction.isDisbursement() || transaction.isNonMonetaryTransaction())) { repaymentsOrWaivers.add(transaction); @@ -3258,7 +3261,8 @@ public class Loan extends AbstractPersistableCustom { boolean isAllChargesPaid = true; for (final LoanCharge loanCharge : this.charges) { - if (loanCharge.isActive() && loanCharge.amount().compareTo(BigDecimal.ZERO) > 0 && !(loanCharge.isPaid() || loanCharge.isWaived())) { + if (loanCharge.isActive() && loanCharge.amount().compareTo(BigDecimal.ZERO) > 0 + && !(loanCharge.isPaid() || loanCharge.isWaived())) { isAllChargesPaid = false; break; } @@ -3289,15 +3293,15 @@ public class Loan extends AbstractPersistableCustom { determineCumulativeIncomeFromInstallments(cumulativeIncomeFromInstallments); HashMap cumulativeIncomeFromIncomePosting = new HashMap<>(); determineCumulativeIncomeDetails(retreiveListOfIncomePostingTransactions(), cumulativeIncomeFromIncomePosting); - BigDecimal interestToPost = cumulativeIncomeFromInstallments.get("interest").subtract( - cumulativeIncomeFromIncomePosting.get("interest")); + BigDecimal interestToPost = cumulativeIncomeFromInstallments.get("interest") + .subtract(cumulativeIncomeFromIncomePosting.get("interest")); BigDecimal feeToPost = cumulativeIncomeFromInstallments.get("fee").subtract(cumulativeIncomeFromIncomePosting.get("fee")); - BigDecimal penaltyToPost = cumulativeIncomeFromInstallments.get("penalty").subtract( - cumulativeIncomeFromIncomePosting.get("penalty")); + BigDecimal penaltyToPost = cumulativeIncomeFromInstallments.get("penalty") + .subtract(cumulativeIncomeFromIncomePosting.get("penalty")); BigDecimal amountToPost = interestToPost.add(feeToPost).add(penaltyToPost); LoanTransaction finalIncomeTransaction = LoanTransaction.incomePosting(this, this.getOffice(), closedDate, amountToPost, interestToPost, feeToPost, penaltyToPost, null); - addLoanTransaction(finalIncomeTransaction) ; + addLoanTransaction(finalIncomeTransaction); if (isPeriodicAccrualAccountingEnabledOnLoanProduct()) { List updatedAccrualTransactions = retreiveListOfAccrualTransactions(); LocalDate lastAccruedDate = this.getDisbursementDate(); @@ -3309,7 +3313,7 @@ public class Loan extends AbstractPersistableCustom { LoanTransaction finalAccrual = LoanTransaction.accrueTransaction(this, this.getOffice(), closedLocalDate, amountToPost, interestToPost, feeToPost, penaltyToPost, null); updateLoanChargesPaidBy(finalAccrual, feeDetails, null); - addLoanTransaction(finalAccrual) ; + addLoanTransaction(finalAccrual); } } updateLoanOutstandingBalaces(); @@ -3319,7 +3323,7 @@ public class Loan extends AbstractPersistableCustom { BigDecimal interest = BigDecimal.ZERO; BigDecimal fee = BigDecimal.ZERO; BigDecimal penalty = BigDecimal.ZERO; - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (LoanRepaymentScheduleInstallment installment : installments) { interest = interest.add(installment.getInterestCharged(getCurrency()).getAmount()); fee = fee.add(installment.getFeeChargesCharged(getCurrency()).getAmount()); @@ -3388,7 +3392,8 @@ public class Loan extends AbstractPersistableCustom { return isAfterLatRepayment; } - private boolean isChronologicallyLatestTransaction(final LoanTransaction loanTransaction, final List loanTransactions) { + private boolean isChronologicallyLatestTransaction(final LoanTransaction loanTransaction, + final List loanTransactions) { boolean isChronologicallyLatestRepaymentOrWaiver = true; @@ -3408,7 +3413,7 @@ public class Loan extends AbstractPersistableCustom { public LocalDate possibleNextRepaymentDate() { LocalDate earliestUnpaidInstallmentDate = new LocalDate(); - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment installment : installments) { if (installment.isNotFullyPaidOff()) { earliestUnpaidInstallmentDate = installment.getDueDate(); @@ -3433,7 +3438,7 @@ public class Loan extends AbstractPersistableCustom { public LoanRepaymentScheduleInstallment possibleNextRepaymentInstallment() { LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment = null; - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment installment : installments) { if (installment.isNotFullyPaidOff()) { loanRepaymentScheduleInstallment = installment; @@ -3453,7 +3458,7 @@ public class Loan extends AbstractPersistableCustom { if (totalInterestOutstanding.isGreaterThanZero()) { // find earliest known instance of overdue interest and default to // that - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment scheduledRepayment : installments) { final Money outstandingForPeriod = scheduledRepayment.getInterestOutstanding(loanCurrency()); @@ -3517,8 +3522,8 @@ public class Loan extends AbstractPersistableCustom { return changedTransactionDetail; } - public ChangedTransactionDetail undoWrittenOff(final List existingTransactionIds, - final List existingReversedTransactionIds, final ScheduleGeneratorDTO scheduleGeneratorDTO, final AppUser currentUser) { + public ChangedTransactionDetail undoWrittenOff(final List existingTransactionIds, final List existingReversedTransactionIds, + final ScheduleGeneratorDTO scheduleGeneratorDTO, final AppUser currentUser) { validateAccountStatus(LoanEvent.WRITE_OFF_OUTSTANDING_UNDO); existingTransactionIds.addAll(findExistingTransactionIds()); @@ -3562,7 +3567,7 @@ public class Loan extends AbstractPersistableCustom { final MonetaryCurrency currency = loanCurrency(); Money cumulativeTotalPaidOnInstallments = Money.zero(currency); Money cumulativeTotalWaivedOnInstallments = Money.zero(currency); - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment scheduledRepayment : installments) { cumulativeTotalPaidOnInstallments = cumulativeTotalPaidOnInstallments @@ -3648,7 +3653,7 @@ public class Loan extends AbstractPersistableCustom { writtenOffOnLocalDate); } - addLoanTransaction(loanTransaction) ; + addLoanTransaction(loanTransaction); loanRepaymentScheduleTransactionProcessor.handleWriteOff(loanTransaction, loanCurrency(), getRepaymentScheduleInstallments()); updateLoanSummaryDerivedFields(); @@ -3675,7 +3680,7 @@ public class Loan extends AbstractPersistableCustom { allNonContraTransactionsPostDisbursement, getCurrency(), getRepaymentScheduleInstallments(), charges()); for (final Map.Entry mapEntry : changedTransactionDetail.getNewTransactionMappings().entrySet()) { mapEntry.getValue().updateLoan(this); - addLoanTransaction(mapEntry.getValue()) ; + addLoanTransaction(mapEntry.getValue()); } updateLoanSummaryDerivedFields(); LoanTransaction loanTransaction = findlatestTransaction(); @@ -3748,7 +3753,7 @@ public class Loan extends AbstractPersistableCustom { errorMessage, closureDate); } - addLoanTransaction(loanTransaction) ; + addLoanTransaction(loanTransaction); loanRepaymentScheduleTransactionProcessor.handleWriteOff(loanTransaction, loanCurrency(), getRepaymentScheduleInstallments()); @@ -4029,7 +4034,7 @@ public class Loan extends AbstractPersistableCustom { private Money getTotalInterestOutstandingOnLoan() { Money cumulativeInterest = Money.zero(loanCurrency()); - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment scheduledRepayment : installments) { cumulativeInterest = cumulativeInterest.plus(scheduledRepayment.getInterestOutstanding(loanCurrency())); } @@ -4040,7 +4045,7 @@ public class Loan extends AbstractPersistableCustom { @SuppressWarnings("unused") private Money getTotalInterestOverdueOnLoan() { Money cumulativeInterestOverdue = Money.zero(this.loanRepaymentScheduleDetail.getPrincipal().getCurrency()); - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment scheduledRepayment : installments) { final Money interestOutstandingForPeriod = scheduledRepayment.getInterestOutstanding(loanCurrency()); @@ -4169,8 +4174,8 @@ public class Loan extends AbstractPersistableCustom { final String errorMessage = "The Loan officer Unassign date(" + unassignDate + ") cannot be before its assignment date (" + latestHistoryRecord.getStartDate() + ")."; - throw new LoanOfficerUnassignmentDateException("cannot.be.before.assignment.date", errorMessage, getId(), getLoanOfficer() - .getId(), latestHistoryRecord.getStartDate(), unassignDate); + throw new LoanOfficerUnassignmentDateException("cannot.be.before.assignment.date", errorMessage, getId(), + getLoanOfficer().getId(), latestHistoryRecord.getStartDate(), unassignDate); } else if (unassignDate.isAfter(today)) { @@ -4231,10 +4236,10 @@ public class Loan extends AbstractPersistableCustom { public Long getGlimId() { Long glimId = null; if (this.glim != null) { - glimId = this.glim.getId(); + glimId = this.glim.getId(); } return glimId; - } + } public Long getOfficeId() { Long officeId = null; @@ -4384,7 +4389,7 @@ public class Loan extends AbstractPersistableCustom { LocalDate newRepaymentDate = null; Boolean isFirstTime = true; LocalDate latestRepaymentDate = null; - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : installments) { LocalDate oldDueDate = loanRepaymentScheduleInstallment.getDueDate(); @@ -4441,7 +4446,7 @@ public class Loan extends AbstractPersistableCustom { LocalDate newRepaymentDate = null; LocalDate seedDate = meetingStartDate; LocalDate latestRepaymentDate = null; - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : installments) { LocalDate oldDueDate = loanRepaymentScheduleInstallment.getDueDate(); @@ -4457,8 +4462,8 @@ public class Loan extends AbstractPersistableCustom { loanRepaymentInterval, tmpFromDate); if (newRepaymentDate.isAfter(maxDateLimitForNewRepayment)) { - newRepaymentDate = CalendarUtils.getNextRepaymentMeetingDate(recuringRule, seedDate, tmpFromDate, - loanRepaymentInterval, frequency, workingDays, isSkipRepaymentonfirstdayofmonth, numberofDays); + newRepaymentDate = CalendarUtils.getNextRepaymentMeetingDate(recuringRule, seedDate, tmpFromDate, loanRepaymentInterval, + frequency, workingDays, isSkipRepaymentonfirstdayofmonth, numberofDays); } if (isHolidayEnabled) { @@ -4511,7 +4516,7 @@ public class Loan extends AbstractPersistableCustom { // first repayment's from date is same as disbursement date. LocalDate tmpFromDate = getDisbursementDate(); // Loop through all loanRepayments - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : installments) { final LocalDate oldDueDate = loanRepaymentScheduleInstallment.getDueDate(); @@ -4620,17 +4625,17 @@ public class Loan extends AbstractPersistableCustom { return this.termPeriodFrequencyType; } - //This method returns copy of all transactions + // This method returns copy of all transactions public List getLoanTransactions() { return this.loanTransactions; } public void addLoanTransaction(final LoanTransaction loanTransaction) { - this.loanTransactions.add(loanTransaction) ; + this.loanTransactions.add(loanTransaction); } public void removeLoanTransaction(final LoanTransaction loanTransaction) { - this.loanTransactions.remove(loanTransaction) ; + this.loanTransactions.remove(loanTransaction); } public void setLoanStatus(final Integer loanStatus) { @@ -4727,7 +4732,9 @@ public class Loan extends AbstractPersistableCustom { } private void validateActivityNotBeforeLastTransactionDate(final LoanEvent event, final LocalDate activityDate) { - if (!(this.repaymentScheduleDetail().isInterestRecalculationEnabled() || this.loanProduct().isHoldGuaranteeFundsEnabled())) { return; } + if (!(this.repaymentScheduleDetail().isInterestRecalculationEnabled() || this.loanProduct().isHoldGuaranteeFundsEnabled())) { + return; + } LocalDate lastTransactionDate = getLastUserTransactionDate(); if (lastTransactionDate.isAfter(activityDate)) { String errorMessage = null; @@ -4813,9 +4820,9 @@ public class Loan extends AbstractPersistableCustom { public List generateInstallmentLoanCharges(final LoanCharge loanCharge) { final List loanChargePerInstallments = new ArrayList<>(); if (loanCharge.isInstalmentFee()) { - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment installment : installments) { - if(installment.isRecalculatedInterestComponent()){ + if (installment.isRecalculatedInterestComponent()) { continue; } BigDecimal amount = BigDecimal.ZERO; @@ -4842,8 +4849,8 @@ public class Loan extends AbstractPersistableCustom { case LOAN_APPROVED: if (!isSubmittedAndPendingApproval()) { final String defaultUserMessage = "Loan Account Approval is not allowed. Loan Account is not in submitted and pending approval state."; - final ApiParameterError error = ApiParameterError.generalError( - "error.msg.loan.approve.account.is.not.submitted.and.pending.state", defaultUserMessage); + final ApiParameterError error = ApiParameterError + .generalError("error.msg.loan.approve.account.is.not.submitted.and.pending.state", defaultUserMessage); dataValidationErrors.add(error); } break; @@ -4859,8 +4866,8 @@ public class Loan extends AbstractPersistableCustom { if ((!(isApproved() && isNotDisbursed()) && !this.loanProduct.isMultiDisburseLoan()) || (this.loanProduct.isMultiDisburseLoan() && !isAllTranchesNotDisbursed())) { final String defaultUserMessage = "Loan Disbursal is not allowed. Loan Account is not in approved and not disbursed state."; - final ApiParameterError error = ApiParameterError.generalError( - "error.msg.loan.disbursal.account.is.not.approve.not.disbursed.state", defaultUserMessage); + final ApiParameterError error = ApiParameterError + .generalError("error.msg.loan.disbursal.account.is.not.approve.not.disbursed.state", defaultUserMessage); dataValidationErrors.add(error); } break; @@ -4871,34 +4878,34 @@ public class Loan extends AbstractPersistableCustom { defaultUserMessage); dataValidationErrors.add(error); } - if(isOpen() && this.isTopup()){ + if (isOpen() && this.isTopup()) { final String defaultUserMessage = "Loan Undo disbursal is not allowed on Topup Loans"; - final ApiParameterError error = ApiParameterError.generalError("error.msg.loan.undo.disbursal.not.allowed.on.topup.loan", - defaultUserMessage); + final ApiParameterError error = ApiParameterError + .generalError("error.msg.loan.undo.disbursal.not.allowed.on.topup.loan", defaultUserMessage); dataValidationErrors.add(error); } break; case LOAN_REPAYMENT_OR_WAIVER: if (!isOpen()) { final String defaultUserMessage = "Loan Repayment or Waiver is not allowed. Loan Account is not active."; - final ApiParameterError error = ApiParameterError.generalError( - "error.msg.loan.repayment.or.waiver.account.is.not.active", defaultUserMessage); + final ApiParameterError error = ApiParameterError + .generalError("error.msg.loan.repayment.or.waiver.account.is.not.active", defaultUserMessage); dataValidationErrors.add(error); } break; case LOAN_REJECTED: if (!isSubmittedAndPendingApproval()) { final String defaultUserMessage = "Loan application cannot be rejected. Loan Account is not in Submitted and Pending approval state."; - final ApiParameterError error = ApiParameterError.generalError( - "error.msg.loan.reject.account.is.not.submitted.pending.approval.state", defaultUserMessage); + final ApiParameterError error = ApiParameterError + .generalError("error.msg.loan.reject.account.is.not.submitted.pending.approval.state", defaultUserMessage); dataValidationErrors.add(error); } break; case LOAN_WITHDRAWN: if (!isSubmittedAndPendingApproval()) { final String defaultUserMessage = "Loan application cannot be withdrawn. Loan Account is not in Submitted and Pending approval state."; - final ApiParameterError error = ApiParameterError.generalError( - "error.msg.loan.withdrawn.account.is.not.submitted.pending.approval.state", defaultUserMessage); + final ApiParameterError error = ApiParameterError + .generalError("error.msg.loan.withdrawn.account.is.not.submitted.pending.approval.state", defaultUserMessage); dataValidationErrors.add(error); } break; @@ -4913,8 +4920,8 @@ public class Loan extends AbstractPersistableCustom { case WRITE_OFF_OUTSTANDING_UNDO: if (!isClosedWrittenOff()) { final String defaultUserMessage = "Loan Undo Written off is not allowed. Loan Account is not Written off."; - final ApiParameterError error = ApiParameterError.generalError( - "error.msg.loan.undo.writtenoff.account.is.not.written.off", defaultUserMessage); + final ApiParameterError error = ApiParameterError + .generalError("error.msg.loan.undo.writtenoff.account.is.not.written.off", defaultUserMessage); dataValidationErrors.add(error); } break; @@ -4939,8 +4946,8 @@ public class Loan extends AbstractPersistableCustom { case LOAN_EDIT_MULTI_DISBURSE_DATE: if (isClosed()) { final String defaultUserMessage = "Edit disbursement is not allowed. Loan Account is not active."; - final ApiParameterError error = ApiParameterError.generalError( - "error.msg.loan.edit.disbursement.account.is.not.active", defaultUserMessage); + final ApiParameterError error = ApiParameterError.generalError("error.msg.loan.edit.disbursement.account.is.not.active", + defaultUserMessage); dataValidationErrors.add(error); } break; @@ -4963,16 +4970,16 @@ public class Loan extends AbstractPersistableCustom { case LOAN_DISBURSAL_UNDO_LAST: if (!isOpen()) { final String defaultUserMessage = "Loan Undo last disbursal is not allowed. Loan Account is not active."; - final ApiParameterError error = ApiParameterError.generalError( - "error.msg.loan.undo.last.disbursal.account.is.not.active", defaultUserMessage); + final ApiParameterError error = ApiParameterError + .generalError("error.msg.loan.undo.last.disbursal.account.is.not.active", defaultUserMessage); dataValidationErrors.add(error); } break; case LOAN_FORECLOSURE: if (!isOpen()) { final String defaultUserMessage = "Loan foreclosure is not allowed. Loan Account is not active."; - final ApiParameterError error = ApiParameterError.generalError( - "error.msg.loan.foreclosure.account.is.not.active", defaultUserMessage); + final ApiParameterError error = ApiParameterError.generalError("error.msg.loan.foreclosure.account.is.not.active", + defaultUserMessage); dataValidationErrors.add(error); } break; @@ -5068,7 +5075,7 @@ public class Loan extends AbstractPersistableCustom { public LoanRepaymentScheduleInstallment fetchRepaymentScheduleInstallment(final Integer installmentNumber) { LoanRepaymentScheduleInstallment installment = null; if (installmentNumber == null) { return installment; } - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment scheduleInstallment : installments) { if (scheduleInstallment.getInstallmentNumber().equals(installmentNumber)) { installment = scheduleInstallment; @@ -5205,15 +5212,15 @@ public class Loan extends AbstractPersistableCustom { if (loanCharges != null) { for (LoanCharge loanCharge : loanCharges) { Integer installmentNumber = null == installment ? null : installment.getInstallmentNumber(); - final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(accrual, loanCharge, loanCharge.getAmount(getCurrency()) - .getAmount(), installmentNumber); + final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(accrual, loanCharge, + loanCharge.getAmount(getCurrency()).getAmount(), installmentNumber); accrual.getLoanChargesPaid().add(loanChargePaidBy); } } if (loanInstallmentCharges != null) { for (LoanInstallmentCharge loanInstallmentCharge : loanInstallmentCharges) { - Integer installmentNumber = null == loanInstallmentCharge.getInstallment() ? null : loanInstallmentCharge.getInstallment() - .getInstallmentNumber(); + Integer installmentNumber = null == loanInstallmentCharge.getInstallment() ? null + : loanInstallmentCharge.getInstallment().getInstallmentNumber(); final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(accrual, loanInstallmentCharge.getLoancharge(), loanInstallmentCharge.getAmount(getCurrency()).getAmount(), installmentNumber); accrual.getLoanChargesPaid().add(loanChargePaidBy); @@ -5237,7 +5244,7 @@ public class Loan extends AbstractPersistableCustom { accrualTransaction); lastCompoundingDate = compoundingDetail.getEffectiveDate(); } - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); LoanRepaymentScheduleInstallment lastInstallment = installments.get(installments.size() - 1); reverseTransactionsPostEffectiveDate(incomeTransactions, lastInstallment.getDueDate()); reverseTransactionsPostEffectiveDate(accrualTransactions, lastInstallment.getDueDate()); @@ -5261,16 +5268,16 @@ public class Loan extends AbstractPersistableCustom { BigDecimal penalties = BigDecimal.ZERO; HashMap feeDetails = new HashMap<>(); - if (this.loanInterestRecalculationDetails.getInterestRecalculationCompoundingMethod().equals( - InterestRecalculationCompoundingMethod.INTEREST)) { + if (this.loanInterestRecalculationDetails.getInterestRecalculationCompoundingMethod() + .equals(InterestRecalculationCompoundingMethod.INTEREST)) { interest = compoundingDetail.getAmount(); - } else if (this.loanInterestRecalculationDetails.getInterestRecalculationCompoundingMethod().equals( - InterestRecalculationCompoundingMethod.FEE)) { + } else if (this.loanInterestRecalculationDetails.getInterestRecalculationCompoundingMethod() + .equals(InterestRecalculationCompoundingMethod.FEE)) { determineFeeDetails(lastCompoundingDate, compoundingDetail.getEffectiveDate(), feeDetails); fee = (BigDecimal) feeDetails.get("fee"); penalties = (BigDecimal) feeDetails.get("penalties"); - } else if (this.loanInterestRecalculationDetails.getInterestRecalculationCompoundingMethod().equals( - InterestRecalculationCompoundingMethod.INTEREST_AND_FEE)) { + } else if (this.loanInterestRecalculationDetails.getInterestRecalculationCompoundingMethod() + .equals(InterestRecalculationCompoundingMethod.INTEREST_AND_FEE)) { determineFeeDetails(lastCompoundingDate, compoundingDetail.getEffectiveDate(), feeDetails); fee = (BigDecimal) feeDetails.get("fee"); penalties = (BigDecimal) feeDetails.get("penalties"); @@ -5278,13 +5285,13 @@ public class Loan extends AbstractPersistableCustom { } if (existingIncomeTransaction == null) { - LoanTransaction transaction = LoanTransaction.incomePosting(this, this.getOffice(), compoundingDetail.getEffectiveDate() - .toDate(), compoundingDetail.getAmount(), interest, fee, penalties, currentUser); + LoanTransaction transaction = LoanTransaction.incomePosting(this, this.getOffice(), + compoundingDetail.getEffectiveDate().toDate(), compoundingDetail.getAmount(), interest, fee, penalties, currentUser); addLoanTransaction(transaction); } else if (existingIncomeTransaction.getAmount(getCurrency()).getAmount().compareTo(compoundingDetail.getAmount()) != 0) { existingIncomeTransaction.reverse(); - LoanTransaction transaction = LoanTransaction.incomePosting(this, this.getOffice(), compoundingDetail.getEffectiveDate() - .toDate(), compoundingDetail.getAmount(), interest, fee, penalties, currentUser); + LoanTransaction transaction = LoanTransaction.incomePosting(this, this.getOffice(), + compoundingDetail.getEffectiveDate().toDate(), compoundingDetail.getAmount(), interest, fee, penalties, currentUser); addLoanTransaction(transaction); } @@ -5310,7 +5317,7 @@ public class Loan extends AbstractPersistableCustom { BigDecimal penalties = BigDecimal.ZERO; List installments = new ArrayList<>(); - List repaymentSchedule = getRepaymentScheduleInstallments() ; + List repaymentSchedule = getRepaymentScheduleInstallments(); for (LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment : repaymentSchedule) { if (loanRepaymentScheduleInstallment.getDueDate().isAfter(fromDate) && !loanRepaymentScheduleInstallment.getDueDate().isAfter(toDate)) { @@ -5362,7 +5369,7 @@ public class Loan extends AbstractPersistableCustom { private List extractInterestRecalculationAdditionalDetails() { List retDetails = new ArrayList<>(); - List repaymentSchedule = getRepaymentScheduleInstallments() ; + List repaymentSchedule = getRepaymentScheduleInstallments(); if (null != this.repaymentScheduleInstallments && this.repaymentScheduleInstallments.size() > 0) { Iterator installmentsItr = repaymentSchedule.iterator(); while (installmentsItr.hasNext()) { @@ -5490,15 +5497,16 @@ public class Loan extends AbstractPersistableCustom { this.maxOutstandingLoanBalance, interestChargedFromDate, this.loanProduct.getPrincipalThresholdForLastInstallment(), this.loanProduct.getInstallmentAmountInMultiplesOf(), recalculationFrequencyType, restCalendarInstance, compoundingMethod, compoundingCalendarInstance, compoundingFrequencyType, this.loanProduct.preCloseInterestCalculationStrategy(), - rescheduleStrategyMethod, calendar, getApprovedPrincipal(), annualNominalInterestRate, loanTermVariations, calendarHistoryDataWrapper, - scheduleGeneratorDTO.getNumberOfdays(), scheduleGeneratorDTO.isSkipRepaymentOnFirstDayofMonth(), holidayDetailDTO, allowCompoundingOnEod); + rescheduleStrategyMethod, calendar, getApprovedPrincipal(), annualNominalInterestRate, loanTermVariations, + calendarHistoryDataWrapper, scheduleGeneratorDTO.getNumberOfdays(), scheduleGeneratorDTO.isSkipRepaymentOnFirstDayofMonth(), + holidayDetailDTO, allowCompoundingOnEod); return loanApplicationTerms; } public BigDecimal constructLoanTermVariations(FloatingRateDTO floatingRateDTO, BigDecimal annualNominalInterestRate, List loanTermVariations) { for (LoanTermVariations variationTerms : this.loanTermVariations) { - if(variationTerms.isActive()) { + if (variationTerms.isActive()) { loanTermVariations.add(variationTerms.toData()); } } @@ -5512,7 +5520,7 @@ public class Loan extends AbstractPersistableCustom { Money totalPrincipal = Money.zero(loanCurrency()); Money totalInterest = Money.zero(loanCurrency()); final Set compoundingDetails = null; - List repaymentSchedule = getRepaymentScheduleInstallments() ; + List repaymentSchedule = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment scheduledRepayment : repaymentSchedule) { totalPrincipal = totalPrincipal.plus(scheduledRepayment.getPrincipalOutstanding(loanCurrency())); totalInterest = totalInterest.plus(scheduledRepayment.getInterestOutstanding(loanCurrency())); @@ -5577,12 +5585,14 @@ public class Loan extends AbstractPersistableCustom { } public Integer getLoanRepaymentScheduleInstallmentsSize() { - return this.repaymentScheduleInstallments.size() ; + return this.repaymentScheduleInstallments.size(); } + public void addLoanRepaymentScheduleInstallment(final LoanRepaymentScheduleInstallment installment) { installment.updateLoan(this); this.repaymentScheduleInstallments.add(installment); } + /** * @return Loan product minimum repayments schedule related detail **/ @@ -5613,7 +5623,7 @@ public class Loan extends AbstractPersistableCustom { LoanRepaymentScheduleInstallment installment = null; if (dueDate != null) { - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (LoanRepaymentScheduleInstallment repaymentScheduleInstallment : installments) { if (repaymentScheduleInstallment.getDueDate().isEqual(dueDate)) { @@ -5873,8 +5883,9 @@ public class Loan extends AbstractPersistableCustom { private void validateRefundDateIsAfterLastRepayment(final LocalDate refundTransactionDate) { final LocalDate possibleNextRefundDate = possibleNextRefundDate(); - if (possibleNextRefundDate == null || refundTransactionDate.isBefore(possibleNextRefundDate)) { throw new InvalidRefundDateException( - refundTransactionDate.toString()); } + if (possibleNextRefundDate == null || refundTransactionDate.isBefore(possibleNextRefundDate)) { + throw new InvalidRefundDateException(refundTransactionDate.toString()); + } } @@ -5986,7 +5997,7 @@ public class Loan extends AbstractPersistableCustom { public void addTrancheLoanCharge(final Charge charge) { final List appliedCharges = new ArrayList<>(); - for(final LoanTrancheCharge loanTrancheCharge: this.trancheCharges){ + for (final LoanTrancheCharge loanTrancheCharge : this.trancheCharges) { appliedCharges.add(loanTrancheCharge.getCharge()); } if (!appliedCharges.contains(charge)) { @@ -6008,8 +6019,9 @@ public class Loan extends AbstractPersistableCustom { Collections.reverse(loanTransactions); for (final LoanTransaction previousTransaction : loanTransactions) { if (lastTransactionDate.isBefore(previousTransaction.getTransactionDate())) { - if (previousTransaction.isRepayment() || previousTransaction.isWaiver() || previousTransaction.isChargePayment()) { throw new UndoLastTrancheDisbursementException( - previousTransaction.getId()); } + if (previousTransaction.isRepayment() || previousTransaction.isWaiver() || previousTransaction.isChargePayment()) { + throw new UndoLastTrancheDisbursementException(previousTransaction.getId()); + } } if (previousTransaction.isDisbursement()) { lastTransactionDate = previousTransaction.getTransactionDate(); @@ -6023,7 +6035,7 @@ public class Loan extends AbstractPersistableCustom { if ((loanTermVariations.getTermType().isDueDateVariation() && loanTermVariations.fetchDateValue().isAfter(actualDisbursementDate)) || (loanTermVariations.getTermType().isEMIAmountVariation() - && loanTermVariations.getTermApplicableFrom().equals(actualDisbursementDate.toDate())) + && loanTermVariations.getTermApplicableFrom().equals(actualDisbursementDate.toDate())) || loanTermVariations.getTermApplicableFrom().after(actualDisbursementDate.toDate())) { iterator.remove(); } @@ -6048,8 +6060,9 @@ public class Loan extends AbstractPersistableCustom { public List reverseExistingTransactionsTillLastDisbursal(LocalDate actualDisbursementDate) { final List reversedTransactions = new ArrayList<>(); for (final LoanTransaction transaction : this.loanTransactions) { - if ((actualDisbursementDate.equals(transaction.getTransactionDate()) || actualDisbursementDate.isBefore(transaction - .getTransactionDate())) && transaction.isAllowTypeTransactionAtTheTimeOfLastUndo()) { + if ((actualDisbursementDate.equals(transaction.getTransactionDate()) + || actualDisbursementDate.isBefore(transaction.getTransactionDate())) + && transaction.isAllowTypeTransactionAtTheTimeOfLastUndo()) { reversedTransactions.add(transaction); transaction.reverse(); } @@ -6062,9 +6075,8 @@ public class Loan extends AbstractPersistableCustom { for (final LoanCharge charge : charges()) { if (charge.isOverdueInstallmentCharge()) { charge.setActive(false); - } else if (charge.isTrancheDisbursementCharge() - && actualDisbursementDate.equals(new LocalDate(charge.getTrancheDisbursementCharge().getloanDisbursementDetails() - .actualDisbursementDate()))) { + } else if (charge.isTrancheDisbursementCharge() && actualDisbursementDate + .equals(new LocalDate(charge.getTrancheDisbursementCharge().getloanDisbursementDetails().actualDisbursementDate()))) { charge.resetToOriginal(loanCurrency()); } } @@ -6111,7 +6123,7 @@ public class Loan extends AbstractPersistableCustom { public int fetchNumberOfInstallmensAfterExceptions() { if (this.repaymentScheduleInstallments.size() > 0) { - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); int numberOfInstallments = 0; for (final LoanRepaymentScheduleInstallment installment : installments) { if (!installment.isRecalculatedInterestComponent()) { @@ -6135,11 +6147,11 @@ public class Loan extends AbstractPersistableCustom { LocalDate nextRepaymentDate = new LocalDate(); for (LoanDisbursementDetails loanDisbursementDetail : loanDisbursementDetails) { if (loanDisbursementDetail.actualDisbursementDate() == null) { - List installments = getRepaymentScheduleInstallments() ; + List installments = getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment installment : installments) { if (installment.getDueDate().isEqual(loanDisbursementDetail.expectedDisbursementDateAsLocalDate()) || (installment.getDueDate().isAfter(loanDisbursementDetail.expectedDisbursementDateAsLocalDate()) - && installment.isNotFullyPaidOff())) { + && installment.isNotFullyPaidOff())) { nextRepaymentDate = installment.getDueDate(); break; } @@ -6176,7 +6188,6 @@ public class Loan extends AbstractPersistableCustom { this.writeOffReason = writeOffReason; } - public Group getGroup() { return group; } @@ -6210,8 +6221,7 @@ public class Loan extends AbstractPersistableCustom { } else if (installment.getFromDate().isBefore(paymentDate)) { Money[] balancesForCurrentPeroid = fetchInterestFeeAndPenaltyTillDate(paymentDate, currency, installment); if (balancesForCurrentPeroid[0].isGreaterThan(balancesForCurrentPeroid[5])) { - interest = interest.plus(balancesForCurrentPeroid[0]) - .minus(balancesForCurrentPeroid[5]); + interest = interest.plus(balancesForCurrentPeroid[0]).minus(balancesForCurrentPeroid[5]); } else { paidFromFutureInstallments = paidFromFutureInstallments.plus(balancesForCurrentPeroid[5]) .minus(balancesForCurrentPeroid[0]); @@ -6219,12 +6229,14 @@ public class Loan extends AbstractPersistableCustom { if (balancesForCurrentPeroid[1].isGreaterThan(balancesForCurrentPeroid[3])) { fee = fee.plus(balancesForCurrentPeroid[1].minus(balancesForCurrentPeroid[3])); } else { - paidFromFutureInstallments = paidFromFutureInstallments.plus(balancesForCurrentPeroid[3].minus(balancesForCurrentPeroid[1])); + paidFromFutureInstallments = paidFromFutureInstallments + .plus(balancesForCurrentPeroid[3].minus(balancesForCurrentPeroid[1])); } if (balancesForCurrentPeroid[2].isGreaterThan(balancesForCurrentPeroid[4])) { penalty = penalty.plus(balancesForCurrentPeroid[2].minus(balancesForCurrentPeroid[4])); } else { - paidFromFutureInstallments = paidFromFutureInstallments.plus(balancesForCurrentPeroid[4]).minus(balancesForCurrentPeroid[2]); + paidFromFutureInstallments = paidFromFutureInstallments.plus(balancesForCurrentPeroid[4]) + .minus(balancesForCurrentPeroid[2]); } } else if (installment.getDueDate().isAfter(paymentDate)) { paidFromFutureInstallments = paidFromFutureInstallments.plus(installment.getInterestPaid(currency)) @@ -6239,41 +6251,39 @@ public class Loan extends AbstractPersistableCustom { return balances; } - private Money[] fetchInterestFeeAndPenaltyTillDate(final LocalDate paymentDate, final MonetaryCurrency currency, final LoanRepaymentScheduleInstallment installment) { + private Money[] fetchInterestFeeAndPenaltyTillDate(final LocalDate paymentDate, final MonetaryCurrency currency, + final LoanRepaymentScheduleInstallment installment) { Money penaltyForCurrentPeriod = Money.zero(getCurrency()); Money penaltyAccoutedForCurrentPeriod = Money.zero(getCurrency()); Money feeForCurrentPeriod = Money.zero(getCurrency()); Money feeAccountedForCurrentPeriod = Money.zero(getCurrency()); - Money interestForCurrentPeriod=Money.zero(getCurrency()); - Money interestAccountedForCurrentPeriod=Money.zero(getCurrency()); + Money interestForCurrentPeriod = Money.zero(getCurrency()); + Money interestAccountedForCurrentPeriod = Money.zero(getCurrency()); int totalPeriodDays = Days.daysBetween(installment.getFromDate(), installment.getDueDate()).getDays(); int tillDays = Days.daysBetween(installment.getFromDate(), paymentDate).getDays(); - interestForCurrentPeriod = Money.of(getCurrency(),BigDecimal.valueOf(calculateInterestForDays(totalPeriodDays, installment.getInterestCharged(getCurrency()) - .getAmount(), tillDays))); + interestForCurrentPeriod = Money.of(getCurrency(), BigDecimal + .valueOf(calculateInterestForDays(totalPeriodDays, installment.getInterestCharged(getCurrency()).getAmount(), tillDays))); interestAccountedForCurrentPeriod = installment.getInterestWaived(getCurrency()).plus(installment.getInterestPaid(getCurrency())); for (LoanCharge loanCharge : this.charges) { if (loanCharge.isActive() && !loanCharge.isDueAtDisbursement()) { if (loanCharge.isDueForCollectionFromAndUpToAndIncluding(installment.getFromDate(), paymentDate)) { if (loanCharge.isPenaltyCharge()) { penaltyForCurrentPeriod = penaltyForCurrentPeriod.plus(loanCharge.getAmount(getCurrency())); - penaltyAccoutedForCurrentPeriod = penaltyAccoutedForCurrentPeriod.plus(loanCharge - .getAmountWaived(getCurrency()).plus(loanCharge.getAmountPaid(getCurrency()))); + penaltyAccoutedForCurrentPeriod = penaltyAccoutedForCurrentPeriod + .plus(loanCharge.getAmountWaived(getCurrency()).plus(loanCharge.getAmountPaid(getCurrency()))); } else { feeForCurrentPeriod = feeForCurrentPeriod.plus(loanCharge.getAmount(currency)); - feeAccountedForCurrentPeriod = feeAccountedForCurrentPeriod - .plus(loanCharge.getAmountWaived(getCurrency()).plus( + feeAccountedForCurrentPeriod = feeAccountedForCurrentPeriod.plus(loanCharge.getAmountWaived(getCurrency()).plus( - loanCharge.getAmountPaid(getCurrency()))); + loanCharge.getAmountPaid(getCurrency()))); } } else if (loanCharge.isInstalmentFee()) { - LoanInstallmentCharge loanInstallmentCharge = loanCharge - .getInstallmentLoanCharge(installment.getInstallmentNumber()); + LoanInstallmentCharge loanInstallmentCharge = loanCharge.getInstallmentLoanCharge(installment.getInstallmentNumber()); if (loanCharge.isPenaltyCharge()) { penaltyAccoutedForCurrentPeriod = penaltyAccoutedForCurrentPeriod .plus(loanInstallmentCharge.getAmountPaid(currency)); } else { - feeAccountedForCurrentPeriod = feeAccountedForCurrentPeriod - .plus(loanInstallmentCharge.getAmountPaid(currency)); + feeAccountedForCurrentPeriod = feeAccountedForCurrentPeriod.plus(loanInstallmentCharge.getAmountPaid(currency)); } } } @@ -6289,13 +6299,12 @@ public class Loan extends AbstractPersistableCustom { return balances; } - public Money[] retriveIncomeForOverlappingPeriod(final LocalDate paymentDate) { Money[] balances = new Money[3]; final MonetaryCurrency currency = getCurrency(); balances[0] = balances[1] = balances[2] = Money.zero(currency); for (final LoanRepaymentScheduleInstallment installment : this.repaymentScheduleInstallments) { - if (installment.getDueDate().isEqual(paymentDate)){ + if (installment.getDueDate().isEqual(paymentDate)) { Money interest = installment.getInterestCharged(currency); Money fee = installment.getFeeChargesCharged(currency); Money penalty = installment.getPenaltyChargesCharged(currency); @@ -6303,7 +6312,7 @@ public class Loan extends AbstractPersistableCustom { balances[1] = fee; balances[2] = penalty; break; - }else if(installment.getDueDate().isAfter(paymentDate) && installment.getFromDate().isBefore(paymentDate)){ + } else if (installment.getDueDate().isAfter(paymentDate) && installment.getFromDate().isBefore(paymentDate)) { balances = fetchInterestFeeAndPenaltyTillDate(paymentDate, currency, installment); break; } @@ -6311,6 +6320,7 @@ public class Loan extends AbstractPersistableCustom { return balances; } + private double calculateInterestForDays(int daysInPeriod, BigDecimal interest, int days) { if (interest.doubleValue() == 0) { return 0; } return interest.doubleValue() / daysInPeriod * days; @@ -6423,12 +6433,12 @@ public class Loan extends AbstractPersistableCustom { List newInstallments = new ArrayList<>(this.repaymentScheduleInstallments); final MonetaryCurrency currency = getCurrency(); Money totalPrincipal = Money.zero(currency); - Money [] balances = retriveIncomeForOverlappingPeriod(transactionDate); + Money[] balances = retriveIncomeForOverlappingPeriod(transactionDate); boolean isInterestComponent = true; for (final LoanRepaymentScheduleInstallment installment : this.repaymentScheduleInstallments) { if (!installment.getDueDate().isBefore(transactionDate)) { - totalPrincipal = totalPrincipal.plus(installment.getPrincipal(currency)); - newInstallments.remove(installment); + totalPrincipal = totalPrincipal.plus(installment.getPrincipal(currency)); + newInstallments.remove(installment); if (installment.getDueDate().isEqual(transactionDate)) { isInterestComponent = false; } @@ -6436,9 +6446,9 @@ public class Loan extends AbstractPersistableCustom { } - for(LoanDisbursementDetails loanDisbursementDetails : getDisbursementDetails()){ - if(loanDisbursementDetails.actualDisbursementDate() == null){ - totalPrincipal = Money.of(currency, totalPrincipal.getAmount().subtract(loanDisbursementDetails.principal())); + for (LoanDisbursementDetails loanDisbursementDetails : getDisbursementDetails()) { + if (loanDisbursementDetails.actualDisbursementDate() == null) { + totalPrincipal = Money.of(currency, totalPrincipal.getAmount().subtract(loanDisbursementDetails.principal())); } } @@ -6454,10 +6464,9 @@ public class Loan extends AbstractPersistableCustom { installmentNumber++; } - LoanRepaymentScheduleInstallment newInstallment = new LoanRepaymentScheduleInstallment(null, newInstallments.size() + 1, - installmentStartDate, transactionDate, totalPrincipal.getAmount(), - balances[0].getAmount(), balances[1].getAmount(), balances[2].getAmount(), isInterestComponent, null); + installmentStartDate, transactionDate, totalPrincipal.getAmount(), balances[0].getAmount(), balances[1].getAmount(), + balances[2].getAmount(), isInterestComponent, null); newInstallment.updateInstallmentNumber(newInstallments.size() + 1); newInstallments.add(newInstallment); updateLoanScheduleOnForeclosure(newInstallments); @@ -6465,8 +6474,7 @@ public class Loan extends AbstractPersistableCustom { Set charges = this.charges(); int penaltyWaitPeriod = 0; for (LoanCharge loanCharge : charges) { - if (loanCharge.getDueLocalDate() != null - && loanCharge.getDueLocalDate().isAfter(transactionDate)) { + if (loanCharge.getDueLocalDate() != null && loanCharge.getDueLocalDate().isAfter(transactionDate)) { loanCharge.setActive(false); } else if (loanCharge.getDueLocalDate() == null) { recalculateLoanCharge(loanCharge, penaltyWaitPeriod); @@ -6476,14 +6484,11 @@ public class Loan extends AbstractPersistableCustom { for (LoanTransaction loanTransaction : getLoanTransactions()) { if (loanTransaction.isChargesWaiver()) { - for (LoanChargePaidBy chargePaidBy : loanTransaction - .getLoanChargesPaid()) { - if ((chargePaidBy.getLoanCharge().isDueDateCharge() && chargePaidBy - .getLoanCharge().getDueLocalDate() - .isAfter(transactionDate)) - || (chargePaidBy.getLoanCharge().isInstalmentFee() && chargePaidBy - .getInstallmentNumber() != null && chargePaidBy - .getInstallmentNumber() > installmentNumber)) { + for (LoanChargePaidBy chargePaidBy : loanTransaction.getLoanChargesPaid()) { + if ((chargePaidBy.getLoanCharge().isDueDateCharge() + && chargePaidBy.getLoanCharge().getDueLocalDate().isAfter(transactionDate)) + || (chargePaidBy.getLoanCharge().isInstalmentFee() && chargePaidBy.getInstallmentNumber() != null + && chargePaidBy.getInstallmentNumber() > installmentNumber)) { loanTransaction.reverse(); } } @@ -6503,9 +6508,9 @@ public class Loan extends AbstractPersistableCustom { return this.loanSubStatus; } - private boolean isForeclosure(){ + private boolean isForeclosure() { boolean isForeClosure = false; - if(this.loanSubStatus != null){ + if (this.loanSubStatus != null) { isForeClosure = LoanSubStatus.fromInt(loanSubStatus).isForeclosed(); } @@ -6514,14 +6519,14 @@ public class Loan extends AbstractPersistableCustom { public Set getActiveLoanTermVariations() { Set retData = new HashSet<>(); - if(this.loanTermVariations != null && this.loanTermVariations.size() > 0){ + if (this.loanTermVariations != null && this.loanTermVariations.size() > 0) { for (LoanTermVariations loanTermVariations : this.loanTermVariations) { - if(loanTermVariations.isActive()){ + if (loanTermVariations.isActive()) { retData.add(loanTermVariations); } } } - return retData.size()>0?retData:null; + return retData.size() > 0 ? retData : null; } public void setIsTopup(final boolean isTopup) { @@ -6535,11 +6540,11 @@ public class Loan extends AbstractPersistableCustom { public BigDecimal getFirstDisbursalAmount() { BigDecimal firstDisbursalAmount; - if(this.isMultiDisburmentLoan()){ + if (this.isMultiDisburmentLoan()) { List disbursementData = getDisbursmentData(); Collections.sort(disbursementData); - firstDisbursalAmount = disbursementData.get(disbursementData.size()-1).amount(); - }else{ + firstDisbursalAmount = disbursementData.get(disbursementData.size() - 1).amount(); + } else { firstDisbursalAmount = this.getLoanRepaymentScheduleDetail().getPrincipal().getAmount(); } return firstDisbursalAmount; @@ -6556,6 +6561,7 @@ public class Loan extends AbstractPersistableCustom { public Collection getLoanCharges() { return this.charges; } + public void initializeLazyCollections() { checkAndFetchLazyCollection(this.charges); checkAndFetchLazyCollection(this.trancheCharges); @@ -6567,27 +6573,31 @@ public class Loan extends AbstractPersistableCustom { checkAndFetchLazyCollection(this.loanOfficerHistory); } - private void checkAndFetchLazyCollection(Collection lazyCollection){ + private void checkAndFetchLazyCollection(Collection lazyCollection) { if (lazyCollection != null) { lazyCollection.size(); } } + public void initializeLoanOfficerHistory() { - this.loanOfficerHistory.size() ; + this.loanOfficerHistory.size(); } public void initilizeTransactions() { - this.loanTransactions.size() ; + this.loanTransactions.size(); } public void initializeRepaymentSchedule() { - this.repaymentScheduleInstallments.size() ; + this.repaymentScheduleInstallments.size(); } + public boolean hasInvalidLoanType() { return AccountType.fromInt(this.loanType).isInvalid(); } - public boolean isIndividualLoan(){return AccountType.fromInt(this.loanType).isIndividualAccount();} + public boolean isIndividualLoan() { + return AccountType.fromInt(this.loanType).isIndividualAccount(); + } public void setRates(List rates) { this.rates = rates; @@ -6599,10 +6609,10 @@ public class Loan extends AbstractPersistableCustom { public Integer getLoanType() { return loanType; - } + } - public void setLoanType(Integer loanType) { + public void setLoanType(Integer loanType) { this.loanType = loanType; - } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanAccountDomainService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanAccountDomainService.java old mode 100755 new mode 100644 index 4e0468e1e..fc1e3d5ce --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanAccountDomainService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanAccountDomainService.java @@ -29,7 +29,8 @@ public interface LoanAccountDomainService { LoanTransaction makeRepayment(Loan loan, CommandProcessingResultBuilder builderResult, LocalDate transactionDate, BigDecimal transactionAmount, PaymentDetail paymentDetail, String noteText, String txnExternalId, - final boolean isRecoveryRepayment, boolean isAccountTransfer, HolidayDetailDTO holidatDetailDto, Boolean isHolidayValidationDone); + final boolean isRecoveryRepayment, boolean isAccountTransfer, HolidayDetailDTO holidatDetailDto, + Boolean isHolidayValidationDone); LoanTransaction makeRefund(Long accountId, CommandProcessingResultBuilder builderResult, LocalDate transactionDate, BigDecimal transactionAmount, PaymentDetail paymentDetail, String noteText, String txnExternalId); @@ -68,7 +69,8 @@ public interface LoanAccountDomainService { /** * Disables all standing instructions linked to a closed loan * - * @param loan {@link Loan} object + * @param loan + * {@link Loan} object */ void disableStandingInstructionsLinkedToClosedLoan(Loan loan); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanAccountDomainServiceJpa.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanAccountDomainServiceJpa.java old mode 100755 new mode 100644 index 06bda57cf..ae112b724 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanAccountDomainServiceJpa.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanAccountDomainServiceJpa.java @@ -139,8 +139,8 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { final LocalDate transactionDate, final BigDecimal transactionAmount, final PaymentDetail paymentDetail, final String noteText, final String txnExternalId, final boolean isRecoveryRepayment, boolean isAccountTransfer, HolidayDetailDTO holidayDetailDto, Boolean isHolidayValidationDone) { - return makeRepayment(loan, builderResult, transactionDate, transactionAmount, paymentDetail, noteText, - txnExternalId, isRecoveryRepayment, isAccountTransfer, holidayDetailDto, isHolidayValidationDone, false); + return makeRepayment(loan, builderResult, transactionDate, transactionAmount, paymentDetail, noteText, txnExternalId, + isRecoveryRepayment, isAccountTransfer, holidayDetailDto, isHolidayValidationDone, false); } @Transactional @@ -225,13 +225,12 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_MAKE_REPAYMENT, constructEntityMap(BusinessEntity.LOAN_TRANSACTION, newRepaymentTransaction)); - // disable all active standing orders linked to this loan if status changes to closed + // disable all active standing orders linked to this loan if status + // changes to closed disableStandingInstructionsLinkedToClosedLoan(loan); - builderResult.withEntityId(newRepaymentTransaction.getId()) - .withOfficeId(loan.getOfficeId()) - .withClientId(loan.getClientId()) - .withGroupId(loan.getGroupId()); + builderResult.withEntityId(newRepaymentTransaction.getId()).withOfficeId(loan.getOfficeId()).withClientId(loan.getClientId()) + .withGroupId(loan.getGroupId()); return newRepaymentTransaction; } @@ -245,10 +244,12 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.transaction"); if (realCause.getMessage().toLowerCase().contains("external_id_unique")) { baseDataValidator.reset().parameter("externalId").value(newRepaymentTransaction.getExternalId()) - .failWithCode("value.must.be.unique"); + .failWithCode("value.must.be.unique"); + } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } } } @@ -268,8 +269,10 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { if (realCause.getMessage().toLowerCase().contains("external_id_unique")) { baseDataValidator.reset().parameter("externalId").failWithCode("value.must.be.unique"); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } @@ -290,8 +293,10 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { if (realCause.getMessage().toLowerCase().contains("external_id_unique")) { baseDataValidator.reset().parameter("externalId").failWithCode("value.must.be.unique"); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } @@ -346,7 +351,7 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { private void postJournalEntries(final Loan loanAccount, final List existingTransactionIds, final List existingReversedTransactionIds, boolean isAccountTransfer) { - postJournalEntries(loanAccount,existingTransactionIds,existingReversedTransactionIds,isAccountTransfer, false); + postJournalEntries(loanAccount, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer, false); } private void postJournalEntries(final Loan loanAccount, final List existingTransactionIds, @@ -394,8 +399,8 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { final LoanTransaction newRefundTransaction = LoanTransaction.refund(loan.getOffice(), refundAmount, paymentDetail, transactionDate, txnExternalId, DateUtils.getLocalDateTimeOfTenant(), currentUser); final boolean allowTransactionsOnHoliday = this.configurationDomainService.allowTransactionsOnHolidayEnabled(); - final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(loan.getOfficeId(), - transactionDate.toDate(), HolidayStatusType.ACTIVE.getValue()); + final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(loan.getOfficeId(), transactionDate.toDate(), + HolidayStatusType.ACTIVE.getValue()); final WorkingDays workingDays = this.workingDaysRepository.findOne(); final boolean allowTransactionsOnNonWorkingDay = this.configurationDomainService.allowTransactionsOnNonWorkingDayEnabled(); @@ -413,10 +418,8 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { postJournalEntries(loan, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer); this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_REFUND, constructEntityMap(BusinessEntity.LOAN_TRANSACTION, newRefundTransaction)); - builderResult.withEntityId(newRefundTransaction.getId()) - .withOfficeId(loan.getOfficeId()) - .withClientId(loan.getClientId()) - .withGroupId(loan.getGroupId()); + builderResult.withEntityId(newRefundTransaction.getId()).withOfficeId(loan.getOfficeId()).withClientId(loan.getClientId()) + .withGroupId(loan.getGroupId()); return newRefundTransaction; } @@ -466,7 +469,8 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { * * @see * org.apache.fineract.portfolio.loanaccount.domain.LoanAccountDomainService - * #recalculateAccruals(org.apache.fineract.portfolio.loanaccount.domain.Loan) + * #recalculateAccruals(org.apache.fineract.portfolio.loanaccount.domain. + * Loan) */ @Override public void recalculateAccruals(Loan loan) { @@ -477,12 +481,14 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { @Override public void recalculateAccruals(Loan loan, boolean isInterestCalcualtionHappened) { LocalDate accruedTill = loan.getAccruedTill(); - if (!loan.isPeriodicAccrualAccountingEnabledOnLoanProduct() || !isInterestCalcualtionHappened - || accruedTill == null || loan.isNpa() || !loan.status().isActive()) { return; } + if (!loan.isPeriodicAccrualAccountingEnabledOnLoanProduct() || !isInterestCalcualtionHappened || accruedTill == null || loan.isNpa() + || !loan.status().isActive()) { + return; + } boolean isOrganisationDateEnabled = this.configurationDomainService.isOrganisationstartDateEnabled(); Date organisationStartDate = new Date(); - if(isOrganisationDateEnabled){ + if (isOrganisationDateEnabled) { organisationStartDate = this.configurationDomainService.retrieveOrganisationStartDate(); } Collection loanScheduleAccrualDatas = new ArrayList<>(); @@ -503,9 +509,10 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { if (installment.getDueDate().isAfter(loan.getMaturityDate())) { accruedTill = DateUtils.getLocalDateOfTenant(); } - if(!isOrganisationDateEnabled || new LocalDate(organisationStartDate).isBefore(installment.getDueDate())){ - generateLoanScheduleAccrualData(accruedTill, loanScheduleAccrualDatas, loanId, officeId, accrualStartDate, repaymentFrequency, - repayEvery, interestCalculatedFrom, loanProductId, currency, currencyData, loanCharges, installment); + if (!isOrganisationDateEnabled || new LocalDate(organisationStartDate).isBefore(installment.getDueDate())) { + generateLoanScheduleAccrualData(accruedTill, loanScheduleAccrualDatas, loanId, officeId, accrualStartDate, + repaymentFrequency, repayEvery, interestCalculatedFrom, loanProductId, currency, currencyData, loanCharges, + installment); } } @@ -519,10 +526,11 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { } } - private void generateLoanScheduleAccrualData(final LocalDate accruedTill, final Collection loanScheduleAccrualDatas, - final Long loanId, Long officeId, final LocalDate accrualStartDate, final PeriodFrequencyType repaymentFrequency, final Integer repayEvery, - final LocalDate interestCalculatedFrom, final Long loanProductId, final MonetaryCurrency currency, final CurrencyData currencyData, - final Set loanCharges, final LoanRepaymentScheduleInstallment installment) { + private void generateLoanScheduleAccrualData(final LocalDate accruedTill, + final Collection loanScheduleAccrualDatas, final Long loanId, Long officeId, + final LocalDate accrualStartDate, final PeriodFrequencyType repaymentFrequency, final Integer repayEvery, + final LocalDate interestCalculatedFrom, final Long loanProductId, final MonetaryCurrency currency, + final CurrencyData currencyData, final Set loanCharges, final LoanRepaymentScheduleInstallment installment) { if (!accruedTill.isBefore(installment.getDueDate()) || (accruedTill.isAfter(installment.getFromDate()) && !accruedTill.isAfter(installment.getDueDate()))) { @@ -544,11 +552,11 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { } LoanScheduleAccrualData accrualData = new LoanScheduleAccrualData(loanId, officeId, installment.getInstallmentNumber(), accrualStartDate, repaymentFrequency, repayEvery, installment.getDueDate(), installment.getFromDate(), - installment.getId(), loanProductId, installment.getInterestCharged(currency).getAmount(), installment - .getFeeChargesCharged(currency).getAmount(), installment.getPenaltyChargesCharged(currency).getAmount(), - installment.getInterestAccrued(currency).getAmount(), installment.getFeeAccrued(currency).getAmount(), installment - .getPenaltyAccrued(currency).getAmount(), currencyData, interestCalculatedFrom, installment - .getInterestWaived(currency).getAmount()); + installment.getId(), loanProductId, installment.getInterestCharged(currency).getAmount(), + installment.getFeeChargesCharged(currency).getAmount(), installment.getPenaltyChargesCharged(currency).getAmount(), + installment.getInterestAccrued(currency).getAmount(), installment.getFeeAccrued(currency).getAmount(), + installment.getPenaltyAccrued(currency).getAmount(), currencyData, interestCalculatedFrom, + installment.getInterestWaived(currency).getAmount()); loanScheduleAccrualDatas.add(accrualData); } @@ -585,8 +593,8 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { final LoanTransaction newRefundTransaction = LoanTransaction.refundForActiveLoan(loan.getOffice(), refundAmount, paymentDetail, transactionDate, txnExternalId, DateUtils.getLocalDateTimeOfTenant(), currentUser); final boolean allowTransactionsOnHoliday = this.configurationDomainService.allowTransactionsOnHolidayEnabled(); - final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(loan.getOfficeId(), - transactionDate.toDate(), HolidayStatusType.ACTIVE.getValue()); + final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(loan.getOfficeId(), transactionDate.toDate(), + HolidayStatusType.ACTIVE.getValue()); final WorkingDays workingDays = this.workingDaysRepository.findOne(); final boolean allowTransactionsOnNonWorkingDay = this.configurationDomainService.allowTransactionsOnNonWorkingDayEnabled(); @@ -606,10 +614,8 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_REFUND, constructEntityMap(BusinessEntity.LOAN_TRANSACTION, newRefundTransaction)); - builderResult.withEntityId(newRefundTransaction.getId()) - .withOfficeId(loan.getOfficeId()) - .withClientId(loan.getClientId()) - .withGroupId(loan.getGroupId()); + builderResult.withEntityId(newRefundTransaction.getId()).withOfficeId(loan.getOfficeId()).withClientId(loan.getClientId()) + .withGroupId(loan.getGroupId()); return newRefundTransaction; } @@ -650,19 +656,17 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { loan.addLoanTransaction(accrualTransaction); Set accrualCharges = accrualTransaction.getLoanChargesPaid(); for (LoanCharge loanCharge : loan.charges()) { - if (loanCharge.isActive() - && !loanCharge.isPaid() - && (loanCharge.isDueForCollectionFromAndUpToAndIncluding(fromDate, foreClosureDate) || loanCharge - .isInstalmentFee())) { - final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(accrualTransaction, loanCharge, loanCharge - .getAmountOutstanding(currency).getAmount(), null); + if (loanCharge.isActive() && !loanCharge.isPaid() + && (loanCharge.isDueForCollectionFromAndUpToAndIncluding(fromDate, foreClosureDate) + || loanCharge.isInstalmentFee())) { + final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(accrualTransaction, loanCharge, + loanCharge.getAmountOutstanding(currency).getAmount(), null); accrualCharges.add(loanChargePaidBy); } } } } - Money interestPayable = foreCloseDetail.getInterestCharged(currency); Money feePayable = foreCloseDetail.getFeeChargesCharged(currency); Money penaltyPayable = foreCloseDetail.getPenaltyChargesCharged(currency); @@ -671,7 +675,6 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { LoanTransaction payment = null; - if (payPrincipal.plus(interestPayable).plus(feePayable).plus(penaltyPayable).isGreaterThanZero()) { final PaymentDetail paymentDetail = null; String externalId = null; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanCharge.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanCharge.java old mode 100755 new mode 100644 index 553c77bab..d1176bcef --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanCharge.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanCharge.java @@ -118,7 +118,7 @@ public class LoanCharge extends AbstractPersistableCustom { @Column(name = "max_cap", scale = 6, precision = 19, nullable = true) private BigDecimal maxCap; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loancharge", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loancharge", orphanRemoval = true, fetch = FetchType.EAGER) private Set loanInstallmentCharge = new HashSet<>(); @Column(name = "is_active", nullable = false) @@ -158,8 +158,8 @@ public class LoanCharge extends AbstractPersistableCustom { break; case PERCENT_OF_AMOUNT_AND_INTEREST: if (command.hasParameter("principal") && command.hasParameter("interest")) { - amountPercentageAppliedTo = command.bigDecimalValueOfParameterNamed("principal").add( - command.bigDecimalValueOfParameterNamed("interest")); + amountPercentageAppliedTo = command.bigDecimalValueOfParameterNamed("principal") + .add(command.bigDecimalValueOfParameterNamed("interest")); } else { amountPercentageAppliedTo = loan.getPrincpal().getAmount().add(loan.getTotalInterest()); } @@ -524,11 +524,12 @@ public class LoanCharge extends AbstractPersistableCustom { } else { int index = 0; final List oldChargeInstallments = new ArrayList<>(); - if(this.loanInstallmentCharge != null && !this.loanInstallmentCharge.isEmpty()){ + if (this.loanInstallmentCharge != null && !this.loanInstallmentCharge.isEmpty()) { oldChargeInstallments.addAll(this.loanInstallmentCharge); } Collections.sort(oldChargeInstallments); - final LoanInstallmentCharge[] loanChargePerInstallmentArray = newChargeInstallments.toArray(new LoanInstallmentCharge[newChargeInstallments.size()]); + final LoanInstallmentCharge[] loanChargePerInstallmentArray = newChargeInstallments + .toArray(new LoanInstallmentCharge[newChargeInstallments.size()]); for (final LoanInstallmentCharge chargePerInstallment : oldChargeInstallments) { if (index == loanChargePerInstallmentArray.length) { remove.add(chargePerInstallment); @@ -543,10 +544,10 @@ public class LoanCharge extends AbstractPersistableCustom { } } Money amount = Money.zero(this.loan.getCurrency()); - for(LoanInstallmentCharge charge:this.loanInstallmentCharge){ - amount =amount.plus(charge.getAmount()); + for (LoanInstallmentCharge charge : this.loanInstallmentCharge) { + amount = amount.plus(charge.getAmount()); } - this.amount =amount.getAmount(); + this.amount = amount.getAmount(); } public boolean isDueAtDisbursement() { @@ -701,7 +702,7 @@ public class LoanCharge extends AbstractPersistableCustom { return !isPaid(); } - public boolean isChargePending(){ + public boolean isChargePending() { return isNotFullyPaid() && !isWaived(); } @@ -802,29 +803,23 @@ public class LoanCharge extends AbstractPersistableCustom { return this.charge; } - /*@Override - public boolean equals(final Object obj) { - if (obj == null) { return false; } - if (obj == this) { return true; } - if (obj.getClass() != getClass()) { return false; } - final LoanCharge rhs = (LoanCharge) obj; - return new EqualsBuilder().appendSuper(super.equals(obj)) // - .append(getId(), rhs.getId()) // - .append(this.charge.getId(), rhs.charge.getId()) // - .append(this.amount, rhs.amount) // - .append(getDueLocalDate(), rhs.getDueLocalDate()) // - .isEquals(); - } - - @Override - public int hashCode() { - return 1; - - * return new HashCodeBuilder(3, 5) // .append(getId()) // - * .append(this.charge.getId()) // - * .append(this.amount).append(getDueLocalDate()) // .toHashCode(); - - }*/ + /* + * @Override public boolean equals(final Object obj) { if (obj == null) { + * return false; } if (obj == this) { return true; } if (obj.getClass() != + * getClass()) { return false; } final LoanCharge rhs = (LoanCharge) obj; + * return new EqualsBuilder().appendSuper(super.equals(obj)) // + * .append(getId(), rhs.getId()) // .append(this.charge.getId(), + * rhs.charge.getId()) // .append(this.amount, rhs.amount) // + * .append(getDueLocalDate(), rhs.getDueLocalDate()) // .isEquals(); } + * + * @Override public int hashCode() { return 1; + * + * return new HashCodeBuilder(3, 5) // .append(getId()) // + * .append(this.charge.getId()) // + * .append(this.amount).append(getDueLocalDate()) // .toHashCode(); + * + * } + */ public ChargePaymentMode getChargePaymentMode() { return ChargePaymentMode.fromInt(this.chargePaymentMode); @@ -846,9 +841,8 @@ public class LoanCharge extends AbstractPersistableCustom { public LoanInstallmentCharge getUnpaidInstallmentLoanCharge() { LoanInstallmentCharge unpaidChargePerInstallment = null; for (final LoanInstallmentCharge loanChargePerInstallment : this.loanInstallmentCharge) { - if (loanChargePerInstallment.isPending() - && (unpaidChargePerInstallment == null || unpaidChargePerInstallment.getRepaymentInstallment().getDueDate() - .isAfter(loanChargePerInstallment.getRepaymentInstallment().getDueDate()))) { + if (loanChargePerInstallment.isPending() && (unpaidChargePerInstallment == null || unpaidChargePerInstallment + .getRepaymentInstallment().getDueDate().isAfter(loanChargePerInstallment.getRepaymentInstallment().getDueDate()))) { unpaidChargePerInstallment = loanChargePerInstallment; } } @@ -864,7 +858,9 @@ public class LoanCharge extends AbstractPersistableCustom { public LoanInstallmentCharge getInstallmentLoanCharge(final Integer installmentNumber) { for (final LoanInstallmentCharge loanChargePerInstallment : this.loanInstallmentCharge) { - if (installmentNumber.equals(loanChargePerInstallment.getRepaymentInstallment().getInstallmentNumber().intValue())) { return loanChargePerInstallment; } + if (installmentNumber.equals(loanChargePerInstallment.getRepaymentInstallment().getInstallmentNumber().intValue())) { + return loanChargePerInstallment; + } } return null; } @@ -1013,9 +1009,8 @@ public class LoanCharge extends AbstractPersistableCustom { Money outstanding = Money.of(currency, loanChargePerInstallment.getAmountOutstanding()); final boolean partiallyPaid = outstanding.isGreaterThanZero() && outstanding.isLessThan(loanChargePerInstallment.getAmount(currency)); - if ((partiallyPaid || loanChargePerInstallment.isPaid()) - && (paidChargePerInstallment == null || paidChargePerInstallment.getRepaymentInstallment().getDueDate() - .isBefore(loanChargePerInstallment.getRepaymentInstallment().getDueDate()))) { + if ((partiallyPaid || loanChargePerInstallment.isPaid()) && (paidChargePerInstallment == null || paidChargePerInstallment + .getRepaymentInstallment().getDueDate().isBefore(loanChargePerInstallment.getRepaymentInstallment().getDueDate()))) { paidChargePerInstallment = loanChargePerInstallment; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanChargePaidBy.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanChargePaidBy.java old mode 100755 new mode 100644 index 083d2c54b..8924ba16c --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanChargePaidBy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanChargePaidBy.java @@ -35,7 +35,7 @@ public class LoanChargePaidBy extends AbstractPersistableCustom { @JoinColumn(name = "loan_transaction_id", nullable = false) private LoanTransaction loanTransaction; - @ManyToOne(cascade= CascadeType.ALL) + @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "loan_charge_id", nullable = false) private LoanCharge loanCharge; @@ -81,7 +81,6 @@ public class LoanChargePaidBy extends AbstractPersistableCustom { this.amount = amount; } - public Integer getInstallmentNumber() { return this.installmentNumber; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanDisbursementDetails.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanDisbursementDetails.java index 9029326b9..50190856f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanDisbursementDetails.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanDisbursementDetails.java @@ -59,7 +59,7 @@ public class LoanDisbursementDetails extends AbstractPersistableCustom { this.expectedDisbursementDate = expectedDisbursementDate; this.actualDisbursementDate = actualDisbursementDate; this.principal = principal; - } + } public void updateLoan(final Loan loan) { this.loan = loan; @@ -67,13 +67,12 @@ public class LoanDisbursementDetails extends AbstractPersistableCustom { @Override public boolean equals(final Object obj) { - if (!(obj instanceof LoanDisbursementDetails)) { - return false; - } + if (!(obj instanceof LoanDisbursementDetails)) { return false; } final LoanDisbursementDetails loanDisbursementDetails = (LoanDisbursementDetails) obj; if (loanDisbursementDetails.principal.equals(this.principal) - && loanDisbursementDetails.expectedDisbursementDate.equals(this.expectedDisbursementDate)) - { return true; } + && loanDisbursementDetails.expectedDisbursementDate.equals(this.expectedDisbursementDate)) { + return true; + } return false; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanInstallmentCharge.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanInstallmentCharge.java old mode 100755 new mode 100644 index f3cfb4fda..9c4bf3967 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanInstallmentCharge.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanInstallmentCharge.java @@ -264,7 +264,6 @@ public class LoanInstallmentCharge extends AbstractPersistableCustom implements } } - public void updateInstallment(LoanRepaymentScheduleInstallment installment) { this.installment = installment; } @@ -275,12 +274,12 @@ public class LoanInstallmentCharge extends AbstractPersistableCustom implements Money amountToDeductOnThisCharge = Money.zero(incrementBy.getCurrency()); if (incrementBy.isGreaterThanOrEqualTo(amountPaidToDate)) { - amountToDeductOnThisCharge = amountPaidToDate; + amountToDeductOnThisCharge = amountPaidToDate; amountPaidToDate = Money.zero(incrementBy.getCurrency()); this.amountPaid = amountPaidToDate.getAmount(); this.amountOutstanding = this.amount; } else { - amountToDeductOnThisCharge = incrementBy; + amountToDeductOnThisCharge = incrementBy; amountPaidToDate = amountPaidToDate.minus(incrementBy); this.amountPaid = amountPaidToDate.getAmount(); this.amountOutstanding = calculateAmountOutstanding(incrementBy.getCurrency()); @@ -294,9 +293,9 @@ public class LoanInstallmentCharge extends AbstractPersistableCustom implements public LoanCharge getLoancharge() { return this.loancharge; } + public LoanRepaymentScheduleInstallment getInstallment() { return this.installment; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanInterestRecalculationDetails.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanInterestRecalculationDetails.java index 1d1f5f6a2..a2712782f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanInterestRecalculationDetails.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanInterestRecalculationDetails.java @@ -117,12 +117,13 @@ public class LoanInterestRecalculationDetails extends AbstractPersistableCustom public static LoanInterestRecalculationDetails createFrom( final LoanProductInterestRecalculationDetails loanProductInterestRecalculationDetails) { return new LoanInterestRecalculationDetails(loanProductInterestRecalculationDetails.getInterestRecalculationCompoundingMethod(), - loanProductInterestRecalculationDetails.getRescheduleStrategyMethod(), loanProductInterestRecalculationDetails - .getRestFrequencyType().getValue(), loanProductInterestRecalculationDetails.getRestInterval(), - loanProductInterestRecalculationDetails.getRestFrequencyNthDay(), + loanProductInterestRecalculationDetails.getRescheduleStrategyMethod(), + loanProductInterestRecalculationDetails.getRestFrequencyType().getValue(), + loanProductInterestRecalculationDetails.getRestInterval(), loanProductInterestRecalculationDetails.getRestFrequencyNthDay(), loanProductInterestRecalculationDetails.getRestFrequencyWeekday(), - loanProductInterestRecalculationDetails.getRestFrequencyOnDay(), loanProductInterestRecalculationDetails - .getCompoundingFrequencyType().getValue(), loanProductInterestRecalculationDetails.getCompoundingInterval(), + loanProductInterestRecalculationDetails.getRestFrequencyOnDay(), + loanProductInterestRecalculationDetails.getCompoundingFrequencyType().getValue(), + loanProductInterestRecalculationDetails.getCompoundingInterval(), loanProductInterestRecalculationDetails.getCompoundingFrequencyNthDay(), loanProductInterestRecalculationDetails.getCompoundingFrequencyWeekday(), loanProductInterestRecalculationDetails.getCompoundingFrequencyOnDay(), diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentDataComparator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentDataComparator.java index b92e9046d..5e89a12b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentDataComparator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentDataComparator.java @@ -27,4 +27,4 @@ public class LoanRepaymentDataComparator implements Comparator { +public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCustom + implements Comparable { @ManyToOne(optional = false) - @JoinColumn(name = "loan_id", referencedColumnName="id") + @JoinColumn(name = "loan_id", referencedColumnName = "id") private Loan loan; @Column(name = "installment", nullable = false) @@ -127,7 +128,7 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus @Column(name = "recalculated_interest_component", nullable = false) private boolean recalculatedInterestComponent; - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "loan_repayment_schedule_id", referencedColumnName = "id", nullable = false) private Set loanCompoundingDetails = new HashSet<>(); @@ -252,8 +253,8 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus } public Money getFeeChargesOutstanding(final MonetaryCurrency currency) { - final Money feeChargesAccountedFor = getFeeChargesPaid(currency).plus(getFeeChargesWaived(currency)).plus( - getFeeChargesWrittenOff(currency)); + final Money feeChargesAccountedFor = getFeeChargesPaid(currency).plus(getFeeChargesWaived(currency)) + .plus(getFeeChargesWrittenOff(currency)); return getFeeChargesCharged(currency).minus(feeChargesAccountedFor); } @@ -278,8 +279,8 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus } public Money getPenaltyChargesOutstanding(final MonetaryCurrency currency) { - final Money feeChargesAccountedFor = getPenaltyChargesPaid(currency).plus(getPenaltyChargesWaived(currency)).plus( - getPenaltyChargesWrittenOff(currency)); + final Money feeChargesAccountedFor = getPenaltyChargesPaid(currency).plus(getPenaltyChargesWaived(currency)) + .plus(getPenaltyChargesWrittenOff(currency)); return getPenaltyChargesCharged(currency).minus(feeChargesAccountedFor); } @@ -594,8 +595,7 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus this.obligationsMet = getTotalOutstanding(currency).isZero(); if (this.obligationsMet) { this.obligationsMetOnDate = transactionDate.toDate(); - } - else { + } else { this.obligationsMetOnDate = null; } } @@ -681,7 +681,7 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus return obligationsMetOnDate; } - /********** UNPAY COMPONENTS ****/ + /********** UNPAY COMPONENTS ****/ public Money unpayPenaltyChargesComponent(final LocalDate transactionDate, final Money transactionAmountRemaining) { @@ -768,29 +768,31 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus private void reduceAdvanceAndLateTotalsForRepaymentPeriod(final LocalDate transactionDate, final MonetaryCurrency currency, final Money amountDeductedInRepaymentPeriod) { - if (isInAdvance(transactionDate)) { - Money mTotalPaidInAdvance = Money.of(currency,this.totalPaidInAdvance); + Money mTotalPaidInAdvance = Money.of(currency, this.totalPaidInAdvance); - if(mTotalPaidInAdvance.isLessThan(amountDeductedInRepaymentPeriod) || mTotalPaidInAdvance.isEqualTo(amountDeductedInRepaymentPeriod)) { - this.totalPaidInAdvance = Money.zero(currency).getAmount(); - } else { - this.totalPaidInAdvance = mTotalPaidInAdvance.minus(amountDeductedInRepaymentPeriod).getAmount(); - } + if (mTotalPaidInAdvance.isLessThan(amountDeductedInRepaymentPeriod) + || mTotalPaidInAdvance.isEqualTo(amountDeductedInRepaymentPeriod)) { + this.totalPaidInAdvance = Money.zero(currency).getAmount(); + } else { + this.totalPaidInAdvance = mTotalPaidInAdvance.minus(amountDeductedInRepaymentPeriod).getAmount(); + } } else if (isLatePayment(transactionDate)) { - Money mTotalPaidLate = Money.of(currency,this.totalPaidLate); + Money mTotalPaidLate = Money.of(currency, this.totalPaidLate); - if(mTotalPaidLate.isLessThan(amountDeductedInRepaymentPeriod) || mTotalPaidLate.isEqualTo(amountDeductedInRepaymentPeriod)) { - this.totalPaidLate = Money.zero(currency).getAmount(); - } else { - this.totalPaidLate = mTotalPaidLate.minus(amountDeductedInRepaymentPeriod).getAmount(); - } + if (mTotalPaidLate.isLessThan(amountDeductedInRepaymentPeriod) || mTotalPaidLate.isEqualTo(amountDeductedInRepaymentPeriod)) { + this.totalPaidLate = Money.zero(currency).getAmount(); + } else { + this.totalPaidLate = mTotalPaidLate.minus(amountDeductedInRepaymentPeriod).getAmount(); + } } } public Money getDue(MonetaryCurrency currency) { - return getPrincipal(currency).plus(getInterestCharged(currency)).plus(getFeeChargesCharged(currency)).plus(getPenaltyChargesCharged(currency)); + return getPrincipal(currency).plus(getInterestCharged(currency)).plus(getFeeChargesCharged(currency)) + .plus(getPenaltyChargesCharged(currency)); } + public Set getLoanCompoundingDetails() { return this.loanCompoundingDetails; } @@ -805,4 +807,4 @@ public final class LoanRepaymentScheduleInstallment extends AbstractAuditableCus return getPenaltyChargesPaid(currency).plus(getFeeChargesPaid(currency)).plus(getInterestPaid(currency)) .plus(getPrincipalCompleted(currency)); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleInstallmentRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleInstallmentRepository.java old mode 100755 new mode 100644 index 08fe459c3..32e14f605 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleInstallmentRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleInstallmentRepository.java @@ -21,7 +21,7 @@ package org.apache.fineract.portfolio.loanaccount.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface LoanRepaymentScheduleInstallmentRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface LoanRepaymentScheduleInstallmentRepository + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleProcessingWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleProcessingWrapper.java index 17e067deb..1dcca2338 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleProcessingWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleProcessingWrapper.java @@ -50,8 +50,8 @@ public class LoanRepaymentScheduleProcessingWrapper { final Money feeChargesWrittenOffForRepaymentPeriod = cumulativeFeeChargesWrittenOffWithin(startDate, period.getDueDate(), loanCharges, currency, !period.isRecalculatedInterestComponent()); - final Money penaltyChargesDueForRepaymentPeriod = cumulativePenaltyChargesDueWithin(startDate, period.getDueDate(), - loanCharges, currency, period, totalPrincipal, totalInterest, !period.isRecalculatedInterestComponent()); + final Money penaltyChargesDueForRepaymentPeriod = cumulativePenaltyChargesDueWithin(startDate, period.getDueDate(), loanCharges, + currency, period, totalPrincipal, totalInterest, !period.isRecalculatedInterestComponent()); final Money penaltyChargesWaivedForRepaymentPeriod = cumulativePenaltyChargesWaivedWithin(startDate, period.getDueDate(), loanCharges, currency, !period.isRecalculatedInterestComponent()); final Money penaltyChargesWrittenOffForRepaymentPeriod = cumulativePenaltyChargesWrittenOffWithin(startDate, @@ -76,8 +76,8 @@ public class LoanRepaymentScheduleProcessingWrapper { if (loanCharge.getChargeCalculation().isPercentageBased()) { BigDecimal amount = BigDecimal.ZERO; if (loanCharge.getChargeCalculation().isPercentageOfAmountAndInterest()) { - amount = amount.add(period.getPrincipal(monetaryCurrency).getAmount()).add( - period.getInterestCharged(monetaryCurrency).getAmount()); + amount = amount.add(period.getPrincipal(monetaryCurrency).getAmount()) + .add(period.getInterestCharged(monetaryCurrency).getAmount()); } else if (loanCharge.getChargeCalculation().isPercentageOfInterest()) { amount = amount.add(period.getInterestCharged(monetaryCurrency).getAmount()); } else { @@ -104,7 +104,8 @@ public class LoanRepaymentScheduleProcessingWrapper { // multi disburment loan. // Then we need to get as of this loan charge due date // how much amount disbursed. - if (loanCharge.getLoan() != null && loanCharge.isSpecifiedDueDate() && loanCharge.getLoan().isMultiDisburmentLoan()) { + if (loanCharge.getLoan() != null && loanCharge.isSpecifiedDueDate() + && loanCharge.getLoan().isMultiDisburmentLoan()) { for (final LoanDisbursementDetails loanDisbursementDetails : loanCharge.getLoan().getDisbursementDetails()) { if (!loanDisbursementDetails.expectedDisbursementDate().after(loanCharge.getDueDate())) { amount = amount.add(loanDisbursementDetails.principal()); @@ -179,8 +180,8 @@ public class LoanRepaymentScheduleProcessingWrapper { if (loanCharge.getChargeCalculation().isPercentageBased()) { BigDecimal amount = BigDecimal.ZERO; if (loanCharge.getChargeCalculation().isPercentageOfAmountAndInterest()) { - amount = amount.add(period.getPrincipal(currency).getAmount()).add( - period.getInterestCharged(currency).getAmount()); + amount = amount.add(period.getPrincipal(currency).getAmount()) + .add(period.getInterestCharged(currency).getAmount()); } else if (loanCharge.getChargeCalculation().isPercentageOfInterest()) { amount = amount.add(period.getInterestCharged(currency).getAmount()); } else { @@ -257,4 +258,4 @@ public class LoanRepaymentScheduleProcessingWrapper { return cumulative; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleTransactionProcessorFactory.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleTransactionProcessorFactory.java index 059216445..23e6ccfb6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleTransactionProcessorFactory.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepaymentScheduleTransactionProcessorFactory.java @@ -70,4 +70,4 @@ public class LoanRepaymentScheduleTransactionProcessorFactory { return processor; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepository.java old mode 100755 new mode 100644 index 681d5eaf4..533c8cf68 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepository.java @@ -157,4 +157,4 @@ public interface LoanRepository extends JpaRepository, JpaSpecificat @Query(FIND_NON_CLOSED_LOAN_THAT_BELONGS_TO_CLIENT) Loan findNonClosedLoanThatBelongsToClient(@Param("loanId") Long loanId, @Param("clientId") Long clientId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepositoryWrapper.java old mode 100755 new mode 100644 index 3b3ce424d..3dd04c9e9 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRepositoryWrapper.java @@ -46,21 +46,19 @@ public class LoanRepositoryWrapper { } public Loan findOneWithNotFoundDetection(final Long id) { - return this.findOneWithNotFoundDetection(id, false) ; + return this.findOneWithNotFoundDetection(id, false); } - @Transactional(readOnly=true) + @Transactional(readOnly = true) public Loan findOneWithNotFoundDetection(final Long id, boolean loadLazyCollections) { - final Loan loan = this.repository.findById(id) - .orElseThrow(() -> new LoanNotFoundException(id)); - if(loadLazyCollections) { + final Loan loan = this.repository.findById(id).orElseThrow(() -> new LoanNotFoundException(id)); + if (loadLazyCollections) { loan.initializeLazyCollections(); } return loan; } - - //Root Entities are enough + // Root Entities are enough public Collection findActiveLoansByLoanIdAndGroupId(Long clientId, Long groupId) { final Collection loanStatuses = new ArrayList<>(Arrays.asList(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue(), LoanStatus.APPROVED.getValue(), LoanStatus.ACTIVE.getValue(), LoanStatus.OVERPAID.getValue())); @@ -69,17 +67,18 @@ public class LoanRepositoryWrapper { } public Loan saveAndFlush(final Loan loan) { - return this.repository.saveAndFlush(loan) ; + return this.repository.saveAndFlush(loan); } @Transactional public Loan save(final Loan loan) { - return this.repository.save(loan) ; + return this.repository.save(loan); } public List save(List loans) { - return this.repository.saveAll(loans) ; + return this.repository.saveAll(loans); } + public void flush() { this.repository.flush(); } @@ -87,154 +86,157 @@ public class LoanRepositoryWrapper { public void delete(final Long loanId) { this.repository.deleteById(loanId); } - //Only root entities is enough + + // Only root entities is enough public List getGroupLoansDisbursedAfter(@Param("disbursementDate") Date disbursementDate, @Param("groupId") Long groupId, @Param("loanType") Integer loanType) { - return this.repository.getGroupLoansDisbursedAfter(disbursementDate, groupId, loanType) ; + return this.repository.getGroupLoansDisbursedAfter(disbursementDate, groupId, loanType); } - //Only root entities enough - public List getClientOrJLGLoansDisbursedAfter(@Param("disbursementDate") Date disbursementDate, @Param("clientId") Long clientId) { - return this.repository.getClientOrJLGLoansDisbursedAfter(disbursementDate, clientId) ; + + // Only root entities enough + public List getClientOrJLGLoansDisbursedAfter(@Param("disbursementDate") Date disbursementDate, + @Param("clientId") Long clientId) { + return this.repository.getClientOrJLGLoansDisbursedAfter(disbursementDate, clientId); } public Integer getMaxGroupLoanCounter(@Param("groupId") Long groupId, @Param("loanType") Integer loanType) { - return this.repository.getMaxGroupLoanCounter(groupId, loanType) ; + return this.repository.getMaxGroupLoanCounter(groupId, loanType); } public Integer getMaxGroupLoanProductCounter(@Param("productId") Long productId, @Param("groupId") Long groupId, @Param("loanType") Integer loanType) { - return this.repository.getMaxGroupLoanProductCounter(productId, groupId, loanType) ; + return this.repository.getMaxGroupLoanProductCounter(productId, groupId, loanType); } public Integer getMaxClientOrJLGLoanCounter(@Param("clientId") Long clientId) { - return this.repository.getMaxClientOrJLGLoanCounter(clientId) ; + return this.repository.getMaxClientOrJLGLoanCounter(clientId); } public Integer getMaxClientOrJLGLoanProductCounter(@Param("productId") Long productId, @Param("clientId") Long clientId) { - return this.repository.getMaxClientOrJLGLoanProductCounter(productId, clientId) ; + return this.repository.getMaxClientOrJLGLoanProductCounter(productId, clientId); } - //Only root entities are enough + // Only root entities are enough public List getGroupLoansToUpdateLoanCounter(@Param("loanCounter") Integer loanCounter, @Param("groupId") Long groupId, @Param("groupLoanType") Integer groupLoanType) { - return this.repository.getGroupLoansToUpdateLoanCounter(loanCounter, groupId, groupLoanType) ; + return this.repository.getGroupLoansToUpdateLoanCounter(loanCounter, groupId, groupLoanType); } - //Only root entities are enough + // Only root entities are enough public List getClientOrJLGLoansToUpdateLoanCounter(@Param("loanCounter") Integer loanCounter, @Param("clientId") Long clientId) { - return this.repository.getClientOrJLGLoansToUpdateLoanCounter(loanCounter, clientId) ; + return this.repository.getClientOrJLGLoansToUpdateLoanCounter(loanCounter, clientId); } - //Only root entities are enough + // Only root entities are enough public List getGroupLoansToUpdateLoanProductCounter(@Param("loanProductCounter") Integer loanProductCounter, @Param("groupId") Long groupId, @Param("groupLoanType") Integer groupLoanType) { - return this.repository.getGroupLoansToUpdateLoanProductCounter(loanProductCounter, groupId, groupLoanType) ; + return this.repository.getGroupLoansToUpdateLoanProductCounter(loanProductCounter, groupId, groupLoanType); } - //Only root entities are enough + // Only root entities are enough public List getClientLoansToUpdateLoanProductCounter(@Param("loanProductCounter") Integer loanProductCounter, @Param("clientId") Long clientId) { - return this.repository.getClientLoansToUpdateLoanProductCounter(loanProductCounter, clientId) ; + return this.repository.getClientLoansToUpdateLoanProductCounter(loanProductCounter, clientId); } - //Need loanOfficerHistory. Check whether FETCH JOIN is good enough here - @Transactional(readOnly=true) + // Need loanOfficerHistory. Check whether FETCH JOIN is good enough here + @Transactional(readOnly = true) public List findByClientIdAndGroupId(@Param("clientId") Long clientId, @Param("groupId") Long groupId) { - List loans = this.repository.findByClientIdAndGroupId(clientId, groupId) ; - if(loans != null && loans.size() > 0) { - for(Loan loan: loans) { + List loans = this.repository.findByClientIdAndGroupId(clientId, groupId); + if (loans != null && loans.size() > 0) { + for (Loan loan : loans) { loan.initializeLoanOfficerHistory(); } } - return loans ; + return loans; } - //need loanTransactions, loanOfficerHistory - @Transactional(readOnly=true) + // need loanTransactions, loanOfficerHistory + @Transactional(readOnly = true) public List findLoanByClientId(@Param("clientId") Long clientId) { - List loans = this.repository.findLoanByClientId(clientId) ; - if(loans != null && loans.size() > 0) { - for(Loan loan: loans) { + List loans = this.repository.findLoanByClientId(clientId); + if (loans != null && loans.size() > 0) { + for (Loan loan : loans) { loan.initilizeTransactions(); loan.initializeLoanOfficerHistory(); } } - return loans ; + return loans; } - //Root entities are enough + // Root entities are enough public List findByGroupId(@Param("groupId") Long groupId) { - return this.repository.findByGroupId(groupId) ; + return this.repository.findByGroupId(groupId); } - //Looks like we need complete Data + // Looks like we need complete Data public List findByIdsAndLoanStatusAndLoanType(@Param("ids") Collection ids, @Param("loanStatuses") Collection loanStatuses, @Param("loanTypes") Collection loanTypes) { - List loans =this.repository.findByIdsAndLoanStatusAndLoanType(ids, loanStatuses, loanTypes) ; - if(loans != null && loans.size() > 0) { - for(Loan loan: loans) { + List loans = this.repository.findByIdsAndLoanStatusAndLoanType(ids, loanStatuses, loanTypes); + if (loans != null && loans.size() > 0) { + for (Loan loan : loans) { loan.initializeLazyCollections(); } } - return loans ; + return loans; } - //This method is not used + // This method is not used public List getLoansDisbursedAfter(@Param("disbursalDate") Date disbursalDate) { - return this.repository.getLoansDisbursedAfter(disbursalDate) ; + return this.repository.getLoansDisbursedAfter(disbursalDate); } - //Repayments Schedule + // Repayments Schedule public List findByClientOfficeIdsAndLoanStatus(@Param("officeIds") Collection officeIds, @Param("loanStatuses") Collection loanStatuses) { - List loans = this.repository.findByClientOfficeIdsAndLoanStatus(officeIds, loanStatuses) ; - if(loans != null && loans.size() >0) { - for(Loan loan: loans) { + List loans = this.repository.findByClientOfficeIdsAndLoanStatus(officeIds, loanStatuses); + if (loans != null && loans.size() > 0) { + for (Loan loan : loans) { loan.initializeRepaymentSchedule(); } } - return loans ; + return loans; } - //Repayments Schedule + // Repayments Schedule public List findByGroupOfficeIdsAndLoanStatus(@Param("officeIds") Collection officeIds, @Param("loanStatuses") Collection loanStatuses) { - List loans = this.repository.findByGroupOfficeIdsAndLoanStatus(officeIds, loanStatuses) ; - if(loans != null && loans.size() >0) { - for(Loan loan: loans) { + List loans = this.repository.findByGroupOfficeIdsAndLoanStatus(officeIds, loanStatuses); + if (loans != null && loans.size() > 0) { + for (Loan loan : loans) { loan.initializeRepaymentSchedule(); } } - return loans ; + return loans; } public List findActiveLoansLoanProductIdsByClient(@Param("clientId") Long clientId, @Param("loanStatus") Integer loanStatus) { - return this.repository.findActiveLoansLoanProductIdsByClient(clientId, loanStatus) ; + return this.repository.findActiveLoansLoanProductIdsByClient(clientId, loanStatus); } public List findActiveLoansLoanProductIdsByGroup(@Param("groupId") Long groupId, @Param("loanStatus") Integer loanStatus) { - return this.repository.findActiveLoansLoanProductIdsByGroup(groupId, loanStatus) ; + return this.repository.findActiveLoansLoanProductIdsByGroup(groupId, loanStatus); } public boolean doNonClosedLoanAccountsExistForClient(@Param("clientId") Long clientId) { - return this.repository.doNonClosedLoanAccountsExistForClient(clientId) ; + return this.repository.doNonClosedLoanAccountsExistForClient(clientId); } public boolean doNonClosedLoanAccountsExistForProduct(@Param("productId") Long productId) { - return this.repository.doNonClosedLoanAccountsExistForProduct(productId) ; + return this.repository.doNonClosedLoanAccountsExistForProduct(productId); } public Loan findNonClosedLoanByAccountNumber(@Param("accountNumber") String accountNumber) { - return this.repository.findNonClosedLoanByAccountNumber(accountNumber) ; + return this.repository.findNonClosedLoanByAccountNumber(accountNumber); } - //Looks like we need complete entity - @Transactional(readOnly=true) + // Looks like we need complete entity + @Transactional(readOnly = true) public Loan findNonClosedLoanThatBelongsToClient(@Param("loanId") Long loanId, @Param("clientId") Long clientId) { - Loan loan = this.repository.findNonClosedLoanThatBelongsToClient(loanId, clientId) ; - if(loan != null) { + Loan loan = this.repository.findNonClosedLoanThatBelongsToClient(loanId, clientId); + if (loan != null) { loan.initilizeTransactions(); } - return loan ; + return loan; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRescheduleRequestToTermVariationMapping.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRescheduleRequestToTermVariationMapping.java index d3798bb93..721b83f0c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRescheduleRequestToTermVariationMapping.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanRescheduleRequestToTermVariationMapping.java @@ -26,15 +26,14 @@ import javax.persistence.Table; import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity -@Table(name="m_loan_reschedule_request_term_variations_mapping") +@Table(name = "m_loan_reschedule_request_term_variations_mapping") public class LoanRescheduleRequestToTermVariationMapping extends AbstractPersistableCustom { - @ManyToOne(optional = false, cascade = CascadeType.PERSIST) @JoinColumn(name = "loan_term_variations_id", nullable = false) private LoanTermVariations loanTermVariations; - protected LoanRescheduleRequestToTermVariationMapping(){ + protected LoanRescheduleRequestToTermVariationMapping() { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanStatus.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanStatus.java index 6be1b07b8..b2056ad59 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanStatus.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanStatus.java @@ -152,4 +152,4 @@ public enum LoanStatus { public boolean isOverpaid() { return this.value.equals(LoanStatus.OVERPAID.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSubStatus.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSubStatus.java index afe3247f3..b157b6e0e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSubStatus.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSubStatus.java @@ -21,6 +21,7 @@ package org.apache.fineract.portfolio.loanaccount.domain; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public enum LoanSubStatus { + INVALID(0, "loanSubStatusType.invalid"), // FORECLOSED(100, "loanSubStatusType.foreclosed"); @@ -68,8 +69,8 @@ public enum LoanSubStatus { EnumOptionData optionData = null; switch (type) { case FORECLOSED: - optionData = new EnumOptionData(LoanSubStatus.FORECLOSED.getValue().longValue(), codePrefix - + LoanSubStatus.FORECLOSED.getCode(), "Foreclosed"); + optionData = new EnumOptionData(LoanSubStatus.FORECLOSED.getValue().longValue(), + codePrefix + LoanSubStatus.FORECLOSED.getCode(), "Foreclosed"); break; default: optionData = new EnumOptionData(LoanSubStatus.INVALID.getValue().longValue(), LoanSubStatus.INVALID.getCode(), "Invalid"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSummary.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSummary.java index 48563cd01..8e4b1b52b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSummary.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSummary.java @@ -222,16 +222,16 @@ public final class LoanSummary { this.totalInterestOutstanding = totalInterestCharged.minus(this.totalInterestRepaid).minus(this.totalInterestWaived) .minus(this.totalInterestWrittenOff).getAmount(); - final Money totalFeeChargesCharged = summaryWrapper.calculateTotalFeeChargesCharged(repaymentScheduleInstallments, currency).plus( - this.totalFeeChargesDueAtDisbursement); + final Money totalFeeChargesCharged = summaryWrapper.calculateTotalFeeChargesCharged(repaymentScheduleInstallments, currency) + .plus(this.totalFeeChargesDueAtDisbursement); this.totalFeeChargesCharged = totalFeeChargesCharged.getAmount(); - Money totalFeeChargesRepaidAtDisbursement = summaryWrapper.calculateTotalChargesRepaidAtDisbursement(charges,currency); + Money totalFeeChargesRepaidAtDisbursement = summaryWrapper.calculateTotalChargesRepaidAtDisbursement(charges, currency); this.totalFeeChargesRepaid = totalFeeChargesRepaidAtDisbursement.getAmount(); - if(charges != null) { + if (charges != null) { this.totalFeeChargesWaived = summaryWrapper.calculateTotalFeeChargesWaived(charges, currency).getAmount(); - }else { + } else { this.totalFeeChargesWaived = BigDecimal.ZERO; } @@ -241,8 +241,8 @@ public final class LoanSummary { this.totalFeeChargesOutstanding = totalFeeChargesCharged.minus(this.totalFeeChargesRepaid).minus(this.totalFeeChargesWaived) .minus(this.totalFeeChargesWrittenOff).getAmount(); - final Money totalPenaltyChargesCharged = summaryWrapper - .calculateTotalPenaltyChargesCharged(repaymentScheduleInstallments, currency); + final Money totalPenaltyChargesCharged = summaryWrapper.calculateTotalPenaltyChargesCharged(repaymentScheduleInstallments, + currency); this.totalPenaltyChargesCharged = totalPenaltyChargesCharged.getAmount(); this.totalPenaltyChargesRepaid = summaryWrapper.calculateTotalPenaltyChargesRepaid(repaymentScheduleInstallments, currency) .getAmount(); @@ -334,8 +334,7 @@ public final class LoanSummary { return this.totalPenaltyChargesWaived; } - public BigDecimal getTotalExpectedRepayment() { return this.totalExpectedRepayment; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSummaryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSummaryWrapper.java index 6295123b5..8ac9bfb89 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSummaryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanSummaryWrapper.java @@ -126,11 +126,10 @@ public final class LoanSummaryWrapper { return total; } - public Money calculateTotalFeeChargesWaived(Set charges, - final MonetaryCurrency currency) { + public Money calculateTotalFeeChargesWaived(Set charges, final MonetaryCurrency currency) { Money total = Money.zero(currency); for (final LoanCharge charge : charges) { - if(charge.isActive() && !charge.isPenaltyCharge()){ + if (charge.isActive() && !charge.isPenaltyCharge()) { total = total.plus(charge.getAmountWaived(currency)); } } @@ -235,9 +234,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalChargesRepaidAtDisbursement(Set charges, MonetaryCurrency currency) { Money total = Money.zero(currency); - if(charges == null) { - return total; - } + if (charges == null) { return total; } for (final LoanCharge loanCharge : charges) { if (!loanCharge.isPenaltyCharge() && loanCharge.getAmountPaid(currency).isGreaterThanZero()) { total = total.plus(loanCharge.getAmountPaid(currency)); @@ -246,4 +243,4 @@ public final class LoanSummaryWrapper { return total; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTermVariationType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTermVariationType.java index aad395717..121faf4ef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTermVariationType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTermVariationType.java @@ -26,11 +26,9 @@ public enum LoanTermVariationType { PRINCIPAL_AMOUNT(3, "loanTermType.principalAmount"), // DUE_DATE(4, "loanTermType.dueDate"), // INSERT_INSTALLMENT(5, "loanTermType.insertInstallment"), // - DELETE_INSTALLMENT(6, "loanTermType.deleteInstallment"), - GRACE_ON_INTEREST(7, "loanTermType.graceOnInterest"), - GRACE_ON_PRINCIPAL(8, "loanTermType.graceOnPrincipal"), - EXTEND_REPAYMENT_PERIOD(9, "loanTermType.extendRepaymentPeriod"), - INTEREST_RATE_FROM_INSTALLMENT(10, "loanTermType.interestRateFromInstallment"); + DELETE_INSTALLMENT(6, "loanTermType.deleteInstallment"), GRACE_ON_INTEREST(7, "loanTermType.graceOnInterest"), GRACE_ON_PRINCIPAL(8, + "loanTermType.graceOnPrincipal"), EXTEND_REPAYMENT_PERIOD(9, + "loanTermType.extendRepaymentPeriod"), INTEREST_RATE_FROM_INSTALLMENT(10, "loanTermType.interestRateFromInstallment"); private final Integer value; private final String code; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTermVariations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTermVariations.java index 8c3408c34..430e2d636 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTermVariations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTermVariations.java @@ -97,7 +97,8 @@ public class LoanTermVariations extends AbstractPersistableCustom { } public LoanTermVariations(final Integer termType, final Date termApplicableFrom, final BigDecimal decimalValue, final Date dateValue, - final boolean isSpecificToInstallment, final Loan loan, final Integer loanStatus, final Boolean isActive, final LoanTermVariations parent) { + final boolean isSpecificToInstallment, final Loan loan, final Integer loanStatus, final Boolean isActive, + final LoanTermVariations parent) { this.loan = loan; this.termApplicableFrom = termApplicableFrom; this.termType = termType; @@ -155,7 +156,6 @@ public class LoanTermVariations extends AbstractPersistableCustom { this.decimalValue = decimalValue; } - public Integer getOnLoanStatus() { return this.onLoanStatus; } @@ -168,7 +168,7 @@ public class LoanTermVariations extends AbstractPersistableCustom { return this.parent; } - public void updateIsActive(final Boolean isActive){ + public void updateIsActive(final Boolean isActive) { this.isActive = isActive; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTopupDetails.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTopupDetails.java index 12a670eaf..d3553df47 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTopupDetails.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTopupDetails.java @@ -28,42 +28,42 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity @Table(name = "m_loan_topup") -public class LoanTopupDetails extends AbstractPersistableCustom { +public class LoanTopupDetails extends AbstractPersistableCustom { - @OneToOne - @JoinColumn(name = "loan_id", nullable = false) - private Loan loan; + @OneToOne + @JoinColumn(name = "loan_id", nullable = false) + private Loan loan; - @Column(name = "closure_loan_id", nullable = false) - private Long closureLoanId; + @Column(name = "closure_loan_id", nullable = false) + private Long closureLoanId; - @Column(name = "account_transfer_details_id", nullable = true) - private Long accountTransferDetailsId; + @Column(name = "account_transfer_details_id", nullable = true) + private Long accountTransferDetailsId; - @Column(name = "topup_amount", nullable = true) - private BigDecimal topupAmount; + @Column(name = "topup_amount", nullable = true) + private BigDecimal topupAmount; - protected LoanTopupDetails(){}; + protected LoanTopupDetails() {}; - public LoanTopupDetails(final Loan loan, final Long loanIdToClose) { - this.loan = loan; - this.closureLoanId = loanIdToClose; - } + public LoanTopupDetails(final Loan loan, final Long loanIdToClose) { + this.loan = loan; + this.closureLoanId = loanIdToClose; + } - public Long getLoanIdToClose(){ - return this.closureLoanId; - } + public Long getLoanIdToClose() { + return this.closureLoanId; + } - public BigDecimal getTopupAmount() { - return this.topupAmount; - } + public BigDecimal getTopupAmount() { + return this.topupAmount; + } - public void setTopupAmount(BigDecimal topupAmount) { - this.topupAmount = topupAmount; - } + public void setTopupAmount(BigDecimal topupAmount) { + this.topupAmount = topupAmount; + } - public void setAccountTransferDetails(Long accountTransferDetailsId) { - this.accountTransferDetailsId = accountTransferDetailsId; - } + public void setAccountTransferDetails(Long accountTransferDetailsId) { + this.accountTransferDetailsId = accountTransferDetailsId; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTrancheCharge.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTrancheCharge.java index 267c20bca..bdb025a2b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTrancheCharge.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTrancheCharge.java @@ -43,21 +43,23 @@ public class LoanTrancheCharge extends AbstractPersistableCustom { } LoanTrancheCharge(Charge chargeDefinition) { - this.charge = chargeDefinition ; + this.charge = chargeDefinition; } + public LoanTrancheCharge(Charge charge, Loan loan) { this.charge = charge; - this.loan = loan ; + this.loan = loan; } public static LoanTrancheCharge createLoanTrancheCharge(Charge chargeDefinition) { - return new LoanTrancheCharge(chargeDefinition) ; + return new LoanTrancheCharge(chargeDefinition); } + public static LoanTrancheCharge createLoanTrancheChargeWithLoan(Charge chargeDefinition, Loan loan) { - return new LoanTrancheCharge(chargeDefinition, loan) ; + return new LoanTrancheCharge(chargeDefinition, loan); } public Charge getCharge() { - return charge ; + return charge; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTrancheDisbursementCharge.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTrancheDisbursementCharge.java index b1d861863..d9b1bd185 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTrancheDisbursementCharge.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTrancheDisbursementCharge.java @@ -26,7 +26,7 @@ import javax.persistence.Table; import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity -@Table(name="m_loan_tranche_disbursement_charge") +@Table(name = "m_loan_tranche_disbursement_charge") public class LoanTrancheDisbursementCharge extends AbstractPersistableCustom { @ManyToOne @@ -34,19 +34,19 @@ public class LoanTrancheDisbursementCharge extends AbstractPersistableCustom { private LoanCharge loancharge; @ManyToOne(cascade = CascadeType.ALL, optional = false) - @JoinColumn(name="disbursement_detail_id", referencedColumnName = "id", nullable = false) + @JoinColumn(name = "disbursement_detail_id", referencedColumnName = "id", nullable = false) private LoanDisbursementDetails loanDisbursementDetails; - public LoanTrancheDisbursementCharge(){ + public LoanTrancheDisbursementCharge() { } - public LoanTrancheDisbursementCharge(final LoanCharge loancharge, final LoanDisbursementDetails loanDisbursementDetails){ + public LoanTrancheDisbursementCharge(final LoanCharge loancharge, final LoanDisbursementDetails loanDisbursementDetails) { this.loancharge = loancharge; this.loanDisbursementDetails = loanDisbursementDetails; } - public LoanDisbursementDetails getloanDisbursementDetails(){ + public LoanDisbursementDetails getloanDisbursementDetails() { return this.loanDisbursementDetails; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransaction.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransaction.java old mode 100755 new mode 100644 index 83cfabafe..8cfbb22e0 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransaction.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransaction.java @@ -116,11 +116,11 @@ public class LoanTransaction extends AbstractPersistableCustom { @Column(name = "created_date", nullable = false) private Date createdDate; - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "appuser_id", nullable = true) private AppUser appUser; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loanTransaction", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loanTransaction", orphanRemoval = true, fetch = FetchType.EAGER) private Set loanChargesPaid = new HashSet<>(); @Column(name = "outstanding_loan_balance_derived", scale = 6, precision = 19, nullable = true) @@ -129,17 +129,16 @@ public class LoanTransaction extends AbstractPersistableCustom { @Column(name = "manually_adjusted_or_reversed", nullable = false) private boolean manuallyAdjustedOrReversed; - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) - @JoinColumn(name = "loan_transaction_id", referencedColumnName= "id" , nullable = false) + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "loan_transaction_id", referencedColumnName = "id", nullable = false) private Set loanTransactionToRepaymentScheduleMappings = new HashSet<>(); protected LoanTransaction() { - /* this.loan = null; - this.dateOf = null; - this.typeOf = null; - this.submittedOnDate = DateUtils.getDateOfTenant(); - this.createdDate = new Date(); - this.appUser = null;*/ + /* + * this.loan = null; this.dateOf = null; this.typeOf = null; + * this.submittedOnDate = DateUtils.getDateOfTenant(); this.createdDate + * = new Date(); this.appUser = null; + */ } public static LoanTransaction incomePosting(final Loan loan, final Office office, final Date dateOf, final BigDecimal amount, @@ -233,26 +232,29 @@ public class LoanTransaction extends AbstractPersistableCustom { public static LoanTransaction initiateTransfer(final Office office, final Loan loan, final LocalDate transferDate, final LocalDateTime createdDate, final AppUser appUser) { - return new LoanTransaction(loan, office, LoanTransactionType.INITIATE_TRANSFER.getValue(), transferDate.toDateTimeAtStartOfDay() - .toDate(), loan.getSummary().getTotalOutstanding(), loan.getSummary().getTotalPrincipalOutstanding(), loan.getSummary() - .getTotalInterestOutstanding(), loan.getSummary().getTotalFeeChargesOutstanding(), loan.getSummary() - .getTotalPenaltyChargesOutstanding(), null, false, null, null, createdDate, appUser); + return new LoanTransaction(loan, office, LoanTransactionType.INITIATE_TRANSFER.getValue(), + transferDate.toDateTimeAtStartOfDay().toDate(), loan.getSummary().getTotalOutstanding(), + loan.getSummary().getTotalPrincipalOutstanding(), loan.getSummary().getTotalInterestOutstanding(), + loan.getSummary().getTotalFeeChargesOutstanding(), loan.getSummary().getTotalPenaltyChargesOutstanding(), null, false, null, + null, createdDate, appUser); } public static LoanTransaction approveTransfer(final Office office, final Loan loan, final LocalDate transferDate, final LocalDateTime createdDate, final AppUser appUser) { - return new LoanTransaction(loan, office, LoanTransactionType.APPROVE_TRANSFER.getValue(), transferDate.toDateTimeAtStartOfDay() - .toDate(), loan.getSummary().getTotalOutstanding(), loan.getSummary().getTotalPrincipalOutstanding(), loan.getSummary() - .getTotalInterestOutstanding(), loan.getSummary().getTotalFeeChargesOutstanding(), loan.getSummary() - .getTotalPenaltyChargesOutstanding(), null, false, null, null, createdDate, appUser); + return new LoanTransaction(loan, office, LoanTransactionType.APPROVE_TRANSFER.getValue(), + transferDate.toDateTimeAtStartOfDay().toDate(), loan.getSummary().getTotalOutstanding(), + loan.getSummary().getTotalPrincipalOutstanding(), loan.getSummary().getTotalInterestOutstanding(), + loan.getSummary().getTotalFeeChargesOutstanding(), loan.getSummary().getTotalPenaltyChargesOutstanding(), null, false, null, + null, createdDate, appUser); } public static LoanTransaction withdrawTransfer(final Office office, final Loan loan, final LocalDate transferDate, final LocalDateTime createdDate, final AppUser appUser) { - return new LoanTransaction(loan, office, LoanTransactionType.WITHDRAW_TRANSFER.getValue(), transferDate.toDateTimeAtStartOfDay() - .toDate(), loan.getSummary().getTotalOutstanding(), loan.getSummary().getTotalPrincipalOutstanding(), loan.getSummary() - .getTotalInterestOutstanding(), loan.getSummary().getTotalFeeChargesOutstanding(), loan.getSummary() - .getTotalPenaltyChargesOutstanding(), null, false, null, null, createdDate, appUser); + return new LoanTransaction(loan, office, LoanTransactionType.WITHDRAW_TRANSFER.getValue(), + transferDate.toDateTimeAtStartOfDay().toDate(), loan.getSummary().getTotalOutstanding(), + loan.getSummary().getTotalPrincipalOutstanding(), loan.getSummary().getTotalInterestOutstanding(), + loan.getSummary().getTotalFeeChargesOutstanding(), loan.getSummary().getTotalPenaltyChargesOutstanding(), null, false, null, + null, createdDate, appUser); } public static LoanTransaction refund(final Office office, final Money amount, final PaymentDetail paymentDetail, @@ -265,8 +267,8 @@ public class LoanTransaction extends AbstractPersistableCustom { return new LoanTransaction(loanTransaction.loan, loanTransaction.office, loanTransaction.typeOf, loanTransaction.dateOf, loanTransaction.amount, loanTransaction.principalPortion, loanTransaction.interestPortion, loanTransaction.feeChargesPortion, loanTransaction.penaltyChargesPortion, loanTransaction.overPaymentPortion, - loanTransaction.reversed, loanTransaction.paymentDetail, loanTransaction.externalId, new LocalDateTime( - loanTransaction.createdDate), loanTransaction.appUser); + loanTransaction.reversed, loanTransaction.paymentDetail, loanTransaction.externalId, + new LocalDateTime(loanTransaction.createdDate), loanTransaction.appUser); } public static LoanTransaction accrueLoanCharge(final Loan loan, final Office office, final Money amount, final LocalDate applyDate, @@ -280,8 +282,8 @@ public class LoanTransaction extends AbstractPersistableCustom { public static LoanTransaction refundForActiveLoan(final Office office, final Money amount, final PaymentDetail paymentDetail, final LocalDate paymentDate, final String externalId, final LocalDateTime createdDate, final AppUser appUser) { - return new LoanTransaction(null, office, LoanTransactionType.REFUND_FOR_ACTIVE_LOAN, paymentDetail, amount.getAmount(), - paymentDate, externalId, createdDate, appUser); + return new LoanTransaction(null, office, LoanTransactionType.REFUND_FOR_ACTIVE_LOAN, paymentDetail, amount.getAmount(), paymentDate, + externalId, createdDate, appUser); } public static boolean transactionAmountsMatch(final MonetaryCurrency currency, final LoanTransaction loanTransaction, @@ -291,7 +293,9 @@ public class LoanTransaction extends AbstractPersistableCustom { && loanTransaction.getInterestPortion(currency).isEqualTo(newLoanTransaction.getInterestPortion(currency)) && loanTransaction.getFeeChargesPortion(currency).isEqualTo(newLoanTransaction.getFeeChargesPortion(currency)) && loanTransaction.getPenaltyChargesPortion(currency).isEqualTo(newLoanTransaction.getPenaltyChargesPortion(currency)) - && loanTransaction.getOverPaymentPortion(currency).isEqualTo(newLoanTransaction.getOverPaymentPortion(currency))) { return true; } + && loanTransaction.getOverPaymentPortion(currency).isEqualTo(newLoanTransaction.getOverPaymentPortion(currency))) { + return true; + } return false; } @@ -319,8 +323,8 @@ public class LoanTransaction extends AbstractPersistableCustom { } public static LoanTransaction waiveLoanCharge(final Loan loan, final Office office, final Money waived, final LocalDate waiveDate, - final Money feeChargesWaived, final Money penaltyChargesWaived, final Money unrecognizedCharge, - final LocalDateTime createdDate, final AppUser appUser) { + final Money feeChargesWaived, final Money penaltyChargesWaived, final Money unrecognizedCharge, final LocalDateTime createdDate, + final AppUser appUser) { final LoanTransaction waiver = new LoanTransaction(loan, office, LoanTransactionType.WAIVE_CHARGES, waived.getAmount(), waiveDate, null, createdDate, appUser); waiver.updateChargesComponents(feeChargesWaived, penaltyChargesWaived, unrecognizedCharge); @@ -347,7 +351,8 @@ public class LoanTransaction extends AbstractPersistableCustom { } private LoanTransaction(final Loan loan, final Office office, final LoanTransactionType type, final PaymentDetail paymentDetail, - final BigDecimal amount, final LocalDate date, final String externalId, final LocalDateTime createdDate, final AppUser appUser) { + final BigDecimal amount, final LocalDate date, final String externalId, final LocalDateTime createdDate, + final AppUser appUser) { this.loan = loan; this.typeOf = type.getValue(); this.paymentDetail = paymentDetail; @@ -385,10 +390,14 @@ public class LoanTransaction extends AbstractPersistableCustom { * This accumulates the values passed to the already existent values for * each of the portions. * - * @param principal principal - * @param interest interest - * @param feeCharges feeCharges - * @param penaltyCharges penaltyCharges + * @param principal + * principal + * @param interest + * interest + * @param feeCharges + * feeCharges + * @param penaltyCharges + * penaltyCharges */ public void updateComponents(final Money principal, final Money interest, final Money feeCharges, final Money penaltyCharges) { final MonetaryCurrency currency = principal.getCurrency(); @@ -676,12 +685,10 @@ public class LoanTransaction extends AbstractPersistableCustom { } public boolean isNonMonetaryTransaction() { - return isNotReversed() - && (LoanTransactionType.CONTRA.equals(getTypeOf()) || LoanTransactionType.MARKED_FOR_RESCHEDULING.equals(getTypeOf()) - || LoanTransactionType.APPROVE_TRANSFER.equals(getTypeOf()) - || LoanTransactionType.INITIATE_TRANSFER.equals(getTypeOf()) - || LoanTransactionType.REJECT_TRANSFER.equals(getTypeOf()) || LoanTransactionType.WITHDRAW_TRANSFER - .equals(getTypeOf())); + return isNotReversed() && (LoanTransactionType.CONTRA.equals(getTypeOf()) + || LoanTransactionType.MARKED_FOR_RESCHEDULING.equals(getTypeOf()) + || LoanTransactionType.APPROVE_TRANSFER.equals(getTypeOf()) || LoanTransactionType.INITIATE_TRANSFER.equals(getTypeOf()) + || LoanTransactionType.REJECT_TRANSFER.equals(getTypeOf()) || LoanTransactionType.WITHDRAW_TRANSFER.equals(getTypeOf())); } public void updateOutstandingLoanBalance(BigDecimal outstandingLoanBalance) { @@ -721,8 +728,8 @@ public class LoanTransaction extends AbstractPersistableCustom { boolean isLatest = false; if (loanTransaction != null) { isLatest = this.getTransactionDate().isBefore(loanTransaction.getTransactionDate()) - || (this.getTransactionDate().isEqual(loanTransaction.getTransactionDate()) && this.getCreatedDate().isBefore( - loanTransaction.getCreatedDate())); + || (this.getTransactionDate().isEqual(loanTransaction.getTransactionDate()) + && this.getCreatedDate().isBefore(loanTransaction.getCreatedDate())); } return isLatest; } @@ -790,10 +797,10 @@ public class LoanTransaction extends AbstractPersistableCustom { } public boolean isPaymentTransaction() { - return this.isNotReversed() - && !(this.isDisbursement() || this.isAccrual() || this.isRepaymentAtDisbursement() || this.isNonMonetaryTransaction() || this - .isIncomePosting()); + return this.isNotReversed() && !(this.isDisbursement() || this.isAccrual() || this.isRepaymentAtDisbursement() + || this.isNonMonetaryTransaction() || this.isIncomePosting()); } - // TODO missing hashCode(), equals(Object obj), but probably OK as long as this is never stored in a Collection. -} \ No newline at end of file + // TODO missing hashCode(), equals(Object obj), but probably OK as long as + // this is never stored in a Collection. +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionProcessingStrategyRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionProcessingStrategyRepository.java index e7c11acec..49c875e08 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionProcessingStrategyRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionProcessingStrategyRepository.java @@ -22,7 +22,7 @@ import org.apache.fineract.portfolio.loanproduct.domain.LoanTransactionProcessin import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface LoanTransactionProcessingStrategyRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface LoanTransactionProcessingStrategyRepository + extends JpaRepository, JpaSpecificationExecutor { // no added behaviour -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionRepository.java index 8c11f1011..bdd343013 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionRepository.java @@ -23,4 +23,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface LoanTransactionRepository extends JpaRepository, JpaSpecificationExecutor { // no added behaviour -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionToRepaymentScheduleMapping.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionToRepaymentScheduleMapping.java index cea9f3427..2eeaf6dcc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionToRepaymentScheduleMapping.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionToRepaymentScheduleMapping.java @@ -56,9 +56,9 @@ public class LoanTransactionToRepaymentScheduleMapping extends AbstractPersistab } - private LoanTransactionToRepaymentScheduleMapping(final LoanRepaymentScheduleInstallment installment, - final BigDecimal principalPortion, final BigDecimal interestPortion, final BigDecimal feeChargesPortion, - final BigDecimal penaltyChargesPortion, final BigDecimal amount) { + private LoanTransactionToRepaymentScheduleMapping(final LoanRepaymentScheduleInstallment installment, final BigDecimal principalPortion, + final BigDecimal interestPortion, final BigDecimal feeChargesPortion, final BigDecimal penaltyChargesPortion, + final BigDecimal amount) { this.installment = installment; this.principalPortion = principalPortion; this.interestPortion = interestPortion; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionType.java index 735489adc..3f2e29aeb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/LoanTransactionType.java @@ -50,9 +50,9 @@ public enum LoanTransactionType { WITHDRAW_TRANSFER(14, "loanTransactionType.withdrawTransfer"), // REJECT_TRANSFER(15, "loanTransactionType.rejectTransfer"), // REFUND(16, "loanTransactionType.refund"), // - CHARGE_PAYMENT(17, "loanTransactionType.chargePayment"), // + CHARGE_PAYMENT(17, "loanTransactionType.chargePayment"), // REFUND_FOR_ACTIVE_LOAN(18, "loanTransactionType.refund"), // - INCOME_POSTING(19,"loanTransactionType.incomePosting"); + INCOME_POSTING(19, "loanTransactionType.incomePosting"); private final Integer value; private final String code; @@ -129,7 +129,7 @@ public enum LoanTransactionType { break; case 19: loanTransactionType = LoanTransactionType.INCOME_POSTING; - break; + break; default: loanTransactionType = LoanTransactionType.INVALID; break; @@ -176,7 +176,8 @@ public enum LoanTransactionType { public boolean isRefundForActiveLoan() { return this.value.equals(LoanTransactionType.REFUND_FOR_ACTIVE_LOAN.getValue()); } + public boolean isIncomePosting() { return this.value.equals(LoanTransactionType.INCOME_POSTING.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/AbstractLoanRepaymentScheduleTransactionProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/AbstractLoanRepaymentScheduleTransactionProcessor.java old mode 100755 new mode 100644 index 95d59cce1..328da6071 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/AbstractLoanRepaymentScheduleTransactionProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/AbstractLoanRepaymentScheduleTransactionProcessor.java @@ -176,8 +176,8 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen * changedTransactionDetail accordingly **/ if (LoanTransaction.transactionAmountsMatch(currency, loanTransaction, newLoanTransaction)) { - loanTransaction.updateLoanTransactionToRepaymentScheduleMappings(newLoanTransaction - .getLoanTransactionToRepaymentScheduleMappings()); + loanTransaction.updateLoanTransactionToRepaymentScheduleMappings( + newLoanTransaction.getLoanTransactionToRepaymentScheduleMappings()); } else { loanTransaction.reverse(); loanTransaction.updateExternalId(null); @@ -284,7 +284,8 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen // is this transaction early/late/on-time with respect to // the // current installment? - if (isTransactionInAdvanceOfInstallment(installmentIndex, installments, transactionDate, transactionAmountUnprocessed)) { + if (isTransactionInAdvanceOfInstallment(installmentIndex, installments, transactionDate, + transactionAmountUnprocessed)) { transactionAmountUnprocessed = handleTransactionThatIsPaymentInAdvanceOfInstallment(currentInstallment, installments, loanTransaction, transactionDate, transactionAmountUnprocessed, transactionMappings); } else if (isTransactionALateRepaymentOnInstallment(installmentIndex, installments, @@ -369,9 +370,8 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen if (loanCharge.getAmountOutstanding(currency).isGreaterThanZero() && !loanCharge.isDueAtDisbursement()) { if (loanCharge.isInstalmentFee()) { LoanInstallmentCharge unpaidLoanChargePerInstallment = loanCharge.getUnpaidInstallmentLoanCharge(); - if (chargePerInstallment == null - || chargePerInstallment.getRepaymentInstallment().getDueDate() - .isAfter(unpaidLoanChargePerInstallment.getRepaymentInstallment().getDueDate())) { + if (chargePerInstallment == null || chargePerInstallment.getRepaymentInstallment().getDueDate() + .isAfter(unpaidLoanChargePerInstallment.getRepaymentInstallment().getDueDate())) { installemntCharge = loanCharge; chargePerInstallment = unpaidLoanChargePerInstallment; } @@ -380,9 +380,8 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen } } } - if (earliestUnpaidCharge == null - || (chargePerInstallment != null && earliestUnpaidCharge.getDueLocalDate().isAfter( - chargePerInstallment.getRepaymentInstallment().getDueDate()))) { + if (earliestUnpaidCharge == null || (chargePerInstallment != null + && earliestUnpaidCharge.getDueLocalDate().isAfter(chargePerInstallment.getRepaymentInstallment().getDueDate()))) { earliestUnpaidCharge = installemntCharge; } @@ -407,8 +406,8 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen principalPortion = principalPortion.plus(currentInstallment.writeOffOutstandingPrincipal(transactionDate, currency)); interestPortion = interestPortion.plus(currentInstallment.writeOffOutstandingInterest(transactionDate, currency)); feeChargesPortion = feeChargesPortion.plus(currentInstallment.writeOffOutstandingFeeCharges(transactionDate, currency)); - penaltychargesPortion = penaltychargesPortion.plus(currentInstallment.writeOffOutstandingPenaltyCharges(transactionDate, - currency)); + penaltychargesPortion = penaltychargesPortion + .plus(currentInstallment.writeOffOutstandingPenaltyCharges(transactionDate, currency)); } } @@ -463,9 +462,9 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen * @param transactionMappings * TODO */ - protected abstract Money handleTransactionThatIsPaymentInAdvanceOfInstallment( - final LoanRepaymentScheduleInstallment currentInstallment, final List installments, - final LoanTransaction loanTransaction, final LocalDate transactionDate, final Money paymentInAdvance, + protected abstract Money handleTransactionThatIsPaymentInAdvanceOfInstallment(final LoanRepaymentScheduleInstallment currentInstallment, + final List installments, final LoanTransaction loanTransaction, + final LocalDate transactionDate, final Money paymentInAdvance, final List transactionMappings); /** @@ -588,8 +587,8 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen feeAmount); if (amountDeductedTowardsCharge.isGreaterThanZero()) { - final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(loanTransaction, paidCharge, amountDeductedTowardsCharge - .getAmount().multiply(new BigDecimal(-1)), null); + final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(loanTransaction, paidCharge, + amountDeductedTowardsCharge.getAmount().multiply(new BigDecimal(-1)), null); loanTransaction.getLoanChargesPaid().add(loanChargePaidBy); amountRemaining = amountRemaining.minus(amountDeductedTowardsCharge); @@ -621,9 +620,8 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen } } } - if (latestPaidCharge == null - || (chargePerInstallment != null && latestPaidCharge.getDueLocalDate().isAfter( - chargePerInstallment.getRepaymentInstallment().getDueDate()))) { + if (latestPaidCharge == null || (chargePerInstallment != null + && latestPaidCharge.getDueLocalDate().isAfter(chargePerInstallment.getRepaymentInstallment().getDueDate()))) { latestPaidCharge = installemntCharge; } @@ -689,8 +687,8 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen principal = principal.minus(principalPortion); } } - if (!(principal.isGreaterThanZero() || interest.isGreaterThanZero() || feeCharges.isGreaterThanZero() || penaltyCharges - .isGreaterThanZero())) { + if (!(principal.isGreaterThanZero() || interest.isGreaterThanZero() || feeCharges.isGreaterThanZero() + || penaltyCharges.isGreaterThanZero())) { break; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/LoanRepaymentScheduleTransactionProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/LoanRepaymentScheduleTransactionProcessor.java index 1e6dc9ebe..015f3e7da 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/LoanRepaymentScheduleTransactionProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/LoanRepaymentScheduleTransactionProcessor.java @@ -54,4 +54,4 @@ public interface LoanRepaymentScheduleTransactionProcessor { void processTransactionsFromDerivedFields(List transactionsPostDisbursement, MonetaryCurrency currency, List installments, Set charges); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/CreocoreLoanRepaymentScheduleTransactionProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/CreocoreLoanRepaymentScheduleTransactionProcessor.java index 1c23d4142..a1f36decf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/CreocoreLoanRepaymentScheduleTransactionProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/CreocoreLoanRepaymentScheduleTransactionProcessor.java @@ -68,7 +68,8 @@ public class CreocoreLoanRepaymentScheduleTransactionProcessor extends AbstractL final LocalDate transactionDate, final Money paymentInAdvance, final List transactionMappings) { - return handleTransactionThatIsOnTimePaymentOfInstallment(currentInstallment, loanTransaction, paymentInAdvance, transactionMappings); + return handleTransactionThatIsOnTimePaymentOfInstallment(currentInstallment, loanTransaction, paymentInAdvance, + transactionMappings); } /** @@ -106,8 +107,8 @@ public class CreocoreLoanRepaymentScheduleTransactionProcessor extends AbstractL loanTransaction.getPenaltyChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - feeChargesPortion = currentInstallment - .waiveFeeChargesComponent(transactionDate, loanTransaction.getFeeChargesPortion(currency)); + feeChargesPortion = currentInstallment.waiveFeeChargesComponent(transactionDate, + loanTransaction.getFeeChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } else if (loanTransaction.isInterestWaiver()) { @@ -185,4 +186,4 @@ public class CreocoreLoanRepaymentScheduleTransactionProcessor extends AbstractL } return transactionAmountRemaining; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/EarlyPaymentLoanRepaymentScheduleTransactionProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/EarlyPaymentLoanRepaymentScheduleTransactionProcessor.java index cb17c208e..d412ad441 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/EarlyPaymentLoanRepaymentScheduleTransactionProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/EarlyPaymentLoanRepaymentScheduleTransactionProcessor.java @@ -57,8 +57,8 @@ public class EarlyPaymentLoanRepaymentScheduleTransactionProcessor extends Abstr loanTransaction.getPenaltyChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - feeChargesPortion = currentInstallment - .waiveFeeChargesComponent(transactionDate, loanTransaction.getFeeChargesPortion(currency)); + feeChargesPortion = currentInstallment.waiveFeeChargesComponent(transactionDate, + loanTransaction.getFeeChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } else if (loanTransaction.isInterestWaiver()) { @@ -202,4 +202,4 @@ public class EarlyPaymentLoanRepaymentScheduleTransactionProcessor extends Abstr return transactionAmountRemaining; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/FineractStyleLoanRepaymentScheduleTransactionProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/FineractStyleLoanRepaymentScheduleTransactionProcessor.java index 61f7a36e1..b28621715 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/FineractStyleLoanRepaymentScheduleTransactionProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/FineractStyleLoanRepaymentScheduleTransactionProcessor.java @@ -61,7 +61,8 @@ public class FineractStyleLoanRepaymentScheduleTransactionProcessor extends Abst final LocalDate transactionDate, final Money paymentInAdvance, List transactionMappings) { - return handleTransactionThatIsOnTimePaymentOfInstallment(currentInstallment, loanTransaction, paymentInAdvance, transactionMappings); + return handleTransactionThatIsOnTimePaymentOfInstallment(currentInstallment, loanTransaction, paymentInAdvance, + transactionMappings); } /** @@ -98,8 +99,8 @@ public class FineractStyleLoanRepaymentScheduleTransactionProcessor extends Abst loanTransaction.getPenaltyChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - feeChargesPortion = currentInstallment - .waiveFeeChargesComponent(transactionDate, loanTransaction.getFeeChargesPortion(currency)); + feeChargesPortion = currentInstallment.waiveFeeChargesComponent(transactionDate, + loanTransaction.getFeeChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } else if (loanTransaction.isInterestWaiver()) { @@ -180,4 +181,4 @@ public class FineractStyleLoanRepaymentScheduleTransactionProcessor extends Abst } return transactionAmountRemaining; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/HeavensFamilyLoanRepaymentScheduleTransactionProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/HeavensFamilyLoanRepaymentScheduleTransactionProcessor.java index a521a7cfe..3750b9928 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/HeavensFamilyLoanRepaymentScheduleTransactionProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/HeavensFamilyLoanRepaymentScheduleTransactionProcessor.java @@ -163,8 +163,8 @@ public class HeavensFamilyLoanRepaymentScheduleTransactionProcessor extends Abst loanTransaction.getPenaltyChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - feeChargesPortion = currentInstallment - .waiveFeeChargesComponent(transactionDate, loanTransaction.getFeeChargesPortion(currency)); + feeChargesPortion = currentInstallment.waiveFeeChargesComponent(transactionDate, + loanTransaction.getFeeChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } else if (loanTransaction.isInterestWaiver()) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java index 918140b26..6e5a8592d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java @@ -32,8 +32,8 @@ import org.joda.time.LocalDate; * This {@link LoanRepaymentScheduleTransactionProcessor} defaults to having the * payment order of Interest first, then principal, penalties and fees. */ -public class InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor extends - AbstractLoanRepaymentScheduleTransactionProcessor { +public class InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor + extends AbstractLoanRepaymentScheduleTransactionProcessor { /** * For early/'in advance' repayments, pay off in the same way as on-time @@ -46,7 +46,8 @@ public class InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionPr final LocalDate transactionDate, final Money paymentInAdvance, List transactionMappings) { - return handleTransactionThatIsOnTimePaymentOfInstallment(currentInstallment, loanTransaction, paymentInAdvance, transactionMappings); + return handleTransactionThatIsOnTimePaymentOfInstallment(currentInstallment, loanTransaction, paymentInAdvance, + transactionMappings); } /** @@ -84,8 +85,8 @@ public class InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionPr loanTransaction.getPenaltyChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - feeChargesPortion = currentInstallment - .waiveFeeChargesComponent(transactionDate, loanTransaction.getFeeChargesPortion(currency)); + feeChargesPortion = currentInstallment.waiveFeeChargesComponent(transactionDate, + loanTransaction.getFeeChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } else if (loanTransaction.isInterestWaiver()) { @@ -163,4 +164,4 @@ public class InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionPr } return transactionAmountRemaining; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java index 7895deab2..a86b87529 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java @@ -32,8 +32,8 @@ import org.joda.time.LocalDate; * This {@link LoanRepaymentScheduleTransactionProcessor} defaults to having the * payment order of principal first, then interest, penalties and fees. */ -public class PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor extends - AbstractLoanRepaymentScheduleTransactionProcessor { +public class PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor + extends AbstractLoanRepaymentScheduleTransactionProcessor { /** * For early/'in advance' repayments, pay off in the same way as on-time @@ -46,7 +46,8 @@ public class PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionPr final LocalDate transactionDate, final Money paymentInAdvance, List transactionMappings) { - return handleTransactionThatIsOnTimePaymentOfInstallment(currentInstallment, loanTransaction, paymentInAdvance, transactionMappings); + return handleTransactionThatIsOnTimePaymentOfInstallment(currentInstallment, loanTransaction, paymentInAdvance, + transactionMappings); } /** @@ -84,8 +85,8 @@ public class PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionPr loanTransaction.getPenaltyChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - feeChargesPortion = currentInstallment - .waiveFeeChargesComponent(transactionDate, loanTransaction.getFeeChargesPortion(currency)); + feeChargesPortion = currentInstallment.waiveFeeChargesComponent(transactionDate, + loanTransaction.getFeeChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } else if (loanTransaction.isInterestWaiver()) { @@ -167,4 +168,4 @@ public class PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionPr return transactionAmountRemaining; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/RBILoanRepaymentScheduleTransactionProcessor.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/RBILoanRepaymentScheduleTransactionProcessor.java index 7234b50d6..00b153a13 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/RBILoanRepaymentScheduleTransactionProcessor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/RBILoanRepaymentScheduleTransactionProcessor.java @@ -68,7 +68,8 @@ public class RBILoanRepaymentScheduleTransactionProcessor extends AbstractLoanRe final LocalDate transactionDate, final Money paymentInAdvance, List transactionMappings) { - return handleTransactionThatIsOnTimePaymentOfInstallment(currentInstallment, loanTransaction, paymentInAdvance, transactionMappings); + return handleTransactionThatIsOnTimePaymentOfInstallment(currentInstallment, loanTransaction, paymentInAdvance, + transactionMappings); } /** @@ -119,10 +120,10 @@ public class RBILoanRepaymentScheduleTransactionProcessor extends AbstractLoanRe loanTransaction.getTransactionDate(), installments); for (final LoanRepaymentScheduleInstallment installment : installments) { - if ((installment.isInterestDue(currency) || installment.getFeeChargesOutstanding(currency).isGreaterThanZero() || installment - .getPenaltyChargesOutstanding(currency).isGreaterThanZero()) - && (installment.isOverdueOn(loanTransaction.getTransactionDate()) || installment.getInstallmentNumber().equals( - currentInstallmentBasedOnTransactionDate.getInstallmentNumber()))) { + if ((installment.isInterestDue(currency) || installment.getFeeChargesOutstanding(currency).isGreaterThanZero() + || installment.getPenaltyChargesOutstanding(currency).isGreaterThanZero()) + && (installment.isOverdueOn(loanTransaction.getTransactionDate()) || installment.getInstallmentNumber() + .equals(currentInstallmentBasedOnTransactionDate.getInstallmentNumber()))) { penaltyChargesPortion = installment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); @@ -159,9 +160,8 @@ public class RBILoanRepaymentScheduleTransactionProcessor extends AbstractLoanRe break; } } - if (!isMappingUpdated - && principalPortion.plus(interestPortion).plus(feeChargesPortion).plus(penaltyChargesPortion) - .isGreaterThanZero()) { + if (!isMappingUpdated && principalPortion.plus(interestPortion).plus(feeChargesPortion).plus(penaltyChargesPortion) + .isGreaterThanZero()) { transactionMappings.add(LoanTransactionToRepaymentScheduleMapping.createFrom(installment, principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion)); } @@ -208,8 +208,8 @@ public class RBILoanRepaymentScheduleTransactionProcessor extends AbstractLoanRe loanTransaction.getPenaltyChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - feeChargesPortion = currentInstallment - .waiveFeeChargesComponent(transactionDate, loanTransaction.getFeeChargesPortion(currency)); + feeChargesPortion = currentInstallment.waiveFeeChargesComponent(transactionDate, + loanTransaction.getFeeChargesPortion(currency)); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } else if (loanTransaction.isInterestWaiver()) { @@ -298,4 +298,4 @@ public class RBILoanRepaymentScheduleTransactionProcessor extends AbstractLoanRe } return transactionAmountRemaining; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/DateMismatchException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/DateMismatchException.java index 8c18da892..31e34b347 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/DateMismatchException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/DateMismatchException.java @@ -22,18 +22,15 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR import org.joda.time.LocalDate; /** - * {@link AbstractPlatformDomainRuleException} thrown when - * actual disbursement date does not match with - * expected disbursement date + * {@link AbstractPlatformDomainRuleException} thrown when actual disbursement + * date does not match with expected disbursement date * */ public class DateMismatchException extends AbstractPlatformDomainRuleException { - public DateMismatchException(final LocalDate actualDisbursementDate, - final LocalDate expectedDisbursedOnLocalDate) { - super("error.msg.actual.disbursement.date.does.not.match.with.expected.disbursal.date", - "Actual disbursement date (" + actualDisbursementDate + ") " - + "should be equal to Expected disbursal date (" + expectedDisbursedOnLocalDate+ ")", actualDisbursementDate, - expectedDisbursedOnLocalDate, null); + public DateMismatchException(final LocalDate actualDisbursementDate, final LocalDate expectedDisbursedOnLocalDate) { + super("error.msg.actual.disbursement.date.does.not.match.with.expected.disbursal.date", "Actual disbursement date (" + + actualDisbursementDate + ") " + "should be equal to Expected disbursal date (" + expectedDisbursedOnLocalDate + ")", + actualDisbursementDate, expectedDisbursedOnLocalDate, null); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanStateTransitionException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanStateTransitionException.java index 63505b8f7..71ab58430 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanStateTransitionException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanStateTransitionException.java @@ -30,4 +30,4 @@ public class InvalidLoanStateTransitionException extends AbstractPlatformDomainR final Object... defaultUserMessageArgs) { super("error.msg.loan." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanTransactionTypeException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanTransactionTypeException.java index 82751d11f..4f629f8a0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanTransactionTypeException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanTransactionTypeException.java @@ -30,4 +30,4 @@ public class InvalidLoanTransactionTypeException extends AbstractPlatformDomainR final Object... defaultUserMessageArgs) { super("error.msg.loan." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanTypeException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanTypeException.java index 6c64060b2..ba0989856 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanTypeException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidLoanTypeException.java @@ -29,4 +29,4 @@ public class InvalidLoanTypeException extends AbstractPlatformDomainRuleExceptio public InvalidLoanTypeException(final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.loan.type.invalid", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidPaidInAdvanceAmountException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidPaidInAdvanceAmountException.java index fd7239a2e..090c62000 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidPaidInAdvanceAmountException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidPaidInAdvanceAmountException.java @@ -27,8 +27,9 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class InvalidPaidInAdvanceAmountException extends AbstractPlatformDomainRuleException { public InvalidPaidInAdvanceAmountException(final String refundAmountString) { - super("error.msg.loan.refund.amount.invalid", "The refund amount `" + refundAmountString + "`" - + "` is invalid or loan is not paid in advance.", new Object[] { refundAmountString}); + super("error.msg.loan.refund.amount.invalid", + "The refund amount `" + refundAmountString + "`" + "` is invalid or loan is not paid in advance.", + new Object[] { refundAmountString }); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidRefundDateException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidRefundDateException.java index 9215016c7..de90e8faa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidRefundDateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/InvalidRefundDateException.java @@ -23,11 +23,12 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class InvalidRefundDateException extends AbstractPlatformDomainRuleException { public InvalidRefundDateException(final String refundDateAsString) { - super("error.msg.loan.refund.failed", "The refund date`" + refundDateAsString + "`" - + "` cannot be before the smallest repayment transaction date", new Object[] { refundDateAsString}); + super("error.msg.loan.refund.failed", + "The refund date`" + refundDateAsString + "`" + "` cannot be before the smallest repayment transaction date", + new Object[] { refundDateAsString }); } - public InvalidRefundDateException(final String defaultUserMessage,final String entity,final Object... defaultUserMessageArgs) { - super("error.msg.loan." + entity , defaultUserMessage, defaultUserMessageArgs); + public InvalidRefundDateException(final String defaultUserMessage, final String entity, final Object... defaultUserMessageArgs) { + super("error.msg.loan." + entity, defaultUserMessage, defaultUserMessageArgs); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeDeleted.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeDeleted.java index e0dadd9a7..ed7d734e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeDeleted.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeDeleted.java @@ -27,8 +27,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeDeleted extends AbstractPlatformDomainRuleException { public LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeDeleted(final Long id) { - super("error.msg.loan.cannot.delete.loan.in.its.present.state", "Loan with identifier " + id - + " cannot be deleted in its current state.", id); + super("error.msg.loan.cannot.delete.loan.in.its.present.state", + "Loan with identifier " + id + " cannot be deleted in its current state.", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeModified.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeModified.java index 8386e63c1..721be7931 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeModified.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeModified.java @@ -27,8 +27,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeModified extends AbstractPlatformDomainRuleException { public LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeModified(final Long id) { - super("error.msg.loan.cannot.modify.loan.in.its.present.state", "Loan application with identifier " + id - + " cannot be modified in its current state.", id); + super("error.msg.loan.cannot.modify.loan.in.its.present.state", + "Loan application with identifier " + id + " cannot be modified in its current state.", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanDisbursalException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanDisbursalException.java index 1d86a039d..e319217b1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanDisbursalException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanDisbursalException.java @@ -23,8 +23,9 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class LoanDisbursalException extends AbstractPlatformDomainRuleException { public LoanDisbursalException(final String currentProduct, final String restrictedProduct) { - super("error.msg.loan.disbursal.failed", "This loan could not be disbursed as `" + currentProduct + "` and `" + restrictedProduct - + "` are not allowed to co-exist", new Object[] { currentProduct, restrictedProduct }); + super("error.msg.loan.disbursal.failed", + "This loan could not be disbursed as `" + currentProduct + "` and `" + restrictedProduct + "` are not allowed to co-exist", + new Object[] { currentProduct, restrictedProduct }); } public LoanDisbursalException(final String defaultUserMessage, final String entity, final Object... defaultUserMessageArgs) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanNotFoundException.java index 9cde61070..85607958a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanNotFoundException.java @@ -28,4 +28,4 @@ public class LoanNotFoundException extends AbstractPlatformResourceNotFoundExcep public LoanNotFoundException(final Long id) { super("error.msg.loan.id.invalid", "Loan with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanOfficerAssignmentDateException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanOfficerAssignmentDateException.java index 979143710..918dbf468 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanOfficerAssignmentDateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanOfficerAssignmentDateException.java @@ -22,7 +22,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class LoanOfficerAssignmentDateException extends AbstractPlatformDomainRuleException { - public LoanOfficerAssignmentDateException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { + public LoanOfficerAssignmentDateException(final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg.loan.assignment.date." + postFix, defaultUserMessage, defaultUserMessageArgs); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanOfficerAssignmentException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanOfficerAssignmentException.java index 33aa00b5f..4c8acad11 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanOfficerAssignmentException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanOfficerAssignmentException.java @@ -24,12 +24,12 @@ import org.joda.time.LocalDate; public class LoanOfficerAssignmentException extends AbstractPlatformDomainRuleException { public LoanOfficerAssignmentException(final Long loanId, final Long fromLoanOfficerId) { - super("error.msg.loan.not.assigned.to.loan.officer", "Loan with identifier " + loanId - + " is not assigned to Loan Officer with identifier " + fromLoanOfficerId + ".", loanId); + super("error.msg.loan.not.assigned.to.loan.officer", + "Loan with identifier " + loanId + " is not assigned to Loan Officer with identifier " + fromLoanOfficerId + ".", loanId); } public LoanOfficerAssignmentException(final Long loanId, final LocalDate date) { - super("error.msg.loan.assignment.date.is.before.last.assignment.date", "Loan with identifier " + loanId - + " was already assigned before date " + date.toString()); + super("error.msg.loan.assignment.date.is.before.last.assignment.date", + "Loan with identifier " + loanId + " was already assigned before date " + date.toString()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTemplateTypeRequiredException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTemplateTypeRequiredException.java index 3acbca95f..8819c3142 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTemplateTypeRequiredException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTemplateTypeRequiredException.java @@ -29,4 +29,4 @@ public class LoanTemplateTypeRequiredException extends AbstractPlatformDomainRul public LoanTemplateTypeRequiredException(final String defaultUserMessage) { super("error.msg.loan.template.type.required", defaultUserMessage); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTransactionNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTransactionNotFoundException.java index d1d32154b..eb373fd9c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTransactionNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTransactionNotFoundException.java @@ -30,7 +30,7 @@ public class LoanTransactionNotFoundException extends AbstractPlatformResourceNo } public LoanTransactionNotFoundException(final Long id, final Long loanId) { - super("error.msg.loan.id.invalid", - "Transaction with identifier " + id + " does not exist for loan with identifier " + loanId + ".", id, loanId); + super("error.msg.loan.id.invalid", "Transaction with identifier " + id + " does not exist for loan with identifier " + loanId + ".", + id, loanId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTransactionProcessingStrategyNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTransactionProcessingStrategyNotFoundException.java index 8780fd4e7..c33889c9d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTransactionProcessingStrategyNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/LoanTransactionProcessingStrategyNotFoundException.java @@ -27,7 +27,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class LoanTransactionProcessingStrategyNotFoundException extends AbstractPlatformResourceNotFoundException { public LoanTransactionProcessingStrategyNotFoundException(final Long id) { - super("error.msg.transactions.processing.strategy.id.invalid", "Loan transaction processing strategy with identifier " + id - + " does not exist", id); + super("error.msg.transactions.processing.strategy.id.invalid", + "Loan transaction processing strategy with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/MinDaysBetweenDisbursalAndFirstRepaymentViolationException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/MinDaysBetweenDisbursalAndFirstRepaymentViolationException.java index dc70dae0c..e08ac5433 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/MinDaysBetweenDisbursalAndFirstRepaymentViolationException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/MinDaysBetweenDisbursalAndFirstRepaymentViolationException.java @@ -33,7 +33,7 @@ public class MinDaysBetweenDisbursalAndFirstRepaymentViolationException extends Integer minimumDaysBetweenDisbursalAndFirstRepayment) { super("error.msg.loan.days.between.first.repayment.and.disbursal.are.less.than.minimum.allowed", "Number of days between loan disbursal (" + disbursalDate + ") and first repayment (" + firstRepaymentDate - + ") can't be less than (" + minimumDaysBetweenDisbursalAndFirstRepayment + ").", disbursalDate, - firstRepaymentDate, minimumDaysBetweenDisbursalAndFirstRepayment); + + ") can't be less than (" + minimumDaysBetweenDisbursalAndFirstRepayment + ").", + disbursalDate, firstRepaymentDate, minimumDaysBetweenDisbursalAndFirstRepayment); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/NotSupportedLoanTemplateTypeException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/NotSupportedLoanTemplateTypeException.java index af8973070..0248609da 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/NotSupportedLoanTemplateTypeException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/NotSupportedLoanTemplateTypeException.java @@ -29,4 +29,4 @@ public class NotSupportedLoanTemplateTypeException extends AbstractPlatformDomai public NotSupportedLoanTemplateTypeException(final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.loan.template.type.not.supported", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/UndoLastTrancheDisbursementException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/UndoLastTrancheDisbursementException.java index d32dc8425..cd3031e5a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/UndoLastTrancheDisbursementException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/exception/UndoLastTrancheDisbursementException.java @@ -20,11 +20,11 @@ package org.apache.fineract.portfolio.loanaccount.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; -public class UndoLastTrancheDisbursementException extends AbstractPlatformDomainRuleException{ +public class UndoLastTrancheDisbursementException extends AbstractPlatformDomainRuleException { public UndoLastTrancheDisbursementException(final Object... defaultUserMessageArgs) { - super("error.msg.cannot.undo.last.disbursal.after.repayments or waivers"," Cannot undo last disbursement after repayments or waivers.", - defaultUserMessageArgs); + super("error.msg.cannot.undo.last.disbursal.after.repayments or waivers", + " Cannot undo last disbursement after repayments or waivers.", defaultUserMessageArgs); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/GuarantorConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/GuarantorConstants.java old mode 100755 new mode 100644 index 7c35d1035..c0a386039 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/GuarantorConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/GuarantorConstants.java @@ -29,10 +29,12 @@ public class GuarantorConstants { * Enum of all parameters passed in while creating/updating a loan product ***/ public enum GuarantorJSONinputParams { + LOAN_ID("loanId"), CLIENT_RELATIONSHIP_TYPE_ID("clientRelationshipTypeId"), GUARANTOR_TYPE_ID("guarantorTypeId"), ENTITY_ID( - "entityId"), FIRSTNAME("firstname"), LASTNAME("lastname"), ADDRESS_LINE_1("addressLine1"), ADDRESS_LINE_2("addressLine2"), CITY( - "city"), STATE("state"), ZIP("zip"), COUNTRY("country"), MOBILE_NUMBER("mobileNumber"), PHONE_NUMBER("housePhoneNumber"), COMMENT( - "comment"), DATE_OF_BIRTH("dob"), AMOUNT("amount"), SAVINGS_ID("savingsId"); + "entityId"), FIRSTNAME("firstname"), LASTNAME( + "lastname"), ADDRESS_LINE_1("addressLine1"), ADDRESS_LINE_2("addressLine2"), CITY("city"), STATE("state"), ZIP( + "zip"), COUNTRY("country"), MOBILE_NUMBER("mobileNumber"), PHONE_NUMBER("housePhoneNumber"), COMMENT( + "comment"), DATE_OF_BIRTH("dob"), AMOUNT("amount"), SAVINGS_ID("savingsId"); private final String value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/api/GuarantorsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/api/GuarantorsApiResource.java index df5473f9e..9cd33f1e9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/api/GuarantorsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/api/GuarantorsApiResource.java @@ -74,11 +74,10 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class GuarantorsApiResource { - private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "loanId", - "clientRelationshipType", - "guarantorType", "firstname", "lastname", "entityId", "externalId", "officeName", "joinedDate", "addressLine1", "addressLine2", - "city", "state", "zip", "country", "mobileNumber", "housePhoneNumber", "comment", "dob", "guarantorTypeOptions", - "allowedClientRelationshipTypes")); + private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "loanId", "clientRelationshipType", "guarantorType", "firstname", "lastname", "entityId", "externalId", + "officeName", "joinedDate", "addressLine1", "addressLine2", "city", "state", "zip", "country", "mobileNumber", + "housePhoneNumber", "comment", "dob", "guarantorTypeOptions", "allowedClientRelationshipTypes")); private static final Set ACCOUNT_TRANSFER_API_RESPONSE_DATA_PARAMETERS = new HashSet<>( Arrays.asList(AccountDetailConstants.idParamName, AccountTransfersApiConstants.transferDescriptionParamName, @@ -97,15 +96,13 @@ public class GuarantorsApiResource { private final BulkImportWorkbookService bulkImportWorkbookService; private final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService; - @Autowired public GuarantorsApiResource(final PlatformSecurityContext context, final GuarantorReadPlatformService guarantorReadPlatformService, final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final CodeValueReadPlatformService codeValueReadPlatformService, final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService, - final LoanReadPlatformService loanReadPlatformService, - final BulkImportWorkbookService bulkImportWorkbookService, + final LoanReadPlatformService loanReadPlatformService, final BulkImportWorkbookService bulkImportWorkbookService, final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService) { this.context = context; this.apiRequestParameterHelper = apiRequestParameterHelper; @@ -115,8 +112,8 @@ public class GuarantorsApiResource { this.codeValueReadPlatformService = codeValueReadPlatformService; this.portfolioAccountReadPlatformService = portfolioAccountReadPlatformService; this.loanReadPlatformService = loanReadPlatformService; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; } @GET @@ -234,18 +231,18 @@ public class GuarantorsApiResource { @GET @Path("downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getGuarantorTemplate(@QueryParam("officeId") final Long officeId,@QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.GUARANTORS.toString(), officeId,null,dateFormat); + public Response getGuarantorTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("dateFormat") final String dateFormat) { + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.GUARANTORS.toString(), officeId, null, dateFormat); } @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postGuarantorTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail,@FormDataParam("locale") final String locale, - @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId =this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.GUARANTORS.toString(), - uploadedInputStream,fileDetail,locale,dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.GUARANTORS.toString(), + uploadedInputStream, fileDetail, locale, dateFormat); return this.apiJsonSerializerService.serialize(importDocumentId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/command/GuarantorCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/command/GuarantorCommand.java index b686409cf..eed36b404 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/command/GuarantorCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/command/GuarantorCommand.java @@ -57,10 +57,10 @@ public class GuarantorCommand { private final Long savingsId; private final BigDecimal amount; - public GuarantorCommand(final Long clientRelationshipTypeId, final Integer guarantorTypeId, final Long entityId, - final String firstname, final String lastname, final String addressLine1, final String addressLine2, final String city, - final String state, final String zip, final String country, final String mobileNumber, final String housePhoneNumber, - final String comment, final LocalDate dob, final Long savingsId, final BigDecimal amount) { + public GuarantorCommand(final Long clientRelationshipTypeId, final Integer guarantorTypeId, final Long entityId, final String firstname, + final String lastname, final String addressLine1, final String addressLine2, final String city, final String state, + final String zip, final String country, final String mobileNumber, final String housePhoneNumber, final String comment, + final LocalDate dob, final Long savingsId, final BigDecimal amount) { this.clientRelationshipTypeId = clientRelationshipTypeId; @@ -109,8 +109,7 @@ public class GuarantorCommand { if (!isExternalGuarantor()) { baseDataValidator.reset().parameter(GuarantorJSONinputParams.ENTITY_ID.getValue()).value(this.entityId).notNull() .integerGreaterThanZero(); - baseDataValidator.reset().parameter(GuarantorJSONinputParams.SAVINGS_ID.getValue()).value(this.savingsId) - .longGreaterThanZero(); + baseDataValidator.reset().parameter(GuarantorJSONinputParams.SAVINGS_ID.getValue()).value(this.savingsId).longGreaterThanZero(); if (this.savingsId != null) { baseDataValidator.reset().parameter(GuarantorJSONinputParams.AMOUNT.getValue()).value(this.amount).notNull() .positiveAmount(); @@ -124,8 +123,10 @@ public class GuarantorCommand { validateNonMandatoryFieldsForMaxLength(baseDataValidator); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForUpdate() { @@ -143,8 +144,7 @@ public class GuarantorCommand { if (!isExternalGuarantor()) { baseDataValidator.reset().parameter(GuarantorJSONinputParams.ENTITY_ID.getValue()).value(this.entityId).ignoreIfNull() .integerGreaterThanZero(); - baseDataValidator.reset().parameter(GuarantorJSONinputParams.SAVINGS_ID.getValue()).value(this.savingsId) - .longGreaterThanZero(); + baseDataValidator.reset().parameter(GuarantorJSONinputParams.SAVINGS_ID.getValue()).value(this.savingsId).longGreaterThanZero(); if (this.savingsId != null) { baseDataValidator.reset().parameter(GuarantorJSONinputParams.AMOUNT.getValue()).value(this.amount).notNull() .positiveAmount(); @@ -165,8 +165,10 @@ public class GuarantorCommand { baseDataValidator.reset().anyOfNotNull(this.entityId, this.addressLine1, this.addressLine2, this.city, this.comment, this.country, this.firstname, this.housePhoneNumber, this.lastname, this.mobileNumber, this.state, this.zip); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } /** @@ -188,8 +190,8 @@ public class GuarantorCommand { .notExceedingLengthOf(50); baseDataValidator.reset().parameter(GuarantorJSONinputParams.MOBILE_NUMBER.getValue()).value(this.mobileNumber).ignoreIfNull() .notExceedingLengthOf(20).validatePhoneNumber(); - baseDataValidator.reset().parameter(GuarantorJSONinputParams.PHONE_NUMBER.getValue()).value(this.housePhoneNumber) - .ignoreIfNull().notExceedingLengthOf(20).validatePhoneNumber(); + baseDataValidator.reset().parameter(GuarantorJSONinputParams.PHONE_NUMBER.getValue()).value(this.housePhoneNumber).ignoreIfNull() + .notExceedingLengthOf(20).validatePhoneNumber(); baseDataValidator.reset().parameter(GuarantorJSONinputParams.COMMENT.getValue()).value(this.comment).ignoreIfNull() .notExceedingLengthOf(500); } @@ -222,4 +224,4 @@ public class GuarantorCommand { public BigDecimal getAmount() { return this.amount; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/GuarantorData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/GuarantorData.java index 11fdeac5f..6b125e64a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/GuarantorData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/GuarantorData.java @@ -67,7 +67,7 @@ public class GuarantorData { private final Collection allowedClientRelationshipTypes; private final Collection accountLinkingOptions; - //import fields + // import fields private Integer guarantorTypeId; private Integer clientRelationshipTypeId; private Integer savingsId; @@ -77,16 +77,17 @@ public class GuarantorData { private String dateFormat; private String locale; - public static GuarantorData importInstance(Integer guarantorTypeId,Integer clientRelationshipTypeId,Long entityId,String firstname, - String lastname,String addressLine1,String addressLine2,String city,LocalDate dob, String zip, - Integer savingsId, BigDecimal amount,Integer rowIndex,Long accountId,String locale,String dateFormat){ - return new GuarantorData(guarantorTypeId,clientRelationshipTypeId,entityId,firstname, lastname, - addressLine1, addressLine2,city,dob,zip,savingsId,amount, rowIndex, accountId,locale,dateFormat); + public static GuarantorData importInstance(Integer guarantorTypeId, Integer clientRelationshipTypeId, Long entityId, String firstname, + String lastname, String addressLine1, String addressLine2, String city, LocalDate dob, String zip, Integer savingsId, + BigDecimal amount, Integer rowIndex, Long accountId, String locale, String dateFormat) { + return new GuarantorData(guarantorTypeId, clientRelationshipTypeId, entityId, firstname, lastname, addressLine1, addressLine2, city, + dob, zip, savingsId, amount, rowIndex, accountId, locale, dateFormat); } - private GuarantorData(Integer guarantorTypeId,Integer clientRelationshipTypeId,Long entityId,String firstname, - String lastname,String addressLine1,String addressLine2,String city,LocalDate dob, String zip, - Integer savingsId, BigDecimal amount,Integer rowIndex,Long accountId,String locale,String dateFormat) { - this.rowIndex=rowIndex; + + private GuarantorData(Integer guarantorTypeId, Integer clientRelationshipTypeId, Long entityId, String firstname, String lastname, + String addressLine1, String addressLine2, String city, LocalDate dob, String zip, Integer savingsId, BigDecimal amount, + Integer rowIndex, Long accountId, String locale, String dateFormat) { + this.rowIndex = rowIndex; this.firstname = firstname; this.lastname = lastname; this.entityId = entityId; @@ -100,8 +101,8 @@ public class GuarantorData { this.savingsId = savingsId; this.amount = amount; this.accountId = accountId; - this.dateFormat=dateFormat; - this.locale= locale; + this.dateFormat = dateFormat; + this.locale = locale; this.clientRelationshipType = null; this.guarantorType = null; this.id = null; @@ -141,18 +142,18 @@ public class GuarantorData { public static GuarantorData templateOnTop(final GuarantorData guarantorData, final List guarantorTypeOptions, final Collection allowedClientRelationshipTypes, Collection accountLinkingOptions) { return new GuarantorData(guarantorData.id, guarantorData.loanId, guarantorData.clientRelationshipType, guarantorData.entityId, - guarantorData.guarantorType, guarantorData.firstname, guarantorData.lastname, guarantorData.dob, - guarantorData.addressLine1, guarantorData.addressLine2, guarantorData.city, guarantorData.state, guarantorData.zip, - guarantorData.country, guarantorData.mobileNumber, guarantorData.housePhoneNumber, guarantorData.comment, - guarantorData.officeName, guarantorData.joinedDate, guarantorData.externalId, guarantorData.status, - guarantorData.guarantorFundingDetails, guarantorTypeOptions, allowedClientRelationshipTypes, accountLinkingOptions); + guarantorData.guarantorType, guarantorData.firstname, guarantorData.lastname, guarantorData.dob, guarantorData.addressLine1, + guarantorData.addressLine2, guarantorData.city, guarantorData.state, guarantorData.zip, guarantorData.country, + guarantorData.mobileNumber, guarantorData.housePhoneNumber, guarantorData.comment, guarantorData.officeName, + guarantorData.joinedDate, guarantorData.externalId, guarantorData.status, guarantorData.guarantorFundingDetails, + guarantorTypeOptions, allowedClientRelationshipTypes, accountLinkingOptions); } public static GuarantorData mergeClientData(final ClientData clientData, final GuarantorData guarantorData) { return new GuarantorData(guarantorData.id, guarantorData.loanId, guarantorData.clientRelationshipType, guarantorData.entityId, guarantorData.guarantorType, clientData.getFirstname(), clientData.getLastname(), null, null, null, null, null, null, null, - null, null, null, clientData.officeName(), clientData.getActivationDate(), clientData.getExternalId(), - guarantorData.status, guarantorData.guarantorFundingDetails, null, guarantorData.allowedClientRelationshipTypes, + null, null, null, clientData.officeName(), clientData.getActivationDate(), clientData.getExternalId(), guarantorData.status, + guarantorData.guarantorFundingDetails, null, guarantorData.allowedClientRelationshipTypes, guarantorData.accountLinkingOptions); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/GuarantorFundingData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/GuarantorFundingData.java old mode 100755 new mode 100644 index b075f8488..061f60fc9 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/GuarantorFundingData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/GuarantorFundingData.java @@ -42,8 +42,8 @@ public class GuarantorFundingData { @SuppressWarnings("unused") private final Collection guarantorTransactions; - private GuarantorFundingData(final Long id, final EnumOptionData status, final PortfolioAccountData savingsAccount, final BigDecimal amount, - final BigDecimal amountReleased, final BigDecimal amountRemaining, final BigDecimal amountTransfered, + private GuarantorFundingData(final Long id, final EnumOptionData status, final PortfolioAccountData savingsAccount, + final BigDecimal amount, final BigDecimal amountReleased, final BigDecimal amountRemaining, final BigDecimal amountTransfered, final Collection guarantorTransactions) { this.id = id; this.status = status; @@ -55,8 +55,8 @@ public class GuarantorFundingData { this.guarantorTransactions = guarantorTransactions; } - public static GuarantorFundingData instance(final Long id, final EnumOptionData status, final PortfolioAccountData savingsAccount, final BigDecimal amount, - final BigDecimal amountReleased, final BigDecimal amountRemaining, final BigDecimal amountTransfered, + public static GuarantorFundingData instance(final Long id, final EnumOptionData status, final PortfolioAccountData savingsAccount, + final BigDecimal amount, final BigDecimal amountReleased, final BigDecimal amountRemaining, final BigDecimal amountTransfered, final Collection guarantorTransactions) { return new GuarantorFundingData(id, status, savingsAccount, amount, amountReleased, amountRemaining, amountTransfered, guarantorTransactions); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/ObligeeData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/ObligeeData.java index 227b09eab..992b6a9a6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/ObligeeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/data/ObligeeData.java @@ -33,9 +33,8 @@ public class ObligeeData { private final BigDecimal amountReleased; private final BigDecimal amountTransferred; - private ObligeeData(String firstName, String lastName, String displayName, String accountNumber, - BigDecimal loanAmount, BigDecimal guaranteeAmount, BigDecimal amountReleased, - BigDecimal amountTransferred) { + private ObligeeData(String firstName, String lastName, String displayName, String accountNumber, BigDecimal loanAmount, + BigDecimal guaranteeAmount, BigDecimal amountReleased, BigDecimal amountTransferred) { this.firstName = firstName; this.lastName = lastName; this.displayName = displayName; @@ -46,11 +45,11 @@ public class ObligeeData { this.amountTransferred = amountTransferred; } - public static ObligeeData instance(final String firstName, final String lastName, final String displayName, - final String accountNumber, final BigDecimal loanAmount, final BigDecimal guaranteeAmount, - final BigDecimal amountReleased, final BigDecimal amountTransferred) { - return new ObligeeData(firstName, lastName, displayName, accountNumber, loanAmount, guaranteeAmount, - amountReleased, amountTransferred); + public static ObligeeData instance(final String firstName, final String lastName, final String displayName, final String accountNumber, + final BigDecimal loanAmount, final BigDecimal guaranteeAmount, final BigDecimal amountReleased, + final BigDecimal amountTransferred) { + return new ObligeeData(firstName, lastName, displayName, accountNumber, loanAmount, guaranteeAmount, amountReleased, + amountTransferred); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/Guarantor.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/Guarantor.java old mode 100755 new mode 100644 index ca58ce5f1..0002548e0 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/Guarantor.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/Guarantor.java @@ -98,7 +98,7 @@ public class Guarantor extends AbstractPersistableCustom { @Column(name = "is_active", nullable = false) private boolean active; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "guarantor", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "guarantor", orphanRemoval = true, fetch = FetchType.EAGER) private List guarantorFundDetails = new ArrayList<>(); protected Guarantor() { @@ -132,8 +132,7 @@ public class Guarantor extends AbstractPersistableCustom { public static Guarantor fromJson(final Loan loan, final CodeValue clientRelationshipType, final JsonCommand command, final List fundingDetails) { - final Integer gurantorType = command.integerValueSansLocaleOfParameterNamed(GuarantorJSONinputParams.GUARANTOR_TYPE_ID - .getValue()); + final Integer gurantorType = command.integerValueSansLocaleOfParameterNamed(GuarantorJSONinputParams.GUARANTOR_TYPE_ID.getValue()); final Long entityId = command.longValueOfParameterNamed(GuarantorJSONinputParams.ENTITY_ID.getValue()); final boolean active = true; if (GuarantorType.EXTERNAL.getValue().equals(gurantorType)) { @@ -206,7 +205,7 @@ public class Guarantor extends AbstractPersistableCustom { newValue = command.integerValueOfParameterNamed(paramName); } actualChanges.put(paramName, newValue); - //propertyToBeUpdated = newValue; + // propertyToBeUpdated = newValue; // now update actual property if (paramName.equals(GuarantorJSONinputParams.GUARANTOR_TYPE_ID.getValue())) { @@ -220,7 +219,7 @@ public class Guarantor extends AbstractPersistableCustom { if (command.isChangeInStringParameterNamed(paramName, propertyToBeUpdated)) { final String newValue = command.stringValueOfParameterNamed(paramName); actualChanges.put(paramName, newValue); - //propertyToBeUpdated = newValue; + // propertyToBeUpdated = newValue; // now update actual property if (paramName.equals(GuarantorJSONinputParams.FIRSTNAME.getValue())) { @@ -254,7 +253,7 @@ public class Guarantor extends AbstractPersistableCustom { if (command.isChangeInDateParameterNamed(paramName, propertyToBeUpdated)) { final Date newValue = command.dateValueOfParameterNamed(paramName); actualChanges.put(paramName, newValue); - //propertyToBeUpdated = newValue; + // propertyToBeUpdated = newValue; // now update actual property if (paramName.equals(GuarantorJSONinputParams.DATE_OF_BIRTH.getValue())) { @@ -362,4 +361,4 @@ public class Guarantor extends AbstractPersistableCustom { } return isSelf; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundStatusType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundStatusType.java old mode 100755 new mode 100644 index 11c7dab2d..4396e219a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundStatusType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundStatusType.java @@ -88,4 +88,4 @@ public enum GuarantorFundStatusType { public boolean isDeleted() { return this.value.equals(GuarantorFundStatusType.DELETED.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingDetails.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingDetails.java old mode 100755 new mode 100644 index bee709165..fbec83d20 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingDetails.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingDetails.java @@ -61,7 +61,7 @@ public class GuarantorFundingDetails extends AbstractPersistableCustom { @Column(name = "amount_transfered_derived", scale = 6, precision = 19, nullable = true) private BigDecimal amountTransfered; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "guarantorFundingDetails", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "guarantorFundingDetails", orphanRemoval = true, fetch = FetchType.EAGER) private List guarantorFundingTransactions = new ArrayList<>(); protected GuarantorFundingDetails() {} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingRepository.java old mode 100755 new mode 100644 index f16c0a2b6..911f2a2aa --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingRepository.java @@ -21,5 +21,5 @@ package org.apache.fineract.portfolio.loanaccount.guarantor.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface GuarantorFundingRepository extends JpaRepository, - JpaSpecificationExecutor {} \ No newline at end of file +public interface GuarantorFundingRepository + extends JpaRepository, JpaSpecificationExecutor {} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingTransactionRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingTransactionRepository.java old mode 100755 new mode 100644 index 0ac128027..1635ce7f1 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingTransactionRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorFundingTransactionRepository.java @@ -24,10 +24,10 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface GuarantorFundingTransactionRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface GuarantorFundingTransactionRepository + extends JpaRepository, JpaSpecificationExecutor { @Query("select ft from GuarantorFundingTransaction ft where ft.loanTransaction.id in (:loanTransactions)") List fetchGuarantorFundingTransactions(@Param("loanTransactions") List loanTransactions); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorRepository.java old mode 100755 new mode 100644 index acf40b4fb..ec965fff4 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorRepository.java @@ -28,4 +28,4 @@ public interface GuarantorRepository extends JpaRepository, Jpa Guarantor findByLoanAndId(Loan loan, Long id); List findByLoan(Loan loan); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorType.java old mode 100755 new mode 100644 index 2cb422bcf..5cf11dab1 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/domain/GuarantorType.java @@ -22,6 +22,7 @@ import java.util.HashMap; import java.util.Map; public enum GuarantorType { + CUSTOMER(1, "guarantor.existing.customer"), STAFF(2, "guarantor.staff"), EXTERNAL(3, "guarantor.external"); private final Integer value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/exception/GuarantorNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/exception/GuarantorNotFoundException.java index 3c03f138f..b5cc3cf9d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/exception/GuarantorNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/exception/GuarantorNotFoundException.java @@ -30,12 +30,12 @@ public class GuarantorNotFoundException extends AbstractPlatformResourceNotFound } public GuarantorNotFoundException(final Long loanId, final Long guarantorId) { - super("error.msg.loan.guarantor.not.found", "Guarantor with identifier " + guarantorId - + " does not exist for loan with Identifier " + loanId, loanId, guarantorId); + super("error.msg.loan.guarantor.not.found", + "Guarantor with identifier " + guarantorId + " does not exist for loan with Identifier " + loanId, loanId, guarantorId); } public GuarantorNotFoundException(final Long loanId, final Long guarantorId, final Long guarantorFundingId) { super("error.msg.loan.guarantor.not.found", "Guarantor with identifier " + guarantorId + "and with funding detail " + guarantorFundingId + " does not exist for loan with Identifier " + loanId, loanId, guarantorId, guarantorFundingId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/exception/InvalidGuarantorException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/exception/InvalidGuarantorException.java index 474b93caf..894784b70 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/exception/InvalidGuarantorException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/exception/InvalidGuarantorException.java @@ -27,13 +27,15 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class InvalidGuarantorException extends AbstractPlatformDomainRuleException { public InvalidGuarantorException(final Long clientId, final Long loanId) { - super("error.msg.invalid.guarantor", "Tried to set Client with id " + clientId - + " as a guarantor to his/her own loan with loan identifier =" + loanId, clientId, loanId); + super("error.msg.invalid.guarantor", + "Tried to set Client with id " + clientId + " as a guarantor to his/her own loan with loan identifier =" + loanId, clientId, + loanId); } - public InvalidGuarantorException(final Long clientId, final Long loanId,final String errorcode) { - super("error.msg."+errorcode, "Tried to set Client with id " + clientId - + " as a guarantor to his/her own loan with loan identifier =" + loanId, clientId, loanId); + public InvalidGuarantorException(final Long clientId, final Long loanId, final String errorcode) { + super("error.msg." + errorcode, + "Tried to set Client with id " + clientId + " as a guarantor to his/her own loan with loan identifier =" + loanId, clientId, + loanId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/CreateGuarantorCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/CreateGuarantorCommandHandler.java old mode 100755 new mode 100644 index 8467f3671..a532507f4 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/CreateGuarantorCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/CreateGuarantorCommandHandler.java @@ -44,4 +44,4 @@ public class CreateGuarantorCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.createGuarantor(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/DeleteGuarantorCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/DeleteGuarantorCommandHandler.java old mode 100755 new mode 100644 index 661dfd733..032efa57b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/DeleteGuarantorCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/DeleteGuarantorCommandHandler.java @@ -43,4 +43,4 @@ public class DeleteGuarantorCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.guarantorWritePlatformService.removeGuarantor(command.getLoanId(), command.entityId(), command.subentityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/UpdateGuarantorCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/UpdateGuarantorCommandHandler.java old mode 100755 new mode 100644 index d673f88f0..808eb669b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/UpdateGuarantorCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/handler/UpdateGuarantorCommandHandler.java @@ -43,4 +43,4 @@ public class UpdateGuarantorCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.updateGuarantor(command.getLoanId(), command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/serialization/GuarantorCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/serialization/GuarantorCommandFromApiJsonDeserializer.java old mode 100755 new mode 100644 index 35d08a112..fd644b8c2 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/serialization/GuarantorCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/serialization/GuarantorCommandFromApiJsonDeserializer.java @@ -68,23 +68,20 @@ public final class GuarantorCommandFromApiJsonDeserializer extends AbstractFromA } private GuarantorCommand extractGuarantorCommand(final JsonElement element, final Locale locale, final String dateFormat) { - final Long clientRelationshipTypeId = this.fromApiJsonHelper.extractLongNamed( - GuarantorJSONinputParams.CLIENT_RELATIONSHIP_TYPE_ID.getValue(), element); - final Integer guarantorTypeId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - GuarantorJSONinputParams.GUARANTOR_TYPE_ID.getValue(), element); + final Long clientRelationshipTypeId = this.fromApiJsonHelper + .extractLongNamed(GuarantorJSONinputParams.CLIENT_RELATIONSHIP_TYPE_ID.getValue(), element); + final Integer guarantorTypeId = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(GuarantorJSONinputParams.GUARANTOR_TYPE_ID.getValue(), element); final Long entityId = this.fromApiJsonHelper.extractLongNamed(GuarantorJSONinputParams.ENTITY_ID.getValue(), element); final String firstname = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.FIRSTNAME.getValue(), element); final String lastname = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.LASTNAME.getValue(), element); - final String addressLine1 = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.ADDRESS_LINE_1.getValue(), - element); - final String addressLine2 = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.ADDRESS_LINE_2.getValue(), - element); + final String addressLine1 = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.ADDRESS_LINE_1.getValue(), element); + final String addressLine2 = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.ADDRESS_LINE_2.getValue(), element); final String city = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.CITY.getValue(), element); final String state = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.STATE.getValue(), element); final String zip = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.ZIP.getValue(), element); final String country = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.COUNTRY.getValue(), element); - final String mobileNumber = this.fromApiJsonHelper - .extractStringNamed(GuarantorJSONinputParams.MOBILE_NUMBER.getValue(), element); + final String mobileNumber = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.MOBILE_NUMBER.getValue(), element); final String housePhoneNumber = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.PHONE_NUMBER.getValue(), element); final String comment = this.fromApiJsonHelper.extractStringNamed(GuarantorJSONinputParams.COMMENT.getValue(), element); @@ -98,4 +95,4 @@ public final class GuarantorCommandFromApiJsonDeserializer extends AbstractFromA city, state, zip, country, mobileNumber, housePhoneNumber, comment, dob, savingsId, amount); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorDomainServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorDomainServiceImpl.java old mode 100755 new mode 100644 index adb3b8aa9..d284f0fe0 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorDomainServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorDomainServiceImpl.java @@ -74,7 +74,6 @@ public class GuarantorDomainServiceImpl implements GuarantorDomainService { private final Map releaseLoanIds = new HashMap<>(2); private final SavingsAccountAssembler savingsAccountAssembler; - @Autowired public GuarantorDomainServiceImpl(final GuarantorRepository guarantorRepository, final GuarantorFundingRepository guarantorFundingRepository, @@ -156,8 +155,10 @@ public class GuarantorDomainServiceImpl implements GuarantorDomainService { mandatoryAmount); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformService.java index 35f6c2d6f..28f2f3faa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformService.java @@ -45,5 +45,4 @@ public interface GuarantorReadPlatformService { List retrieveObligeeDetails(Long clientId); - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformServiceImpl.java index 00762b007..f5f9230cc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformServiceImpl.java @@ -77,8 +77,7 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe String sql = "select " + rm.schema(); sql += " where loan_id = ? group by g.id,gfd.id, gt.id"; final List guarantorDatas = this.jdbcTemplate.query(sql, rm, - new Object[] { AccountAssociationType.GUARANTOR_ACCOUNT_ASSOCIATION.getValue(), - loanId }); + new Object[] { AccountAssociationType.GUARANTOR_ACCOUNT_ASSOCIATION.getValue(), loanId }); final List mergedGuarantorDatas = new ArrayList<>(); @@ -88,15 +87,13 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe return mergedGuarantorDatas; } - @Override public GuarantorData retrieveGuarantor(final Long loanId, final Long guarantorId) { final GuarantorMapper rm = new GuarantorMapper(); String sql = "select " + rm.schema(); sql += " where g.loan_id = ? and g.id = ? group by g.id, gfd.id, gt.id"; final GuarantorData guarantorData = this.jdbcTemplate.queryForObject(sql, rm, - new Object[] { AccountAssociationType.GUARANTOR_ACCOUNT_ASSOCIATION.getValue(), - loanId, guarantorId }); + new Object[] { AccountAssociationType.GUARANTOR_ACCOUNT_ASSOCIATION.getValue(), loanId, guarantorId }); return mergeDetailsForClientOrStaffGuarantor(guarantorData); } @@ -108,19 +105,19 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe private final StringBuilder sqlBuilder = new StringBuilder( " g.id as id, g.loan_id as loanId, g.client_reln_cv_id clientRelationshipTypeId, g.entity_id as entityId, g.type_enum guarantorType ,g.firstname as firstname, g.lastname as lastname, g.dob as dateOfBirth, g.address_line_1 as addressLine1, g.address_line_2 as addressLine2, g.city as city, g.state as state, g.country as country, g.zip as zip, g.house_phone_number as housePhoneNumber, g.mobile_number as mobilePhoneNumber, g.comment as comment, ") - .append(" g.is_active as guarantorStatus,")// - .append(" cv.code_value as typeName, ")// - .append("gfd.amount,")// - .append(this.guarantorFundingMapper.schema())// - .append(",")// - .append(this.guarantorTransactionMapper.schema())// - .append(" FROM m_guarantor g") // - .append(" left JOIN m_code_value cv on g.client_reln_cv_id = cv.id")// - .append(" left JOIN m_guarantor_funding_details gfd on g.id = gfd.guarantor_id")// - .append(" left JOIN m_portfolio_account_associations aa on gfd.account_associations_id = aa.id and aa.is_active = 1 and aa.association_type_enum = ?")// - .append(" left JOIN m_savings_account sa on sa.id = aa.linked_savings_account_id ")// - .append(" left join m_guarantor_transaction gt on gt.guarantor_fund_detail_id = gfd.id") // - .append(" left join m_deposit_account_on_hold_transaction oht on oht.id = gt.deposit_on_hold_transaction_id"); + .append(" g.is_active as guarantorStatus,")// + .append(" cv.code_value as typeName, ")// + .append("gfd.amount,")// + .append(this.guarantorFundingMapper.schema())// + .append(",")// + .append(this.guarantorTransactionMapper.schema())// + .append(" FROM m_guarantor g") // + .append(" left JOIN m_code_value cv on g.client_reln_cv_id = cv.id")// + .append(" left JOIN m_guarantor_funding_details gfd on g.id = gfd.guarantor_id")// + .append(" left JOIN m_portfolio_account_associations aa on gfd.account_associations_id = aa.id and aa.is_active = 1 and aa.association_type_enum = ?")// + .append(" left JOIN m_savings_account sa on sa.id = aa.linked_savings_account_id ")// + .append(" left join m_guarantor_transaction gt on gt.guarantor_fund_detail_id = gfd.id") // + .append(" left join m_deposit_account_on_hold_transaction oht on oht.id = gt.deposit_on_hold_transaction_id"); public String schema() { return this.sqlBuilder.toString(); @@ -173,8 +170,6 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe } } - - return new GuarantorData(id, loanId, clientRelationshipType, entityId, guarantorType, firstname, lastname, dob, addressLine1, addressLine2, city, state, zip, country, mobileNumber, housePhoneNumber, comment, null, null, null, status, guarantorFundingDetails, null, null, accountLinkingOptions); @@ -312,8 +307,7 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe sb.append( "gfd.amount_released_derived as amountReleased, gfd.amount_transfered_derived as amountTransferred FROM m_guarantor mg"); sb.append(" JOIN m_guarantor_funding_details gfd on mg.id = gfd.guarantor_id "); - sb.append( - " JOIN m_client mc ON mg.entity_id = mc.id AND mc.id = ? JOIN m_loan loan ON mg.loan_id = loan.id "); + sb.append(" JOIN m_client mc ON mg.entity_id = mc.id AND mc.id = ? JOIN m_loan loan ON mg.loan_id = loan.id "); sb.append(" JOIN m_client cl ON loan.client_id = cl.id "); sql = sb.toString(); } @@ -323,8 +317,7 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe } @Override - public ObligeeData mapRow(final ResultSet rs, final int rowNum) - throws SQLException { + public ObligeeData mapRow(final ResultSet rs, final int rowNum) throws SQLException { final String firstName = rs.getString("firstname"); final String lastName = rs.getString("lastname"); final String displayName = rs.getString("displayName"); @@ -335,11 +328,11 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe final BigDecimal amountReleased = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amountReleased"); final BigDecimal amountTransferred = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amountTransferred"); - return ObligeeData.instance(firstName, lastName, displayName, loanAccountNumber, loanAmount, - guaranteeAmount, amountReleased, amountTransferred); + return ObligeeData.instance(firstName, lastName, displayName, loanAccountNumber, loanAmount, guaranteeAmount, amountReleased, + amountTransferred); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformService.java index 260f0200e..ba4fe109c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformService.java @@ -29,4 +29,4 @@ public interface GuarantorWritePlatformService { CommandProcessingResult removeGuarantor(final Long loanId, final Long guarantorId, Long guarantorFundingId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformServiceJpaRepositoryIImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformServiceJpaRepositoryIImpl.java index 428ad565a..c1be1fb49 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformServiceJpaRepositoryIImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformServiceJpaRepositoryIImpl.java @@ -111,15 +111,15 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto AccountAssociations accountAssociations = null; if (guarantorCommand.getSavingsId() != null) { final SavingsAccount savingsAccount = this.savingsAccountAssembler.assembleFrom(guarantorCommand.getSavingsId()); - validateGuarantorSavingsAccountActivationDateWithLoanSubmittedOnDate(loan,savingsAccount); + validateGuarantorSavingsAccountActivationDateWithLoanSubmittedOnDate(loan, savingsAccount); accountAssociations = AccountAssociations.associateSavingsAccount(loan, savingsAccount, AccountAssociationType.GUARANTOR_ACCOUNT_ASSOCIATION.getValue(), true); GuarantorFundingDetails fundingDetails = new GuarantorFundingDetails(accountAssociations, GuarantorFundStatusType.ACTIVE.getValue(), guarantorCommand.getAmount()); guarantorFundingDetails.add(fundingDetails); - if (loan.isDisbursed() || (loan.isApproved() - && (loan.getGuaranteeAmount() != null || loan.loanProduct().isHoldGuaranteeFundsEnabled()))) { + if (loan.isDisbursed() + || (loan.isApproved() && (loan.getGuaranteeAmount() != null || loan.loanProduct().isHoldGuaranteeFundsEnabled()))) { this.guarantorDomainService.assignGuarantor(fundingDetails, LocalDate.now()); loan.updateGuaranteeAmount(fundingDetails.getAmount()); } @@ -180,12 +180,15 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto } } - private void validateGuarantorSavingsAccountActivationDateWithLoanSubmittedOnDate(final Loan loan, final SavingsAccount savingsAccount) { - if (loan.getSubmittedOnDate().isBefore(savingsAccount.getActivationLocalDate())) { throw new GeneralPlatformDomainRuleException( - "error.msg.guarantor.saving.account.activation.date.is.on.or.before.loan.submitted.on.date", - "Guarantor saving account activation date [" + savingsAccount.getActivationLocalDate() - + "] is on or before the loan submitted on date [" + loan.getSubmittedOnDate() + "]", - savingsAccount.getActivationLocalDate(), loan.getSubmittedOnDate()); } + private void validateGuarantorSavingsAccountActivationDateWithLoanSubmittedOnDate(final Loan loan, + final SavingsAccount savingsAccount) { + if (loan.getSubmittedOnDate().isBefore(savingsAccount.getActivationLocalDate())) { + throw new GeneralPlatformDomainRuleException( + "error.msg.guarantor.saving.account.activation.date.is.on.or.before.loan.submitted.on.date", + "Guarantor saving account activation date [" + savingsAccount.getActivationLocalDate() + + "] is on or before the loan submitted on date [" + loan.getSubmittedOnDate() + "]", + savingsAccount.getActivationLocalDate(), loan.getSubmittedOnDate()); + } } @Override @@ -251,8 +254,9 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto final Loan loan = this.loanRepositoryWrapper.findOneWithNotFoundDetection(loanId, true); validateLoanStatus(loan); final Guarantor guarantorForDelete = this.guarantorRepository.findByLoanAndId(loan, guarantorId); - if (guarantorForDelete == null || (guarantorFundingId == null && !guarantorForDelete.getGuarantorFundDetails().isEmpty())) { throw new GuarantorNotFoundException( - loanId, guarantorId, guarantorFundingId); } + if (guarantorForDelete == null || (guarantorFundingId == null && !guarantorForDelete.getGuarantorFundDetails().isEmpty())) { + throw new GuarantorNotFoundException(loanId, guarantorId, guarantorFundingId); + } CommandProcessingResult commandProcessingResult = removeGuarantor(guarantorForDelete, loanId, guarantorFundingId); if (loan.isApproved() || loan.isDisbursed()) { this.guarantorDomainService.validateGuarantorBusinessRules(loan); @@ -271,13 +275,16 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto guarantorForDelete.updateStatus(false); } else { GuarantorFundingDetails guarantorFundingDetails = guarantorForDelete.getGuarantorFundingDetail(guarantorFundingId); - if (guarantorFundingDetails == null) { throw new GuarantorNotFoundException(loanId, guarantorForDelete.getId(), - guarantorFundingId); } + if (guarantorFundingDetails == null) { + throw new GuarantorNotFoundException(loanId, guarantorForDelete.getId(), guarantorFundingId); + } removeguarantorFundDetails(guarantorForDelete, baseDataValidator, guarantorFundingDetails); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } this.guarantorRepository.saveAndFlush(guarantorForDelete); CommandProcessingResultBuilder commandProcessingResultBuilder = new CommandProcessingResultBuilder() .withEntityId(guarantorForDelete.getId()).withLoanId(guarantorForDelete.getLoanId()) diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/AddAndDeleteLoanDisburseDetailsCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/AddAndDeleteLoanDisburseDetailsCommandHandler.java index e96239d03..214827055 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/AddAndDeleteLoanDisburseDetailsCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/AddAndDeleteLoanDisburseDetailsCommandHandler.java @@ -42,4 +42,4 @@ public class AddAndDeleteLoanDisburseDetailsCommandHandler implements NewCommand return this.writePlatformService.addAndDeleteLoanDisburseDetails(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/AddLoanChargeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/AddLoanChargeCommandHandler.java index af23427ec..2d5e631b7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/AddLoanChargeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/AddLoanChargeCommandHandler.java @@ -44,4 +44,4 @@ public class AddLoanChargeCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.addLoanCharge(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/BulkUpdateLoanOfficerCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/BulkUpdateLoanOfficerCommandHandler.java index 9f306e64d..017b354d5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/BulkUpdateLoanOfficerCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/BulkUpdateLoanOfficerCommandHandler.java @@ -44,4 +44,4 @@ public class BulkUpdateLoanOfficerCommandHandler implements NewCommandSourceHand return this.writePlatformService.bulkLoanReassignment(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/CloseLoanAsRescheduledCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/CloseLoanAsRescheduledCommandHandler.java index 83e6d161c..af1ed6c15 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/CloseLoanAsRescheduledCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/CloseLoanAsRescheduledCommandHandler.java @@ -44,4 +44,4 @@ public class CloseLoanAsRescheduledCommandHandler implements NewCommandSourceHan return this.writePlatformService.closeAsRescheduled(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/CloseLoanCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/CloseLoanCommandHandler.java index 90478ebdb..2460bde85 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/CloseLoanCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/CloseLoanCommandHandler.java @@ -44,4 +44,4 @@ public class CloseLoanCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.closeLoan(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DeleteLoanChargeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DeleteLoanChargeCommandHandler.java index 47c07e207..98066bea5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DeleteLoanChargeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DeleteLoanChargeCommandHandler.java @@ -44,4 +44,4 @@ public class DeleteLoanChargeCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.deleteLoanCharge(command.getLoanId(), command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DisburseLoanCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DisburseLoanCommandHandler.java index b20308ee6..e6acaf692 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DisburseLoanCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DisburseLoanCommandHandler.java @@ -44,4 +44,4 @@ public class DisburseLoanCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.disburseLoan(command.entityId(), command, false); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DisburseLoanToSavingsCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DisburseLoanToSavingsCommandHandler.java old mode 100755 new mode 100644 index 07a824fa7..04fff7c9b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DisburseLoanToSavingsCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/DisburseLoanToSavingsCommandHandler.java @@ -44,4 +44,4 @@ public class DisburseLoanToSavingsCommandHandler implements NewCommandSourceHand return this.writePlatformService.disburseLoan(command.entityId(), command, true); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMApplicationRejectionCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMApplicationRejectionCommandHandler.java index cf3e6bf58..017302682 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMApplicationRejectionCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMApplicationRejectionCommandHandler.java @@ -30,20 +30,19 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "GLIMLOAN", action = "REJECT") -public class GLIMApplicationRejectionCommandHandler implements NewCommandSourceHandler -{ +public class GLIMApplicationRejectionCommandHandler implements NewCommandSourceHandler { - private final LoanApplicationWritePlatformService writePlatformService; + private final LoanApplicationWritePlatformService writePlatformService; - @Autowired - public GLIMApplicationRejectionCommandHandler(final LoanApplicationWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public GLIMApplicationRejectionCommandHandler(final LoanApplicationWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.rejectGLIMApplicationApproval(command.entityId(), command); - } -} \ No newline at end of file + return this.writePlatformService.rejectGLIMApplicationApproval(command.entityId(), command); + } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMBulkRepaymentCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMBulkRepaymentCommandHandler.java index c03e7b0d8..13263397c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMBulkRepaymentCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMBulkRepaymentCommandHandler.java @@ -30,7 +30,7 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "GLIMLOAN", action = "REPAYMENT") -public class GLIMBulkRepaymentCommandHandler implements NewCommandSourceHandler { +public class GLIMBulkRepaymentCommandHandler implements NewCommandSourceHandler { private final LoanWritePlatformService writePlatformService; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMLoanApplicationApprovalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMLoanApplicationApprovalCommandHandler.java index 6f876eb1e..6d90455b0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMLoanApplicationApprovalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GLIMLoanApplicationApprovalCommandHandler.java @@ -32,18 +32,18 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "GLIMLOAN", action = "APPROVE") public class GLIMLoanApplicationApprovalCommandHandler implements NewCommandSourceHandler { - private final LoanApplicationWritePlatformService writePlatformService; + private final LoanApplicationWritePlatformService writePlatformService; - @Autowired - public GLIMLoanApplicationApprovalCommandHandler(final LoanApplicationWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public GLIMLoanApplicationApprovalCommandHandler(final LoanApplicationWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.approveGLIMLoanAppication(command.entityId(), command); - } + return this.writePlatformService.approveGLIMLoanAppication(command.entityId(), command); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GlimLoanApplicationDisburseCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GlimLoanApplicationDisburseCommandHandler.java index a77f10fd1..a7cba15e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GlimLoanApplicationDisburseCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/GlimLoanApplicationDisburseCommandHandler.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.fineract.portfolio.loanaccount.handler; import org.apache.fineract.commands.annotation.CommandType; @@ -29,11 +28,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - @Service @CommandType(entity = "GLIMLOAN", action = "DISBURSE") -public class GlimLoanApplicationDisburseCommandHandler implements NewCommandSourceHandler -{ +public class GlimLoanApplicationDisburseCommandHandler implements NewCommandSourceHandler { private final LoanWritePlatformService writePlatformService; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationApprovalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationApprovalCommandHandler.java index b1ed5fed7..aebec3d7c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationApprovalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationApprovalCommandHandler.java @@ -44,4 +44,4 @@ public class LoanApplicationApprovalCommandHandler implements NewCommandSourceHa return this.writePlatformService.approveApplication(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationApprovalUndoCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationApprovalUndoCommandHandler.java index b7b4839b8..74300f1d2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationApprovalUndoCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationApprovalUndoCommandHandler.java @@ -44,4 +44,4 @@ public class LoanApplicationApprovalUndoCommandHandler implements NewCommandSour return this.writePlatformService.undoApplicationApproval(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationDeletionCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationDeletionCommandHandler.java index e941faf92..33b4bfe1b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationDeletionCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationDeletionCommandHandler.java @@ -44,4 +44,4 @@ public class LoanApplicationDeletionCommandHandler implements NewCommandSourceHa return this.writePlatformService.deleteApplication(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationModificationCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationModificationCommandHandler.java index 9836dadd5..dbca146b4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationModificationCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationModificationCommandHandler.java @@ -44,4 +44,4 @@ public class LoanApplicationModificationCommandHandler implements NewCommandSour return this.writePlatformService.modifyApplication(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationRejectedCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationRejectedCommandHandler.java index f3b9d7f02..c8cee0ec7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationRejectedCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationRejectedCommandHandler.java @@ -44,4 +44,4 @@ public class LoanApplicationRejectedCommandHandler implements NewCommandSourceHa return this.writePlatformService.rejectApplication(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationSubmittalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationSubmittalCommandHandler.java index 515ddeadf..1bad24bda 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationSubmittalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationSubmittalCommandHandler.java @@ -44,4 +44,4 @@ public class LoanApplicationSubmittalCommandHandler implements NewCommandSourceH return this.writePlatformService.submitApplication(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationWithdrawnByApplicantCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationWithdrawnByApplicantCommandHandler.java index 2d66dbf5b..6e5994b18 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationWithdrawnByApplicantCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanApplicationWithdrawnByApplicantCommandHandler.java @@ -44,4 +44,4 @@ public class LoanApplicationWithdrawnByApplicantCommandHandler implements NewCom return this.writePlatformService.applicantWithdrawsFromApplication(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRefundByCashCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRefundByCashCommandHandler.java index e06568cf3..cefbe0b20 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRefundByCashCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRefundByCashCommandHandler.java @@ -44,4 +44,4 @@ public class LoanRefundByCashCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.makeLoanRefund(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRepaymentAdjustmentCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRepaymentAdjustmentCommandHandler.java index 5616a0853..9097ae4dd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRepaymentAdjustmentCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRepaymentAdjustmentCommandHandler.java @@ -44,4 +44,4 @@ public class LoanRepaymentAdjustmentCommandHandler implements NewCommandSourceHa return this.writePlatformService.adjustLoanTransaction(command.getLoanId(), command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRepaymentCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRepaymentCommandHandler.java index 23d01f79d..4061bf6e2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRepaymentCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/LoanRepaymentCommandHandler.java @@ -44,4 +44,4 @@ public class LoanRepaymentCommandHandler implements NewCommandSourceHandler { boolean isRecoveryRepayment = false; return this.writePlatformService.makeLoanRepayment(command.getLoanId(), command, isRecoveryRepayment); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/PayLoanChargeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/PayLoanChargeCommandHandler.java old mode 100755 new mode 100644 index eba1870dd..15ce2092e --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/PayLoanChargeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/PayLoanChargeCommandHandler.java @@ -43,4 +43,4 @@ public class PayLoanChargeCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.payLoanCharge(command.getLoanId(), command.entityId(), command, command.entityId() == null); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/RemoveLoanOfficerCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/RemoveLoanOfficerCommandHandler.java index d9baeb028..601f20bed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/RemoveLoanOfficerCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/RemoveLoanOfficerCommandHandler.java @@ -44,4 +44,4 @@ public class RemoveLoanOfficerCommandHandler implements NewCommandSourceHandler return this.writePlatformService.removeLoanOfficer(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoDisbursalLoanCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoDisbursalLoanCommandHandler.java index cd08f17f7..c4ef400bf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoDisbursalLoanCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoDisbursalLoanCommandHandler.java @@ -44,4 +44,4 @@ public class UndoDisbursalLoanCommandHandler implements NewCommandSourceHandler return this.writePlatformService.undoLoanDisbursal(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoGLIMLoanApplicationApproval.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoGLIMLoanApplicationApproval.java index 672ad727e..9370256ae 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoGLIMLoanApplicationApproval.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoGLIMLoanApplicationApproval.java @@ -30,20 +30,19 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "GLIMLOAN", action = "UNDOAPPROVAL") -public class UndoGLIMLoanApplicationApproval implements NewCommandSourceHandler -{ +public class UndoGLIMLoanApplicationApproval implements NewCommandSourceHandler { - private final LoanApplicationWritePlatformService writePlatformService; + private final LoanApplicationWritePlatformService writePlatformService; - @Autowired - public UndoGLIMLoanApplicationApproval(final LoanApplicationWritePlatformService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public UndoGLIMLoanApplicationApproval(final LoanApplicationWritePlatformService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.undoGLIMLoanApplicationApproval(command.entityId(), command); - } -} \ No newline at end of file + return this.writePlatformService.undoGLIMLoanApplicationApproval(command.entityId(), command); + } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoGLIMLoanDisbursalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoGLIMLoanDisbursalCommandHandler.java index 050bb88bf..8b5d9eb93 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoGLIMLoanDisbursalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoGLIMLoanDisbursalCommandHandler.java @@ -29,10 +29,9 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "GLIMLOAN", action = "UNDODISBURSAL") -public class UndoGLIMLoanDisbursalCommandHandler implements NewCommandSourceHandler -{ +public class UndoGLIMLoanDisbursalCommandHandler implements NewCommandSourceHandler { -private final LoanWritePlatformService writePlatformService; + private final LoanWritePlatformService writePlatformService; @Autowired public UndoGLIMLoanDisbursalCommandHandler(final LoanWritePlatformService writePlatformService) { @@ -46,4 +45,4 @@ private final LoanWritePlatformService writePlatformService; return this.writePlatformService.undoGLIMLoanDisbursal(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoLastDisbursalLoanCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoLastDisbursalLoanCommandHandler.java index 40e25aba9..32fa41732 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoLastDisbursalLoanCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoLastDisbursalLoanCommandHandler.java @@ -44,4 +44,4 @@ public class UndoLastDisbursalLoanCommandHandler implements NewCommandSourceHand return this.writePlatformService.undoLastLoanDisbursal(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoWriteOffLoanCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoWriteOffLoanCommandHandler.java old mode 100755 new mode 100644 index a6e0f85de..440418196 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoWriteOffLoanCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UndoWriteOffLoanCommandHandler.java @@ -44,4 +44,4 @@ public class UndoWriteOffLoanCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.undoWriteOff(command.getLoanId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanChargeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanChargeCommandHandler.java index cb6d297ad..0b0669030 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanChargeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanChargeCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateLoanChargeCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.updateLoanCharge(command.getLoanId(), command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanDisbuseDateCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanDisbuseDateCommandHandler.java index a378dfcec..6089a67c3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanDisbuseDateCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanDisbuseDateCommandHandler.java @@ -42,4 +42,4 @@ public class UpdateLoanDisbuseDateCommandHandler implements NewCommandSourceHand return this.writePlatformService.updateDisbursementDateAndAmountForTranche(command.getLoanId(), command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanOfficerCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanOfficerCommandHandler.java index 84b68648a..6224cef78 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanOfficerCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/UpdateLoanOfficerCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateLoanOfficerCommandHandler implements NewCommandSourceHandler return this.writePlatformService.loanReassignment(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WaiveInterestPortionOnLoanCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WaiveInterestPortionOnLoanCommandHandler.java index 00dbb385b..def216926 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WaiveInterestPortionOnLoanCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WaiveInterestPortionOnLoanCommandHandler.java @@ -44,4 +44,4 @@ public class WaiveInterestPortionOnLoanCommandHandler implements NewCommandSourc return this.writePlatformService.waiveInterestOnLoan(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WaiveLoanChargeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WaiveLoanChargeCommandHandler.java index e4f84e2ec..9e45bdd7e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WaiveLoanChargeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WaiveLoanChargeCommandHandler.java @@ -44,4 +44,4 @@ public class WaiveLoanChargeCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.waiveLoanCharge(command.getLoanId(), command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WriteOffLoanCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WriteOffLoanCommandHandler.java index 6c2c2b3b5..dc1ae5c75 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WriteOffLoanCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/handler/WriteOffLoanCommandHandler.java @@ -44,4 +44,4 @@ public class WriteOffLoanCommandHandler implements NewCommandSourceHandler { return this.writePlatformService.writeOff(command.getLoanId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleDTO.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleDTO.java index e59bf983d..a33547115 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleDTO.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleDTO.java @@ -35,7 +35,8 @@ public class LoanScheduleDTO { this.loanScheduleModel = loanScheduleModel; } - public static LoanScheduleDTO from(final List installments, final LoanScheduleModel loanScheduleModel){ + public static LoanScheduleDTO from(final List installments, + final LoanScheduleModel loanScheduleModel) { return new LoanScheduleDTO(installments, loanScheduleModel); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleData.java index e940fd4b3..86c7b050e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleData.java @@ -115,4 +115,4 @@ public class LoanScheduleData { public void updateFuturePeriods(Collection futurePeriods) { this.futurePeriods = futurePeriods; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleParams.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleParams.java index 01838fade..69543928e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleParams.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanScheduleParams.java @@ -73,7 +73,6 @@ public class LoanScheduleParams { private Money unCompoundedAmount; private Money compoundedInLastInstallment; - public Money getCompoundedInLastInstallment() { return this.compoundedInLastInstallment; } @@ -466,6 +465,7 @@ public class LoanScheduleParams { public Money getUnCompoundedAmount() { return this.unCompoundedAmount; } + public void addUnCompoundedAmount(Money unCompoundedAmount) { this.unCompoundedAmount = this.unCompoundedAmount.plus(unCompoundedAmount); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanSchedulePeriodData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanSchedulePeriodData.java index 19bd55e21..8b1332209 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanSchedulePeriodData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/LoanSchedulePeriodData.java @@ -93,16 +93,16 @@ public class LoanSchedulePeriodData { public static LoanSchedulePeriodData repaymentPeriodWithPayments(@SuppressWarnings("unused") final Long loanId, final Integer periodNumber, final LocalDate fromDate, final LocalDate dueDate, final LocalDate obligationsMetOnDate, final boolean complete, final BigDecimal principalOriginalDue, final BigDecimal principalPaid, - final BigDecimal principalWrittenOff, final BigDecimal principalOutstanding, - final BigDecimal outstandingPrincipalBalanceOfLoan, final BigDecimal interestDueOnPrincipalOutstanding, - final BigDecimal interestPaid, final BigDecimal interestWaived, final BigDecimal interestWrittenOff, - final BigDecimal interestOutstanding, final BigDecimal feeChargesDue, final BigDecimal feeChargesPaid, - final BigDecimal feeChargesWaived, final BigDecimal feeChargesWrittenOff, final BigDecimal feeChargesOutstanding, - final BigDecimal penaltyChargesDue, final BigDecimal penaltyChargesPaid, final BigDecimal penaltyChargesWaived, - final BigDecimal penaltyChargesWrittenOff, final BigDecimal penaltyChargesOutstanding, final BigDecimal totalDueForPeriod, - final BigDecimal totalPaid, final BigDecimal totalPaidInAdvanceForPeriod, final BigDecimal totalPaidLateForPeriod, - final BigDecimal totalWaived, final BigDecimal totalWrittenOff, final BigDecimal totalOutstanding, - final BigDecimal totalActualCostOfLoanForPeriod, final BigDecimal totalInstallmentAmountForPeriod) { + final BigDecimal principalWrittenOff, final BigDecimal principalOutstanding, final BigDecimal outstandingPrincipalBalanceOfLoan, + final BigDecimal interestDueOnPrincipalOutstanding, final BigDecimal interestPaid, final BigDecimal interestWaived, + final BigDecimal interestWrittenOff, final BigDecimal interestOutstanding, final BigDecimal feeChargesDue, + final BigDecimal feeChargesPaid, final BigDecimal feeChargesWaived, final BigDecimal feeChargesWrittenOff, + final BigDecimal feeChargesOutstanding, final BigDecimal penaltyChargesDue, final BigDecimal penaltyChargesPaid, + final BigDecimal penaltyChargesWaived, final BigDecimal penaltyChargesWrittenOff, final BigDecimal penaltyChargesOutstanding, + final BigDecimal totalDueForPeriod, final BigDecimal totalPaid, final BigDecimal totalPaidInAdvanceForPeriod, + final BigDecimal totalPaidLateForPeriod, final BigDecimal totalWaived, final BigDecimal totalWrittenOff, + final BigDecimal totalOutstanding, final BigDecimal totalActualCostOfLoanForPeriod, + final BigDecimal totalInstallmentAmountForPeriod) { return new LoanSchedulePeriodData(periodNumber, fromDate, dueDate, obligationsMetOnDate, complete, principalOriginalDue, principalPaid, principalWrittenOff, principalOutstanding, outstandingPrincipalBalanceOfLoan, @@ -449,4 +449,4 @@ public class LoanSchedulePeriodData { public Boolean getComplete() { return this.complete; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/OverdueLoanScheduleData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/OverdueLoanScheduleData.java old mode 100755 new mode 100644 index f99b3ebf5..1d5448c6c --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/OverdueLoanScheduleData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/data/OverdueLoanScheduleData.java @@ -70,7 +70,6 @@ public class OverdueLoanScheduleData { return this.locale; } - public Integer getPeriodNumber() { return this.periodNumber; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/AbstractLoanScheduleGenerator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/AbstractLoanScheduleGenerator.java index db97c4ad2..5f304345b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/AbstractLoanScheduleGenerator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/AbstractLoanScheduleGenerator.java @@ -73,8 +73,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener final ApplicationCurrency applicationCurrency = loanApplicationTerms.getApplicationCurrency(); // generate list of proposed schedule due dates LocalDate loanEndDate = this.scheduledDateGenerator.getLastRepaymentDate(loanApplicationTerms, holidayDetailDTO); - LoanTermVariationsData lastDueDateVariation = loanApplicationTerms.getLoanTermVariations().fetchLoanTermDueDateVariationsData( - loanEndDate); + LoanTermVariationsData lastDueDateVariation = loanApplicationTerms.getLoanTermVariations() + .fetchLoanTermDueDateVariationsData(loanEndDate); if (lastDueDateVariation != null) { loanEndDate = lastDueDateVariation.getDateValue(); } @@ -93,10 +93,9 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener scheduleParams = LoanScheduleParams.createLoanScheduleParams(currency, Money.of(currency, chargesDueAtTimeOfDisbursement), loanApplicationTerms.getExpectedDisbursementDate(), getPrincipalToBeScheduled(loanApplicationTerms)); } else if (!loanScheduleParams.isPartialUpdate()) { - scheduleParams = LoanScheduleParams - .createLoanScheduleParams(currency, Money.of(currency, chargesDueAtTimeOfDisbursement), - loanApplicationTerms.getExpectedDisbursementDate(), getPrincipalToBeScheduled(loanApplicationTerms), - loanScheduleParams); + scheduleParams = LoanScheduleParams.createLoanScheduleParams(currency, Money.of(currency, chargesDueAtTimeOfDisbursement), + loanApplicationTerms.getExpectedDisbursementDate(), getPrincipalToBeScheduled(loanApplicationTerms), + loanScheduleParams); } else { scheduleParams = loanScheduleParams; } @@ -106,24 +105,24 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener .getLoanRepaymentScheduleTransactionProcessor(); Collection periods = new ArrayList<>(); - if(!scheduleParams.isPartialUpdate()) { - periods = createNewLoanScheduleListWithDisbursementDetails(numberOfRepayments, - loanApplicationTerms, chargesDueAtTimeOfDisbursement); + if (!scheduleParams.isPartialUpdate()) { + periods = createNewLoanScheduleListWithDisbursementDetails(numberOfRepayments, loanApplicationTerms, + chargesDueAtTimeOfDisbursement); } // Determine the total interest owed over the full loan for FLAT // interest method . if (!scheduleParams.isPartialUpdate() && !loanApplicationTerms.isEqualAmortization()) { - Money totalInterestChargedForFullLoanTerm = loanApplicationTerms.calculateTotalInterestCharged( - this.paymentPeriodsInOneYearCalculator, mc); + Money totalInterestChargedForFullLoanTerm = loanApplicationTerms + .calculateTotalInterestCharged(this.paymentPeriodsInOneYearCalculator, mc); loanApplicationTerms.updateTotalInterestDue(totalInterestChargedForFullLoanTerm); } boolean isFirstRepayment = true; - LocalDate firstRepaymentdate = this.scheduledDateGenerator.generateNextRepaymentDate( - loanApplicationTerms.getExpectedDisbursementDate(), loanApplicationTerms, isFirstRepayment); + LocalDate firstRepaymentdate = this.scheduledDateGenerator + .generateNextRepaymentDate(loanApplicationTerms.getExpectedDisbursementDate(), loanApplicationTerms, isFirstRepayment); final LocalDate idealDisbursementDate = this.scheduledDateGenerator.idealDisbursementDateBasedOnFirstRepaymentDate( loanApplicationTerms.getLoanTermPeriodFrequencyType(), loanApplicationTerms.getRepaymentEvery(), firstRepaymentdate, loanApplicationTerms.getLoanCalendar(), loanApplicationTerms.getHolidayDetailDTO(), loanApplicationTerms); @@ -166,7 +165,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener } final Collection interestRates = loanApplicationTerms.getLoanTermVariations().getInterestRateChanges(); - final Collection interestRatesForInstallments = loanApplicationTerms.getLoanTermVariations().getInterestRateFromInstallment(); + final Collection interestRatesForInstallments = loanApplicationTerms.getLoanTermVariations() + .getInterestRateFromInstallment(); // this block is to start the schedule generation from specified date if (scheduleParams.isPartialUpdate()) { @@ -174,17 +174,18 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener loanApplicationTerms.setPrincipal(scheduleParams.getPrincipalToBeScheduled()); } - applyLoanVariationsForPartialScheduleGenerate(loanApplicationTerms, scheduleParams, interestRates, interestRatesForInstallments); + applyLoanVariationsForPartialScheduleGenerate(loanApplicationTerms, scheduleParams, interestRates, + interestRatesForInstallments); isFirstRepayment = false; } while (!scheduleParams.getOutstandingBalance().isZero() || !scheduleParams.getDisburseDetailMap().isEmpty()) { LocalDate previousRepaymentDate = scheduleParams.getActualRepaymentDate(); - scheduleParams.setActualRepaymentDate(this.scheduledDateGenerator.generateNextRepaymentDate( - scheduleParams.getActualRepaymentDate(), loanApplicationTerms, isFirstRepayment)); - AdjustedDateDetailsDTO adjustedDateDetailsDTO = this.scheduledDateGenerator.adjustRepaymentDate( - scheduleParams.getActualRepaymentDate(), loanApplicationTerms, holidayDetailDTO); + scheduleParams.setActualRepaymentDate(this.scheduledDateGenerator + .generateNextRepaymentDate(scheduleParams.getActualRepaymentDate(), loanApplicationTerms, isFirstRepayment)); + AdjustedDateDetailsDTO adjustedDateDetailsDTO = this.scheduledDateGenerator + .adjustRepaymentDate(scheduleParams.getActualRepaymentDate(), loanApplicationTerms, holidayDetailDTO); scheduleParams.setActualRepaymentDate(adjustedDateDetailsDTO.getChangedActualRepaymentDate()); isFirstRepayment = false; LocalDate scheduledDueDate = adjustedDateDetailsDTO.getChangedScheduleDate(); @@ -206,8 +207,9 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener continue; } - if (scheduleParams.getPeriodStartDate().isAfter(scheduledDueDate)) { throw new ScheduleDateException( - "Due date can't be before period start date", scheduledDueDate); } + if (scheduleParams.getPeriodStartDate().isAfter(scheduledDueDate)) { + throw new ScheduleDateException("Due date can't be before period start date", scheduledDueDate); + } if (extendTermForDailyRepayments) { scheduleParams.setActualRepaymentDate(scheduledDueDate); @@ -217,9 +219,9 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener // date(used for calculating preclosure) boolean isCompletePeriod = true; if (scheduleParams.getScheduleTillDate() != null && !scheduledDueDate.isBefore(scheduleParams.getScheduleTillDate())) { - if(!scheduledDueDate.isEqual(scheduleParams.getScheduleTillDate())){ - isCompletePeriod = false; - } + if (!scheduledDueDate.isEqual(scheduleParams.getScheduleTillDate())) { + isCompletePeriod = false; + } scheduledDueDate = scheduleParams.getScheduleTillDate(); isNextRepaymentAvailable = false; } @@ -275,7 +277,6 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener loanApplicationTerms, scheduleParams.getPeriodNumber(), mc, mergeVariationsToMap(scheduleParams), scheduleParams.getCompoundingMap(), periodStartDateApplicableForInterest, scheduledDueDate, interestRates); - // will check for EMI amount greater than interest calculated if (loanApplicationTerms.getFixedEmiAmount() != null && loanApplicationTerms.getFixedEmiAmount().compareTo(principalInterestForThisPeriod.interest().getAmount()) < 0) { @@ -422,12 +423,12 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener LoanScheduleParams scheduleParams, LocalDate scheduledDueDate, ScheduleCurrentPeriodParams currentPeriodParams) { PrincipalInterest principalInterest = new PrincipalInterest(currentPeriodParams.getPrincipalForThisPeriod(), currentPeriodParams.getInterestForThisPeriod(), null); - currentPeriodParams.setFeeChargesForInstallment(cumulativeFeeChargesDueWithin(scheduleParams.getPeriodStartDate(), - scheduledDueDate, loanCharges, currency, principalInterest, scheduleParams.getPrincipalToBeScheduled(), - scheduleParams.getTotalCumulativeInterest(), true)); - currentPeriodParams.setPenaltyChargesForInstallment(cumulativePenaltyChargesDueWithin(scheduleParams.getPeriodStartDate(), - scheduledDueDate, loanCharges, currency, principalInterest, scheduleParams.getPrincipalToBeScheduled(), - scheduleParams.getTotalCumulativeInterest(), true)); + currentPeriodParams.setFeeChargesForInstallment( + cumulativeFeeChargesDueWithin(scheduleParams.getPeriodStartDate(), scheduledDueDate, loanCharges, currency, + principalInterest, scheduleParams.getPrincipalToBeScheduled(), scheduleParams.getTotalCumulativeInterest(), true)); + currentPeriodParams.setPenaltyChargesForInstallment( + cumulativePenaltyChargesDueWithin(scheduleParams.getPeriodStartDate(), scheduledDueDate, loanCharges, currency, + principalInterest, scheduleParams.getPrincipalToBeScheduled(), scheduleParams.getTotalCumulativeInterest(), true)); scheduleParams.addTotalFeeChargesCharged(currentPeriodParams.getFeeChargesForInstallment()); scheduleParams.addTotalPenaltyChargesCharged(currentPeriodParams.getPenaltyChargesForInstallment()); } @@ -459,7 +460,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener LoanScheduleModelPeriod installment, LocalDate lastRestDate) { LocalDate amountApplicableDate = installment.periodDueDate(); if (loanApplicationTerms.isInterestRecalculationEnabled()) { - amountApplicableDate = getNextRestScheduleDate(installment.periodDueDate().minusDays(1), loanApplicationTerms, holidayDetailDTO); + amountApplicableDate = getNextRestScheduleDate(installment.periodDueDate().minusDays(1), loanApplicationTerms, + holidayDetailDTO); } updateMapWithAmount(scheduleParams.getPrincipalPortionMap(), currentPeriodParams.getPrincipalForThisPeriod().minus(currentPeriodParams.getReducedBalance()), amountApplicableDate); @@ -511,17 +513,15 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener currentPeriodParams.plusPrincipalForThisPeriod(unprocessed.plus(addToPrinciapal)); principalProcessed = principalProcessed.plus(unprocessed.plus(addToPrinciapal)); BigDecimal fixedEmiAmount = loanApplicationTerms.getFixedEmiAmount(); - scheduleParams.setReducePrincipal(applyEarlyPaymentStrategy( - loanApplicationTerms, - scheduleParams.getReducePrincipal(), - scheduleParams.getTotalCumulativePrincipal().plus( - currentPeriodParams.getPrincipalForThisPeriod().minus(principalProcessed)), - scheduleParams.getPeriodNumber() + 1, mc)); - if (loanApplicationTerms.getAmortizationMethod().isEqualInstallment() - && fixedEmiAmount != null - && fixedEmiAmount.compareTo(loanApplicationTerms.getFixedEmiAmount()) != 0) { - currentPeriodParams.setEmiAmountChanged(true); - } + scheduleParams + .setReducePrincipal(applyEarlyPaymentStrategy(loanApplicationTerms, scheduleParams.getReducePrincipal(), + scheduleParams.getTotalCumulativePrincipal() + .plus(currentPeriodParams.getPrincipalForThisPeriod().minus(principalProcessed)), + scheduleParams.getPeriodNumber() + 1, mc)); + if (loanApplicationTerms.getAmortizationMethod().isEqualInstallment() && fixedEmiAmount != null + && fixedEmiAmount.compareTo(loanApplicationTerms.getFixedEmiAmount()) != 0) { + currentPeriodParams.setEmiAmountChanged(true); + } } adjustCompoundedAmountWithPaidDetail(scheduleParams, lastRestDate, currentTransactions, loanApplicationTerms, @@ -545,15 +545,14 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener Money oustanding = scheduleParams.getOutstandingBalance(); PrincipalInterest tempPrincipalInterest = new PrincipalInterest(currentPeriodParams.getPrincipalForThisPeriod(), currentPeriodParams.getInterestForThisPeriod(), null); - oustanding = oustanding.minus(cumulativeFeeChargesDueWithin(transactionDate, - scheduledDueDate, loanCharges, totalInterestChargedForFullLoanTerm.getCurrency(), tempPrincipalInterest, scheduleParams.getPrincipalToBeScheduled(), + oustanding = oustanding.minus(cumulativeFeeChargesDueWithin(transactionDate, scheduledDueDate, loanCharges, + totalInterestChargedForFullLoanTerm.getCurrency(), tempPrincipalInterest, scheduleParams.getPrincipalToBeScheduled(), scheduleParams.getTotalCumulativeInterest(), true)); - oustanding = oustanding.minus(cumulativePenaltyChargesDueWithin(transactionDate, - scheduledDueDate, loanCharges, totalInterestChargedForFullLoanTerm.getCurrency(), tempPrincipalInterest, scheduleParams.getPrincipalToBeScheduled(), + oustanding = oustanding.minus(cumulativePenaltyChargesDueWithin(transactionDate, scheduledDueDate, loanCharges, + totalInterestChargedForFullLoanTerm.getCurrency(), tempPrincipalInterest, scheduleParams.getPrincipalToBeScheduled(), scheduleParams.getTotalCumulativeInterest(), true)); - if (!oustanding.isGreaterThan(currentPeriodParams.getInterestForThisPeriod()) - && !scheduledDueDate.equals(transactionDate)) { + if (!oustanding.isGreaterThan(currentPeriodParams.getInterestForThisPeriod()) && !scheduledDueDate.equals(transactionDate)) { final Collection interestRates = loanApplicationTerms.getLoanTermVariations().getInterestRateChanges(); LocalDate calculateTill = transactionDate; if (loanApplicationTerms.getPreClosureInterestCalculationStrategy().calculateTillRestFrequencyEnabled()) { @@ -561,12 +560,12 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener } if (scheduleParams.getCompoundingDateVariations().containsKey(periodStartDateApplicableForInterest)) { scheduleParams.getCompoundingMap().clear(); - scheduleParams.getCompoundingMap().putAll( - scheduleParams.getCompoundingDateVariations().get(periodStartDateApplicableForInterest)); + scheduleParams.getCompoundingMap() + .putAll(scheduleParams.getCompoundingDateVariations().get(periodStartDateApplicableForInterest)); } if (currentPeriodParams.isEmiAmountChanged()) { - updateFixedInstallmentAmount(mc, loanApplicationTerms, scheduleParams.getPeriodNumber(), loanApplicationTerms - .getPrincipal().minus(scheduleParams.getTotalCumulativePrincipal())); + updateFixedInstallmentAmount(mc, loanApplicationTerms, scheduleParams.getPeriodNumber(), + loanApplicationTerms.getPrincipal().minus(scheduleParams.getTotalCumulativePrincipal())); } scheduleParams.getCompoundingDateVariations().put(periodStartDateApplicableForInterest, @@ -575,11 +574,12 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener populateCompoundingDatesInPeriod(periodStartDateApplicableForInterest, calculateTill, loanApplicationTerms, holidayDetailDTO, scheduleParams, loanCharges, totalInterestChargedForFullLoanTerm.getCurrency()); - // this is to make sure we are recalculating using correct interest rate + // this is to make sure we are recalculating using correct interest + // rate // once calculation is done system will set the actual interest rate BigDecimal currentInterestRate = loanApplicationTerms.getAnnualNominalInterestRate(); - for(LoanTermVariationsData interestRate : interestRates){ - if(interestRate.isApplicable(periodStartDateApplicableForInterest)){ + for (LoanTermVariationsData interestRate : interestRates) { + if (interestRate.isApplicable(periodStartDateApplicableForInterest)) { loanApplicationTerms.updateAnnualNominalInterestRate(interestRate.getDecimalValue()); } } @@ -633,22 +633,20 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener scheduleParams.addReducePrincipal(currentPeriodParams.getEarlyPaidAmount()); BigDecimal fixedEmiAmount = loanApplicationTerms.getFixedEmiAmount(); scheduleParams.setReducePrincipal(applyEarlyPaymentStrategy( - loanApplicationTerms, - scheduleParams.getReducePrincipal(), - scheduleParams.getTotalCumulativePrincipal().plus(currentPeriodParams.getPrincipalForThisPeriod()) - .plus(currentPeriodParams.getEarlyPaidAmount()), scheduleParams.getPeriodNumber() + 1, mc)); - if (loanApplicationTerms.getAmortizationMethod().isEqualInstallment() - && fixedEmiAmount != null - && fixedEmiAmount.compareTo(loanApplicationTerms.getFixedEmiAmount()) != 0) { - currentPeriodParams.setEmiAmountChanged(true); - } - currentPeriodParams.plusPrincipalForThisPeriod(currentPeriodParams.getEarlyPaidAmount()); + loanApplicationTerms, scheduleParams.getReducePrincipal(), scheduleParams.getTotalCumulativePrincipal() + .plus(currentPeriodParams.getPrincipalForThisPeriod()).plus(currentPeriodParams.getEarlyPaidAmount()), + scheduleParams.getPeriodNumber() + 1, mc)); + if (loanApplicationTerms.getAmortizationMethod().isEqualInstallment() && fixedEmiAmount != null + && fixedEmiAmount.compareTo(loanApplicationTerms.getFixedEmiAmount()) != 0) { + currentPeriodParams.setEmiAmountChanged(true); + } + currentPeriodParams.plusPrincipalForThisPeriod(currentPeriodParams.getEarlyPaidAmount()); } // update outstandingLoanBlance using current period // 'principalDue' - scheduleParams.reduceOutstandingBalance(currentPeriodParams.getPrincipalForThisPeriod().minus( - currentPeriodParams.getReducedBalance())); + scheduleParams + .reduceOutstandingBalance(currentPeriodParams.getPrincipalForThisPeriod().minus(currentPeriodParams.getReducedBalance())); } private void updatePrincipalPortionBasedOnPreviousEarlyPayments(final MonetaryCurrency currency, @@ -692,9 +690,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener boolean updateLatePaymentMap = false; final LocalDate transactionDate = detail.getTransactionDate(); if (transactionDate.isBefore(scheduledDueDate)) { - if (scheduleParams.getLoanRepaymentScheduleTransactionProcessor() != null - && scheduleParams.getLoanRepaymentScheduleTransactionProcessor() - .isInterestFirstRepaymentScheduleTransactionProcessor()) { + if (scheduleParams.getLoanRepaymentScheduleTransactionProcessor() != null && scheduleParams + .getLoanRepaymentScheduleTransactionProcessor().isInterestFirstRepaymentScheduleTransactionProcessor()) { if (detail.getTransaction().isWaiver()) { processTransactions.add(detail); continue; @@ -723,8 +720,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener // date PrincipalInterest principalInterestForThisPeriod = calculatePrincipalInterestComponentsForPeriod( this.paymentPeriodsInOneYearCalculator, - currentPeriodParams.getInterestCalculationGraceOnRepaymentPeriodFraction(), scheduleParams - .getTotalCumulativePrincipal().minus(scheduleParams.getReducePrincipal()), + currentPeriodParams.getInterestCalculationGraceOnRepaymentPeriodFraction(), + scheduleParams.getTotalCumulativePrincipal().minus(scheduleParams.getReducePrincipal()), scheduleParams.getTotalCumulativeInterest(), totalInterestChargedForFullLoanTerm, scheduleParams.getTotalOutstandingInterestPaymentDueToGrace(), scheduleParams.getOutstandingBalanceAsPerRest(), loanApplicationTerms, @@ -733,8 +730,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener interestRates); interestForThisinstallment = principalInterestForThisPeriod.interest(); - scheduleParams.setTotalOutstandingInterestPaymentDueToGrace(principalInterestForThisPeriod - .interestPaymentDueToGrace()); + scheduleParams.setTotalOutstandingInterestPaymentDueToGrace( + principalInterestForThisPeriod.interestPaymentDueToGrace()); } Money principalForThisPeriod = Money.zero(currency); @@ -792,8 +789,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener // strategy // on scheduled installments to identify the // unprocessed(early payment ) amounts - Money unprocessed = scheduleParams.getLoanRepaymentScheduleTransactionProcessor().handleRepaymentSchedule( - currentTransactions, currency, scheduleParams.getInstallments()); + Money unprocessed = scheduleParams.getLoanRepaymentScheduleTransactionProcessor() + .handleRepaymentSchedule(currentTransactions, currency, scheduleParams.getInstallments()); if (unprocessed.isGreaterThanZero()) { if (loanApplicationTerms.getPreClosureInterestCalculationStrategy().calculateTillRestFrequencyEnabled()) { @@ -820,9 +817,9 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener // method applies early payment strategy scheduleParams.addReducePrincipal(unprocessed); - scheduleParams.setReducePrincipal(applyEarlyPaymentStrategy(loanApplicationTerms, - scheduleParams.getReducePrincipal(), scheduleParams.getTotalCumulativePrincipal(), - scheduleParams.getPeriodNumber(), mc)); + scheduleParams + .setReducePrincipal(applyEarlyPaymentStrategy(loanApplicationTerms, scheduleParams.getReducePrincipal(), + scheduleParams.getTotalCumulativePrincipal(), scheduleParams.getPeriodNumber(), mc)); } // identify late payments and add compounding // details to @@ -837,8 +834,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener holidayDetailDTO); if (applicableDate.isBefore(scheduledDueDate)) { List currentTransactions = createCurrentTransactionList(detail); - Money unprocessed = scheduleParams.getLoanRepaymentScheduleTransactionProcessor().handleRepaymentSchedule( - currentTransactions, currency, scheduleParams.getInstallments()); + Money unprocessed = scheduleParams.getLoanRepaymentScheduleTransactionProcessor() + .handleRepaymentSchedule(currentTransactions, currency, scheduleParams.getInstallments()); Money arrears = fetchArrears(loanApplicationTerms, currency, detail.getTransaction()); if (unprocessed.isGreaterThanZero()) { updateMapWithAmount(scheduleParams.getPrincipalPortionMap(), unprocessed, applicableDate); @@ -847,17 +844,16 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener // this check is to identify pre-closure and // apply interest calculation as per // configuration for non due date payments - if (!scheduleParams.getOutstandingBalance().isGreaterThan(unprocessed) - && !loanApplicationTerms.getPreClosureInterestCalculationStrategy() - .calculateTillRestFrequencyEnabled()) { + if (!scheduleParams.getOutstandingBalance().isGreaterThan(unprocessed) && !loanApplicationTerms + .getPreClosureInterestCalculationStrategy().calculateTillRestFrequencyEnabled()) { scheduleParams.getCompoundingDateVariations().put(periodStartDateApplicableForInterest, new TreeMap<>(scheduleParams.getCompoundingMap())); LocalDate calculateTill = transactionDate; PrincipalInterest principalInterestForThisPeriod = calculatePrincipalInterestComponentsForPeriod( this.paymentPeriodsInOneYearCalculator, - currentPeriodParams.getInterestCalculationGraceOnRepaymentPeriodFraction(), scheduleParams - .getTotalCumulativePrincipal().minus(scheduleParams.getReducePrincipal()), + currentPeriodParams.getInterestCalculationGraceOnRepaymentPeriodFraction(), + scheduleParams.getTotalCumulativePrincipal().minus(scheduleParams.getReducePrincipal()), scheduleParams.getTotalCumulativeInterest(), totalInterestChargedForFullLoanTerm, scheduleParams.getTotalOutstandingInterestPaymentDueToGrace(), scheduleParams.getOutstandingBalanceAsPerRest(), loanApplicationTerms, @@ -876,8 +872,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener break; } } - LoanTransaction loanTransaction = LoanTransaction.repayment(null, unprocessed, null, scheduledDueDate, - null, DateUtils.getLocalDateTimeOfTenant(), null); + LoanTransaction loanTransaction = LoanTransaction.repayment(null, unprocessed, null, scheduledDueDate, null, + DateUtils.getLocalDateTimeOfTenant(), null); RecalculationDetail recalculationDetail = new RecalculationDetail(scheduledDueDate, loanTransaction); unprocessedTransactions.add(recalculationDetail); checkForOutstanding = false; @@ -950,21 +946,21 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener final BigDecimal chargesDueAtTimeOfDisbursement, LoanScheduleParams scheduleParams, final Collection periods, final LocalDate scheduledDueDate) { for (Map.Entry disburseDetail : scheduleParams.getDisburseDetailMap().entrySet()) { - if (disburseDetail.getKey().isAfter(scheduleParams.getPeriodStartDate()) && !disburseDetail.getKey().isAfter(scheduledDueDate)) { + if (disburseDetail.getKey().isAfter(scheduleParams.getPeriodStartDate()) + && !disburseDetail.getKey().isAfter(scheduledDueDate)) { // validation check for amount not exceeds specified max // amount as per the configuration - if (loanApplicationTerms.getMaxOutstandingBalance() != null - && scheduleParams.getOutstandingBalance().plus(disburseDetail.getValue()) - .isGreaterThan(loanApplicationTerms.getMaxOutstandingBalance())) { + if (loanApplicationTerms.getMaxOutstandingBalance() != null && scheduleParams.getOutstandingBalance() + .plus(disburseDetail.getValue()).isGreaterThan(loanApplicationTerms.getMaxOutstandingBalance())) { String errorMsg = "Outstanding balance must not exceed the amount: " + loanApplicationTerms.getMaxOutstandingBalance(); - throw new MultiDisbursementOutstandingAmoutException(errorMsg, loanApplicationTerms.getMaxOutstandingBalance() - .getAmount(), disburseDetail.getValue()); + throw new MultiDisbursementOutstandingAmoutException(errorMsg, + loanApplicationTerms.getMaxOutstandingBalance().getAmount(), disburseDetail.getValue()); } // creates and add disbursement detail to the repayments // period - final LoanScheduleModelDisbursementPeriod disbursementPeriod = LoanScheduleModelDisbursementPeriod.disbursement( - disburseDetail.getKey(), disburseDetail.getValue(), chargesDueAtTimeOfDisbursement); + final LoanScheduleModelDisbursementPeriod disbursementPeriod = LoanScheduleModelDisbursementPeriod + .disbursement(disburseDetail.getKey(), disburseDetail.getValue(), chargesDueAtTimeOfDisbursement); periods.add(disbursementPeriod); // updates actual outstanding balance with new // disbursement detail @@ -991,8 +987,7 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener */ private LoanTermVariationParams applyLoanTermVariations(final LoanApplicationTerms loanApplicationTerms, final LoanScheduleParams scheduleParams, final LocalDate previousRepaymentDate, final LocalDate scheduledDueDate, - Collection interestRatesForInstallments, PaymentPeriodsInOneYearCalculator calculator, - MathContext mc) { + Collection interestRatesForInstallments, PaymentPeriodsInOneYearCalculator calculator, MathContext mc) { boolean skipPeriod = false; boolean recalculateAmounts = false; LocalDate modifiedScheduledDueDate = scheduledDueDate; @@ -1079,7 +1074,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener Integer rescheduleNumberOfRepayments = loanApplicationTerms.getNumberOfRepayments(); rescheduleNumberOfRepayments += loanTermVariationsData.getDecimalValue().intValue(); loanApplicationTerms.updateNumberOfRepayments(rescheduleNumberOfRepayments); - LocalDate loanEndDate = this.scheduledDateGenerator.getLastRepaymentDate(loanApplicationTerms, loanApplicationTerms.getHolidayDetailDTO()); + LocalDate loanEndDate = this.scheduledDateGenerator.getLastRepaymentDate(loanApplicationTerms, + loanApplicationTerms.getHolidayDetailDTO()); loanApplicationTerms.updateLoanEndDate(loanEndDate); loanApplicationTerms.updateAccountedTillPeriod(scheduleParams.getPeriodNumber() - 1, scheduleParams.getTotalCumulativePrincipal(), scheduleParams.getTotalCumulativeInterest(), @@ -1118,9 +1114,12 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener * @param scheduledDueDate * @param exceptionDataListIterator * @param instalmentNumber - * @param totalCumulativePrincipal TODO - * @param totalCumulativeInterest TODO - * @param mc TODO + * @param totalCumulativePrincipal + * TODO + * @param totalCumulativeInterest + * TODO + * @param mc + * TODO * @param periodNumber * @return */ @@ -1186,7 +1185,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener loanApplicationTerms.updateLoanEndDate(loanEndDate); adjustInstallmentOrPrincipalAmount(loanApplicationTerms, totalCumulativePrincipal, instalmentNumber, mc); loanTermVariationsData.setProcessed(true); - loanApplicationTerms.updateAccountedTillPeriod(instalmentNumber-1, totalCumulativePrincipal, totalCumulativeInterest, loanTermVariationsData.getDecimalValue().intValue()); + loanApplicationTerms.updateAccountedTillPeriod(instalmentNumber - 1, totalCumulativePrincipal, totalCumulativeInterest, + loanTermVariationsData.getDecimalValue().intValue()); break; default: break; @@ -1237,8 +1237,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener // Applies interest rate changes for installments for (LoanTermVariationsData variation : interestRatesForInstallments) { - if (variation.getTermVariationType().isInterestRateFromInstallment() && variation.isApplicable(scheduleParams.getPeriodStartDate()) - && variation.getDecimalValue() != null) { + if (variation.getTermVariationType().isInterestRateFromInstallment() + && variation.isApplicable(scheduleParams.getPeriodStartDate()) && variation.getDecimalValue() != null) { loanApplicationTerms.updateAnnualNominalInterestRate(variation.getDecimalValue()); variation.setProcessed(true); } @@ -1332,8 +1332,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener params.setActualRepaymentDate(currentDate); } - Collection applicableTransactions = getApplicableTransactionsForPeriod( - params.applyInterestRecalculation(), params.getActualRepaymentDate(), transactions); + Collection applicableTransactions = getApplicableTransactionsForPeriod(params.applyInterestRecalculation(), + params.getActualRepaymentDate(), transactions); populateCompoundingDatesInPeriod(params.getPeriodStartDate(), params.getActualRepaymentDate(), loanApplicationTerms, holidayDetailDTO, params, loanCharges, currency); @@ -1347,10 +1347,10 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener if (!params.getPeriodStartDate().isEqual(transactionDate)) { PrincipalInterest principalInterestForThisPeriod = calculatePrincipalInterestComponentsForPeriod( - this.paymentPeriodsInOneYearCalculator, interestCalculationGraceOnRepaymentPeriodFraction, - totalInterest.zero(), totalInterest.zero(), totalInterest.zero(), totalInterest.zero(), outstanding, - loanApplicationTerms, periodNumberTemp, mc, mergeVariationsToMap(params), params.getCompoundingMap(), - params.getPeriodStartDate(), transactionDate, applicableVariations); + this.paymentPeriodsInOneYearCalculator, interestCalculationGraceOnRepaymentPeriodFraction, totalInterest.zero(), + totalInterest.zero(), totalInterest.zero(), totalInterest.zero(), outstanding, loanApplicationTerms, + periodNumberTemp, mc, mergeVariationsToMap(params), params.getCompoundingMap(), params.getPeriodStartDate(), + transactionDate, applicableVariations); Money interest = principalInterestForThisPeriod.interest(); totalInterest = totalInterest.plus(interest); @@ -1372,8 +1372,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener additionalPeriodsStartDate = startDate; } loanRepaymentScheduleTransactionProcessor.handleRepaymentSchedule(currentTransactions, currency, params.getInstallments()); - updateLatePaidAmountsToPrincipalMap(detail.getTransaction(), loanApplicationTerms, currency, holidayDetailDTO, - lastRestDate, params); + updateLatePaidAmountsToPrincipalMap(detail.getTransaction(), loanApplicationTerms, currency, holidayDetailDTO, lastRestDate, + params); updateLatePaymentsToMap(loanApplicationTerms, holidayDetailDTO, currency, params.getLatePaymentMap(), currentDate, params.getInstallments(), false, lastRestDate); if (params.getLatePaymentMap().isEmpty() && isCompleted(params.getInstallments())) { @@ -1396,7 +1396,7 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener Money interest = principalInterestForThisPeriod.interest(); totalInterest = totalInterest.plus(interest); - if(loanApplicationTerms.getInterestRecalculationCompoundingMethod().isCompoundingEnabled()) { + if (loanApplicationTerms.getInterestRecalculationCompoundingMethod().isCompoundingEnabled()) { Money uncompounded = params.getUnCompoundedAmount(); Money compounded = uncompounded.zero(); for (Map.Entry mapEntry : params.getCompoundingMap().entrySet()) { @@ -1405,7 +1405,10 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener } } if (compounded.isGreaterThanZero() && startDate.isEqual(additionalPeriodsStartDate)) { - params.setCompoundedInLastInstallment(uncompoundedFromLastInstallment);// uncompounded in last installment + params.setCompoundedInLastInstallment(uncompoundedFromLastInstallment);// uncompounded + // in + // last + // installment additionalPeriodsStartDate = additionalPeriodsStartDate.plusDays(1); } Money compoundedForThisPeriod = compounded.minus(uncompounded); @@ -1416,7 +1419,7 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener compoundingDate = compoundingDate.minusDays(1); } compoundingDate = getNextCompoundScheduleDate(compoundingDate, loanApplicationTerms, holidayDetailDTO); - if(compoundingDate.isEqual(params.getActualRepaymentDate())){ + if (compoundingDate.isEqual(params.getActualRepaymentDate())) { params.getCompoundingMap().put(compoundingDate, uncompoundedForThisPeriod); params.setUnCompoundedAmount(uncompoundedForThisPeriod.zero()); } @@ -1674,8 +1677,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener } if (periodHasCompoundingDate) { if (isPastDate) { - updateMapWithAmount(params.getPrincipalPortionMap(), - totalCompoundedAmount.plus(params.getUnCompoundedAmount()), lastRestDate); + updateMapWithAmount(params.getPrincipalPortionMap(), totalCompoundedAmount.plus(params.getUnCompoundedAmount()), + lastRestDate); } else { Money amountToBeEffected = amountCharged; if (lastInstallmentIsPastDate) { @@ -1802,7 +1805,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener private void updatePrincipalPaidPortionToMap(final LoanApplicationTerms loanApplicationTerms, final HolidayDetailDTO holidayDetailDTO, Map principalPortionMap, final LoanScheduleModelPeriod installment, final RecalculationDetail detail, final Money unprocessed, final List installments) { - LocalDate applicableDate = getNextRestScheduleDate(detail.getTransactionDate().minusDays(1), loanApplicationTerms, holidayDetailDTO); + LocalDate applicableDate = getNextRestScheduleDate(detail.getTransactionDate().minusDays(1), loanApplicationTerms, + holidayDetailDTO); updateMapWithAmount(principalPortionMap, unprocessed, applicableDate); installment.addPrincipalAmount(unprocessed); LoanRepaymentScheduleInstallment lastInstallment = installments.get(installments.size() - 1); @@ -1930,8 +1934,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener periods = new ArrayList<>(numberOfRepayments + loanApplicationTerms.getDisbursementDatas().size()); } else { periods = new ArrayList<>(numberOfRepayments + 1); - final LoanScheduleModelDisbursementPeriod disbursementPeriod = LoanScheduleModelDisbursementPeriod.disbursement( - loanApplicationTerms, chargesDueAtTimeOfDisbursement); + final LoanScheduleModelDisbursementPeriod disbursementPeriod = LoanScheduleModelDisbursementPeriod + .disbursement(loanApplicationTerms, chargesDueAtTimeOfDisbursement); periods.add(disbursementPeriod); } @@ -1941,9 +1945,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener private Set seperateTotalCompoundingPercentageCharges(final Set loanCharges) { Set interestCharges = new HashSet<>(); for (final LoanCharge loanCharge : loanCharges) { - if (loanCharge.isSpecifiedDueDate() - && (loanCharge.getChargeCalculation().isPercentageOfInterest() || loanCharge.getChargeCalculation() - .isPercentageOfAmountAndInterest())) { + if (loanCharge.isSpecifiedDueDate() && (loanCharge.getChargeCalculation().isPercentageOfInterest() + || loanCharge.getChargeCalculation().isPercentageOfAmountAndInterest())) { interestCharges.add(loanCharge); } } @@ -1952,8 +1955,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener } private Money cumulativeFeeChargesDueWithin(final LocalDate periodStart, final LocalDate periodEnd, final Set loanCharges, - final MonetaryCurrency monetaryCurrency, final PrincipalInterest principalInterestForThisPeriod, - final Money principalDisbursed, final Money totalInterestChargedForFullLoanTerm, boolean isInstallmentChargeApplicable) { + final MonetaryCurrency monetaryCurrency, final PrincipalInterest principalInterestForThisPeriod, final Money principalDisbursed, + final Money totalInterestChargedForFullLoanTerm, boolean isInstallmentChargeApplicable) { Money cumulative = Money.zero(monetaryCurrency); @@ -1998,8 +2001,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener if (loanCharge.getChargeCalculation().isPercentageBased()) { BigDecimal amount = BigDecimal.ZERO; if (loanCharge.getChargeCalculation().isPercentageOfAmountAndInterest()) { - amount = amount.add(principalInterestForThisPeriod.principal().getAmount()).add( - principalInterestForThisPeriod.interest().getAmount()); + amount = amount.add(principalInterestForThisPeriod.principal().getAmount()) + .add(principalInterestForThisPeriod.interest().getAmount()); } else if (loanCharge.getChargeCalculation().isPercentageOfInterest()) { amount = amount.add(principalInterestForThisPeriod.interest().getAmount()); } else { @@ -2057,17 +2060,17 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener } - private LoanScheduleDTO rescheduleNextInstallments(final MathContext mc, final LoanApplicationTerms loanApplicationTerms, - Loan loan, final HolidayDetailDTO holidayDetailDTO, final LoanRepaymentScheduleTransactionProcessor loanRepaymentScheduleTransactionProcessor, - final LocalDate rescheduleFrom, + private LoanScheduleDTO rescheduleNextInstallments(final MathContext mc, final LoanApplicationTerms loanApplicationTerms, Loan loan, + final HolidayDetailDTO holidayDetailDTO, + final LoanRepaymentScheduleTransactionProcessor loanRepaymentScheduleTransactionProcessor, final LocalDate rescheduleFrom, final LocalDate scheduleTillDate) { // Loan transactions to process and find the variation on payments Collection recalculationDetails = new ArrayList<>(); - List transactions = loan.getLoanTransactions() ; + List transactions = loan.getLoanTransactions(); for (LoanTransaction loanTransaction : transactions) { if (loanTransaction.isPaymentTransaction()) { - recalculationDetails.add(new RecalculationDetail(loanTransaction.getTransactionDate(), LoanTransaction - .copyTransactionProperties(loanTransaction))); + recalculationDetails.add(new RecalculationDetail(loanTransaction.getTransactionDate(), + LoanTransaction.copyTransactionProperties(loanTransaction))); } } final boolean applyInterestRecalculation = loanApplicationTerms.isInterestRecalculationEnabled(); @@ -2140,7 +2143,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener // Set fixed Amortization Amounts(either EMI or Principal ) updateAmortization(mc, loanApplicationTerms, periodNumber, outstandingBalance); - // count periods without interest grace to exclude for flat loan calculations + // count periods without interest grace to exclude for flat loan + // calculations final Map disburseDetailMap = new HashMap<>(); if (loanApplicationTerms.isMultiDisburseLoan()) { @@ -2178,15 +2182,14 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener } ArrayList dueDateVariationsDataList = new ArrayList<>(); - - // check for date changes + // check for date changes do { actualRepaymentDate = this.scheduledDateGenerator.generateNextRepaymentDate(actualRepaymentDate, loanApplicationTerms, isFirstRepayment); isFirstRepayment = false; - lastInstallmentDate = this.scheduledDateGenerator.adjustRepaymentDate(actualRepaymentDate, loanApplicationTerms, - holidayDetailDTO).getChangedScheduleDate(); + lastInstallmentDate = this.scheduledDateGenerator + .adjustRepaymentDate(actualRepaymentDate, loanApplicationTerms, holidayDetailDTO).getChangedScheduleDate(); while (loanApplicationTerms.getLoanTermVariations().hasDueDateVariation(lastInstallmentDate)) { LoanTermVariationsData variation = loanApplicationTerms.getLoanTermVariations().nextDueDateVariation(); if (!variation.isSpecificToInstallment()) { @@ -2218,8 +2221,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener && !disburseDetail.getKey().isAfter(installment.getDueDate())) { // creates and add disbursement detail to the repayments // period - final LoanScheduleModelDisbursementPeriod disbursementPeriod = LoanScheduleModelDisbursementPeriod.disbursement( - disburseDetail.getKey(), disburseDetail.getValue(), chargesDueAtTimeOfDisbursement); + final LoanScheduleModelDisbursementPeriod disbursementPeriod = LoanScheduleModelDisbursementPeriod + .disbursement(disburseDetail.getKey(), disburseDetail.getValue(), chargesDueAtTimeOfDisbursement); periods.add(disbursementPeriod); // updates actual outstanding balance with new // disbursement detail @@ -2243,7 +2246,6 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener instalmentNumber++; loanTermInDays = Days.daysBetween(installment.getFromDate(), installment.getDueDate()).getDays(); - if (loanApplicationTerms.isInterestRecalculationEnabled()) { // populates the collection with transactions till the due @@ -2325,12 +2327,12 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener totalFeeChargesCharged, totalPenaltyChargesCharged, totalRepaymentExpected, totalOutstandingInterestPaymentDueToGrace, reducePrincipal, principalPortionMap, latePaymentMap, compoundingMap, uncompoundedAmount, disburseDetailMap, principalToBeScheduled, outstandingBalance, outstandingBalanceAsPerRest, - newRepaymentScheduleInstallments, recalculationDetails, loanRepaymentScheduleTransactionProcessor, - scheduleTillDate, currency, applyInterestRecalculation); + newRepaymentScheduleInstallments, recalculationDetails, loanRepaymentScheduleTransactionProcessor, scheduleTillDate, + currency, applyInterestRecalculation); retainedInstallments.addAll(newRepaymentScheduleInstallments); loanScheduleParams.getCompoundingDateVariations().putAll(compoundingDateVariations); loanApplicationTerms.updateTotalInterestDue(Money.of(currency, loan.getLoanSummary().getTotalInterestCharged())); - }else{ + } else { loanApplicationTerms.getLoanTermVariations().resetVariations(); } @@ -2362,7 +2364,7 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { if (installment.getDueDate().isBefore(rescheduleFrom)) { newRepaymentScheduleInstallments.add(installment); - if(installment.getInterestCharged(currency).isGreaterThanZero()){ + if (installment.getInterestCharged(currency).isGreaterThanZero()) { lastInterestAvilablePeriod = installment.getInstallmentNumber(); } processedPeriod = installment.getInstallmentNumber(); @@ -2376,10 +2378,10 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener // if the last retained period is interest grace period then we // can't get the interest of last period without calculating again // to fix this adjusting retained periods - if(lastInterestAvilablePeriod != processedPeriod){ + if (lastInterestAvilablePeriod != processedPeriod) { final List retainRepaymentScheduleInstallments = new ArrayList<>(); for (LoanRepaymentScheduleInstallment installment : newRepaymentScheduleInstallments) { - if(installment.getInstallmentNumber() <= lastInterestAvilablePeriod){ + if (installment.getInstallmentNumber() <= lastInterestAvilablePeriod) { retainRepaymentScheduleInstallments.add(installment); } } @@ -2555,11 +2557,11 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener private LoanScheduleModelPeriod createLoanScheduleModelPeriod(final LoanRepaymentScheduleInstallment installment, final Money outstandingPrincipal) { final MonetaryCurrency currency = outstandingPrincipal.getCurrency(); - LoanScheduleModelPeriod scheduledLoanInstallment = LoanScheduleModelRepaymentPeriod - .repayment(installment.getInstallmentNumber(), installment.getFromDate(), installment.getDueDate(), - installment.getPrincipal(currency), outstandingPrincipal, installment.getInterestCharged(currency), - installment.getFeeChargesCharged(currency), installment.getPenaltyChargesCharged(currency), - installment.getDue(currency), installment.isRecalculatedInterestComponent()); + LoanScheduleModelPeriod scheduledLoanInstallment = LoanScheduleModelRepaymentPeriod.repayment(installment.getInstallmentNumber(), + installment.getFromDate(), installment.getDueDate(), installment.getPrincipal(currency), outstandingPrincipal, + installment.getInterestCharged(currency), installment.getFeeChargesCharged(currency), + installment.getPenaltyChargesCharged(currency), installment.getDue(currency), + installment.isRecalculatedInterestComponent()); return scheduledLoanInstallment; } @@ -2567,8 +2569,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener final HolidayDetailDTO holidayDetailDTO) { LocalDate nextScheduleDate = null; if (loanApplicationTerms.getRecalculationFrequencyType().isSameAsRepayment()) { - nextScheduleDate = this.scheduledDateGenerator.generateNextScheduleDateStartingFromDisburseDate(startDate, - loanApplicationTerms, holidayDetailDTO); + nextScheduleDate = this.scheduledDateGenerator.generateNextScheduleDateStartingFromDisburseDate(startDate, loanApplicationTerms, + holidayDetailDTO); } else { CalendarInstance calendarInstance = loanApplicationTerms.getRestCalendarInstance(); nextScheduleDate = CalendarUtils.getNextScheduleDate(calendarInstance.getCalendar(), startDate); @@ -2582,8 +2584,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener LocalDate nextScheduleDate = null; if (!loanApplicationTerms.getInterestRecalculationCompoundingMethod().isCompoundingEnabled()) { return null; } if (loanApplicationTerms.getCompoundingFrequencyType().isSameAsRepayment()) { - nextScheduleDate = this.scheduledDateGenerator.generateNextScheduleDateStartingFromDisburseDate(startDate, - loanApplicationTerms, holidayDetailDTO); + nextScheduleDate = this.scheduledDateGenerator.generateNextScheduleDateStartingFromDisburseDate(startDate, loanApplicationTerms, + holidayDetailDTO); } else { CalendarInstance calendarInstance = loanApplicationTerms.getCompoundingCalendarInstance(); nextScheduleDate = CalendarUtils.getNextScheduleDate(calendarInstance.getCalendar(), startDate); @@ -2608,8 +2610,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener calculateTill = getNextRestScheduleDate(onDate.minusDays(1), loanApplicationTerms, holidayDetailDTO); } - LoanScheduleDTO loanScheduleDTO = rescheduleNextInstallments(mc, loanApplicationTerms, loan, holidayDetailDTO, loanRepaymentScheduleTransactionProcessor, - onDate, calculateTill); + LoanScheduleDTO loanScheduleDTO = rescheduleNextInstallments(mc, loanApplicationTerms, loan, holidayDetailDTO, + loanRepaymentScheduleTransactionProcessor, onDate, calculateTill); List loanTransactions = loan.retreiveListOfTransactionsPostDisbursementExcludeAccruals(); loanRepaymentScheduleTransactionProcessor.handleTransaction(loanApplicationTerms.getExpectedDisbursementDate(), loanTransactions, @@ -2631,7 +2633,6 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener feeCharges.getAmount(), penaltyCharges.getAmount(), false, compoundingDetails); } - private final class LoanTermVariationParams { private final boolean skipPeriod; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/AprCalculator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/AprCalculator.java index a317f46b8..749130247 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/AprCalculator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/AprCalculator.java @@ -26,7 +26,8 @@ import org.springframework.stereotype.Component; @Component public class AprCalculator { - public BigDecimal calculateFrom(final PeriodFrequencyType interestPeriodFrequencyType, final BigDecimal interestRatePerPeriod, final Integer numberOfRepayments, final Integer repaymentEvery, final PeriodFrequencyType repaymentPeriodFrequencyType) { + public BigDecimal calculateFrom(final PeriodFrequencyType interestPeriodFrequencyType, final BigDecimal interestRatePerPeriod, + final Integer numberOfRepayments, final Integer repaymentEvery, final PeriodFrequencyType repaymentPeriodFrequencyType) { BigDecimal defaultAnnualNominalInterestRate = BigDecimal.ZERO; switch (interestPeriodFrequencyType) { case DAYS: @@ -42,29 +43,30 @@ public class AprCalculator { defaultAnnualNominalInterestRate = interestRatePerPeriod.multiply(BigDecimal.valueOf(1)); break; case WHOLE_TERM: - final BigDecimal ratePerPeriod = interestRatePerPeriod.divide(BigDecimal.valueOf(numberOfRepayments*repaymentEvery), 8, RoundingMode.HALF_UP); + final BigDecimal ratePerPeriod = interestRatePerPeriod.divide(BigDecimal.valueOf(numberOfRepayments * repaymentEvery), 8, + RoundingMode.HALF_UP); - switch (repaymentPeriodFrequencyType) { - case DAYS: - defaultAnnualNominalInterestRate = ratePerPeriod.multiply(BigDecimal.valueOf(365)); - break; - case WEEKS: - defaultAnnualNominalInterestRate = ratePerPeriod.multiply(BigDecimal.valueOf(52)); - break; - case MONTHS: - defaultAnnualNominalInterestRate = ratePerPeriod.multiply(BigDecimal.valueOf(12)); - break; - case YEARS: - defaultAnnualNominalInterestRate = ratePerPeriod.multiply(BigDecimal.valueOf(1)); - break; - default: - } - break; + switch (repaymentPeriodFrequencyType) { + case DAYS: + defaultAnnualNominalInterestRate = ratePerPeriod.multiply(BigDecimal.valueOf(365)); + break; + case WEEKS: + defaultAnnualNominalInterestRate = ratePerPeriod.multiply(BigDecimal.valueOf(52)); + break; + case MONTHS: + defaultAnnualNominalInterestRate = ratePerPeriod.multiply(BigDecimal.valueOf(12)); + break; + case YEARS: + defaultAnnualNominalInterestRate = ratePerPeriod.multiply(BigDecimal.valueOf(1)); + break; + default: + } + break; case INVALID: break; } - return defaultAnnualNominalInterestRate; - } + return defaultAnnualNominalInterestRate; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DecliningBalanceInterestLoanScheduleGenerator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DecliningBalanceInterestLoanScheduleGenerator.java index 32205cd7e..740517079 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DecliningBalanceInterestLoanScheduleGenerator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DecliningBalanceInterestLoanScheduleGenerator.java @@ -38,7 +38,8 @@ import org.joda.time.LocalDate; *

  • Equal principal payments
  • *
  • Equal installment payments
  • * - *

    + *

    + *

    * *

    * When amortized using equal principal payments, the principal @@ -63,8 +64,8 @@ public class DecliningBalanceInterestLoanScheduleGenerator extends AbstractLoanS @SuppressWarnings("unused") final Money totalCumulativeInterest, @SuppressWarnings("unused") final Money totalInterestDueForLoan, final Money cumulatingInterestPaymentDueToGrace, final Money outstandingBalance, final LoanApplicationTerms loanApplicationTerms, final int periodNumber, final MathContext mc, - final TreeMap principalVariation, final Map compoundingMap, - final LocalDate periodStartDate, final LocalDate periodEndDate, final Collection termVariations) { + final TreeMap principalVariation, final Map compoundingMap, final LocalDate periodStartDate, + final LocalDate periodEndDate, final Collection termVariations) { LocalDate interestStartDate = periodStartDate; Money interestForThisInstallment = totalCumulativePrincipal.zero(); @@ -123,7 +124,6 @@ public class DecliningBalanceInterestLoanScheduleGenerator extends AbstractLoanS } } - final PrincipalInterest result = loanApplicationTerms.calculateTotalInterestForPeriod(calculator, interestCalculationGraceOnRepaymentPeriodFraction, periodNumber, mc, cumulatingInterestDueToGrace, balanceForInterestCalculation, interestStartDate, periodEndDate); @@ -150,4 +150,4 @@ public class DecliningBalanceInterestLoanScheduleGenerator extends AbstractLoanS return new PrincipalInterest(principalForThisInstallment, interestForThisInstallment, interestBroughtFowardDueToGrace); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultLoanScheduleGeneratorFactory.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultLoanScheduleGeneratorFactory.java index df26d7b7e..fdad36ea5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultLoanScheduleGeneratorFactory.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultLoanScheduleGeneratorFactory.java @@ -43,4 +43,4 @@ public class DefaultLoanScheduleGeneratorFactory implements LoanScheduleGenerato return loanScheduleGenerator; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultPaymentPeriodsInOneYearCalculator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultPaymentPeriodsInOneYearCalculator.java index e00612722..9fa9baf14 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultPaymentPeriodsInOneYearCalculator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultPaymentPeriodsInOneYearCalculator.java @@ -63,8 +63,8 @@ public class DefaultPaymentPeriodsInOneYearCalculator implements PaymentPeriodsI periodFraction = Double.valueOf("1.0"); } else if (interestChargedFromLocalDate != null && repaymentPeriod.contains(interestChargedFromLocalDate)) { - final int numberOfDaysInterestCalculationGraceInPeriod = Days.daysBetween(repaymentPeriodStartDate, - interestChargedFromLocalDate).getDays(); + final int numberOfDaysInterestCalculationGraceInPeriod = Days + .daysBetween(repaymentPeriodStartDate, interestChargedFromLocalDate).getDays(); periodFraction = calculateRepaymentPeriodFraction(repaymentPeriodFrequencyType, repaidEvery, numberOfDaysInterestCalculationGraceInPeriod); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultScheduledDateGenerator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultScheduledDateGenerator.java index 18ed7b6e2..6391bee50 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultScheduledDateGenerator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/DefaultScheduledDateGenerator.java @@ -59,8 +59,8 @@ public class DefaultScheduledDateGenerator implements ScheduledDateGenerator { if (isFirstRepayment && firstRepaymentPeriodDate != null) { dueRepaymentPeriodDate = firstRepaymentPeriodDate; } else { - LocalDate seedDate = null; - String reccuringString = null; + LocalDate seedDate = null; + String reccuringString = null; Calendar currentCalendar = loanApplicationTerms.getLoanCalendar(); dueRepaymentPeriodDate = getRepaymentPeriodDate(loanApplicationTerms.getRepaymentPeriodFrequencyType(), loanApplicationTerms.getRepaymentEvery(), lastRepaymentDate); @@ -74,7 +74,7 @@ public class DefaultScheduledDateGenerator implements ScheduledDateGenerator { CalendarHistory calendarHistory = null; CalendarHistoryDataWrapper calendarHistoryDataWrapper = loanApplicationTerms.getCalendarHistoryDataWrapper(); - if(calendarHistoryDataWrapper != null){ + if (calendarHistoryDataWrapper != null) { calendarHistory = loanApplicationTerms.getCalendarHistoryDataWrapper().getCalendarHistory(dueRepaymentPeriodDate); } @@ -90,8 +90,7 @@ public class DefaultScheduledDateGenerator implements ScheduledDateGenerator { dueRepaymentPeriodDate = CalendarUtils.getNextRepaymentMeetingDate(reccuringString, seedDate, lastRepaymentDate, loanApplicationTerms.getRepaymentEvery(), CalendarUtils.getMeetingFrequencyFromPeriodFrequencyType(loanApplicationTerms.getLoanTermPeriodFrequencyType()), - loanApplicationTerms.isSkipRepaymentOnFirstDayofMonth(), - loanApplicationTerms.getNumberOfdays()); + loanApplicationTerms.isSkipRepaymentOnFirstDayofMonth(), loanApplicationTerms.getNumberOfdays()); } } @@ -195,11 +194,13 @@ public class DefaultScheduledDateGenerator implements ScheduledDateGenerator { private void checkAndUpdateWorkingDayIfRepaymentDateIsNonWorkingDay(final AdjustedDateDetailsDTO adjustedDateDetailsDTO, final HolidayDetailDTO holidayDetailDTO, final LoanApplicationTerms loanApplicationTerms, final boolean isFirstRepayment) { while (WorkingDaysUtil.isNonWorkingDay(holidayDetailDTO.getWorkingDays(), adjustedDateDetailsDTO.getChangedScheduleDate())) { - if (WorkingDaysUtil.getRepaymentRescheduleType(holidayDetailDTO.getWorkingDays(), - adjustedDateDetailsDTO.getChangedScheduleDate()).isMoveToNextRepaymentDay()) { + if (WorkingDaysUtil + .getRepaymentRescheduleType(holidayDetailDTO.getWorkingDays(), adjustedDateDetailsDTO.getChangedScheduleDate()) + .isMoveToNextRepaymentDay()) { while (WorkingDaysUtil.isNonWorkingDay(holidayDetailDTO.getWorkingDays(), adjustedDateDetailsDTO.getNextRepaymentPeriodDueDate()) - || adjustedDateDetailsDTO.getChangedScheduleDate().isAfter(adjustedDateDetailsDTO.getNextRepaymentPeriodDueDate())) { + || adjustedDateDetailsDTO.getChangedScheduleDate() + .isAfter(adjustedDateDetailsDTO.getNextRepaymentPeriodDueDate())) { final LocalDate nextRepaymentPeriodDueDate = generateNextRepaymentDate( adjustedDateDetailsDTO.getNextRepaymentPeriodDueDate(), loanApplicationTerms, isFirstRepayment); adjustedDateDetailsDTO.setNextRepaymentPeriodDueDate(nextRepaymentPeriodDueDate); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/FinanicalFunctions.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/FinanicalFunctions.java index 6b8132cf8..9666ff639 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/FinanicalFunctions.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/FinanicalFunctions.java @@ -64,4 +64,4 @@ public class FinanicalFunctions { } return Double.valueOf(numberOfPayments).intValue(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/FlatInterestLoanScheduleGenerator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/FlatInterestLoanScheduleGenerator.java index 68c89e90c..f71fe8922 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/FlatInterestLoanScheduleGenerator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/FlatInterestLoanScheduleGenerator.java @@ -54,14 +54,19 @@ public class FlatInterestLoanScheduleGenerator extends AbstractLoanScheduleGener principalForThisInstallment = loanApplicationTerms.adjustPrincipalIfLastRepaymentPeriod(principalForThisInstallment, totalCumulativePrincipalToDate, periodNumber); - // totalCumulativeInterest from partial schedule generation for multi rescheduling - /*if (loanApplicationTerms.getPartialTotalCumulativeInterest() != null && loanApplicationTerms.getTotalInterestDue() != null) { - totalInterestDueForLoan = loanApplicationTerms.getTotalInterestDue(); - totalInterestDueForLoan = totalInterestDueForLoan.plus(loanApplicationTerms.getPartialTotalCumulativeInterest()); - }*/ + // totalCumulativeInterest from partial schedule generation for multi + // rescheduling + /* + * if (loanApplicationTerms.getPartialTotalCumulativeInterest() != null + * && loanApplicationTerms.getTotalInterestDue() != null) { + * totalInterestDueForLoan = loanApplicationTerms.getTotalInterestDue(); + * totalInterestDueForLoan = + * totalInterestDueForLoan.plus(loanApplicationTerms. + * getPartialTotalCumulativeInterest()); } + */ interestForThisInstallment = loanApplicationTerms.adjustInterestIfLastRepaymentPeriod(interestForThisInstallment, totalCumulativeInterestToDate, totalInterestDueForLoan, periodNumber); return new PrincipalInterest(principalForThisInstallment, interestForThisInstallment, interestBroughtForwardDueToGrace); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanApplicationTerms.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanApplicationTerms.java index 1b2db18e2..3c7663ffa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanApplicationTerms.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanApplicationTerms.java @@ -198,21 +198,17 @@ public final class LoanApplicationTerms { private final Set periodNumbersApplicableForInterestGrace = new HashSet<>(); - // used for FLAT loans when interest rate changed private Integer excludePeriodsForCalculation = 0; private Money totalPrincipalAccountedForInterestCalcualtion; - - //used for FLAT loans generation on modifying terms + // used for FLAT loans generation on modifying terms private Money totalPrincipalAccounted; private Money totalInterestAccounted; private int periodsCompleted = 0; private int extraPeriods = 0; private boolean isEqualAmortization; - - public static LoanApplicationTerms assembleFrom(final ApplicationCurrency currency, final Integer loanTermFrequency, final PeriodFrequencyType loanTermPeriodFrequencyType, final Integer numberOfRepayments, final Integer repaymentEvery, final PeriodFrequencyType repaymentPeriodFrequencyType, Integer nthDay, DayOfWeekType weekDayType, @@ -221,12 +217,12 @@ public final class LoanApplicationTerms { final InterestCalculationPeriodMethod interestCalculationPeriodMethod, final boolean allowPartialPeriodInterestCalcualtion, final Money principalMoney, final LocalDate expectedDisbursementDate, final LocalDate repaymentsStartingFromDate, final LocalDate calculatedRepaymentsStartingFromDate, final Integer graceOnPrincipalPayment, - final Integer recurringMoratoriumOnPrincipalPeriods, final Integer graceOnInterestPayment, - final Integer graceOnInterestCharged, final LocalDate interestChargedFromDate, final Money inArrearsTolerance, - final boolean multiDisburseLoan, final BigDecimal emiAmount, final List disbursementDatas, - final BigDecimal maxOutstandingBalance, final Integer graceOnArrearsAgeing, final DaysInMonthType daysInMonthType, - final DaysInYearType daysInYearType, final boolean isInterestRecalculationEnabled, - final RecalculationFrequencyType recalculationFrequencyType, final CalendarInstance restCalendarInstance, + final Integer recurringMoratoriumOnPrincipalPeriods, final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, + final LocalDate interestChargedFromDate, final Money inArrearsTolerance, final boolean multiDisburseLoan, + final BigDecimal emiAmount, final List disbursementDatas, final BigDecimal maxOutstandingBalance, + final Integer graceOnArrearsAgeing, final DaysInMonthType daysInMonthType, final DaysInYearType daysInYearType, + final boolean isInterestRecalculationEnabled, final RecalculationFrequencyType recalculationFrequencyType, + final CalendarInstance restCalendarInstance, final InterestRecalculationCompoundingMethod interestRecalculationCompoundingMethod, final CalendarInstance compoundingCalendarInstance, final RecalculationFrequencyType compoundingFrequencyType, final BigDecimal principalThresholdForLastInstalment, final Integer installmentAmountInMultiplesOf, @@ -242,14 +238,14 @@ public final class LoanApplicationTerms { repaymentPeriodFrequencyType, nthDay, weekDayType, amortizationMethod, interestMethod, interestRatePerPeriod, interestRatePeriodFrequencyType, annualNominalInterestRate, interestCalculationPeriodMethod, allowPartialPeriodInterestCalcualtion, principalMoney, expectedDisbursementDate, repaymentsStartingFromDate, - calculatedRepaymentsStartingFromDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, - interestChargedFromDate, inArrearsTolerance, multiDisburseLoan, emiAmount, disbursementDatas, maxOutstandingBalance, - graceOnArrearsAgeing, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, rescheduleStrategyMethod, - interestRecalculationCompoundingMethod, restCalendarInstance, recalculationFrequencyType, compoundingCalendarInstance, - compoundingFrequencyType, principalThresholdForLastInstalment, installmentAmountInMultiplesOf, - preClosureInterestCalculationStrategy, loanCalendar, approvedAmount, loanTermVariations, calendarHistoryDataWrapper, - isInterestChargedFromDateSameAsDisbursalDateEnabled, numberOfDays, isSkipRepaymentOnFirstDayOfMonth, holidayDetailDTO, - allowCompoundingOnEod, isEqualAmortization); + calculatedRepaymentsStartingFromDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, + graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, inArrearsTolerance, multiDisburseLoan, emiAmount, + disbursementDatas, maxOutstandingBalance, graceOnArrearsAgeing, daysInMonthType, daysInYearType, + isInterestRecalculationEnabled, rescheduleStrategyMethod, interestRecalculationCompoundingMethod, restCalendarInstance, + recalculationFrequencyType, compoundingCalendarInstance, compoundingFrequencyType, principalThresholdForLastInstalment, + installmentAmountInMultiplesOf, preClosureInterestCalculationStrategy, loanCalendar, approvedAmount, loanTermVariations, + calendarHistoryDataWrapper, isInterestChargedFromDateSameAsDisbursalDateEnabled, numberOfDays, + isSkipRepaymentOnFirstDayOfMonth, holidayDetailDTO, allowCompoundingOnEod, isEqualAmortization); } @@ -258,11 +254,11 @@ public final class LoanApplicationTerms { final LocalDate expectedDisbursementDate, final LocalDate repaymentsStartingFromDate, final LocalDate calculatedRepaymentsStartingFromDate, final Money inArrearsTolerance, final LoanProductRelatedDetail loanProductRelatedDetail, final boolean multiDisburseLoan, final BigDecimal emiAmount, - final List disbursementDatas, final BigDecimal maxOutstandingBalance, - final LocalDate interestChargedFromDate, final BigDecimal principalThresholdForLastInstalment, - final Integer installmentAmountInMultiplesOf, final RecalculationFrequencyType recalculationFrequencyType, - final CalendarInstance restCalendarInstance, final InterestRecalculationCompoundingMethod compoundingMethod, - final CalendarInstance compoundingCalendarInstance, final RecalculationFrequencyType compoundingFrequencyType, + final List disbursementDatas, final BigDecimal maxOutstandingBalance, final LocalDate interestChargedFromDate, + final BigDecimal principalThresholdForLastInstalment, final Integer installmentAmountInMultiplesOf, + final RecalculationFrequencyType recalculationFrequencyType, final CalendarInstance restCalendarInstance, + final InterestRecalculationCompoundingMethod compoundingMethod, final CalendarInstance compoundingCalendarInstance, + final RecalculationFrequencyType compoundingFrequencyType, final LoanPreClosureInterestCalculationStrategy loanPreClosureInterestCalculationStrategy, final LoanRescheduleStrategyMethod rescheduleStrategyMethod, BigDecimal approvedAmount, BigDecimal annualNominalInterestRate, List loanTermVariations, final Integer numberOfDays, final boolean isSkipRepaymentOnFirstDayOfMonth, @@ -283,11 +279,11 @@ public final class LoanApplicationTerms { final LocalDate expectedDisbursementDate, final LocalDate repaymentsStartingFromDate, final LocalDate calculatedRepaymentsStartingFromDate, final Money inArrearsTolerance, final LoanProductRelatedDetail loanProductRelatedDetail, final boolean multiDisburseLoan, final BigDecimal emiAmount, - final List disbursementDatas, final BigDecimal maxOutstandingBalance, - final LocalDate interestChargedFromDate, final BigDecimal principalThresholdForLastInstalment, - final Integer installmentAmountInMultiplesOf, final RecalculationFrequencyType recalculationFrequencyType, - final CalendarInstance restCalendarInstance, final InterestRecalculationCompoundingMethod compoundingMethod, - final CalendarInstance compoundingCalendarInstance, final RecalculationFrequencyType compoundingFrequencyType, + final List disbursementDatas, final BigDecimal maxOutstandingBalance, final LocalDate interestChargedFromDate, + final BigDecimal principalThresholdForLastInstalment, final Integer installmentAmountInMultiplesOf, + final RecalculationFrequencyType recalculationFrequencyType, final CalendarInstance restCalendarInstance, + final InterestRecalculationCompoundingMethod compoundingMethod, final CalendarInstance compoundingCalendarInstance, + final RecalculationFrequencyType compoundingFrequencyType, final LoanPreClosureInterestCalculationStrategy loanPreClosureInterestCalculationStrategy, final LoanRescheduleStrategyMethod rescheduleStrategyMethod, final Calendar loanCalendar, BigDecimal approvedAmount, BigDecimal annualNominalInterestRate, final List loanTermVariations, @@ -322,14 +318,15 @@ public final class LoanApplicationTerms { repaymentEvery, repaymentPeriodFrequencyType, ((nthDay != null) ? nthDay.getValue() : null), dayOfWeek, amortizationMethod, interestMethod, interestRatePerPeriod, interestRatePeriodFrequencyType, annualNominalInterestRate, interestCalculationPeriodMethod, allowPartialPeriodInterestCalcualtion, principalMoney, expectedDisbursementDate, - repaymentsStartingFromDate, calculatedRepaymentsStartingFromDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, - graceOnInterestCharged, interestChargedFromDate, inArrearsTolerance, multiDisburseLoan, emiAmount, disbursementDatas, - maxOutstandingBalance, loanProductRelatedDetail.getGraceOnDueDate(), daysInMonthType, daysInYearType, - isInterestRecalculationEnabled, rescheduleStrategyMethod, compoundingMethod, restCalendarInstance, - recalculationFrequencyType, compoundingCalendarInstance, compoundingFrequencyType, principalThresholdForLastInstalment, - installmentAmountInMultiplesOf, loanPreClosureInterestCalculationStrategy, loanCalendar, approvedAmount, - loanTermVariations, calendarHistoryDataWrapper, isInterestChargedFromDateSameAsDisbursalDateEnabled, numberOfDays, - isSkipRepaymentOnFirstDayOfMonth, holidayDetailDTO, allowCompoundingOnEod, isEqualAmortization); + repaymentsStartingFromDate, calculatedRepaymentsStartingFromDate, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, + inArrearsTolerance, multiDisburseLoan, emiAmount, disbursementDatas, maxOutstandingBalance, + loanProductRelatedDetail.getGraceOnDueDate(), daysInMonthType, daysInYearType, isInterestRecalculationEnabled, + rescheduleStrategyMethod, compoundingMethod, restCalendarInstance, recalculationFrequencyType, compoundingCalendarInstance, + compoundingFrequencyType, principalThresholdForLastInstalment, installmentAmountInMultiplesOf, + loanPreClosureInterestCalculationStrategy, loanCalendar, approvedAmount, loanTermVariations, calendarHistoryDataWrapper, + isInterestChargedFromDateSameAsDisbursalDateEnabled, numberOfDays, isSkipRepaymentOnFirstDayOfMonth, holidayDetailDTO, + allowCompoundingOnEod, isEqualAmortization); } public static LoanApplicationTerms assembleFrom(final ApplicationCurrency applicationCurrency, final Integer loanTermFrequency, @@ -381,14 +378,14 @@ public final class LoanApplicationTerms { repaymentEvery, repaymentPeriodFrequencyType, null, null, amortizationMethod, interestMethod, interestRatePerPeriod, interestRatePeriodFrequencyType, annualNominalInterestRate, interestCalculationPeriodMethod, allowPartialPeriodInterestCalcualtion, principalMoney, expectedDisbursementDate, repaymentsStartingFromDate, - calculatedRepaymentsStartingFromDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, - interestChargedFromDate, inArrearsTolerance, multiDisburseLoan, emiAmount, disbursementDatas, maxOutstandingBalance, - loanProductRelatedDetail.getGraceOnDueDate(), daysInMonthType, daysInYearType, isInterestRecalculationEnabled, - rescheduleStrategyMethod, interestRecalculationCompoundingMethod, restCalendarInstance, recalculationFrequencyType, - compoundingCalendarInstance, compoundingFrequencyType, principalThresholdForLastInstalment, installmentAmountInMultiplesOf, - loanPreClosureInterestCalculationStrategy, loanCalendar, approvedAmount, loanTermVariations, calendarHistoryDataWrapper, - isInterestChargedFromDateSameAsDisbursalDateEnabled, numberOfDays, isSkipRepaymentOnFirstDayOfMonth, holidayDetailDTO, - allowCompoundingOnEod, isEqualAmortization); + calculatedRepaymentsStartingFromDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, + graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, inArrearsTolerance, multiDisburseLoan, emiAmount, + disbursementDatas, maxOutstandingBalance, loanProductRelatedDetail.getGraceOnDueDate(), daysInMonthType, daysInYearType, + isInterestRecalculationEnabled, rescheduleStrategyMethod, interestRecalculationCompoundingMethod, restCalendarInstance, + recalculationFrequencyType, compoundingCalendarInstance, compoundingFrequencyType, principalThresholdForLastInstalment, + installmentAmountInMultiplesOf, loanPreClosureInterestCalculationStrategy, loanCalendar, approvedAmount, loanTermVariations, + calendarHistoryDataWrapper, isInterestChargedFromDateSameAsDisbursalDateEnabled, numberOfDays, + isSkipRepaymentOnFirstDayOfMonth, holidayDetailDTO, allowCompoundingOnEod, isEqualAmortization); } @@ -402,18 +399,18 @@ public final class LoanApplicationTerms { applicationTerms.interestCalculationPeriodMethod, applicationTerms.allowPartialPeriodInterestCalcualtion, applicationTerms.principal, applicationTerms.expectedDisbursementDate, applicationTerms.repaymentsStartingFromDate, applicationTerms.calculatedRepaymentsStartingFromDate, applicationTerms.principalGrace, - applicationTerms.recurringMoratoriumOnPrincipalPeriods, applicationTerms.interestPaymentGrace, applicationTerms.interestChargingGrace, applicationTerms.interestChargedFromDate, - applicationTerms.inArrearsTolerance, applicationTerms.multiDisburseLoan, applicationTerms.actualFixedEmiAmount, - applicationTerms.disbursementDatas, applicationTerms.maxOutstandingBalance, applicationTerms.graceOnArrearsAgeing, - applicationTerms.daysInMonthType, applicationTerms.daysInYearType, applicationTerms.interestRecalculationEnabled, - applicationTerms.rescheduleStrategyMethod, applicationTerms.interestRecalculationCompoundingMethod, - applicationTerms.restCalendarInstance, applicationTerms.recalculationFrequencyType, - applicationTerms.compoundingCalendarInstance, applicationTerms.compoundingFrequencyType, - applicationTerms.principalThresholdForLastInstalment, applicationTerms.installmentAmountInMultiplesOf, - applicationTerms.preClosureInterestCalculationStrategy, applicationTerms.loanCalendar, - applicationTerms.approvedPrincipal.getAmount(), loanTermVariations, applicationTerms.calendarHistoryDataWrapper, - applicationTerms.isInterestChargedFromDateSameAsDisbursalDateEnabled, applicationTerms.numberOfDays, - applicationTerms.isSkipRepaymentOnFirstDayOfMonth, applicationTerms.holidayDetailDTO, + applicationTerms.recurringMoratoriumOnPrincipalPeriods, applicationTerms.interestPaymentGrace, + applicationTerms.interestChargingGrace, applicationTerms.interestChargedFromDate, applicationTerms.inArrearsTolerance, + applicationTerms.multiDisburseLoan, applicationTerms.actualFixedEmiAmount, applicationTerms.disbursementDatas, + applicationTerms.maxOutstandingBalance, applicationTerms.graceOnArrearsAgeing, applicationTerms.daysInMonthType, + applicationTerms.daysInYearType, applicationTerms.interestRecalculationEnabled, applicationTerms.rescheduleStrategyMethod, + applicationTerms.interestRecalculationCompoundingMethod, applicationTerms.restCalendarInstance, + applicationTerms.recalculationFrequencyType, applicationTerms.compoundingCalendarInstance, + applicationTerms.compoundingFrequencyType, applicationTerms.principalThresholdForLastInstalment, + applicationTerms.installmentAmountInMultiplesOf, applicationTerms.preClosureInterestCalculationStrategy, + applicationTerms.loanCalendar, applicationTerms.approvedPrincipal.getAmount(), loanTermVariations, + applicationTerms.calendarHistoryDataWrapper, applicationTerms.isInterestChargedFromDateSameAsDisbursalDateEnabled, + applicationTerms.numberOfDays, applicationTerms.isSkipRepaymentOnFirstDayOfMonth, applicationTerms.holidayDetailDTO, applicationTerms.allowCompoundingOnEod, applicationTerms.isEqualAmortization); } @@ -424,12 +421,12 @@ public final class LoanApplicationTerms { final PeriodFrequencyType interestRatePeriodFrequencyType, final BigDecimal annualNominalInterestRate, final InterestCalculationPeriodMethod interestCalculationPeriodMethod, final boolean allowPartialPeriodInterestCalcualtion, final Money principal, final LocalDate expectedDisbursementDate, final LocalDate repaymentsStartingFromDate, - final LocalDate calculatedRepaymentsStartingFromDate, final Integer principalGrace, final Integer recurringMoratoriumOnPrincipalPeriods, final Integer interestPaymentGrace, - final Integer interestChargingGrace, final LocalDate interestChargedFromDate, final Money inArrearsTolerance, - final boolean multiDisburseLoan, final BigDecimal emiAmount, final List disbursementDatas, - final BigDecimal maxOutstandingBalance, final Integer graceOnArrearsAgeing, final DaysInMonthType daysInMonthType, - final DaysInYearType daysInYearType, final boolean isInterestRecalculationEnabled, - final LoanRescheduleStrategyMethod rescheduleStrategyMethod, + final LocalDate calculatedRepaymentsStartingFromDate, final Integer principalGrace, + final Integer recurringMoratoriumOnPrincipalPeriods, final Integer interestPaymentGrace, final Integer interestChargingGrace, + final LocalDate interestChargedFromDate, final Money inArrearsTolerance, final boolean multiDisburseLoan, + final BigDecimal emiAmount, final List disbursementDatas, final BigDecimal maxOutstandingBalance, + final Integer graceOnArrearsAgeing, final DaysInMonthType daysInMonthType, final DaysInYearType daysInYearType, + final boolean isInterestRecalculationEnabled, final LoanRescheduleStrategyMethod rescheduleStrategyMethod, final InterestRecalculationCompoundingMethod interestRecalculationCompoundingMethod, final CalendarInstance restCalendarInstance, final RecalculationFrequencyType recalculationFrequencyType, final CalendarInstance compoundingCalendarInstance, final RecalculationFrequencyType compoundingFrequencyType, @@ -707,9 +704,9 @@ public final class LoanApplicationTerms { final Money interestForThisInstallmentBeforeGrace = calculateDecliningInterestDueForInstallmentBeforeApplyingGrace( calculator, mc, outstandingBalance, periodStartDate, periodEndDate); - final Money interestForThisInstallmentAfterGrace = calculateDecliningInterestDueForInstallmentAfterApplyingGrace( - calculator, interestCalculationGraceOnRepaymentPeriodFraction, mc, outstandingBalance, periodNumber, - periodStartDate, periodEndDate); + final Money interestForThisInstallmentAfterGrace = calculateDecliningInterestDueForInstallmentAfterApplyingGrace(calculator, + interestCalculationGraceOnRepaymentPeriodFraction, mc, outstandingBalance, periodNumber, periodStartDate, + periodEndDate); interestForInstallment = interestForThisInstallmentAfterGrace; if (interestForThisInstallmentAfterGrace.isGreaterThanZero()) { @@ -745,8 +742,8 @@ public final class LoanApplicationTerms { switch (this.interestMethod) { case FLAT: final BigDecimal interestRateForLoanTerm = calculateFlatInterestRateForLoanTerm(calculator, mc); - totalInterestDue = this.principal.minus(totalPrincipalAccountedForInterestCalcualtion).multiplyRetainScale(interestRateForLoanTerm, - mc.getRoundingMode()); + totalInterestDue = this.principal.minus(totalPrincipalAccountedForInterestCalcualtion) + .multiplyRetainScale(interestRateForLoanTerm, mc.getRoundingMode()); break; case DECLINING_BALANCE: @@ -812,8 +809,8 @@ public final class LoanApplicationTerms { case WEEKS: int numberOfWeeks = Weeks.weeksBetween(startDate, endDate).getWeeks(); int daysLeftAfterWeeks = Days.daysBetween(startDate.plusWeeks(numberOfWeeks), endDate).getDays(); - numberOfPeriods = numberOfPeriods.add(BigDecimal.valueOf(numberOfWeeks)).add( - BigDecimal.valueOf((double) daysLeftAfterWeeks / 7)); + numberOfPeriods = numberOfPeriods.add(BigDecimal.valueOf(numberOfWeeks)) + .add(BigDecimal.valueOf((double) daysLeftAfterWeeks / 7)); break; case MONTHS: int numberOfMonths = Months.monthsBetween(startDate, endDate).getMonths(); @@ -832,8 +829,7 @@ public final class LoanApplicationTerms { if (!CalendarUtils.isValidRedurringDate(loanCalendar.getRecurrence(), loanCalendar.getStartDateLocalDate().minusMonths(getRepaymentEvery()), startDate)) { expectedStartDate = CalendarUtils.getNewRepaymentMeetingDate(loanCalendar.getRecurrence(), - startDate.minusMonths(getRepaymentEvery()), startDate.minusMonths(getRepaymentEvery()), - getRepaymentEvery(), + startDate.minusMonths(getRepaymentEvery()), startDate.minusMonths(getRepaymentEvery()), getRepaymentEvery(), CalendarUtils.getMeetingFrequencyFromPeriodFrequencyType(getLoanTermPeriodFrequencyType()), this.holidayDetailDTO.getWorkingDays(), isSkipRepaymentOnFirstDayOfMonth, numberOfDays); } @@ -855,8 +851,8 @@ public final class LoanApplicationTerms { } int daysLeftAfterMonths = Days.daysBetween(startDateAfterConsideringMonths, endDate).getDays() + diffDays; int daysInPeriodAfterMonths = Days.daysBetween(startDateAfterConsideringMonths, endDateAfterConsideringMonths).getDays(); - numberOfPeriods = numberOfPeriods.add(BigDecimal.valueOf(numberOfMonths)).add( - BigDecimal.valueOf((double) daysLeftAfterMonths / daysInPeriodAfterMonths)); + numberOfPeriods = numberOfPeriods.add(BigDecimal.valueOf(numberOfMonths)) + .add(BigDecimal.valueOf((double) daysLeftAfterMonths / daysInPeriodAfterMonths)); break; case YEARS: int numberOfYears = Years.yearsBetween(startDate, endDate).getYears(); @@ -864,8 +860,8 @@ public final class LoanApplicationTerms { LocalDate endDateAfterConsideringYears = startDate.plusYears(numberOfYears + 1); int daysLeftAfterYears = Days.daysBetween(startDateAfterConsideringYears, endDate).getDays(); int daysInPeriodAfterYears = Days.daysBetween(startDateAfterConsideringYears, endDateAfterConsideringYears).getDays(); - numberOfPeriods = numberOfPeriods.add(BigDecimal.valueOf(numberOfYears)).add( - BigDecimal.valueOf((double) daysLeftAfterYears / daysInPeriodAfterYears)); + numberOfPeriods = numberOfPeriods.add(BigDecimal.valueOf(numberOfYears)) + .add(BigDecimal.valueOf((double) daysLeftAfterYears / daysInPeriodAfterYears)); break; default: break; @@ -877,41 +873,44 @@ public final class LoanApplicationTerms { this.loanEndDate = loanEndDate; } - private Money calculateTotalInterestPerInstallmentWithoutGrace(final PaymentPeriodsInOneYearCalculator calculator, final MathContext mc) { + private Money calculateTotalInterestPerInstallmentWithoutGrace(final PaymentPeriodsInOneYearCalculator calculator, + final MathContext mc) { final Money totalInterestForLoanTerm = calculateTotalFlatInterestDueWithoutGrace(calculator, mc); return flatInterestPerInstallment(mc, totalInterestForLoanTerm); } private Money flatInterestPerInstallment(final MathContext mc, final Money totalInterestForLoanTerm) { - Money interestPerInstallment = totalInterestForLoanTerm.dividedBy(Long.valueOf(this.actualNumberOfRepayments) - - defaultToZeroIfNull(this.excludePeriodsForCalculation), mc.getRoundingMode()); + Money interestPerInstallment = totalInterestForLoanTerm.dividedBy( + Long.valueOf(this.actualNumberOfRepayments) - defaultToZeroIfNull(this.excludePeriodsForCalculation), mc.getRoundingMode()); if (this.excludePeriodsForCalculation < this.periodsCompleted) { Money interestLeft = this.totalInterestDue.minus(this.totalInterestAccounted); - interestPerInstallment = interestLeft.dividedBy(Long.valueOf(this.actualNumberOfRepayments) - - defaultToZeroIfNull(this.periodsCompleted), mc.getRoundingMode()); + interestPerInstallment = interestLeft.dividedBy( + Long.valueOf(this.actualNumberOfRepayments) - defaultToZeroIfNull(this.periodsCompleted), mc.getRoundingMode()); } return interestPerInstallment; } - private Money calculateTotalPrincipalPerPeriodWithoutGrace(final MathContext mc, final int periodNumber, Money interestForThisInstallment) { + private Money calculateTotalPrincipalPerPeriodWithoutGrace(final MathContext mc, final int periodNumber, + Money interestForThisInstallment) { final int totalRepaymentsWithCapitalPayment = calculateNumberOfRepaymentsWithPrincipalPayment(); Money principalPerPeriod = null; if (getFixedEmiAmount() == null) { - principalPerPeriod = this.principal.minus(totalPrincipalAccounted).dividedBy(totalRepaymentsWithCapitalPayment, mc.getRoundingMode()).plus( - this.adjustPrincipalForFlatLoans); + principalPerPeriod = this.principal.minus(totalPrincipalAccounted) + .dividedBy(totalRepaymentsWithCapitalPayment, mc.getRoundingMode()).plus(this.adjustPrincipalForFlatLoans); if (isPrincipalGraceApplicableForThisPeriod(periodNumber)) { principalPerPeriod = principalPerPeriod.zero(); } if (!isPrincipalGraceApplicableForThisPeriod(periodNumber) && currentPeriodFixedPrincipalAmount != null) { - this.adjustPrincipalForFlatLoans = this.adjustPrincipalForFlatLoans.plus(principalPerPeriod.minus( - currentPeriodFixedPrincipalAmount).dividedBy(this.actualNumberOfRepayments - periodNumber, mc.getRoundingMode())); + this.adjustPrincipalForFlatLoans = this.adjustPrincipalForFlatLoans + .plus(principalPerPeriod.minus(currentPeriodFixedPrincipalAmount) + .dividedBy(this.actualNumberOfRepayments - periodNumber, mc.getRoundingMode())); principalPerPeriod = this.principal.zero().plus(currentPeriodFixedPrincipalAmount); } - }else{ - principalPerPeriod = Money.of(this.getCurrency(), getFixedEmiAmount()).minus(interestForThisInstallment); + } else { + principalPerPeriod = Money.of(this.getCurrency(), getFixedEmiAmount()).minus(interestForThisInstallment); return principalPerPeriod; } @@ -961,19 +960,17 @@ public final class LoanApplicationTerms { final Money totalInterestFree = interestPerGracePeriod.multipliedBy(getInterestChargingGrace()); final Money realTotalInterestForLoan = totalInterestForLoanTerm.minus(totalInterestFree); - - Integer interestPaymentDuePeriods = calculateNumberOfRemainingInterestPaymentPeriods(this.actualNumberOfRepayments, this.excludePeriodsForCalculation); - interestForInstallment = realTotalInterestForLoan - .dividedBy(BigDecimal.valueOf(interestPaymentDuePeriods), mc.getRoundingMode()); + interestForInstallment = realTotalInterestForLoan.dividedBy(BigDecimal.valueOf(interestPaymentDuePeriods), + mc.getRoundingMode()); if (this.excludePeriodsForCalculation < this.periodsCompleted) { Money interestLeft = this.totalInterestDue.minus(this.totalInterestAccounted); Integer interestDuePeriods = calculateNumberOfRemainingInterestPaymentPeriods(this.actualNumberOfRepayments, this.periodsCompleted); interestForInstallment = interestLeft.dividedBy(Long.valueOf(interestDuePeriods), mc.getRoundingMode()); } - if(!this.periodNumbersApplicableForInterestGrace.isEmpty()){ + if (!this.periodNumbersApplicableForInterestGrace.isEmpty()) { int periodsElapsed = calculateLastInterestGracePeriod(periodNumber); if (periodsElapsed > this.excludePeriodsForCalculation && periodsElapsed > this.periodsCompleted) { Money interestLeft = this.totalInterestDue.minus(this.totalInterestAccounted); @@ -983,7 +980,6 @@ public final class LoanApplicationTerms { } } - } return interestForInstallment; @@ -995,8 +991,9 @@ public final class LoanApplicationTerms { return periodicInterestRate(calculator, mc, daysInMonthType, daysInYearType, periodStartDate, periodEndDate, false); } - private BigDecimal periodicInterestRate(final PaymentPeriodsInOneYearCalculator calculator, final MathContext mc, final DaysInMonthType daysInMonthType, - final DaysInYearType daysInYearType, LocalDate periodStartDate, LocalDate periodEndDate, boolean isForPMT) { + private BigDecimal periodicInterestRate(final PaymentPeriodsInOneYearCalculator calculator, final MathContext mc, + final DaysInMonthType daysInMonthType, final DaysInYearType daysInYearType, LocalDate periodStartDate, LocalDate periodEndDate, + boolean isForPMT) { final long loanTermPeriodsInOneYear = calculatePeriodsInOneYear(calculator); @@ -1005,7 +1002,7 @@ public final class LoanApplicationTerms { BigDecimal periodicInterestRate = BigDecimal.ZERO; BigDecimal loanTermFrequencyBigDecimal = BigDecimal.ONE; - if(isForPMT){ + if (isForPMT) { loanTermFrequencyBigDecimal = BigDecimal.valueOf(this.repaymentEvery); } else { loanTermFrequencyBigDecimal = calculateLoanTermFrequency(periodStartDate, periodEndDate); @@ -1083,8 +1080,8 @@ public final class LoanApplicationTerms { final BigDecimal divisor = BigDecimal.valueOf(Double.valueOf("100.0")); final BigDecimal loanTermPeriodsInYearBigDecimal = BigDecimal.valueOf(loanTermPeriodsInOneYear); - final BigDecimal oneDayOfYearInterestRate = this.annualNominalInterestRate.divide(loanTermPeriodsInYearBigDecimal, mc).divide( - divisor, mc); + final BigDecimal oneDayOfYearInterestRate = this.annualNominalInterestRate.divide(loanTermPeriodsInYearBigDecimal, mc) + .divide(divisor, mc); BigDecimal interestRate = oneDayOfYearInterestRate.multiply(BigDecimal.valueOf(repaymentEvery), mc); return outstandingBalance.getAmount().multiply(interestRate, mc); } @@ -1094,8 +1091,8 @@ public final class LoanApplicationTerms { // check if daysInYears is set if so change periodsInOneYear to days set // in db long periodsInOneYear; - boolean daysInYearToUse = (this.repaymentPeriodFrequencyType.getCode().equalsIgnoreCase("periodFrequencyType.days") && !this.daysInYearType - .getCode().equalsIgnoreCase("DaysInYearType.actual")); + boolean daysInYearToUse = (this.repaymentPeriodFrequencyType.getCode().equalsIgnoreCase("periodFrequencyType.days") + && !this.daysInYearType.getCode().equalsIgnoreCase("DaysInYearType.actual")); if (daysInYearToUse) { periodsInOneYear = this.daysInYearType.getValue().longValue(); } else { @@ -1103,8 +1100,9 @@ public final class LoanApplicationTerms { } switch (this.interestCalculationPeriodMethod) { case DAILY: - periodsInOneYear = !this.daysInYearType.getCode().equalsIgnoreCase("DaysInYearType.actual") ? this.daysInYearType - .getValue().longValue() : calculator.calculate(PeriodFrequencyType.DAYS).longValue(); + periodsInOneYear = !this.daysInYearType.getCode().equalsIgnoreCase("DaysInYearType.actual") + ? this.daysInYearType.getValue().longValue() + : calculator.calculate(PeriodFrequencyType.DAYS).longValue(); break; case INVALID: break; @@ -1116,9 +1114,8 @@ public final class LoanApplicationTerms { } private int calculateNumberOfRepaymentsWithPrincipalPayment() { - int numPeriods = calculateNumberOfRemainingPrincipalPaymentPeriods(this.actualNumberOfRepayments, - this.periodsCompleted); -// numPeriods = numPeriods - this.periodsCompleted; + int numPeriods = calculateNumberOfRemainingPrincipalPaymentPeriods(this.actualNumberOfRepayments, this.periodsCompleted); + // numPeriods = numPeriods - this.periodsCompleted; return numPeriods; } @@ -1133,16 +1130,16 @@ public final class LoanApplicationTerms { /** * if grace period available then need to be subtracted */ - if(this.interestChargingGrace != null){ + if (this.interestChargingGrace != null) { periodsRemaining = periodsRemaining - this.interestChargingGrace; } return periodsRemaining; } - private Integer calculateLastInterestGracePeriod(int periodNumber){ + private Integer calculateLastInterestGracePeriod(int periodNumber) { int lastGracePeriod = 0; for (Integer grace : this.periodNumbersApplicableForInterestGrace) { - if(grace < periodNumber && lastGracePeriod < grace){ + if (grace < periodNumber && lastGracePeriod < grace) { lastGracePeriod = grace; } } @@ -1241,8 +1238,8 @@ public final class LoanApplicationTerms { final double interestCalculationGraceOnRepaymentPeriodFraction, final MathContext mc, final Money outstandingBalance, final int periodNumber, LocalDate periodStartDate, LocalDate periodEndDate) { - Money interest = calculateDecliningInterestDueForInstallmentBeforeApplyingGrace(calculator, mc, outstandingBalance, - periodStartDate, periodEndDate); + Money interest = calculateDecliningInterestDueForInstallmentBeforeApplyingGrace(calculator, mc, outstandingBalance, periodStartDate, + periodEndDate); if (isInterestPaymentGraceApplicableForThisPeriod(periodNumber)) { interest = interest.zero(); @@ -1277,8 +1274,8 @@ public final class LoanApplicationTerms { private Money calculateEqualPrincipalDueForInstallment(final MathContext mc, final int periodNumber) { Money principal = this.principal; if (this.fixedPrincipalAmount == null) { - final Integer numberOfPrincipalPaymentPeriods = calculateNumberOfRemainingPrincipalPaymentPeriods( - this.actualNumberOfRepayments, periodNumber); + final Integer numberOfPrincipalPaymentPeriods = calculateNumberOfRemainingPrincipalPaymentPeriods(this.actualNumberOfRepayments, + periodNumber); principal = this.principal.dividedBy(numberOfPrincipalPaymentPeriods, mc.getRoundingMode()); this.fixedPrincipalAmount = principal.getAmount(); } @@ -1312,7 +1309,8 @@ public final class LoanApplicationTerms { this.fixedPrincipalAmount = fixedPrincipalAmount; } - private Money calculatePrincipalDueForInstallment(final int periodNumber, final Money totalDuePerInstallment, final Money periodInterest) { + private Money calculatePrincipalDueForInstallment(final int periodNumber, final Money totalDuePerInstallment, + final Money periodInterest) { Money principal = totalDuePerInstallment.minus(periodInterest); if (isPrincipalGraceApplicableForThisPeriod(periodNumber)) { @@ -1336,9 +1334,10 @@ public final class LoanApplicationTerms { return LoanProductRelatedDetail.createFrom(currency, this.principal.getAmount(), this.interestRatePerPeriod, this.interestRatePeriodFrequencyType, this.annualNominalInterestRate, this.interestMethod, this.interestCalculationPeriodMethod, this.allowPartialPeriodInterestCalcualtion, this.repaymentEvery, - this.repaymentPeriodFrequencyType, this.numberOfRepayments, this.principalGrace, this.recurringMoratoriumOnPrincipalPeriods, this.interestPaymentGrace, - this.interestChargingGrace, this.amortizationMethod, this.inArrearsTolerance.getAmount(), this.graceOnArrearsAgeing, - this.daysInMonthType.getValue(), this.daysInYearType.getValue(), this.interestRecalculationEnabled, this.isEqualAmortization); + this.repaymentPeriodFrequencyType, this.numberOfRepayments, this.principalGrace, this.recurringMoratoriumOnPrincipalPeriods, + this.interestPaymentGrace, this.interestChargingGrace, this.amortizationMethod, this.inArrearsTolerance.getAmount(), + this.graceOnArrearsAgeing, this.daysInMonthType.getValue(), this.daysInYearType.getValue(), + this.interestRecalculationEnabled, this.isEqualAmortization); } public Integer getLoanTermFrequency() { @@ -1713,7 +1712,7 @@ public final class LoanApplicationTerms { return (value != null) ? value : 0; } - public void updateExcludePeriodsForCalculation(Integer excludePeriodsForCalculation){ + public void updateExcludePeriodsForCalculation(Integer excludePeriodsForCalculation) { this.excludePeriodsForCalculation = excludePeriodsForCalculation; this.extraPeriods = 0; } @@ -1731,8 +1730,8 @@ public final class LoanApplicationTerms { Integer numberOfRepayments = this.actualNumberOfRepayments; if (this.getRecurringMoratoriumOnPrincipalPeriods() > 0) { while (numberOfRepayments > 0) { - isPrincipalGraceApplicableForThisPeriod = ((periodNumber > 0 && periodNumber <= getPrincipalGrace()) || (periodNumber > 0 && (((periodNumber - getPrincipalGrace()) % (this - .getRecurringMoratoriumOnPrincipalPeriods() + 1)) != 1))); + isPrincipalGraceApplicableForThisPeriod = ((periodNumber > 0 && periodNumber <= getPrincipalGrace()) || (periodNumber > 0 + && (((periodNumber - getPrincipalGrace()) % (this.getRecurringMoratoriumOnPrincipalPeriods() + 1)) != 1))); if (isPrincipalGraceApplicableForThisPeriod) { this.periodNumbersApplicableForPrincipalGrace.add(periodNumber); } @@ -1743,21 +1742,20 @@ public final class LoanApplicationTerms { } - public void setTotalPrincipalAccounted(Money totalPrincipalAccounted) { this.totalPrincipalAccountedForInterestCalcualtion = totalPrincipalAccounted; } - - //Used for FLAT loans to calculate principal and interest per installment - public void updateAccountedTillPeriod(int periodNumber, Money totalPrincipalAccounted,Money totalInterestAccounted, int extendPeriods){ + // Used for FLAT loans to calculate principal and interest per installment + public void updateAccountedTillPeriod(int periodNumber, Money totalPrincipalAccounted, Money totalInterestAccounted, + int extendPeriods) { this.periodsCompleted = periodNumber; this.totalPrincipalAccounted = totalPrincipalAccounted; this.totalInterestAccounted = totalInterestAccounted; this.extraPeriods = this.extraPeriods + extendPeriods; } - public void updateTotalInterestAccounted(Money totalInterestAccounted){ + public void updateTotalInterestAccounted(Money totalInterestAccounted) { this.totalInterestAccounted = totalInterestAccounted; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanRepaymentScheduleHistory.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanRepaymentScheduleHistory.java index 516912e06..4e2db4a17 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanRepaymentScheduleHistory.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanRepaymentScheduleHistory.java @@ -97,9 +97,8 @@ public class LoanRepaymentScheduleHistory extends AbstractPersistableCustom { **/ private LoanRepaymentScheduleHistory(final Loan loan, final LoanRescheduleRequest loanRescheduleRequest, final Integer installmentNumber, final Date fromDate, final Date dueDate, final BigDecimal principal, - final BigDecimal interestCharged, final BigDecimal feeChargesCharged, final BigDecimal penaltyCharges, - final Date createdOnDate, final AppUser createdByUser, final AppUser lastModifiedByUser, final Date lastModifiedOnDate, - final Integer version) { + final BigDecimal interestCharged, final BigDecimal feeChargesCharged, final BigDecimal penaltyCharges, final Date createdOnDate, + final AppUser createdByUser, final AppUser lastModifiedByUser, final Date lastModifiedOnDate, final Integer version) { this.loan = loan; this.loanRescheduleRequest = loanRescheduleRequest; @@ -122,9 +121,8 @@ public class LoanRepaymentScheduleHistory extends AbstractPersistableCustom { **/ public static LoanRepaymentScheduleHistory instance(final Loan loan, final LoanRescheduleRequest loanRescheduleRequest, final Integer installmentNumber, final Date fromDate, final Date dueDate, final BigDecimal principal, - final BigDecimal interestCharged, final BigDecimal feeChargesCharged, final BigDecimal penaltyCharges, - final Date createdOnDate, final AppUser createdByUser, final AppUser lastModifiedByUser, final Date lastModifiedOnDate, - final Integer version) { + final BigDecimal interestCharged, final BigDecimal feeChargesCharged, final BigDecimal penaltyCharges, final Date createdOnDate, + final AppUser createdByUser, final AppUser lastModifiedByUser, final Date lastModifiedOnDate, final Integer version) { return new LoanRepaymentScheduleHistory(loan, loanRescheduleRequest, installmentNumber, fromDate, dueDate, principal, interestCharged, feeChargesCharged, penaltyCharges, createdOnDate, createdByUser, lastModifiedByUser, lastModifiedOnDate, diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanRepaymentScheduleHistoryRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanRepaymentScheduleHistoryRepository.java index 948e72091..5e75779c8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanRepaymentScheduleHistoryRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanRepaymentScheduleHistoryRepository.java @@ -21,6 +21,7 @@ package org.apache.fineract.portfolio.loanaccount.loanschedule.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface LoanRepaymentScheduleHistoryRepository extends JpaRepository, JpaSpecificationExecutor { +public interface LoanRepaymentScheduleHistoryRepository + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleGenerator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleGenerator.java index da22fac70..e3a6673a6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleGenerator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleGenerator.java @@ -42,4 +42,4 @@ public interface LoanScheduleGenerator { LoanApplicationTerms loanApplicationTerms, MathContext mc, Loan loan, HolidayDetailDTO holidayDetailDTO, LoanRepaymentScheduleTransactionProcessor loanRepaymentScheduleTransactionProcessor); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModel.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModel.java index 82a8a60f9..c38636cdd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModel.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModel.java @@ -120,10 +120,8 @@ public final class LoanScheduleModel { return this.totalPenaltyChargesCharged; } - public BigDecimal getTotalInterestCharged() { return this.totalInterestCharged; } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelDisbursementPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelDisbursementPeriod.java index 92ef7ac18..c1eb9fa90 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelDisbursementPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelDisbursementPeriod.java @@ -123,8 +123,9 @@ public final class LoanScheduleModelDisbursementPeriod implements LoanScheduleMo public void addInterestAmount(@SuppressWarnings("unused") Money principalDue) { return; } + @Override public Set getLoanCompoundingDetails() { return null; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelPeriod.java index 3bd3892fb..0a7b8e9da 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelPeriod.java @@ -52,5 +52,6 @@ public interface LoanScheduleModelPeriod { void addPrincipalAmount(Money principalDue); void addInterestAmount(Money interestDue); + Set getLoanCompoundingDetails(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelRepaymentPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelRepaymentPeriod.java index edeeab4ff..138a41f9e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelRepaymentPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelRepaymentPeriod.java @@ -157,8 +157,9 @@ public final class LoanScheduleModelRepaymentPeriod implements LoanScheduleModel this.interestDue = this.interestDue.plus(interestDue); this.totalDue = this.totalDue.plus(principalDue); } + @Override public Set getLoanCompoundingDetails() { return this.loanCompoundingDetails; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/PaymentPeriodsInOneYearCalculator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/PaymentPeriodsInOneYearCalculator.java index 7568fb0d6..bb9058658 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/PaymentPeriodsInOneYearCalculator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/PaymentPeriodsInOneYearCalculator.java @@ -28,4 +28,4 @@ public interface PaymentPeriodsInOneYearCalculator { double calculatePortionOfRepaymentPeriodInterestChargingGrace(LocalDate repaymentPeriodStartDate, LocalDate scheduledDueDate, LocalDate interestChargedFromLocalDate, PeriodFrequencyType repaymentPeriodFrequencyType, Integer repaidEvery); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/ScheduledDateGenerator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/ScheduledDateGenerator.java index 9c8d025fc..c4b33fbd3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/ScheduledDateGenerator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/domain/ScheduledDateGenerator.java @@ -34,7 +34,7 @@ public interface ScheduledDateGenerator { LocalDate generateNextRepaymentDate(LocalDate lastRepaymentDate, LoanApplicationTerms loanApplicationTerms, boolean isFirstRepayment); - AdjustedDateDetailsDTO adjustRepaymentDate(LocalDate dueRepaymentPeriodDate, LoanApplicationTerms loanApplicationTerms, + AdjustedDateDetailsDTO adjustRepaymentDate(LocalDate dueRepaymentPeriodDate, LoanApplicationTerms loanApplicationTerms, final HolidayDetailDTO holidayDetailDTO); LocalDate getRepaymentPeriodDate(PeriodFrequencyType frequency, int repaidEvery, LocalDate startDate); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleAssembler.java index 9dd0273ab..ccbbe64c9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleAssembler.java @@ -212,8 +212,8 @@ public class LoanScheduleAssembler { element); final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod .fromInt(interestCalculationPeriodType); - Boolean allowPartialPeriodInterestCalcualtion = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, element); + Boolean allowPartialPeriodInterestCalcualtion = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, element); if (allowPartialPeriodInterestCalcualtion == null) { allowPartialPeriodInterestCalcualtion = loanProduct.getLoanProductRelatedDetail().isAllowPartialPeriodInterestCalcualtion(); } @@ -223,7 +223,8 @@ public class LoanScheduleAssembler { BigDecimal annualNominalInterestRate = BigDecimal.ZERO; if (interestRatePerPeriod != null) { - annualNominalInterestRate = this.aprCalculator.calculateFrom(interestRatePeriodFrequencyType, interestRatePerPeriod, numberOfRepayments, repaymentEvery, repaymentPeriodFrequencyType); + annualNominalInterestRate = this.aprCalculator.calculateFrom(interestRatePeriodFrequencyType, interestRatePerPeriod, + numberOfRepayments, repaymentEvery, repaymentPeriodFrequencyType); } // disbursement details @@ -250,13 +251,13 @@ public class LoanScheduleAssembler { * meeting freq multiples */ if ((loanType.isJLGAccount() || loanType.isGroupAccount()) && calendarId != null) { - calendar = this.calendarRepository.findById(calendarId) - .orElseThrow(() -> new CalendarNotFoundException(calendarId)); + calendar = this.calendarRepository.findById(calendarId).orElseThrow(() -> new CalendarNotFoundException(calendarId)); final PeriodFrequencyType meetingPeriodFrequency = CalendarUtils.getMeetingPeriodFrequencyType(calendar.getRecurrence()); validateRepaymentFrequencyIsSameAsMeetingFrequency(meetingPeriodFrequency.getValue(), repaymentFrequencyType, CalendarUtils.getInterval(calendar.getRecurrence()), repaymentEvery); } else { - if (repaymentPeriodFrequencyType == PeriodFrequencyType.MONTHS && nthDay != null && !nthDay.equals(NthDayType.INVALID.getValue())) { + if (repaymentPeriodFrequencyType == PeriodFrequencyType.MONTHS && nthDay != null + && !nthDay.equals(NthDayType.INVALID.getValue())) { LocalDate calendarStartDate = repaymentsStartingFromDate; if (calendarStartDate == null) { calendarStartDate = expectedDisbursementDate; @@ -280,16 +281,18 @@ public class LoanScheduleAssembler { */ final Long groupId = this.fromApiJsonHelper.extractLongNamed("groupId", element); Group group = null; - if(groupId != null){ + if (groupId != null) { group = this.groupRepository.findOneWithNotFoundDetection(groupId); } Boolean isSkipMeetingOnFirstDay = false; Integer numberOfDays = 0; boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); - if(isSkipRepaymentOnFirstMonthEnabled){ + if (isSkipRepaymentOnFirstMonthEnabled) { isSkipMeetingOnFirstDay = this.loanUtilService.isLoanRepaymentsSyncWithMeeting(group, calendar); - if(isSkipMeetingOnFirstDay) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } + if (isSkipMeetingOnFirstDay) { + numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); + } } if ((loanType.isJLGAccount() || loanType.isGroupAccount()) && calendar != null) { validateRepaymentsStartDateWithMeetingDates(calculatedRepaymentsStartingFromDate, calendar, isSkipMeetingOnFirstDay, @@ -309,15 +312,16 @@ public class LoanScheduleAssembler { // grace details final Integer graceOnPrincipalPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); - final Integer recurringMoratoriumOnPrincipalPeriods = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("recurringMoratoriumOnPrincipalPeriods", element); + final Integer recurringMoratoriumOnPrincipalPeriods = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed("recurringMoratoriumOnPrincipalPeriods", element); final Integer graceOnInterestPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element); final Integer graceOnInterestCharged = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); final LocalDate interestChargedFromDate = this.fromApiJsonHelper.extractLocalDateNamed("interestChargedFromDate", element); final Boolean isInterestChargedFromDateSameAsDisbursalDateEnabled = this.configurationDomainService .isInterestChargedFromDateSameAsDisbursementDate(); - final Integer graceOnArrearsAgeing = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element); + final Integer graceOnArrearsAgeing = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element); // other final BigDecimal inArrearsTolerance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element); @@ -325,8 +329,8 @@ public class LoanScheduleAssembler { final BigDecimal emiAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(LoanApiConstants.emiAmountParameterName, element); - final BigDecimal maxOutstandingBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanApiConstants.maxOutstandingBalanceParameterName, element); + final BigDecimal maxOutstandingBalance = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanApiConstants.maxOutstandingBalanceParameterName, element); final List disbursementDatas = fetchDisbursementData(element.getAsJsonObject()); @@ -360,11 +364,11 @@ public class LoanScheduleAssembler { expectedDisbursementDate); } else { LocalDate calendarStartDate = expectedDisbursementDate; - restCalendarInstance = createInterestRecalculationCalendarInstance(calendarStartDate, recalculationFrequencyType, - frequency, recalculationFrequencyNthDay, repeatsOnDay); + restCalendarInstance = createInterestRecalculationCalendarInstance(calendarStartDate, recalculationFrequencyType, frequency, + recalculationFrequencyNthDay, repeatsOnDay); } - compoundingMethod = InterestRecalculationCompoundingMethod.fromInt(loanProductInterestRecalculationDetails - .getInterestRecalculationCompoundingMethod()); + compoundingMethod = InterestRecalculationCompoundingMethod + .fromInt(loanProductInterestRecalculationDetails.getInterestRecalculationCompoundingMethod()); if (compoundingMethod.isCompoundingEnabled()) { Integer compoundingRepeatsOnDay = null; Integer recalculationCompoundingFrequencyNthDay = loanProductInterestRecalculationDetails.getCompoundingFrequencyOnDay(); @@ -392,10 +396,10 @@ public class LoanScheduleAssembler { List loanTermVariations = new ArrayList<>(); if (loanProduct.isLinkedToFloatingInterestRate()) { - final BigDecimal interestRateDiff = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanApiConstants.interestRateDifferentialParameterName, element); - final Boolean isFloatingInterestRate = this.fromApiJsonHelper.extractBooleanNamed( - LoanApiConstants.isFloatingInterestRateParameterName, element); + final BigDecimal interestRateDiff = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanApiConstants.interestRateDifferentialParameterName, element); + final Boolean isFloatingInterestRate = this.fromApiJsonHelper + .extractBooleanNamed(LoanApiConstants.isFloatingInterestRateParameterName, element); List baseLendingRatePeriods = null; try { baseLendingRatePeriods = this.floatingRatesReadPlatformService.retrieveBaseLendingRate().getRatePeriods(); @@ -437,19 +441,19 @@ public class LoanScheduleAssembler { final WorkingDays workingDays = this.workingDaysRepository.findOne(); HolidayDetailDTO detailDTO = new HolidayDetailDTO(isHolidayEnabled, holidays, workingDays); - return LoanApplicationTerms.assembleFrom(applicationCurrency, loanTermFrequency, loanTermPeriodFrequencyType, numberOfRepayments, repaymentEvery, repaymentPeriodFrequencyType, nthDay, weekDayType, amortizationMethod, interestMethod, interestRatePerPeriod, interestRatePeriodFrequencyType, annualNominalInterestRate, interestCalculationPeriodMethod, allowPartialPeriodInterestCalcualtion, principalMoney, expectedDisbursementDate, repaymentsStartingFromDate, - calculatedRepaymentsStartingFromDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, - interestChargedFromDate, inArrearsToleranceMoney, loanProduct.isMultiDisburseLoan(), emiAmount, disbursementDatas, - maxOutstandingBalance, graceOnArrearsAgeing, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, - recalculationFrequencyType, restCalendarInstance, compoundingMethod, compoundingCalendarInstance, compoundingFrequencyType, - principalThresholdForLastInstalment, installmentAmountInMultiplesOf, loanProduct.preCloseInterestCalculationStrategy(), - calendar, BigDecimal.ZERO, loanTermVariations, isInterestChargedFromDateSameAsDisbursalDateEnabled,numberOfDays, isSkipMeetingOnFirstDay, detailDTO, + calculatedRepaymentsStartingFromDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, + graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, inArrearsToleranceMoney, + loanProduct.isMultiDisburseLoan(), emiAmount, disbursementDatas, maxOutstandingBalance, graceOnArrearsAgeing, + daysInMonthType, daysInYearType, isInterestRecalculationEnabled, recalculationFrequencyType, restCalendarInstance, + compoundingMethod, compoundingCalendarInstance, compoundingFrequencyType, principalThresholdForLastInstalment, + installmentAmountInMultiplesOf, loanProduct.preCloseInterestCalculationStrategy(), calendar, BigDecimal.ZERO, + loanTermVariations, isInterestChargedFromDateSameAsDisbursalDateEnabled, numberOfDays, isSkipMeetingOnFirstDay, detailDTO, allowCompoundingOnEod, isEqualAmortization); -} + } private CalendarInstance createCalendarForSameAsRepayment(final Integer repaymentEvery, final PeriodFrequencyType repaymentPeriodFrequencyType, final LocalDate expectedDisbursementDate) { @@ -513,8 +517,8 @@ public class LoanScheduleAssembler { BigDecimal principal = null; if (jsonObject.has(LoanApiConstants.disbursementDateParameterName)) { - expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed( - LoanApiConstants.disbursementDateParameterName, jsonObject, dateFormat, locale); + expectedDisbursementDate = this.fromApiJsonHelper + .extractLocalDateNamed(LoanApiConstants.disbursementDateParameterName, jsonObject, dateFormat, locale); } if (jsonObject.has(LoanApiConstants.disbursementPrincipalParameterName) && jsonObject.get(LoanApiConstants.disbursementPrincipalParameterName).isJsonPrimitive() @@ -522,7 +526,8 @@ public class LoanScheduleAssembler { principal = jsonObject.getAsJsonPrimitive(LoanApiConstants.disbursementPrincipalParameterName).getAsBigDecimal(); } BigDecimal waivedChargeAmount = null; - disbursementDatas.add(new DisbursementData(null, expectedDisbursementDate, null, principal, null, null, waivedChargeAmount)); + disbursementDatas + .add(new DisbursementData(null, expectedDisbursementDate, null, principal, null, null, waivedChargeAmount)); i++; } while (i < disbursementDataArray.size()); } @@ -531,17 +536,17 @@ public class LoanScheduleAssembler { } private void validateRepaymentsStartDateWithMeetingDates(final LocalDate repaymentsStartingFromDate, final Calendar calendar, - boolean isSkipRepaymentOnFirstDayOfMonth, final Integer numberOfDays) { - if (repaymentsStartingFromDate != null - && !CalendarUtils.isValidRedurringDate(calendar.getRecurrence(), calendar.getStartDateLocalDate(), - repaymentsStartingFromDate, isSkipRepaymentOnFirstDayOfMonth, numberOfDays)) { + boolean isSkipRepaymentOnFirstDayOfMonth, final Integer numberOfDays) { + if (repaymentsStartingFromDate != null && !CalendarUtils.isValidRedurringDate(calendar.getRecurrence(), + calendar.getStartDateLocalDate(), repaymentsStartingFromDate, isSkipRepaymentOnFirstDayOfMonth, numberOfDays)) { final String errorMessage = "First repayment date '" + repaymentsStartingFromDate + "' do not fall on a meeting date"; throw new LoanApplicationDateException("first.repayment.date.do.not.match.meeting.date", errorMessage, repaymentsStartingFromDate); } } - public void validateDisbursementDateWithMeetingDates(final LocalDate expectedDisbursementDate, final Calendar calendar, Boolean isSkipRepaymentOnFirstMonth, Integer numberOfDays) { + public void validateDisbursementDateWithMeetingDates(final LocalDate expectedDisbursementDate, final Calendar calendar, + Boolean isSkipRepaymentOnFirstMonth, Integer numberOfDays) { // disbursement date should fall on a meeting date if (calendar != null && !calendar.isValidRecurringDate(expectedDisbursementDate, isSkipRepaymentOnFirstMonth, numberOfDays)) { final String errorMessage = "Expected disbursement date '" + expectedDisbursementDate + "' do not fall on a meeting date"; @@ -616,7 +621,6 @@ public class LoanScheduleAssembler { final Set loanCharges = this.loanChargeAssembler.fromParsedJson(element, disbursementDetails); - final RoundingMode roundingMode = MoneyHelper.getRoundingMode(); final MathContext mc = new MathContext(8, roundingMode); HolidayDetailDTO detailDTO = new HolidayDetailDTO(isHolidayEnabled, holidays, workingDays); @@ -628,7 +632,8 @@ public class LoanScheduleAssembler { .create(InterestMethod.DECLINING_BALANCE); LoanScheduleModel loanSchedule = decliningLoanScheduleGenerator.generate(mc, loanApplicationTerms, loanCharges, detailDTO); - loanApplicationTerms.updateTotalInterestDue(Money.of(loanApplicationTerms.getCurrency(), loanSchedule.getTotalInterestCharged())); + loanApplicationTerms + .updateTotalInterestDue(Money.of(loanApplicationTerms.getCurrency(), loanSchedule.getTotalInterestCharged())); } loanScheduleGenerator = this.loanScheduleFactory.create(InterestMethod.FLAT); @@ -646,8 +651,8 @@ public class LoanScheduleAssembler { final MathContext mc = new MathContext(8, roundingMode); final boolean isHolidayEnabled = this.configurationDomainService.isRescheduleRepaymentsOnHolidaysEnabled(); - final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(officeId, loanApplicationTerms - .getExpectedDisbursementDate().toDate(), HolidayStatusType.ACTIVE.getValue()); + final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(officeId, + loanApplicationTerms.getExpectedDisbursementDate().toDate(), HolidayStatusType.ACTIVE.getValue()); final WorkingDays workingDays = this.workingDaysRepository.findOne(); final LoanScheduleGenerator loanScheduleGenerator = this.loanScheduleFactory.create(loanApplicationTerms.getInterestMethod()); @@ -664,8 +669,8 @@ public class LoanScheduleAssembler { final MathContext mc = new MathContext(8, roundingMode); final boolean isHolidayEnabled = this.configurationDomainService.isRescheduleRepaymentsOnHolidaysEnabled(); - final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(officeId, loanApplicationTerms - .getExpectedDisbursementDate().toDate(), HolidayStatusType.ACTIVE.getValue()); + final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(officeId, + loanApplicationTerms.getExpectedDisbursementDate().toDate(), HolidayStatusType.ACTIVE.getValue()); final WorkingDays workingDays = this.workingDaysRepository.findOne(); HolidayDetailDTO holidayDetailDTO = new HolidayDetailDTO(isHolidayEnabled, holidays, workingDays); @@ -688,13 +693,12 @@ public class LoanScheduleAssembler { newVariations = retainVariations; } variations.addAll(newVariations); - //Collections.sort(variations, new LoanTermVariationsComparator()); + // Collections.sort(variations, new LoanTermVariationsComparator()); /* * List loanTermVariationsDatas = new - * ArrayList<>(); - * loanTermVariationsDatas.addAll(loanApplicationTerms.getLoanTermVariations - * ().getExceptionData()); loanApplicationTerms = + * ArrayList<>(); loanTermVariationsDatas.addAll(loanApplicationTerms. + * getLoanTermVariations ().getExceptionData()); loanApplicationTerms = * LoanApplicationTerms.assembleFrom(loanApplicationTerms, * loanTermVariationsDatas); */ @@ -823,9 +827,11 @@ public class LoanScheduleAssembler { Boolean isSkipRepaymentOnFirstMonth = false; Integer numberOfDays = 0; boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); - if(isSkipRepaymentOnFirstMonthEnabled){ + if (isSkipRepaymentOnFirstMonthEnabled) { isSkipRepaymentOnFirstMonth = this.loanUtilService.isLoanRepaymentsSyncWithMeeting(loan.group(), loanCalendar); - if(isSkipRepaymentOnFirstMonth) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } + if (isSkipRepaymentOnFirstMonth) { + numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); + } } final Integer minGap = installmentConfig.getMinimumGap(); final Integer maxGap = installmentConfig.getMaximumGap(); @@ -835,18 +841,12 @@ public class LoanScheduleAssembler { int gap = Days.daysBetween(previousDate, duedate).getDays(); previousDate = duedate; if (gap < minGap || (maxGap != null && gap > maxGap)) { - baseDataValidator - .reset() - .value(duedate) - .failWithCodeNoParameterAddedToErrorCode("variable.schedule.date.must.be.in.min.max.range", - "Loan schedule date invalid"); - } else if (loanCalendar != null && !actualDueDates.contains(duedate) && !loanCalendar.isValidRecurringDate(duedate, - isSkipRepaymentOnFirstMonth, numberOfDays)) { - baseDataValidator - .reset() - .value(duedate) - .failWithCodeNoParameterAddedToErrorCode("variable.schedule.date.not.meeting.date", - "Loan schedule date not in sync with meeting date"); + baseDataValidator.reset().value(duedate).failWithCodeNoParameterAddedToErrorCode( + "variable.schedule.date.must.be.in.min.max.range", "Loan schedule date invalid"); + } else if (loanCalendar != null && !actualDueDates.contains(duedate) + && !loanCalendar.isValidRecurringDate(duedate, isSkipRepaymentOnFirstMonth, numberOfDays)) { + baseDataValidator.reset().value(duedate).failWithCodeNoParameterAddedToErrorCode("variable.schedule.date.not.meeting.date", + "Loan schedule date not in sync with meeting date"); } } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } @@ -892,11 +892,11 @@ public class LoanScheduleAssembler { switch (loanTermVariations.getTermType()) { case DUE_DATE: if (amountVariations.containsKey(loanTermVariations.fetchTermApplicaDate())) { - amountVariations.get(loanTermVariations.fetchTermApplicaDate()).setTermApplicableFrom( - loanTermVariations.getDateValue()); + amountVariations.get(loanTermVariations.fetchTermApplicaDate()) + .setTermApplicableFrom(loanTermVariations.getDateValue()); } else if (insertVariations.containsKey(loanTermVariations.fetchTermApplicaDate())) { - insertVariations.get(loanTermVariations.fetchTermApplicaDate()).setTermApplicableFrom( - loanTermVariations.getDateValue()); + insertVariations.get(loanTermVariations.fetchTermApplicaDate()) + .setTermApplicableFrom(loanTermVariations.getDateValue()); retain = false; } if (dueDateVariations.containsKey(loanTermVariations.fetchTermApplicaDate())) { @@ -998,12 +998,12 @@ public class LoanScheduleAssembler { } boolean isSpecificToInstallment = true; if (isInsertInstallment) { - LoanTermVariations data = new LoanTermVariations(LoanTermVariationType.INSERT_INSTALLMENT.getValue(), dueDate, - decimalValue, modifiedDuedate, isSpecificToInstallment, loan); + LoanTermVariations data = new LoanTermVariations(LoanTermVariationType.INSERT_INSTALLMENT.getValue(), dueDate, decimalValue, + modifiedDuedate, isSpecificToInstallment, loan); loanTermVariations.add(data); } else if (isDeleteInstallment) { - LoanTermVariations data = new LoanTermVariations(LoanTermVariationType.DELETE_INSTALLMENT.getValue(), dueDate, - decimalValue, modifiedDuedate, isSpecificToInstallment, loan); + LoanTermVariations data = new LoanTermVariations(LoanTermVariationType.DELETE_INSTALLMENT.getValue(), dueDate, decimalValue, + modifiedDuedate, isSpecificToInstallment, loan); loanTermVariations.add(data); } else { if (modifiedDuedate != null) { @@ -1059,7 +1059,7 @@ public class LoanScheduleAssembler { refernceDateForCalculatingFirstRepaymentDate, repaymentPeriodFrequencyType, minimumDaysBetweenDisbursalAndFirstRepayment, calendar); - }/*** Individual or group account, or JLG not linked to a meeting ***/ + } /*** Individual or group account, or JLG not linked to a meeting ***/ else { LocalDate dateBasedOnRepaymentFrequency; // Derive the first repayment date as greater date among @@ -1072,11 +1072,12 @@ public class LoanScheduleAssembler { dateBasedOnRepaymentFrequency = expectedDisbursementDate.plusWeeks(repaymentEvery); } else if (repaymentPeriodFrequencyType.isMonthly()) { dateBasedOnRepaymentFrequency = expectedDisbursementDate.plusMonths(repaymentEvery); - }/** yearly loan **/ + } /** yearly loan **/ else { dateBasedOnRepaymentFrequency = expectedDisbursementDate.plusYears(repaymentEvery); } - derivedFirstRepayment = dateBasedOnRepaymentFrequency.isAfter(dateBasedOnMinimumDaysBetweenDisbursalAndFirstRepayment) ? dateBasedOnRepaymentFrequency + derivedFirstRepayment = dateBasedOnRepaymentFrequency.isAfter(dateBasedOnMinimumDaysBetweenDisbursalAndFirstRepayment) + ? dateBasedOnRepaymentFrequency : dateBasedOnMinimumDaysBetweenDisbursalAndFirstRepayment; } @@ -1092,16 +1093,18 @@ public class LoanScheduleAssembler { final LocalDate derivedFirstRepayment = CalendarUtils.getFirstRepaymentMeetingDate(calendar, refernceDateForCalculatingFirstRepaymentDate, repaymentEvery, frequency, isMeetingSkipOnFirstDayOfMonth, numberOfDays); final LocalDate minimumFirstRepaymentDate = expectedDisbursementDate.plusDays(minimumDaysBetweenDisbursalAndFirstRepayment); - return minimumFirstRepaymentDate.isBefore(derivedFirstRepayment) ? derivedFirstRepayment : deriveFirstRepaymentDateForLoans( - repaymentEvery, expectedDisbursementDate, derivedFirstRepayment, repaymentPeriodFrequencyType, - minimumDaysBetweenDisbursalAndFirstRepayment, calendar); + return minimumFirstRepaymentDate.isBefore(derivedFirstRepayment) ? derivedFirstRepayment + : deriveFirstRepaymentDateForLoans(repaymentEvery, expectedDisbursementDate, derivedFirstRepayment, + repaymentPeriodFrequencyType, minimumDaysBetweenDisbursalAndFirstRepayment, calendar); } private void validateMinimumDaysBetweenDisbursalAndFirstRepayment(final LocalDate disbursalDate, final LocalDate firstRepaymentDate, final Integer minimumDaysBetweenDisbursalAndFirstRepayment) { final LocalDate minimumFirstRepaymentDate = disbursalDate.plusDays(minimumDaysBetweenDisbursalAndFirstRepayment); - if (firstRepaymentDate.isBefore(minimumFirstRepaymentDate)) { throw new MinDaysBetweenDisbursalAndFirstRepaymentViolationException( - disbursalDate, firstRepaymentDate, minimumDaysBetweenDisbursalAndFirstRepayment); } + if (firstRepaymentDate.isBefore(minimumFirstRepaymentDate)) { + throw new MinDaysBetweenDisbursalAndFirstRepaymentViolationException(disbursalDate, firstRepaymentDate, + minimumDaysBetweenDisbursalAndFirstRepayment); + } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleCalculationPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleCalculationPlatformServiceImpl.java index b62aaaa59..0a9bab8de 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleCalculationPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleCalculationPlatformServiceImpl.java @@ -137,7 +137,6 @@ public class LoanScheduleCalculationPlatformServiceImpl implements LoanScheduleC return this.loanScheduleAssembler.assembleLoanScheduleFrom(query.parsedJson()); } - @Override public void updateFutureSchedule(LoanScheduleData loanScheduleData, final Long loanId) { @@ -148,7 +147,9 @@ public class LoanScheduleCalculationPlatformServiceImpl implements LoanScheduleC .determineProcessor(loan.transactionProcessingStrategy()); if (!loan.repaymentScheduleDetail().isInterestRecalculationEnabled() || loan.isNpa() || !loan.status().isActive() - || !loanRepaymentScheduleTransactionProcessor.isInterestFirstRepaymentScheduleTransactionProcessor()) { return; } + || !loanRepaymentScheduleTransactionProcessor.isInterestFirstRepaymentScheduleTransactionProcessor()) { + return; + } if (loan.loanProduct().isMultiDisburseLoan()) { BigDecimal disbursedAmount = loan.getDisbursedAmount(); @@ -159,7 +160,7 @@ public class LoanScheduleCalculationPlatformServiceImpl implements LoanScheduleC MonetaryCurrency currency = loan.getCurrency(); Money totalPrincipal = Money.zero(currency); final List futureInstallments = new ArrayList<>(); - List installments = loan.getRepaymentScheduleInstallments() ; + List installments = loan.getRepaymentScheduleInstallments(); for (final LoanRepaymentScheduleInstallment currentInstallment : installments) { if (currentInstallment.isNotFullyPaidOff()) { if (!currentInstallment.getDueDate().isAfter(today)) { @@ -169,10 +170,9 @@ public class LoanScheduleCalculationPlatformServiceImpl implements LoanScheduleC } LoanApplicationTerms loanApplicationTerms = constructLoanApplicationTerms(loan); LoanRepaymentScheduleInstallment loanRepaymentScheduleInstallment = this.loanScheduleAssembler.calculatePrepaymentAmount(currency, - today, loanApplicationTerms, loan, loan.getOfficeId(), - loanRepaymentScheduleTransactionProcessor); - Money totalAmount = totalPrincipal.plus(loanRepaymentScheduleInstallment.getFeeChargesOutstanding(currency)).plus( - loanRepaymentScheduleInstallment.getPenaltyChargesOutstanding(currency)); + today, loanApplicationTerms, loan, loan.getOfficeId(), loanRepaymentScheduleTransactionProcessor); + Money totalAmount = totalPrincipal.plus(loanRepaymentScheduleInstallment.getFeeChargesOutstanding(currency)) + .plus(loanRepaymentScheduleInstallment.getPenaltyChargesOutstanding(currency)); Money interestDue = Money.zero(currency); if (loanRepaymentScheduleInstallment.isInterestDue(currency)) { interestDue = loanRepaymentScheduleInstallment.getInterestOutstanding(currency); @@ -197,9 +197,9 @@ public class LoanScheduleCalculationPlatformServiceImpl implements LoanScheduleC for (LoanSchedulePeriodData periodData : periodDatas) { if ((periodData.periodDueDate().isEqual(today) || periodData.periodDueDate().isAfter(today)) && isNewPaymentRequired) { LoanSchedulePeriodData loanSchedulePeriodData = LoanSchedulePeriodData.repaymentOnlyPeriod(periodData.periodNumber(), - periodData.periodFromDate(), periodData.periodDueDate(), totalPrincipal.getAmount(), periodData - .principalLoanBalanceOutstanding(), interestDue.getAmount(), loanRepaymentScheduleInstallment - .getFeeChargesCharged(currency).getAmount(), + periodData.periodFromDate(), periodData.periodDueDate(), totalPrincipal.getAmount(), + periodData.principalLoanBalanceOutstanding(), interestDue.getAmount(), + loanRepaymentScheduleInstallment.getFeeChargesCharged(currency).getAmount(), loanRepaymentScheduleInstallment.getPenaltyChargesCharged(currency).getAmount(), totalAmount.getAmount(), totalPrincipal.plus(interestDue).getAmount()); futureInstallments.add(loanSchedulePeriodData); @@ -266,9 +266,10 @@ public class LoanScheduleCalculationPlatformServiceImpl implements LoanScheduleC CurrencyData currencyData = this.currencyReadPlatformService.retrieveCurrency(currency.getCode()); - LoanScheduleData scheduleData = new LoanScheduleData(currencyData, installmentData, loan.getLoanRepaymentScheduleDetail() - .getNumberOfRepayments(), principal.getAmount(), principal.getAmount(), totalInterest.getAmount(), totalCharge.getAmount(), - totalPenalty.getAmount(), principal.plus(totalCharge).plus(totalInterest).plus(totalPenalty).getAmount()); + LoanScheduleData scheduleData = new LoanScheduleData(currencyData, installmentData, + loan.getLoanRepaymentScheduleDetail().getNumberOfRepayments(), principal.getAmount(), principal.getAmount(), + totalInterest.getAmount(), totalCharge.getAmount(), totalPenalty.getAmount(), + principal.plus(totalCharge).plus(totalInterest).plus(totalPenalty).getAmount()); return scheduleData; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryReadPlatformServiceImpl.java old mode 100755 new mode 100644 index 6aed23c43..86b349d84 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryReadPlatformServiceImpl.java @@ -60,7 +60,7 @@ public class LoanScheduleHistoryReadPlatformServiceImpl implements LoanScheduleH @Override public Integer fetchCurrentVersionNumber(Long loanId) { final String sql = "select MAX(lrs.version) from m_loan_repayment_schedule_history lrs where lrs.loan_id = ?"; - Integer max = this.jdbcTemplate.queryForObject(sql, new Object[]{loanId}, Integer.class); + Integer max = this.jdbcTemplate.queryForObject(sql, new Object[] { loanId }, Integer.class); return ObjectUtils.defaultIfNull(max, 0); } @@ -105,8 +105,8 @@ public class LoanScheduleHistoryReadPlatformServiceImpl implements LoanScheduleH public String schema() { StringBuilder stringBuilder = new StringBuilder(200); stringBuilder.append(" ls.installment as period, ls.fromdate as fromDate, ls.duedate as dueDate, "); - stringBuilder - .append("ls.principal_amount as principalDue, ls.interest_amount as interestDue, ls.fee_charges_amount as feeChargesDue, ls.penalty_charges_amount as penaltyChargesDue "); + stringBuilder.append( + "ls.principal_amount as principalDue, ls.interest_amount as interestDue, ls.fee_charges_amount as feeChargesDue, ls.penalty_charges_amount as penaltyChargesDue "); stringBuilder.append(" from m_loan_repayment_schedule_history ls "); return stringBuilder.toString(); } @@ -149,15 +149,15 @@ public class LoanScheduleHistoryReadPlatformServiceImpl implements LoanScheduleH for (DisbursementData data : disbursementData) { if (fromDate.equals(this.disbursement.disbursementDate()) && data.disbursementDate().equals(fromDate)) { principal = principal.add(data.amount()); - final LoanSchedulePeriodData periodData = LoanSchedulePeriodData.disbursementOnlyPeriod( - data.disbursementDate(), data.amount(), this.totalFeeChargesDueAtDisbursement, data.isDisbursed()); + final LoanSchedulePeriodData periodData = LoanSchedulePeriodData.disbursementOnlyPeriod(data.disbursementDate(), + data.amount(), this.totalFeeChargesDueAtDisbursement, data.isDisbursed()); periods.add(periodData); this.outstandingLoanPrincipalBalance = this.outstandingLoanPrincipalBalance.add(data.amount()); } else if (data.isDueForDisbursement(fromDate, dueDate) && this.outstandingLoanPrincipalBalance.compareTo(BigDecimal.ZERO) > 0) { principal = principal.add(data.amount()); - final LoanSchedulePeriodData periodData = LoanSchedulePeriodData.disbursementOnlyPeriod( - data.disbursementDate(), data.amount(), BigDecimal.ZERO, data.isDisbursed()); + final LoanSchedulePeriodData periodData = LoanSchedulePeriodData.disbursementOnlyPeriod(data.disbursementDate(), + data.amount(), BigDecimal.ZERO, data.isDisbursed()); periods.add(periodData); this.outstandingLoanPrincipalBalance = this.outstandingLoanPrincipalBalance.add(data.amount()); } @@ -186,8 +186,8 @@ public class LoanScheduleHistoryReadPlatformServiceImpl implements LoanScheduleH final BigDecimal penaltyChargesExpectedDue = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "penaltyChargesDue"); totalPenaltyChargesCharged = totalPenaltyChargesCharged.plus(penaltyChargesExpectedDue); - final BigDecimal totalExpectedCostOfLoanForPeriod = interestExpectedDue.add(feeChargesExpectedDue).add( - penaltyChargesExpectedDue); + final BigDecimal totalExpectedCostOfLoanForPeriod = interestExpectedDue.add(feeChargesExpectedDue) + .add(penaltyChargesExpectedDue); final BigDecimal totalDueForPeriod = principalDue.add(totalExpectedCostOfLoanForPeriod); @@ -209,9 +209,9 @@ public class LoanScheduleHistoryReadPlatformServiceImpl implements LoanScheduleH periods.add(periodData); } - return new LoanScheduleData(this.currency, periods, loanTermInDays, totalPrincipalDisbursed, - totalPrincipalExpected.getAmount(), totalInterestCharged.getAmount(), totalFeeChargesCharged.getAmount(), - totalPenaltyChargesCharged.getAmount(), totalRepaymentExpected.getAmount()); + return new LoanScheduleData(this.currency, periods, loanTermInDays, totalPrincipalDisbursed, totalPrincipalExpected.getAmount(), + totalInterestCharged.getAmount(), totalFeeChargesCharged.getAmount(), totalPenaltyChargesCharged.getAmount(), + totalRepaymentExpected.getAmount()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryWritePlatformService.java old mode 100755 new mode 100644 index 92c077557..4e360d95a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryWritePlatformService.java @@ -26,9 +26,8 @@ import org.apache.fineract.portfolio.loanaccount.rescheduleloan.domain.LoanResch public interface LoanScheduleHistoryWritePlatformService { - List createLoanScheduleArchive( - final List repaymentScheduleInstallments, final Loan loan, - final LoanRescheduleRequest loanRescheduleRequest); + List createLoanScheduleArchive(final List repaymentScheduleInstallments, + final Loan loan, final LoanRescheduleRequest loanRescheduleRequest); void createAndSaveLoanScheduleArchive(List repaymentScheduleInstallments, Loan loan, LoanRescheduleRequest loanRescheduleRequest); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryWritePlatformServiceImpl.java old mode 100755 new mode 100644 index 896ec9cf3..354c18f3e --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/loanschedule/service/LoanScheduleHistoryWritePlatformServiceImpl.java @@ -97,8 +97,8 @@ public class LoanScheduleHistoryWritePlatformServiceImpl implements LoanSchedule @Override public void createAndSaveLoanScheduleArchive(List repaymentScheduleInstallments, Loan loan, LoanRescheduleRequest loanRescheduleRequest) { - List loanRepaymentScheduleHistoryList = createLoanScheduleArchive(repaymentScheduleInstallments, - loan, loanRescheduleRequest); + List loanRepaymentScheduleHistoryList = createLoanScheduleArchive(repaymentScheduleInstallments, loan, + loanRescheduleRequest); this.loanRepaymentScheduleHistoryRepository.saveAll(loanRepaymentScheduleHistoryList); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/RescheduleLoansApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/RescheduleLoansApiConstants.java index 78845b968..1d190dfe7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/RescheduleLoansApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/RescheduleLoansApiConstants.java @@ -59,11 +59,9 @@ public class RescheduleLoansApiConstants { // approve action request parameters public static final String approvedOnDateParam = "approvedOnDate"; - public static final Set APPROVE_REQUEST_DATA_PARAMETERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(localeParamName, dateFormatParamName, - approvedOnDateParam))); + public static final Set APPROVE_REQUEST_DATA_PARAMETERS = Collections + .unmodifiableSet(new HashSet<>(Arrays.asList(localeParamName, dateFormatParamName, approvedOnDateParam))); - public static final Set commandParams = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(allCommandParamName, approveCommandParamName, - pendingCommandParamName, rejectCommandParamName))); + public static final Set commandParams = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList(allCommandParamName, approveCommandParamName, pendingCommandParamName, rejectCommandParamName))); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/api/RescheduleLoansApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/api/RescheduleLoansApiResource.java index a912fa196..a17e4cba7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/api/RescheduleLoansApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/api/RescheduleLoansApiResource.java @@ -178,29 +178,38 @@ public class RescheduleLoansApiResource { this.platformSecurityContext.authenticatedUser().validateHasReadPermission(RescheduleLoansApiConstants.ENTITY_NAME); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - if (StringUtils.isNotBlank(command) && !RescheduleLoansApiConstants.commandParams.contains(command.toLowerCase())) { throw new UnrecognizedQueryParamException( - "command", command, new Object[] { RescheduleLoansApiConstants.allCommandParamName, - RescheduleLoansApiConstants.pendingCommandParamName, RescheduleLoansApiConstants.approveCommandParamName, - RescheduleLoansApiConstants.rejectCommandParamName }); } + if (StringUtils.isNotBlank(command) && !RescheduleLoansApiConstants.commandParams.contains(command.toLowerCase())) { + throw new UnrecognizedQueryParamException("command", command, + new Object[] { RescheduleLoansApiConstants.allCommandParamName, RescheduleLoansApiConstants.pendingCommandParamName, + RescheduleLoansApiConstants.approveCommandParamName, RescheduleLoansApiConstants.rejectCommandParamName }); + } final List loanRescheduleRequestsData = this.loanRescheduleRequestReadPlatformService .retrieveAllRescheduleRequests(command); return this.loanRescheduleRequestToApiJsonSerializer.serialize(settings, loanRescheduleRequestsData); } - /*@GET - @Path("{scheduleId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveTemplate(@Context final UriInfo uriInfo) { - - this.platformSecurityContext.authenticatedUser().validateHasReadPermission(RescheduleLoansApiConstants.ENTITY_NAME); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - - LoanRescheduleRequestData loanRescheduleReasons = null; - loanRescheduleReasons = this.loanRescheduleRequestReadPlatformService - .retrieveAllRescheduleReasons(RescheduleLoansApiConstants.LOAN_RESCHEDULE_REASON); - - return this.loanRescheduleRequestToApiJsonSerializer.serialize(settings, loanRescheduleReasons); - }*/ + /* + * @GET + * + * @Path("{scheduleId}") + * + * @Consumes({ MediaType.APPLICATION_JSON }) + * + * @Produces({ MediaType.APPLICATION_JSON }) public String + * retrieveTemplate(@Context final UriInfo uriInfo) { + * + * this.platformSecurityContext.authenticatedUser(). + * validateHasReadPermission(RescheduleLoansApiConstants.ENTITY_NAME); final + * ApiRequestJsonSerializationSettings settings = + * this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + * + * LoanRescheduleRequestData loanRescheduleReasons = null; + * loanRescheduleReasons = this.loanRescheduleRequestReadPlatformService + * .retrieveAllRescheduleReasons(RescheduleLoansApiConstants. + * LOAN_RESCHEDULE_REASON); + * + * return this.loanRescheduleRequestToApiJsonSerializer.serialize(settings, + * loanRescheduleReasons); } + */ } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestData.java index 4655b7aa5..7cd0d9946 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestData.java @@ -47,7 +47,9 @@ public class LoanRescheduleRequestData { /** * LoanRescheduleRequestData constructor - * @param loanTermVariationsData TODO + * + * @param loanTermVariationsData + * TODO **/ private LoanRescheduleRequestData(Long id, Long loanId, LoanRescheduleRequestStatusEnumData statusEnum, Integer rescheduleFromInstallment, LocalDate rescheduleFromDate, CodeValueData rescheduleReasonCodeValue, @@ -67,12 +69,13 @@ public class LoanRescheduleRequestData { this.loanAccountNumber = loanAccountNumber; this.clientId = clientId; this.recalculateInterest = recalculateInterest; - this.rescheduleReasons = rescheduleReasons ; + this.rescheduleReasons = rescheduleReasons; this.loanTermVariationsData = loanTermVariationsData; } /** - * @param loanTermVariationsData TODO + * @param loanTermVariationsData + * TODO * @return an instance of the LoanRescheduleRequestData class **/ public static LoanRescheduleRequestData instance(Long id, Long loanId, LoanRescheduleRequestStatusEnumData statusEnum, @@ -122,6 +125,7 @@ public class LoanRescheduleRequestData { return new LoanRescheduleRequestData(id, loanId, statusEnum, clientName, loanAccountNumber, clientId, rescheduleFromDate, rescheduleReasonCodeValue); } + /** * @return the id */ diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestDataValidator.java index 0d6fb73a0..883a263b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestDataValidator.java @@ -48,18 +48,15 @@ import org.springframework.stereotype.Component; public class LoanRescheduleRequestDataValidator { private final FromJsonHelper fromJsonHelper; - private static final Set CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - RescheduleLoansApiConstants.localeParamName, RescheduleLoansApiConstants.dateFormatParamName, - RescheduleLoansApiConstants.graceOnPrincipalParamName, - RescheduleLoansApiConstants.recurringMoratoriumOnPrincipalPeriodsParamName, - RescheduleLoansApiConstants.graceOnInterestParamName, RescheduleLoansApiConstants.extraTermsParamName, - RescheduleLoansApiConstants.rescheduleFromDateParamName, - RescheduleLoansApiConstants.newInterestRateParamName, - RescheduleLoansApiConstants.rescheduleReasonIdParamName, - RescheduleLoansApiConstants.rescheduleReasonCommentParamName, - RescheduleLoansApiConstants.submittedOnDateParamName, RescheduleLoansApiConstants.loanIdParamName, - RescheduleLoansApiConstants.adjustedDueDateParamName, - RescheduleLoansApiConstants.recalculateInterestParamName)); + private static final Set CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(RescheduleLoansApiConstants.localeParamName, RescheduleLoansApiConstants.dateFormatParamName, + RescheduleLoansApiConstants.graceOnPrincipalParamName, + RescheduleLoansApiConstants.recurringMoratoriumOnPrincipalPeriodsParamName, + RescheduleLoansApiConstants.graceOnInterestParamName, RescheduleLoansApiConstants.extraTermsParamName, + RescheduleLoansApiConstants.rescheduleFromDateParamName, RescheduleLoansApiConstants.newInterestRateParamName, + RescheduleLoansApiConstants.rescheduleReasonIdParamName, RescheduleLoansApiConstants.rescheduleReasonCommentParamName, + RescheduleLoansApiConstants.submittedOnDateParamName, RescheduleLoansApiConstants.loanIdParamName, + RescheduleLoansApiConstants.adjustedDueDateParamName, RescheduleLoansApiConstants.recalculateInterestParamName)); private static final Set REJECT_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(RescheduleLoansApiConstants.localeParamName, RescheduleLoansApiConstants.dateFormatParamName, @@ -88,12 +85,11 @@ public class LoanRescheduleRequestDataValidator { if (StringUtils.isBlank(jsonString)) { throw new InvalidJsonException(); } final Type typeToken = new TypeToken>() {}.getType(); - this.fromJsonHelper - .checkForUnsupportedParameters(typeToken, jsonString, CREATE_REQUEST_DATA_PARAMETERS); + this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, CREATE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors).resource(StringUtils - .lowerCase(RescheduleLoansApiConstants.ENTITY_NAME)); + final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors) + .resource(StringUtils.lowerCase(RescheduleLoansApiConstants.ENTITY_NAME)); final JsonElement jsonElement = jsonCommand.parsedJson(); @@ -114,17 +110,17 @@ public class LoanRescheduleRequestDataValidator { .failWithCode("before.loan.disbursement.date", "Submission date cannot be before the loan disbursement date"); } - final LocalDate rescheduleFromDate = this.fromJsonHelper.extractLocalDateNamed( - RescheduleLoansApiConstants.rescheduleFromDateParamName, jsonElement); + final LocalDate rescheduleFromDate = this.fromJsonHelper + .extractLocalDateNamed(RescheduleLoansApiConstants.rescheduleFromDateParamName, jsonElement); dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleFromDateParamName).value(rescheduleFromDate).notNull(); - final Integer graceOnPrincipal = this.fromJsonHelper.extractIntegerWithLocaleNamed( - RescheduleLoansApiConstants.graceOnPrincipalParamName, jsonElement); - dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.graceOnPrincipalParamName).value(graceOnPrincipal) - .ignoreIfNull().integerGreaterThanZero(); + final Integer graceOnPrincipal = this.fromJsonHelper + .extractIntegerWithLocaleNamed(RescheduleLoansApiConstants.graceOnPrincipalParamName, jsonElement); + dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.graceOnPrincipalParamName).value(graceOnPrincipal).ignoreIfNull() + .integerGreaterThanZero(); - final Integer graceOnInterest = this.fromJsonHelper.extractIntegerWithLocaleNamed( - RescheduleLoansApiConstants.graceOnInterestParamName, jsonElement); + final Integer graceOnInterest = this.fromJsonHelper + .extractIntegerWithLocaleNamed(RescheduleLoansApiConstants.graceOnInterestParamName, jsonElement); dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.graceOnInterestParamName).value(graceOnInterest).ignoreIfNull() .integerGreaterThanZero(); @@ -138,8 +134,8 @@ public class LoanRescheduleRequestDataValidator { dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleReasonIdParamName).value(rescheduleReasonId).notNull() .integerGreaterThanZero(); - final String rescheduleReasonComment = this.fromJsonHelper.extractStringNamed( - RescheduleLoansApiConstants.rescheduleReasonCommentParamName, jsonElement); + final String rescheduleReasonComment = this.fromJsonHelper + .extractStringNamed(RescheduleLoansApiConstants.rescheduleReasonCommentParamName, jsonElement); dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleReasonCommentParamName).value(rescheduleReasonComment) .ignoreIfNull().notExceedingLengthOf(500); @@ -147,11 +143,8 @@ public class LoanRescheduleRequestDataValidator { jsonElement); if (adjustedDueDate != null && rescheduleFromDate != null && adjustedDueDate.isBefore(rescheduleFromDate)) { - dataValidatorBuilder - .reset() - .parameter(RescheduleLoansApiConstants.rescheduleFromDateParamName) - .failWithCode("adjustedDueDate.before.rescheduleFromDate", - "Adjusted due date cannot be before the reschedule from date"); + dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rescheduleFromDateParamName).failWithCode( + "adjustedDueDate.before.rescheduleFromDate", "Adjusted due date cannot be before the reschedule from date"); } // at least one of the following must be provided => graceOnPrincipal, @@ -179,20 +172,21 @@ public class LoanRescheduleRequestDataValidator { } - if(loan.isMultiDisburmentLoan()) { - dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode(RescheduleLoansApiConstants.resheduleForMultiDisbursementNotSupportedErrorCode, + if (loan.isMultiDisburmentLoan()) { + dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode( + RescheduleLoansApiConstants.resheduleForMultiDisbursementNotSupportedErrorCode, "Loan rescheduling is not supported for multidisbursement loans"); } - if(loan.isInterestRecalculationEnabledForProduct()) { - dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode(RescheduleLoansApiConstants.resheduleWithInterestRecalculationNotSupportedErrorCode, + if (loan.isInterestRecalculationEnabledForProduct()) { + dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode( + RescheduleLoansApiConstants.resheduleWithInterestRecalculationNotSupportedErrorCode, "Loan rescheduling is not supported for the loan product with interest recalculation enabled"); } validateForOverdueCharges(dataValidatorBuilder, loan, installment); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - private void validateForOverdueCharges(DataValidatorBuilder dataValidatorBuilder, final Loan loan, final LoanRepaymentScheduleInstallment installment) { if (installment != null) { @@ -223,8 +217,8 @@ public class LoanRescheduleRequestDataValidator { this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, APPROVE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors).resource(StringUtils - .lowerCase(RescheduleLoansApiConstants.ENTITY_NAME)); + final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors) + .resource(StringUtils.lowerCase(RescheduleLoansApiConstants.ENTITY_NAME)); final JsonElement jsonElement = jsonCommand.parsedJson(); @@ -233,16 +227,15 @@ public class LoanRescheduleRequestDataValidator { dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.approvedOnDateParam).value(approvedOnDate).notNull(); if (approvedOnDate != null && loanRescheduleRequest.getSubmittedOnDate().isAfter(approvedOnDate)) { - dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.approvedOnDateParam) - .failWithCode("before.submission.date", "Approval date cannot be before the request submission date."); + dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.approvedOnDateParam).failWithCode("before.submission.date", + "Approval date cannot be before the request submission date."); } LoanRescheduleRequestStatusEnumData loanRescheduleRequestStatusEnumData = LoanRescheduleRequestEnumerations .status(loanRescheduleRequest.getStatusEnum()); if (!loanRescheduleRequestStatusEnumData.isPendingApproval()) { - dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode( - "request.is.not.in.submitted.and.pending.state", + dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode("request.is.not.in.submitted.and.pending.state", "Loan reschedule request approval is not allowed. " + "Loan reschedule request is not in submitted and pending approval state."); } @@ -257,7 +250,7 @@ public class LoanRescheduleRequestDataValidator { } if (rescheduleFromDate != null) { - installment = loan.getRepaymentScheduleInstallment(rescheduleFromDate); + installment = loan.getRepaymentScheduleInstallment(rescheduleFromDate); if (installment == null) { dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode( @@ -289,12 +282,11 @@ public class LoanRescheduleRequestDataValidator { if (StringUtils.isBlank(jsonString)) { throw new InvalidJsonException(); } final Type typeToken = new TypeToken>() {}.getType(); - this.fromJsonHelper - .checkForUnsupportedParameters(typeToken, jsonString, REJECT_REQUEST_DATA_PARAMETERS); + this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, REJECT_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors).resource(StringUtils - .lowerCase(RescheduleLoansApiConstants.ENTITY_NAME)); + final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors) + .resource(StringUtils.lowerCase(RescheduleLoansApiConstants.ENTITY_NAME)); final JsonElement jsonElement = jsonCommand.parsedJson(); @@ -303,16 +295,15 @@ public class LoanRescheduleRequestDataValidator { dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rejectedOnDateParam).value(rejectedOnDate).notNull(); if (rejectedOnDate != null && loanRescheduleRequest.getSubmittedOnDate().isAfter(rejectedOnDate)) { - dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rejectedOnDateParam) - .failWithCode("before.submission.date", "Rejection date cannot be before the request submission date."); + dataValidatorBuilder.reset().parameter(RescheduleLoansApiConstants.rejectedOnDateParam).failWithCode("before.submission.date", + "Rejection date cannot be before the request submission date."); } LoanRescheduleRequestStatusEnumData loanRescheduleRequestStatusEnumData = LoanRescheduleRequestEnumerations .status(loanRescheduleRequest.getStatusEnum()); if (!loanRescheduleRequestStatusEnumData.isPendingApproval()) { - dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode( - "request.is.not.in.submitted.and.pending.state", + dataValidatorBuilder.reset().failWithCodeNoParameterAddedToErrorCode("request.is.not.in.submitted.and.pending.state", "Loan reschedule request rejection is not allowed. " + "Loan reschedule request is not in submitted and pending approval state."); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestEnumerations.java index f77020547..82994d348 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestEnumerations.java @@ -37,30 +37,27 @@ public class LoanRescheduleRequestEnumerations { public static LoanRescheduleRequestStatusEnumData status(final LoanStatus status) { LoanRescheduleRequestStatusEnumData enumData = new LoanRescheduleRequestStatusEnumData( - LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue().longValue(), - LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getCode(), "Submitted and pending approval"); + LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue().longValue(), LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getCode(), + "Submitted and pending approval"); - switch(status) { + switch (status) { case SUBMITTED_AND_PENDING_APPROVAL: - enumData = new LoanRescheduleRequestStatusEnumData( - LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue().longValue(), + enumData = new LoanRescheduleRequestStatusEnumData(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue().longValue(), LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getCode(), "Submitted and pending approval"); - break; + break; case APPROVED: - enumData = new LoanRescheduleRequestStatusEnumData( - LoanStatus.APPROVED.getValue().longValue(), + enumData = new LoanRescheduleRequestStatusEnumData(LoanStatus.APPROVED.getValue().longValue(), LoanStatus.APPROVED.getCode(), "Approved"); - break; + break; case REJECTED: - enumData = new LoanRescheduleRequestStatusEnumData( - LoanStatus.REJECTED.getValue().longValue(), + enumData = new LoanRescheduleRequestStatusEnumData(LoanStatus.REJECTED.getValue().longValue(), LoanStatus.REJECTED.getCode(), "Rejected"); - break; + break; default: - break; + break; } return enumData; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestTimelineData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestTimelineData.java index 29e3eb544..5f9318c7b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestTimelineData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/data/LoanRescheduleRequestTimelineData.java @@ -21,10 +21,12 @@ package org.apache.fineract.portfolio.loanaccount.rescheduleloan.data; import org.joda.time.LocalDate; /** - * Immutable data object represent the timeline events of a loan reschedule request + * Immutable data object represent the timeline events of a loan reschedule + * request **/ @SuppressWarnings("unused") public class LoanRescheduleRequestTimelineData { + private final LocalDate submittedOnDate; private final String submittedByUsername; private final String submittedByFirstname; @@ -40,9 +42,10 @@ public class LoanRescheduleRequestTimelineData { private final String rejectedByFirstname; private final String rejectedByLastname; - public LoanRescheduleRequestTimelineData(final LocalDate submittedOnDate, final String submittedByUsername, final String submittedByFirstname, - final String submittedByLastname, final LocalDate approvedOnDate, final String approvedByUsername, final String approvedByFirstname, - final String approvedByLastname, final LocalDate rejectedOnDate, final String rejectedByUsername, final String rejectedByFirstname, + public LoanRescheduleRequestTimelineData(final LocalDate submittedOnDate, final String submittedByUsername, + final String submittedByFirstname, final String submittedByLastname, final LocalDate approvedOnDate, + final String approvedByUsername, final String approvedByFirstname, final String approvedByLastname, + final LocalDate rejectedOnDate, final String rejectedByUsername, final String rejectedByFirstname, final String rejectedByLastname) { this.submittedOnDate = submittedOnDate; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleModel.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleModel.java index 9906be0d4..9f87bc32e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleModel.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleModel.java @@ -68,20 +68,19 @@ public final class LoanRescheduleModel { final BigDecimal totalPrincipalPaid, final BigDecimal totalInterestCharged, final BigDecimal totalFeeChargesCharged, final BigDecimal totalPenaltyChargesCharged, final BigDecimal totalRepaymentExpected, final BigDecimal totalOutstanding) { - return new LoanRescheduleModel(periods, oldPeriods, applicationCurrency, loanTermInDays, principalDisbursed, - totalPrincipalExpected, totalPrincipalPaid, totalInterestCharged, totalFeeChargesCharged, totalPenaltyChargesCharged, - totalRepaymentExpected, totalOutstanding); + return new LoanRescheduleModel(periods, oldPeriods, applicationCurrency, loanTermInDays, principalDisbursed, totalPrincipalExpected, + totalPrincipalPaid, totalInterestCharged, totalFeeChargesCharged, totalPenaltyChargesCharged, totalRepaymentExpected, + totalOutstanding); } public static LoanRescheduleModel createWithSchedulehistory(LoanRescheduleModel loanRescheduleModel, final Collection oldPeriods) { return new LoanRescheduleModel(loanRescheduleModel.periods, oldPeriods, loanRescheduleModel.applicationCurrency, - loanRescheduleModel.loanTermInDays, loanRescheduleModel.totalPrincipalDisbursed, - loanRescheduleModel.totalPrincipalExpected, loanRescheduleModel.totalPrincipalPaid, - loanRescheduleModel.totalInterestCharged, loanRescheduleModel.totalFeeChargesCharged, - loanRescheduleModel.totalPenaltyChargesCharged, loanRescheduleModel.totalRepaymentExpected, - loanRescheduleModel.totalOutstanding); + loanRescheduleModel.loanTermInDays, loanRescheduleModel.totalPrincipalDisbursed, loanRescheduleModel.totalPrincipalExpected, + loanRescheduleModel.totalPrincipalPaid, loanRescheduleModel.totalInterestCharged, + loanRescheduleModel.totalFeeChargesCharged, loanRescheduleModel.totalPenaltyChargesCharged, + loanRescheduleModel.totalRepaymentExpected, loanRescheduleModel.totalOutstanding); } public LoanScheduleData toData() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleRequest.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleRequest.java index e86ab0fe8..e0f6200d9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleRequest.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleRequest.java @@ -93,7 +93,7 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { @JoinColumn(name = "rejected_by_user_id") private AppUser rejectedByUser; - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "loan_reschedule_request_id", nullable = false) private Set loanRescheduleRequestToTermVariationMappings = new HashSet<>(); @@ -165,7 +165,7 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { LocalDate localDate = null; - if(this.rescheduleFromDate != null) { + if (this.rescheduleFromDate != null) { localDate = new LocalDate(this.rescheduleFromDate); } @@ -192,7 +192,7 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { public LocalDate getSubmittedOnDate() { LocalDate localDate = null; - if(this.submittedOnDate != null) { + if (this.submittedOnDate != null) { localDate = new LocalDate(this.submittedOnDate); } @@ -212,7 +212,7 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { public LocalDate getApprovedOnDate() { LocalDate localDate = null; - if(this.approvedOnDate != null) { + if (this.approvedOnDate != null) { localDate = new LocalDate(this.approvedOnDate); } @@ -232,7 +232,7 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { public LocalDate getRejectedOnDate() { LocalDate localDate = null; - if(this.rejectedOnDate != null) { + if (this.rejectedOnDate != null) { localDate = new LocalDate(this.rejectedOnDate); } @@ -245,7 +245,7 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { public Boolean getRecalculateInterest() { boolean recalculateInterest = false; - if(this.recalculateInterest != null) { + if (this.recalculateInterest != null) { recalculateInterest = this.recalculateInterest; } @@ -260,16 +260,18 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { } /** - * change the status of the loan reschedule request to approved, also updating the - * approvedByUser and approvedOnDate properties + * change the status of the loan reschedule request to approved, also + * updating the approvedByUser and approvedOnDate properties * - * @param approvedByUser the user who approved the request - * @param approvedOnDate the date of the approval + * @param approvedByUser + * the user who approved the request + * @param approvedOnDate + * the date of the approval * **/ public void approve(final AppUser approvedByUser, final LocalDate approvedOnDate) { - if(approvedOnDate != null) { + if (approvedOnDate != null) { this.approvedByUser = approvedByUser; this.approvedOnDate = approvedOnDate.toDate(); this.statusEnum = LoanStatus.APPROVED.getValue(); @@ -277,16 +279,18 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { } /** - * change the status of the loan reschedule request to rejected, also updating the - * approvedByUser and approvedOnDate properties + * change the status of the loan reschedule request to rejected, also + * updating the approvedByUser and approvedOnDate properties * - * @param approvedByUser the user who approved the request - * @param approvedOnDate the date of the approval + * @param approvedByUser + * the user who approved the request + * @param approvedOnDate + * the date of the approval * **/ public void reject(final AppUser approvedByUser, final LocalDate approvedOnDate) { - if(approvedOnDate != null) { + if (approvedOnDate != null) { this.rejectedByUser = approvedByUser; this.rejectedOnDate = approvedOnDate.toDate(); this.statusEnum = LoanStatus.REJECTED.getValue(); @@ -302,12 +306,9 @@ public class LoanRescheduleRequest extends AbstractPersistableCustom { } public LoanTermVariations getDueDateTermVariationIfExists() { - if(this.loanRescheduleRequestToTermVariationMappings != null - && this.loanRescheduleRequestToTermVariationMappings.size() > 0){ + if (this.loanRescheduleRequestToTermVariationMappings != null && this.loanRescheduleRequestToTermVariationMappings.size() > 0) { for (LoanRescheduleRequestToTermVariationMapping mapping : this.loanRescheduleRequestToTermVariationMappings) { - if(mapping.getLoanTermVariations().getTermType().isDueDateVariation()){ - return mapping.getLoanTermVariations(); - } + if (mapping.getLoanTermVariations().getTermType().isDueDateVariation()) { return mapping.getLoanTermVariations(); } } } return null; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleRequestRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleRequestRepository.java index 0822279b5..64ed26bc0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleRequestRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/domain/LoanRescheduleRequestRepository.java @@ -21,6 +21,7 @@ package org.apache.fineract.portfolio.loanaccount.rescheduleloan.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface LoanRescheduleRequestRepository extends JpaRepository, JpaSpecificationExecutor { +public interface LoanRescheduleRequestRepository + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/exception/LoanRescheduleRequestNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/exception/LoanRescheduleRequestNotFoundException.java index bffbddaa2..1aa61e50f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/exception/LoanRescheduleRequestNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/exception/LoanRescheduleRequestNotFoundException.java @@ -21,19 +21,21 @@ package org.apache.fineract.portfolio.loanaccount.rescheduleloan.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when loan reschedule request resources are not found. + * A {@link RuntimeException} thrown when loan reschedule request resources are + * not found. **/ public class LoanRescheduleRequestNotFoundException extends AbstractPlatformResourceNotFoundException { /** * LoanRescheduleRequestNotFoundException constructor * - * @param requestId the loan reschedule request identifier + * @param requestId + * the loan reschedule request identifier * **/ public LoanRescheduleRequestNotFoundException(final Long requestId) { - super("error.msg.loan.reschedule.request.id.invalid", - "Loan reschedule request with identifier " + requestId + " does not exist", requestId); + super("error.msg.loan.reschedule.request.id.invalid", "Loan reschedule request with identifier " + requestId + " does not exist", + requestId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/ApproveLoanRescheduleRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/ApproveLoanRescheduleRequestCommandHandler.java index 52c497d30..20964b619 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/ApproveLoanRescheduleRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/ApproveLoanRescheduleRequestCommandHandler.java @@ -30,11 +30,11 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "RESCHEDULELOAN", action = "APPROVE") public class ApproveLoanRescheduleRequestCommandHandler implements NewCommandSourceHandler { + private final LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService; @Autowired - public ApproveLoanRescheduleRequestCommandHandler( - LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService) { + public ApproveLoanRescheduleRequestCommandHandler(LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService) { this.loanRescheduleRequestWritePlatformService = loanRescheduleRequestWritePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/CreateLoanRescheduleRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/CreateLoanRescheduleRequestCommandHandler.java index 381099c31..e8dbda6b7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/CreateLoanRescheduleRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/CreateLoanRescheduleRequestCommandHandler.java @@ -34,8 +34,7 @@ public class CreateLoanRescheduleRequestCommandHandler implements NewCommandSour private final LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService; @Autowired - public CreateLoanRescheduleRequestCommandHandler( - LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService) { + public CreateLoanRescheduleRequestCommandHandler(LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService) { this.loanRescheduleRequestWritePlatformService = loanRescheduleRequestWritePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/RejectLoanRescheduleRequestCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/RejectLoanRescheduleRequestCommandHandler.java index bed0a18de..a57eed4a4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/RejectLoanRescheduleRequestCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/handler/RejectLoanRescheduleRequestCommandHandler.java @@ -30,11 +30,11 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "RESCHEDULELOAN", action = "REJECT") public class RejectLoanRescheduleRequestCommandHandler implements NewCommandSourceHandler { + private final LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService; @Autowired - public RejectLoanRescheduleRequestCommandHandler( - LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService) { + public RejectLoanRescheduleRequestCommandHandler(LoanRescheduleRequestWritePlatformService loanRescheduleRequestWritePlatformService) { this.loanRescheduleRequestWritePlatformService = loanRescheduleRequestWritePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanReschedulePreviewPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanReschedulePreviewPlatformServiceImpl.java index e3160362c..eedacc099 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanReschedulePreviewPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanReschedulePreviewPlatformServiceImpl.java @@ -71,7 +71,8 @@ public class LoanReschedulePreviewPlatformServiceImpl implements LoanRescheduleP @Override public LoanScheduleModel previewLoanReschedule(Long requestId) { - final LoanRescheduleRequest loanRescheduleRequest = this.loanRescheduleRequestRepository.findOneWithNotFoundDetection(requestId, true); + final LoanRescheduleRequest loanRescheduleRequest = this.loanRescheduleRequestRepository.findOneWithNotFoundDetection(requestId, + true); if (loanRescheduleRequest == null) { throw new LoanRescheduleRequestNotFoundException(requestId); } @@ -83,7 +84,7 @@ public class LoanReschedulePreviewPlatformServiceImpl implements LoanRescheduleP List removeLoanTermVariationsData = new ArrayList<>(); final LoanApplicationTerms loanApplicationTerms = loan.constructLoanApplicationTerms(scheduleGeneratorDTO); LoanTermVariations dueDateVariationInCurrentRequest = loanRescheduleRequest.getDueDateTermVariationIfExists(); - if(dueDateVariationInCurrentRequest != null){ + if (dueDateVariationInCurrentRequest != null) { for (LoanTermVariationsData loanTermVariation : loanApplicationTerms.getLoanTermVariations().getDueDateVariation()) { if (loanTermVariation.getDateValue().equals(dueDateVariationInCurrentRequest.fetchTermApplicaDate())) { rescheduleFromDate = loanTermVariation.getTermApplicableFrom(); @@ -97,14 +98,14 @@ public class LoanReschedulePreviewPlatformServiceImpl implements LoanRescheduleP } List loanTermVariationsData = new ArrayList<>(); LocalDate adjustedApplicableDate = null; - Set loanRescheduleRequestToTermVariationMappings = loanRescheduleRequest.getLoanRescheduleRequestToTermVariationMappings(); + Set loanRescheduleRequestToTermVariationMappings = loanRescheduleRequest + .getLoanRescheduleRequestToTermVariationMappings(); if (!loanRescheduleRequestToTermVariationMappings.isEmpty()) { for (LoanRescheduleRequestToTermVariationMapping loanRescheduleRequestToTermVariationMapping : loanRescheduleRequestToTermVariationMappings) { if (loanRescheduleRequestToTermVariationMapping.getLoanTermVariations().getTermType().isDueDateVariation() && rescheduleFromDate != null) { adjustedApplicableDate = loanRescheduleRequestToTermVariationMapping.getLoanTermVariations().fetchDateValue(); - loanRescheduleRequestToTermVariationMapping.getLoanTermVariations().setTermApplicableFrom( - rescheduleFromDate.toDate()); + loanRescheduleRequestToTermVariationMapping.getLoanTermVariations().setTermApplicableFrom(rescheduleFromDate.toDate()); } loanTermVariationsData.add(loanRescheduleRequestToTermVariationMapping.getLoanTermVariations().toData()); } @@ -131,9 +132,8 @@ public class LoanReschedulePreviewPlatformServiceImpl implements LoanRescheduleP final LoanScheduleGenerator loanScheduleGenerator = this.loanScheduleFactory.create(loanApplicationTerms.getInterestMethod()); final LoanLifecycleStateMachine loanLifecycleStateMachine = null; loan.setHelpers(loanLifecycleStateMachine, this.loanSummaryWrapper, this.loanRepaymentScheduleTransactionProcessorFactory); - final LoanScheduleDTO loanSchedule = loanScheduleGenerator.rescheduleNextInstallments(mathContext, loanApplicationTerms, - loan, loanApplicationTerms.getHolidayDetailDTO(), - loanRepaymentScheduleTransactionProcessor, rescheduleFromDate); + final LoanScheduleDTO loanSchedule = loanScheduleGenerator.rescheduleNextInstallments(mathContext, loanApplicationTerms, loan, + loanApplicationTerms.getHolidayDetailDTO(), loanRepaymentScheduleTransactionProcessor, rescheduleFromDate); final LoanScheduleModel loanScheduleModel = loanSchedule.getLoanScheduleModel(); LoanScheduleModel loanScheduleModels = LoanScheduleModel.withLoanScheduleModelPeriods(loanScheduleModel.getPeriods(), loanScheduleModel); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestReadPlatformService.java index 05d0742b2..f121607e8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestReadPlatformService.java @@ -58,14 +58,14 @@ public interface LoanRescheduleRequestReadPlatformService { * @return list of LoanRescheduleRequestData objects **/ public LoanRescheduleRequestData retrieveAllRescheduleReasons(String loanRescheduleReason); + /** * get all loan reschedule request * * @param command - * all/null - give all request - * approved - give all approved request - * pending - give all request which is pending for approval - * reject - give all rejected requests + * all/null - give all request approved - give all approved + * request pending - give all request which is pending for + * approval reject - give all rejected requests * @return list of LoanRescheduleRequestData objects **/ public List retrieveAllRescheduleRequests(String command); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestReadPlatformServiceImpl.java index a60abc5bd..884736a0b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestReadPlatformServiceImpl.java @@ -108,7 +108,7 @@ public class LoanRescheduleRequestReadPlatformServiceImpl implements LoanResched sqlBuilder.append("left join m_loan ml on ml.id = lr.loan_id "); sqlBuilder.append("left join m_client mc on mc.id = ml.client_id "); sqlBuilder.append("join m_loan_reschedule_request_term_variations_mapping rrtvm on lr.id = rrtvm.loan_reschedule_request_id "); - sqlBuilder.append("join m_loan_term_variations tv on tv.id = rrtvm.loan_term_variations_id and tv.parent_id is null") ; + sqlBuilder.append("join m_loan_term_variations tv on tv.id = rrtvm.loan_term_variations_id and tv.parent_id is null"); this.schema = sqlBuilder.toString(); } @@ -198,8 +198,8 @@ public class LoanRescheduleRequestReadPlatformServiceImpl implements LoanResched sqlBuilder.append("lrr.id as id, lrr.status_enum as statusEnum, lrr.reschedule_from_date as rescheduleFromDate, "); sqlBuilder.append("cv.id as rescheduleReasonCvId, cv.code_value as rescheduleReasonCvValue, "); - sqlBuilder - .append(" loan.id as loanId, loan.account_no as loanAccountNumber, client.id as clientId, client.display_name as clientName "); + sqlBuilder.append( + " loan.id as loanId, loan.account_no as loanAccountNumber, client.id as clientId, client.display_name as clientName "); sqlBuilder.append("from m_loan_reschedule_request lrr "); sqlBuilder.append("left join m_loan loan on loan.id = lrr.loan_id "); sqlBuilder.append("left join m_client client on client.id = loan.client_id "); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestWritePlatformServiceImpl.java index d4056c17d..86263b773 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/rescheduleloan/service/LoanRescheduleRequestWritePlatformServiceImpl.java @@ -275,21 +275,16 @@ public class LoanRescheduleRequestWritePlatformServiceImpl implements LoanResche Date dueDate = null; // create term variations for flat and declining balance loans createLoanTermVariationsForRegularLoans(loan, graceOnPrincipal, graceOnInterest, extraTerms, interestRate, rescheduleFromDate, - adjustedDueDate, loanRescheduleRequest, loanRescheduleRequestToTermVariationMappings, isActive, - isSpecificToInstallment, decimalValue, dueDate); + adjustedDueDate, loanRescheduleRequest, loanRescheduleRequestToTermVariationMappings, isActive, isSpecificToInstallment, + decimalValue, dueDate); // create a new entry in the m_loan_reschedule_request table this.loanRescheduleRequestRepository.save(loanRescheduleRequest); this.loanRepositoryWrapper.save(loan); - return new CommandProcessingResultBuilder() - .withCommandId(jsonCommand.commandId()) - .withEntityId(loanRescheduleRequest.getId()) - .withLoanId(loan.getId()) - .withClientId(loan.getClientId()) - .withOfficeId(loan.getOfficeId()) - .withGroupId(loan.getGroupId()) - .build(); + return new CommandProcessingResultBuilder().withCommandId(jsonCommand.commandId()).withEntityId(loanRescheduleRequest.getId()) + .withLoanId(loan.getId()).withClientId(loan.getClientId()).withOfficeId(loan.getOfficeId()) + .withGroupId(loan.getGroupId()).build(); } catch (final DataIntegrityViolationException dve) { @@ -376,8 +371,8 @@ public class LoanRescheduleRequestWritePlatformServiceImpl implements LoanResche final Map changes = new LinkedHashMap<>(); LocalDate approvedOnDate = jsonCommand.localDateValueOfParameterNamed("approvedOnDate"); - final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat()).withLocale( - jsonCommand.extractLocale()); + final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat()) + .withLocale(jsonCommand.extractLocale()); changes.put("locale", jsonCommand.locale()); changes.put("dateFormat", jsonCommand.dateFormat()); @@ -420,8 +415,8 @@ public class LoanRescheduleRequestWritePlatformServiceImpl implements LoanResche changeMap.put(currentScheduleDate, modifiedScheduleDate); } if (changeMap.containsKey(activeLoanTermVariation.fetchTermApplicaDate())) { - activeLoanTermVariation.setTermApplicableFrom(changeMap.get(activeLoanTermVariation.fetchTermApplicaDate()) - .toDate()); + activeLoanTermVariation + .setTermApplicableFrom(changeMap.get(activeLoanTermVariation.fetchTermApplicaDate()).toDate()); } } } @@ -438,17 +433,21 @@ public class LoanRescheduleRequestWritePlatformServiceImpl implements LoanResche loan.constructLoanTermVariations(scheduleGeneratorDTO.getFloatingRateDTO(), annualNominalInterestRate, loanTermVariations); loanApplicationTerms.getLoanTermVariations().setExceptionData(loanTermVariations); - /*for (LoanTermVariationsData loanTermVariation : loanApplicationTerms.getLoanTermVariations().getDueDateVariation()) { - if (rescheduleFromDate.isBefore(loanTermVariation.getTermApplicableFrom())) { - LocalDate applicableDate = this.scheduledDateGenerator.generateNextRepaymentDate(rescheduleFromDate, - loanApplicationTerms, false, loanApplicationTerms.getHolidayDetailDTO()); - if (loanTermVariation.getTermApplicableFrom().equals(applicableDate)) { - LocalDate adjustedDate = this.scheduledDateGenerator.generateNextRepaymentDate(adjustedApplicableDate, - loanApplicationTerms, false, loanApplicationTerms.getHolidayDetailDTO()); - loanTermVariation.setApplicableFromDate(adjustedDate); - } - } - }*/ + /* + * for (LoanTermVariationsData loanTermVariation : + * loanApplicationTerms.getLoanTermVariations().getDueDateVariation( + * )) { if (rescheduleFromDate.isBefore(loanTermVariation. + * getTermApplicableFrom())) { LocalDate applicableDate = + * this.scheduledDateGenerator.generateNextRepaymentDate( + * rescheduleFromDate, loanApplicationTerms, false, + * loanApplicationTerms.getHolidayDetailDTO()); if + * (loanTermVariation.getTermApplicableFrom().equals(applicableDate) + * ) { LocalDate adjustedDate = + * this.scheduledDateGenerator.generateNextRepaymentDate( + * adjustedApplicableDate, loanApplicationTerms, false, + * loanApplicationTerms.getHolidayDetailDTO()); + * loanTermVariation.setApplicableFromDate(adjustedDate); } } } + */ final RoundingMode roundingMode = MoneyHelper.getRoundingMode(); final MathContext mathContext = new MathContext(8, roundingMode); @@ -457,13 +456,12 @@ public class LoanRescheduleRequestWritePlatformServiceImpl implements LoanResche final LoanScheduleGenerator loanScheduleGenerator = this.loanScheduleFactory.create(loanApplicationTerms.getInterestMethod()); final LoanLifecycleStateMachine loanLifecycleStateMachine = null; loan.setHelpers(loanLifecycleStateMachine, this.loanSummaryWrapper, this.loanRepaymentScheduleTransactionProcessorFactory); - final LoanScheduleDTO loanSchedule = loanScheduleGenerator.rescheduleNextInstallments(mathContext, loanApplicationTerms, - loan, loanApplicationTerms.getHolidayDetailDTO(), - loanRepaymentScheduleTransactionProcessor, rescheduleFromDate); + final LoanScheduleDTO loanSchedule = loanScheduleGenerator.rescheduleNextInstallments(mathContext, loanApplicationTerms, loan, + loanApplicationTerms.getHolidayDetailDTO(), loanRepaymentScheduleTransactionProcessor, rescheduleFromDate); loan.updateLoanSchedule(loanSchedule.getInstallments(), appUser); loan.recalculateAllCharges(); - ChangedTransactionDetail changedTransactionDetail = loan.processTransactions(); + ChangedTransactionDetail changedTransactionDetail = loan.processTransactions(); for (LoanRepaymentScheduleHistory loanRepaymentScheduleHistory : loanRepaymentScheduleHistoryList) { this.loanRepaymentScheduleHistoryRepository.save(loanRepaymentScheduleHistory); @@ -491,15 +489,9 @@ public class LoanRescheduleRequestWritePlatformServiceImpl implements LoanResche this.loanAccountDomainService.recalculateAccruals(loan, true); - return new CommandProcessingResultBuilder() - .withCommandId(jsonCommand.commandId()) - .withEntityId(loanRescheduleRequestId) - .withLoanId(loanRescheduleRequest.getLoan().getId()) - .with(changes) - .withClientId(loan.getClientId()) - .withOfficeId(loan.getOfficeId()) - .withGroupId(loan.getGroupId()) - .build(); + return new CommandProcessingResultBuilder().withCommandId(jsonCommand.commandId()).withEntityId(loanRescheduleRequestId) + .withLoanId(loanRescheduleRequest.getLoan().getId()).with(changes).withClientId(loan.getClientId()) + .withOfficeId(loan.getOfficeId()).withGroupId(loan.getGroupId()).build(); } catch (final DataIntegrityViolationException dve) { @@ -527,8 +519,10 @@ public class LoanRescheduleRequestWritePlatformServiceImpl implements LoanResche if (realCause.getMessage().toLowerCase().contains("external_id_unique")) { baseDataValidator.reset().parameter("externalId").failWithCode("value.must.be.unique"); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } @@ -559,8 +553,8 @@ public class LoanRescheduleRequestWritePlatformServiceImpl implements LoanResche final Map changes = new LinkedHashMap<>(); LocalDate rejectedOnDate = jsonCommand.localDateValueOfParameterNamed("rejectedOnDate"); - final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat()).withLocale( - jsonCommand.extractLocale()); + final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat()) + .withLocale(jsonCommand.extractLocale()); changes.put("locale", jsonCommand.locale()); changes.put("dateFormat", jsonCommand.dateFormat()); @@ -576,15 +570,10 @@ public class LoanRescheduleRequestWritePlatformServiceImpl implements LoanResche } } - return new CommandProcessingResultBuilder() - .withCommandId(jsonCommand.commandId()) - .withEntityId(loanRescheduleRequestId) - .withLoanId(loanRescheduleRequest.getLoan().getId()) - .with(changes) - .withClientId(loanRescheduleRequest.getLoan().getClientId()) - .withOfficeId(loanRescheduleRequest.getLoan().getOfficeId()) - .withGroupId(loanRescheduleRequest.getLoan().getGroupId()) - .build(); + return new CommandProcessingResultBuilder().withCommandId(jsonCommand.commandId()).withEntityId(loanRescheduleRequestId) + .withLoanId(loanRescheduleRequest.getLoan().getId()).with(changes) + .withClientId(loanRescheduleRequest.getLoan().getClientId()).withOfficeId(loanRescheduleRequest.getLoan().getOfficeId()) + .withGroupId(loanRescheduleRequest.getLoan().getGroupId()).build(); } catch (final DataIntegrityViolationException dve) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/CalculateLoanScheduleQueryFromApiJsonHelper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/CalculateLoanScheduleQueryFromApiJsonHelper.java index 65dd0d029..486d7d941 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/CalculateLoanScheduleQueryFromApiJsonHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/CalculateLoanScheduleQueryFromApiJsonHelper.java @@ -55,20 +55,20 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { LoanApiConstants.loanTermFrequencyTypeParameterName, LoanApiConstants.repaymentFrequencyTypeParameterName, LoanApiConstants.amortizationTypeParameterName, LoanApiConstants.interestTypeParameterName, LoanApiConstants.interestCalculationPeriodTypeParameterName, - LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, LoanApiConstants.interestRateFrequencyTypeParameterName, - LoanApiConstants.disbursementDateParameterName, LoanApiConstants.repaymentsStartingFromDateParameterName, - LoanApiConstants.graceOnPrincipalPaymentParameterName, LoanApiConstants.graceOnInterestPaymentParameterName, - LoanApiConstants.graceOnInterestChargedParameterName, LoanApiConstants.interestChargedFromDateParameterName, - LoanApiConstants.submittedOnDateParameterName, LoanApiConstants.submittedOnNoteParameterName, - LoanApiConstants.localeParameterName, LoanApiConstants.dateFormatParameterName, LoanApiConstants.chargesParameterName, - LoanApiConstants.collateralParameterName, LoanApiConstants.syncDisbursementWithMeetingParameterName, - LoanApiConstants.linkAccountIdParameterName, LoanApiConstants.disbursementDataParameterName, - LoanApiConstants.emiAmountParameterName, LoanApiConstants.maxOutstandingBalanceParameterName, - LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, LoanApiConstants.createStandingInstructionAtDisbursementParameterName, - LoanApiConstants.isFloatingInterestRateParameterName, LoanApiConstants.interestRateDifferentialParameterName, - LoanApiConstants.repaymentFrequencyNthDayTypeParameterName, LoanApiConstants.repaymentFrequencyDayOfWeekTypeParameterName, - LoanApiConstants.isTopup, LoanApiConstants.loanIdToClose, LoanApiConstants.datatables, LoanApiConstants.isEqualAmortizationParam, - LoanProductConstants.RATES_PARAM_NAME)); + LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, + LoanApiConstants.interestRateFrequencyTypeParameterName, LoanApiConstants.disbursementDateParameterName, + LoanApiConstants.repaymentsStartingFromDateParameterName, LoanApiConstants.graceOnPrincipalPaymentParameterName, + LoanApiConstants.graceOnInterestPaymentParameterName, LoanApiConstants.graceOnInterestChargedParameterName, + LoanApiConstants.interestChargedFromDateParameterName, LoanApiConstants.submittedOnDateParameterName, + LoanApiConstants.submittedOnNoteParameterName, LoanApiConstants.localeParameterName, LoanApiConstants.dateFormatParameterName, + LoanApiConstants.chargesParameterName, LoanApiConstants.collateralParameterName, + LoanApiConstants.syncDisbursementWithMeetingParameterName, LoanApiConstants.linkAccountIdParameterName, + LoanApiConstants.disbursementDataParameterName, LoanApiConstants.emiAmountParameterName, + LoanApiConstants.maxOutstandingBalanceParameterName, LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, + LoanApiConstants.createStandingInstructionAtDisbursementParameterName, LoanApiConstants.isFloatingInterestRateParameterName, + LoanApiConstants.interestRateDifferentialParameterName, LoanApiConstants.repaymentFrequencyNthDayTypeParameterName, + LoanApiConstants.repaymentFrequencyDayOfWeekTypeParameterName, LoanApiConstants.isTopup, LoanApiConstants.loanIdToClose, + LoanApiConstants.datatables, LoanApiConstants.isEqualAmortizationParam, LoanProductConstants.RATES_PARAM_NAME)); private final FromJsonHelper fromApiJsonHelper; @@ -123,9 +123,10 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { validateRepaymentsStartingFromDateIsAfterDisbursementDate(dataValidationErrors, expectedDisbursementDate, repaymentsStartingFromDate); - - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateSelectedPeriodFrequencyTypeIsTheSame(final List dataValidationErrors, @@ -141,21 +142,19 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { if (loanTermFrequency != null && repaymentEvery != null && numberOfRepayments != null) { final int suggestsedLoanTerm = repaymentEvery * numberOfRepayments; if (loanTermFrequency.intValue() < suggestsedLoanTerm) { - final ApiParameterError error = ApiParameterError - .parameterError( - "validation.msg.loan.loanTermFrequency.less.than.repayment.structure.suggests", - "The parameter loanTermFrequency is less than the suggest loan term as indicated by numberOfRepayments and repaymentEvery.", - "loanTermFrequency", loanTermFrequency, numberOfRepayments, repaymentEvery); + final ApiParameterError error = ApiParameterError.parameterError( + "validation.msg.loan.loanTermFrequency.less.than.repayment.structure.suggests", + "The parameter loanTermFrequency is less than the suggest loan term as indicated by numberOfRepayments and repaymentEvery.", + "loanTermFrequency", loanTermFrequency, numberOfRepayments, repaymentEvery); dataValidationErrors.add(error); } else { - if (loanTermFrequency.intValue() > suggestsedLoanTerm) { - final ApiParameterError error = ApiParameterError - .parameterError( - "validation.msg.loan.loanTermFrequency.greater.than.repayment.structure.suggests", - "The parameter loanTermFrequency is greater than the suggested loan term as indicated by numberOfRepayments and repaymentEvery.", - "loanTermFrequency", loanTermFrequency, numberOfRepayments, repaymentEvery); - dataValidationErrors.add(error); - } + if (loanTermFrequency.intValue() > suggestsedLoanTerm) { + final ApiParameterError error = ApiParameterError.parameterError( + "validation.msg.loan.loanTermFrequency.greater.than.repayment.structure.suggests", + "The parameter loanTermFrequency is greater than the suggested loan term as indicated by numberOfRepayments and repaymentEvery.", + "loanTermFrequency", loanTermFrequency, numberOfRepayments, repaymentEvery); + dataValidationErrors.add(error); + } } } @@ -174,4 +173,4 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { } } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanApplicationCommandFromApiJsonHelper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanApplicationCommandFromApiJsonHelper.java index 9929fb69d..480cbe7eb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanApplicationCommandFromApiJsonHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanApplicationCommandFromApiJsonHelper.java @@ -62,38 +62,33 @@ public final class LoanApplicationCommandFromApiJsonHelper { final Set supportedParameters = new HashSet<>(Arrays.asList(LoanApiConstants.dateFormatParameterName, LoanApiConstants.localeParameterName, LoanApiConstants.idParameterName, LoanApiConstants.clientIdParameterName, LoanApiConstants.groupIdParameterName, LoanApiConstants.loanTypeParameterName, LoanApiConstants.productIdParameterName, - LoanApiConstants.principalParamName,LoanApiConstants.totalLoanParamName,LoanApiConstants.parentAccountParamName, LoanApiConstants.loanTermFrequencyParameterName, - LoanApiConstants.loanTermFrequencyTypeParameterName, LoanApiConstants.numberOfRepaymentsParameterName, - LoanApiConstants.repaymentEveryParameterName, LoanApiConstants.repaymentFrequencyTypeParameterName, - LoanApiConstants.repaymentFrequencyNthDayTypeParameterName, LoanApiConstants.repaymentFrequencyDayOfWeekTypeParameterName, - LoanApiConstants.interestRatePerPeriodParameterName, LoanApiConstants.amortizationTypeParameterName, - LoanApiConstants.interestTypeParameterName, LoanApiConstants.isFloatingInterestRate, LoanApiConstants.interestRateDifferential, + LoanApiConstants.principalParamName, LoanApiConstants.totalLoanParamName, LoanApiConstants.parentAccountParamName, + LoanApiConstants.loanTermFrequencyParameterName, LoanApiConstants.loanTermFrequencyTypeParameterName, + LoanApiConstants.numberOfRepaymentsParameterName, LoanApiConstants.repaymentEveryParameterName, + LoanApiConstants.repaymentFrequencyTypeParameterName, LoanApiConstants.repaymentFrequencyNthDayTypeParameterName, + LoanApiConstants.repaymentFrequencyDayOfWeekTypeParameterName, LoanApiConstants.interestRatePerPeriodParameterName, + LoanApiConstants.amortizationTypeParameterName, LoanApiConstants.interestTypeParameterName, + LoanApiConstants.isFloatingInterestRate, LoanApiConstants.interestRateDifferential, LoanApiConstants.interestCalculationPeriodTypeParameterName, - LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, LoanApiConstants.interestRateFrequencyTypeParameterName, - LoanApiConstants.disbursementDateParameterName, LoanApiConstants.repaymentsStartingFromDateParameterName, - LoanApiConstants.graceOnPrincipalPaymentParameterName, - LoanApiConstants.graceOnInterestPaymentParameterName, - LoanApiConstants.graceOnInterestChargedParameterName, - LoanApiConstants.interestChargedFromDateParameterName, - LoanApiConstants.submittedOnDateParameterName, - LoanApiConstants.submittedOnNoteParameterName, - LoanApiConstants.accountNoParameterName, - LoanApiConstants.externalIdParameterName, - LoanApiConstants.fundIdParameterName, - LoanApiConstants.loanOfficerIdParameterName, // optional - LoanApiConstants.loanPurposeIdParameterName, - LoanApiConstants.inArrearsToleranceParameterName, - LoanApiConstants.chargesParameterName, - LoanApiConstants.collateralParameterName, // optional + LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, + LoanApiConstants.interestRateFrequencyTypeParameterName, LoanApiConstants.disbursementDateParameterName, + LoanApiConstants.repaymentsStartingFromDateParameterName, LoanApiConstants.graceOnPrincipalPaymentParameterName, + LoanApiConstants.graceOnInterestPaymentParameterName, LoanApiConstants.graceOnInterestChargedParameterName, + LoanApiConstants.interestChargedFromDateParameterName, LoanApiConstants.submittedOnDateParameterName, + LoanApiConstants.submittedOnNoteParameterName, LoanApiConstants.accountNoParameterName, + LoanApiConstants.externalIdParameterName, LoanApiConstants.fundIdParameterName, LoanApiConstants.loanOfficerIdParameterName, // optional + LoanApiConstants.loanPurposeIdParameterName, LoanApiConstants.inArrearsToleranceParameterName, + LoanApiConstants.chargesParameterName, LoanApiConstants.collateralParameterName, // optional LoanApiConstants.transactionProcessingStrategyIdParameterName, // settings LoanApiConstants.calendarIdParameterName, // optional - LoanApiConstants.syncDisbursementWithMeetingParameterName,// optional + LoanApiConstants.syncDisbursementWithMeetingParameterName, // optional LoanApiConstants.linkAccountIdParameterName, LoanApiConstants.disbursementDataParameterName, LoanApiConstants.emiAmountParameterName, LoanApiConstants.maxOutstandingBalanceParameterName, - LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, LoanApiConstants.createStandingInstructionAtDisbursementParameterName, - LoanApiConstants.isTopup, LoanApiConstants.loanIdToClose, LoanApiConstants.datatables, LoanApiConstants.isEqualAmortizationParam,LoanProductConstants.RATES_PARAM_NAME, - LoanApiConstants.applicationId, // glim specific - LoanApiConstants.lastApplication)); // glim specific + LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, + LoanApiConstants.createStandingInstructionAtDisbursementParameterName, LoanApiConstants.isTopup, LoanApiConstants.loanIdToClose, + LoanApiConstants.datatables, LoanApiConstants.isEqualAmortizationParam, LoanProductConstants.RATES_PARAM_NAME, + LoanApiConstants.applicationId, // glim specific + LoanApiConstants.lastApplication)); // glim specific private final FromJsonHelper fromApiJsonHelper; private final CalculateLoanScheduleQueryFromApiJsonHelper apiJsonHelper; @@ -166,8 +161,9 @@ public final class LoanApplicationCommandFromApiJsonHelper { isEqualAmortization = this.fromApiJsonHelper.extractBooleanNamed(LoanApiConstants.isEqualAmortizationParam, element); baseDataValidator.reset().parameter(LoanApiConstants.isEqualAmortizationParam).value(isEqualAmortization).ignoreIfNull() .validateForBooleanValue(); - if (isEqualAmortization && loanProduct.isInterestRecalculationEnabled()) { throw new EqualAmortizationUnsupportedFeatureException( - "interest.recalculation", "interest recalculation"); } + if (isEqualAmortization && loanProduct.isInterestRecalculationEnabled()) { + throw new EqualAmortizationUnsupportedFeatureException("interest.recalculation", "interest recalculation"); + } } final Long productId = this.fromApiJsonHelper.extractLongNamed("productId", element); @@ -226,8 +222,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { final String repaymentEveryFrequencyTypeParameterName = "repaymentFrequencyType"; final Integer repaymentEveryType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(repaymentEveryFrequencyTypeParameterName, element); - baseDataValidator.reset().parameter(repaymentEveryFrequencyTypeParameterName).value(repaymentEveryType).notNull() - .inMinMaxRange(0, 3); + baseDataValidator.reset().parameter(repaymentEveryFrequencyTypeParameterName).value(repaymentEveryType).notNull().inMinMaxRange(0, + 3); final String repaymentFrequencyNthDayTypeParameterName = "repaymentFrequencyNthDayType"; final String repaymentFrequencyDayOfWeekTypeParameterName = "repaymentFrequencyDayOfWeekType"; @@ -238,20 +234,19 @@ public final class LoanApplicationCommandFromApiJsonHelper { baseDataValidator.reset().parameter(interestTypeParameterName).value(interestType).notNull().inMinMaxRange(0, 1); final String interestCalculationPeriodTypeParameterName = "interestCalculationPeriodType"; - final Integer interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCalculationPeriodTypeParameterName, element); + final Integer interestCalculationPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCalculationPeriodTypeParameterName, element); baseDataValidator.reset().parameter(interestCalculationPeriodTypeParameterName).value(interestCalculationPeriodType).notNull() .inMinMaxRange(0, 1); if (loanProduct.isLinkedToFloatingInterestRate()) { - if (isEqualAmortization) { throw new EqualAmortizationUnsupportedFeatureException("floating.interest.rate", - "floating interest rate"); } + if (isEqualAmortization) { + throw new EqualAmortizationUnsupportedFeatureException("floating.interest.rate", "floating interest rate"); + } if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) { - baseDataValidator - .reset() - .parameter("interestRatePerPeriod") - .failWithCode("not.supported.loanproduct.linked.to.floating.rate", - "interestRatePerPeriod param is not supported, selected Loan Product is linked with floating interest rate."); + baseDataValidator.reset().parameter("interestRatePerPeriod").failWithCode( + "not.supported.loanproduct.linked.to.floating.rate", + "interestRatePerPeriod param is not supported, selected Loan Product is linked with floating interest rate."); } if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isFloatingInterestRate, element)) { @@ -259,56 +254,42 @@ public final class LoanApplicationCommandFromApiJsonHelper { element); if (isFloatingInterestRate != null && isFloatingInterestRate && !loanProduct.getFloatingRates().isFloatingInterestRateCalculationAllowed()) { - baseDataValidator - .reset() - .parameter(LoanApiConstants.isFloatingInterestRate) - .failWithCode("true.not.supported.for.selected.loanproduct", - "isFloatingInterestRate value of true not supported for selected Loan Product."); + baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).failWithCode( + "true.not.supported.for.selected.loanproduct", + "isFloatingInterestRate value of true not supported for selected Loan Product."); } } else { baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).trueOrFalseRequired(false); } if (interestType != null && interestType.equals(InterestMethod.FLAT.getValue())) { - baseDataValidator - .reset() - .parameter(interestTypeParameterName) - .failWithCode("should.be.0.for.selected.loan.product", - "interestType should be DECLINING_BALANCE for selected Loan Product as it is linked to floating rates."); + baseDataValidator.reset().parameter(interestTypeParameterName).failWithCode("should.be.0.for.selected.loan.product", + "interestType should be DECLINING_BALANCE for selected Loan Product as it is linked to floating rates."); } final String interestRateDifferentialParameterName = LoanApiConstants.interestRateDifferential; - final BigDecimal interestRateDifferential = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - interestRateDifferentialParameterName, element); - baseDataValidator - .reset() - .parameter(interestRateDifferentialParameterName) - .value(interestRateDifferential) - .notNull() - .zeroOrPositiveAmount() - .inMinAndMaxAmountRange(loanProduct.getFloatingRates().getMinDifferentialLendingRate(), + final BigDecimal interestRateDifferential = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(interestRateDifferentialParameterName, element); + baseDataValidator.reset().parameter(interestRateDifferentialParameterName).value(interestRateDifferential).notNull() + .zeroOrPositiveAmount().inMinAndMaxAmountRange(loanProduct.getFloatingRates().getMinDifferentialLendingRate(), loanProduct.getFloatingRates().getMaxDifferentialLendingRate()); } else { if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isFloatingInterestRate, element)) { - baseDataValidator - .reset() - .parameter(LoanApiConstants.isFloatingInterestRate) - .failWithCode("not.supported.loanproduct.not.linked.to.floating.rate", - "isFloatingInterestRate param is not supported, selected Loan Product is not linked with floating interest rate."); + baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).failWithCode( + "not.supported.loanproduct.not.linked.to.floating.rate", + "isFloatingInterestRate param is not supported, selected Loan Product is not linked with floating interest rate."); } if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.interestRateDifferential, element)) { - baseDataValidator - .reset() - .parameter(LoanApiConstants.interestRateDifferential) - .failWithCode("not.supported.loanproduct.not.linked.to.floating.rate", - "interestRateDifferential param is not supported, selected Loan Product is not linked with floating interest rate."); + baseDataValidator.reset().parameter(LoanApiConstants.interestRateDifferential).failWithCode( + "not.supported.loanproduct.not.linked.to.floating.rate", + "interestRateDifferential param is not supported, selected Loan Product is not linked with floating interest rate."); } final String interestRatePerPeriodParameterName = "interestRatePerPeriod"; - final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - interestRatePerPeriodParameterName, element); + final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, element); baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod).notNull() .zeroOrPositiveAmount(); @@ -333,8 +314,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { final Integer graceOnInterestCharged = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged).zeroOrPositiveAmount(); - final Integer graceOnArrearsAgeing = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element); + final Integer graceOnArrearsAgeing = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME).value(graceOnArrearsAgeing) .zeroOrPositiveAmount(); @@ -348,8 +329,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { final String repaymentsStartingFromDateParameterName = "repaymentsStartingFromDate"; if (this.fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) { - final LocalDate repaymentsStartingFromDate = this.fromApiJsonHelper.extractLocalDateNamed( - repaymentsStartingFromDateParameterName, element); + final LocalDate repaymentsStartingFromDate = this.fromApiJsonHelper + .extractLocalDateNamed(repaymentsStartingFromDateParameterName, element); baseDataValidator.reset().parameter(repaymentsStartingFromDateParameterName).value(repaymentsStartingFromDate).ignoreIfNull() .notNull(); } @@ -389,8 +370,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { final String createSiAtDisbursementParameterName = "createStandingInstructionAtDisbursement"; if (this.fromApiJsonHelper.parameterExists(createSiAtDisbursementParameterName, element)) { - final Boolean createStandingInstructionAtDisbursement = this.fromApiJsonHelper.extractBooleanNamed( - createSiAtDisbursementParameterName, element); + final Boolean createStandingInstructionAtDisbursement = this.fromApiJsonHelper + .extractBooleanNamed(createSiAtDisbursementParameterName, element); final Long linkAccountId = this.fromApiJsonHelper.extractLongNamed(linkAccountIdParameterName, element); if (createStandingInstructionAtDisbursement) { @@ -407,8 +388,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { if (topLevelJsonElement.get(chargesParameterName).isJsonArray()) { final Type arrayObjectParameterTypeOfMap = new TypeToken>() {}.getType(); - final Set supportedParameters = new HashSet<>(Arrays.asList("id", "chargeId", "amount", "chargeTimeType", - "chargeCalculationType", "dueDate")); + final Set supportedParameters = new HashSet<>( + Arrays.asList("id", "chargeId", "amount", "chargeTimeType", "chargeCalculationType", "dueDate")); final JsonArray array = topLevelJsonElement.get("charges").getAsJsonArray(); for (int i = 1; i <= array.size(); i++) { @@ -451,8 +432,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("type", i).value(collateralTypeId).notNull() .integerGreaterThanZero(); - final BigDecimal collateralValue = this.fromApiJsonHelper - .extractBigDecimalNamed("value", collateralItemElement, locale); + final BigDecimal collateralValue = this.fromApiJsonHelper.extractBigDecimalNamed("value", collateralItemElement, + locale); baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("value", i).value(collateralValue) .ignoreIfNull().positiveAmount(); @@ -478,24 +459,24 @@ public final class LoanApplicationCommandFromApiJsonHelper { baseDataValidator.reset().parameter(LoanApiConstants.emiAmountParameterName).value(emiAnount).ignoreIfNull().positiveAmount(); } if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.maxOutstandingBalanceParameterName, element)) { - final BigDecimal maxOutstandingBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanApiConstants.maxOutstandingBalanceParameterName, element); + final BigDecimal maxOutstandingBalance = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanApiConstants.maxOutstandingBalanceParameterName, element); baseDataValidator.reset().parameter(LoanApiConstants.maxOutstandingBalanceParameterName).value(maxOutstandingBalance) .ignoreIfNull().positiveAmount(); } - if(loanProduct.canUseForTopup()){ - if(this.fromApiJsonHelper.parameterExists(LoanApiConstants.isTopup, element)){ + if (loanProduct.canUseForTopup()) { + if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isTopup, element)) { final Boolean isTopup = this.fromApiJsonHelper.extractBooleanNamed(LoanApiConstants.isTopup, element); baseDataValidator.reset().parameter(LoanApiConstants.isTopup).value(isTopup).validateForBooleanValue(); - if(isTopup != null && isTopup){ + if (isTopup != null && isTopup) { final Long loanId = this.fromApiJsonHelper.extractLongNamed(LoanApiConstants.loanIdToClose, element); baseDataValidator.reset().parameter(LoanApiConstants.loanIdToClose).value(loanId).notNull().longGreaterThanZero(); } } } - if(this.fromApiJsonHelper.parameterExists(LoanApiConstants.datatables, element)){ + if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.datatables, element)) { final JsonArray datatables = this.fromApiJsonHelper.extractJsonArrayNamed(LoanApiConstants.datatables, element); baseDataValidator.reset().parameter(LoanApiConstants.datatables).value(datatables).notNull().jsonArrayNotEmpty(); } @@ -549,8 +530,9 @@ public final class LoanApplicationCommandFromApiJsonHelper { isEqualAmortization = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM, element); baseDataValidator.reset().parameter(LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM).value(isEqualAmortization).ignoreIfNull() .validateForBooleanValue(); - if (isEqualAmortization && loanProduct.isInterestRecalculationEnabled()) { throw new EqualAmortizationUnsupportedFeatureException( - "interest.recalculation", "interest recalculation"); } + if (isEqualAmortization && loanProduct.isInterestRecalculationEnabled()) { + throw new EqualAmortizationUnsupportedFeatureException("interest.recalculation", "interest recalculation"); + } } final String externalIdParameterName = "externalId"; @@ -577,8 +559,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { final String transactionProcessingStrategyIdParameterName = "transactionProcessingStrategyId"; if (this.fromApiJsonHelper.parameterExists(transactionProcessingStrategyIdParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Long transactionProcessingStrategyId = this.fromApiJsonHelper.extractLongNamed( - transactionProcessingStrategyIdParameterName, element); + final Long transactionProcessingStrategyId = this.fromApiJsonHelper + .extractLongNamed(transactionProcessingStrategyIdParameterName, element); baseDataValidator.reset().parameter(transactionProcessingStrategyIdParameterName).value(transactionProcessingStrategyId) .notNull().integerGreaterThanZero(); } @@ -612,8 +594,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { atLeastOneParameterPassedForUpdate = true; final Integer loanTermFrequencyType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyTypeParameterName, element); - baseDataValidator.reset().parameter(loanTermFrequencyTypeParameterName).value(loanTermFrequencyType).notNull() - .inMinMaxRange(0, 3); + baseDataValidator.reset().parameter(loanTermFrequencyTypeParameterName).value(loanTermFrequencyType).notNull().inMinMaxRange(0, + 3); } final String numberOfRepaymentsParameterName = "numberOfRepayments"; @@ -653,14 +635,13 @@ public final class LoanApplicationCommandFromApiJsonHelper { } if (loanProduct.isLinkedToFloatingInterestRate()) { - if (isEqualAmortization) { throw new EqualAmortizationUnsupportedFeatureException("floating.interest.rate", - "floating interest rate"); } + if (isEqualAmortization) { + throw new EqualAmortizationUnsupportedFeatureException("floating.interest.rate", "floating interest rate"); + } if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) { - baseDataValidator - .reset() - .parameter("interestRatePerPeriod") - .failWithCode("not.supported.loanproduct.linked.to.floating.rate", - "interestRatePerPeriod param is not supported, selected Loan Product is linked with floating interest rate."); + baseDataValidator.reset().parameter("interestRatePerPeriod").failWithCode( + "not.supported.loanproduct.linked.to.floating.rate", + "interestRatePerPeriod param is not supported, selected Loan Product is linked with floating interest rate."); } Boolean isFloatingInterestRate = existingLoanApplication.getIsFloatingInterestRate(); @@ -670,11 +651,9 @@ public final class LoanApplicationCommandFromApiJsonHelper { } if (isFloatingInterestRate != null) { if (isFloatingInterestRate && !loanProduct.getFloatingRates().isFloatingInterestRateCalculationAllowed()) { - baseDataValidator - .reset() - .parameter(LoanApiConstants.isFloatingInterestRate) - .failWithCode("true.not.supported.for.selected.loanproduct", - "isFloatingInterestRate value of true not supported for selected Loan Product."); + baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).failWithCode( + "true.not.supported.for.selected.loanproduct", + "isFloatingInterestRate value of true not supported for selected Loan Product."); } } else { baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).trueOrFalseRequired(false); @@ -684,11 +663,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { interestType = existingLoanApplication.getLoanProductRelatedDetail().getInterestMethod().getValue(); } if (interestType != null && interestType.equals(InterestMethod.FLAT.getValue())) { - baseDataValidator - .reset() - .parameter(interestTypeParameterName) - .failWithCode("should.be.0.for.selected.loan.product", - "interestType should be DECLINING_BALANCE for selected Loan Product as it is linked to floating rates."); + baseDataValidator.reset().parameter(interestTypeParameterName).failWithCode("should.be.0.for.selected.loan.product", + "interestType should be DECLINING_BALANCE for selected Loan Product as it is linked to floating rates."); } final String interestRateDifferentialParameterName = LoanApiConstants.interestRateDifferential; @@ -698,30 +674,21 @@ public final class LoanApplicationCommandFromApiJsonHelper { element); atLeastOneParameterPassedForUpdate = true; } - baseDataValidator - .reset() - .parameter(interestRateDifferentialParameterName) - .value(interestRateDifferential) - .notNull() - .zeroOrPositiveAmount() - .inMinAndMaxAmountRange(loanProduct.getFloatingRates().getMinDifferentialLendingRate(), + baseDataValidator.reset().parameter(interestRateDifferentialParameterName).value(interestRateDifferential).notNull() + .zeroOrPositiveAmount().inMinAndMaxAmountRange(loanProduct.getFloatingRates().getMinDifferentialLendingRate(), loanProduct.getFloatingRates().getMaxDifferentialLendingRate()); } else { if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isFloatingInterestRate, element)) { - baseDataValidator - .reset() - .parameter(LoanApiConstants.isFloatingInterestRate) - .failWithCode("not.supported.loanproduct.not.linked.to.floating.rate", - "isFloatingInterestRate param is not supported, selected Loan Product is not linked with floating interest rate."); + baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).failWithCode( + "not.supported.loanproduct.not.linked.to.floating.rate", + "isFloatingInterestRate param is not supported, selected Loan Product is not linked with floating interest rate."); } if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.interestRateDifferential, element)) { - baseDataValidator - .reset() - .parameter(LoanApiConstants.interestRateDifferential) - .failWithCode("not.supported.loanproduct.not.linked.to.floating.rate", - "interestRateDifferential param is not supported, selected Loan Product is not linked with floating interest rate."); + baseDataValidator.reset().parameter(LoanApiConstants.interestRateDifferential).failWithCode( + "not.supported.loanproduct.not.linked.to.floating.rate", + "interestRateDifferential param is not supported, selected Loan Product is not linked with floating interest rate."); } final String interestRatePerPeriodParameterName = "interestRatePerPeriod"; @@ -739,8 +706,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { final String interestCalculationPeriodTypeParameterName = "interestCalculationPeriodType"; if (this.fromApiJsonHelper.parameterExists(interestCalculationPeriodTypeParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - interestCalculationPeriodTypeParameterName, element); + interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(interestCalculationPeriodTypeParameterName, + element); baseDataValidator.reset().parameter(interestCalculationPeriodTypeParameterName).value(interestCalculationPeriodType).notNull() .inMinMaxRange(0, 1); } @@ -767,8 +734,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { // grace validation if (this.fromApiJsonHelper.parameterExists("graceOnPrincipalPayment", element)) { - final Integer graceOnPrincipalPayment = this.fromApiJsonHelper - .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); + final Integer graceOnPrincipalPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", + element); baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment).zeroOrPositiveAmount(); } @@ -783,8 +750,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element)) { - final Integer graceOnArrearsAgeing = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element); + final Integer graceOnArrearsAgeing = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME).value(graceOnArrearsAgeing) .zeroOrPositiveAmount(); } @@ -800,8 +767,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { final String repaymentsStartingFromDateParameterName = "repaymentsStartingFromDate"; if (this.fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final LocalDate repaymentsStartingFromDate = this.fromApiJsonHelper.extractLocalDateNamed( - repaymentsStartingFromDateParameterName, element); + final LocalDate repaymentsStartingFromDate = this.fromApiJsonHelper + .extractLocalDateNamed(repaymentsStartingFromDateParameterName, element); baseDataValidator.reset().parameter(repaymentsStartingFromDateParameterName).value(repaymentsStartingFromDate).ignoreIfNull(); if (!existingLoanApplication.getLoanTermVariations().isEmpty()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("cannot.modify.application.due.to.variable.installments"); @@ -841,8 +808,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { if (topLevelJsonElement.get(chargesParameterName).isJsonArray()) { final Type arrayObjectParameterTypeOfMap = new TypeToken>() {}.getType(); - final Set supportedParameters = new HashSet<>(Arrays.asList("id", "chargeId", "amount", "chargeTimeType", - "chargeCalculationType", "dueDate")); + final Set supportedParameters = new HashSet<>( + Arrays.asList("id", "chargeId", "amount", "chargeTimeType", "chargeCalculationType", "dueDate")); final JsonArray array = topLevelJsonElement.get("charges").getAsJsonArray(); for (int i = 1; i <= array.size(); i++) { @@ -885,8 +852,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("type", i).value(collateralTypeId).notNull() .integerGreaterThanZero(); - final BigDecimal collateralValue = this.fromApiJsonHelper - .extractBigDecimalNamed("value", collateralItemElement, locale); + final BigDecimal collateralValue = this.fromApiJsonHelper.extractBigDecimalNamed("value", collateralItemElement, + locale); baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("value", i).value(collateralValue) .ignoreIfNull().positiveAmount(); @@ -937,18 +904,18 @@ public final class LoanApplicationCommandFromApiJsonHelper { } if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.maxOutstandingBalanceParameterName, element)) { - final BigDecimal maxOutstandingBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanApiConstants.maxOutstandingBalanceParameterName, element); + final BigDecimal maxOutstandingBalance = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanApiConstants.maxOutstandingBalanceParameterName, element); baseDataValidator.reset().parameter(LoanApiConstants.maxOutstandingBalanceParameterName).value(maxOutstandingBalance) .ignoreIfNull().positiveAmount(); } - if(loanProduct.canUseForTopup()){ - if(this.fromApiJsonHelper.parameterExists(LoanApiConstants.isTopup, element)){ + if (loanProduct.canUseForTopup()) { + if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isTopup, element)) { final Boolean isTopup = this.fromApiJsonHelper.extractBooleanNamed(LoanApiConstants.isTopup, element); baseDataValidator.reset().parameter(LoanApiConstants.isTopup).value(isTopup).ignoreIfNull().validateForBooleanValue(); - if(isTopup != null && isTopup){ + if (isTopup != null && isTopup) { final Long loanId = this.fromApiJsonHelper.extractLongNamed(LoanApiConstants.loanIdToClose, element); baseDataValidator.reset().parameter(LoanApiConstants.loanIdToClose).value(loanId).notNull().longGreaterThanZero(); } @@ -958,8 +925,10 @@ public final class LoanApplicationCommandFromApiJsonHelper { validateLoanMultiDisbursementdate(element, baseDataValidator, expectedDisbursementDate, principal); validatePartialPeriodSupport(interestCalculationPeriodType, baseDataValidator, element, loanProduct); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForUndo(final String json) { @@ -997,8 +966,10 @@ public final class LoanApplicationCommandFromApiJsonHelper { .inMinAndMaxAmountRange(minPrincipal, maxPrincipal); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateLoanTermAndRepaidEveryValues(final Integer loanTermFrequency, final Integer loanTermFrequencyType, @@ -1022,8 +993,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { final ApiParameterError error = ApiParameterError.generalError( "validation.msg.loan.numberOfRepayments.lesser.than.minimumNumberOfRepayments", "The total number of calculated repayments for this loan " + actualNumberOfRepayments - + " is lesser than the allowed minimum of " + minimumNoOfRepayments, actualNumberOfRepayments, - minimumNoOfRepayments); + + " is lesser than the allowed minimum of " + minimumNoOfRepayments, + actualNumberOfRepayments, minimumNoOfRepayments); dataValidationErrors.add(error); } @@ -1033,14 +1004,16 @@ public final class LoanApplicationCommandFromApiJsonHelper { final ApiParameterError error = ApiParameterError.generalError( "validation.msg.loan.numberOfRepayments.greater.than.maximumNumberOfRepayments", "The total number of calculated repayments for this loan " + actualNumberOfRepayments - + " is greater than the allowed maximum of " + maximumNoOfRepayments, actualNumberOfRepayments, - maximumNoOfRepayments); + + " is greater than the allowed maximum of " + maximumNoOfRepayments, + actualNumberOfRepayments, maximumNoOfRepayments); dataValidationErrors.add(error); } } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validatelinkedSavingsAccount(final SavingsAccount savingsAccount, final Loan loanApplication) { @@ -1052,12 +1025,15 @@ public final class LoanApplicationCommandFromApiJsonHelper { dataValidationErrors.add(error); } else if (!loanApplication.getClientId().equals(savingsAccount.clientId())) { final ApiParameterError error = ApiParameterError.parameterError( - "validation.msg.loan.linked.savings.account.not.belongs.to.same.client", "Linked Savings account with id:" - + savingsAccount.getId() + " is not belongs to the same client", "linkAccountId", savingsAccount.getId()); + "validation.msg.loan.linked.savings.account.not.belongs.to.same.client", + "Linked Savings account with id:" + savingsAccount.getId() + " is not belongs to the same client", "linkAccountId", + savingsAccount.getId()); dataValidationErrors.add(error); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } private void validateDisbursementsAreDatewiseOrdered(JsonElement element, final DataValidatorBuilder baseDataValidator) { @@ -1109,38 +1085,39 @@ public final class LoanApplicationCommandFromApiJsonHelper { if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isEqualAmortizationParam, element)) { boolean isEqualAmortization = this.fromApiJsonHelper.extractBooleanNamed(LoanApiConstants.isEqualAmortizationParam, element); - if (isEqualAmortization) { throw new EqualAmortizationUnsupportedFeatureException("tranche.disbursal", - "tranche disbursal"); } + if (isEqualAmortization) { + throw new EqualAmortizationUnsupportedFeatureException("tranche.disbursal", "tranche disbursal"); + } } int i = 0; do { final JsonObject jsonObject = variationArray.get(i).getAsJsonObject(); - LocalDate expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed( - LoanApiConstants.disbursementDateParameterName, jsonObject, dateFormat, locale); + LocalDate expectedDisbursementDate = this.fromApiJsonHelper + .extractLocalDateNamed(LoanApiConstants.disbursementDateParameterName, jsonObject, dateFormat, locale); + baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName) + .parameterAtIndexArray(LoanApiConstants.disbursementDateParameterName, i).value(expectedDisbursementDate) + .notNull(); + if (i == 0 && expectedDisbursementDate != null && !expectedDisbursement.equals(expectedDisbursementDate)) { + baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName) + .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_START_WITH_ERROR); + } else if (i > 0 && expectedDisbursementDate != null && expectedDisbursementDate.isBefore(expectedDisbursement)) { baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName) - .parameterAtIndexArray(LoanApiConstants.disbursementDateParameterName, i).value(expectedDisbursementDate) - .notNull(); - if(i == 0 && expectedDisbursementDate != null && !expectedDisbursement.equals(expectedDisbursementDate)) { - baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName) - .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_START_WITH_ERROR); - }else if(i > 0 && expectedDisbursementDate != null && expectedDisbursementDate.isBefore(expectedDisbursement)) { - baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName) - .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_BEFORE_ERROR); - } + .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_BEFORE_ERROR); + } - if (expectedDisbursementDate != null && expectedDisbursementDates.contains(expectedDisbursementDate)) { - baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName) - .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_UNIQUE_ERROR); - } - expectedDisbursementDates.add(expectedDisbursementDate); + if (expectedDisbursementDate != null && expectedDisbursementDates.contains(expectedDisbursementDate)) { + baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName) + .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_UNIQUE_ERROR); + } + expectedDisbursementDates.add(expectedDisbursementDate); - BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalNamed( - LoanApiConstants.disbursementPrincipalParameterName, jsonObject, locale); - baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName) - .parameterAtIndexArray(LoanApiConstants.disbursementPrincipalParameterName, i).value(principal).notBlank(); - if (principal != null) { - tatalDisbursement = tatalDisbursement.add(principal); - } + BigDecimal principal = this.fromApiJsonHelper + .extractBigDecimalNamed(LoanApiConstants.disbursementPrincipalParameterName, jsonObject, locale); + baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName) + .parameterAtIndexArray(LoanApiConstants.disbursementPrincipalParameterName, i).value(principal).notBlank(); + if (principal != null) { + tatalDisbursement = tatalDisbursement.add(principal); + } i++; } while (i < variationArray.size()); @@ -1207,9 +1184,10 @@ public final class LoanApplicationCommandFromApiJsonHelper { .fromInt(interestCalculationPeriodType); boolean considerPartialPeriodUpdates = interestCalculationPeriodMethod.isDaily() ? interestCalculationPeriodMethod.isDaily() : loanProduct.getLoanProductRelatedDetail().isAllowPartialPeriodInterestCalcualtion(); - if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, element)) { - final Boolean considerPartialInterestEnabled = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, element); + if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, + element)) { + final Boolean considerPartialInterestEnabled = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME) .value(considerPartialInterestEnabled).notNull().isOneOfTheseValues(true, false); boolean considerPartialPeriods = considerPartialInterestEnabled == null ? false : considerPartialInterestEnabled; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanApplicationTransitionApiJsonValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanApplicationTransitionApiJsonValidator.java index d4cbd2941..1165d5192 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanApplicationTransitionApiJsonValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanApplicationTransitionApiJsonValidator.java @@ -50,17 +50,20 @@ public final class LoanApplicationTransitionApiJsonValidator { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateApproval(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set disbursementParameters = new HashSet<>(Arrays.asList(LoanApiConstants.loanIdTobeApproved,LoanApiConstants.approvedLoanAmountParameterName, - LoanApiConstants.approvedOnDateParameterName, LoanApiConstants.noteParameterName, LoanApiConstants.localeParameterName, - LoanApiConstants.dateFormatParameterName,LoanApiConstants.disbursementDataParameterName,LoanApiConstants.disbursementDateParameterName)); + final Set disbursementParameters = new HashSet<>(Arrays.asList(LoanApiConstants.loanIdTobeApproved, + LoanApiConstants.approvedLoanAmountParameterName, LoanApiConstants.approvedOnDateParameterName, + LoanApiConstants.noteParameterName, LoanApiConstants.localeParameterName, LoanApiConstants.dateFormatParameterName, + LoanApiConstants.disbursementDataParameterName, LoanApiConstants.disbursementDateParameterName)); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); @@ -70,13 +73,13 @@ public final class LoanApplicationTransitionApiJsonValidator { final JsonElement element = this.fromApiJsonHelper.parse(json); - final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanApiConstants.approvedLoanAmountParameterName, element); + final BigDecimal principal = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanApiConstants.approvedLoanAmountParameterName, element); baseDataValidator.reset().parameter(LoanApiConstants.approvedLoanAmountParameterName).value(principal).ignoreIfNull() .positiveAmount(); - final LocalDate approvedOnDate = this.fromApiJsonHelper - .extractLocalDateNamed(LoanApiConstants.approvedOnDateParameterName, element); + final LocalDate approvedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(LoanApiConstants.approvedOnDateParameterName, + element); baseDataValidator.reset().parameter(LoanApiConstants.approvedOnDateParameterName).value(approvedOnDate).notNull(); final LocalDate expectedDisbursementDate = this.fromApiJsonHelper @@ -86,7 +89,7 @@ public final class LoanApplicationTransitionApiJsonValidator { final String note = this.fromApiJsonHelper.extractStringNamed(LoanApiConstants.noteParameterName, element); baseDataValidator.reset().parameter(LoanApiConstants.noteParameterName).value(note).notExceedingLengthOf(1000); - throwExceptionIfValidationWarningsExist(dataValidationErrors); + throwExceptionIfValidationWarningsExist(dataValidationErrors); } public void validateRejection(final String json) { @@ -103,7 +106,8 @@ public final class LoanApplicationTransitionApiJsonValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanapplication"); final JsonElement element = this.fromApiJsonHelper.parse(json); - final LocalDate rejectedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(LoanApiConstants.rejectedOnDateParameterName, element); + final LocalDate rejectedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(LoanApiConstants.rejectedOnDateParameterName, + element); baseDataValidator.reset().parameter(LoanApiConstants.rejectedOnDateParameterName).value(rejectedOnDate).notNull(); final String note = this.fromApiJsonHelper.extractStringNamed(LoanApiConstants.noteParameterName, element); @@ -126,7 +130,8 @@ public final class LoanApplicationTransitionApiJsonValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanapplication"); final JsonElement element = this.fromApiJsonHelper.parse(json); - final LocalDate withdrawnOnDate = this.fromApiJsonHelper.extractLocalDateNamed(LoanApiConstants.withdrawnOnDateParameterName, element); + final LocalDate withdrawnOnDate = this.fromApiJsonHelper.extractLocalDateNamed(LoanApiConstants.withdrawnOnDateParameterName, + element); baseDataValidator.reset().parameter(LoanApiConstants.withdrawnOnDateParameterName).value(withdrawnOnDate).notNull(); final String note = this.fromApiJsonHelper.extractStringNamed(LoanApiConstants.noteParameterName, element); @@ -134,4 +139,4 @@ public final class LoanApplicationTransitionApiJsonValidator { throwExceptionIfValidationWarningsExist(dataValidationErrors); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanEventApiJsonValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanEventApiJsonValidator.java index 2baa44285..226047ebf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanEventApiJsonValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanEventApiJsonValidator.java @@ -51,17 +51,18 @@ public final class LoanEventApiJsonValidator { private final FromJsonHelper fromApiJsonHelper; private final LoanApplicationCommandFromApiJsonHelper fromApiJsonDeserializer; - @Autowired public LoanEventApiJsonValidator(final FromJsonHelper fromApiJsonHelper, - final LoanApplicationCommandFromApiJsonHelper fromApiJsonDeserializer) { + final LoanApplicationCommandFromApiJsonHelper fromApiJsonDeserializer) { this.fromApiJsonHelper = fromApiJsonHelper; this.fromApiJsonDeserializer = fromApiJsonDeserializer; } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateDisbursement(final String json, boolean isAccountTransfer) { @@ -71,11 +72,11 @@ public final class LoanEventApiJsonValidator { Set disbursementParameters = null; if (isAccountTransfer) { - disbursementParameters = new HashSet<>(Arrays.asList("actualDisbursementDate", "externalId", "note", "locale", - "dateFormat", LoanApiConstants.principalDisbursedParameterName, LoanApiConstants.emiAmountParameterName)); + disbursementParameters = new HashSet<>(Arrays.asList("actualDisbursementDate", "externalId", "note", "locale", "dateFormat", + LoanApiConstants.principalDisbursedParameterName, LoanApiConstants.emiAmountParameterName)); } else { - disbursementParameters = new HashSet<>(Arrays.asList("actualDisbursementDate", "externalId", "note", "locale", - "dateFormat", "paymentTypeId", "accountNumber", "checkNumber", "routingCode", "receiptNumber", "bankNumber", "adjustRepaymentDate", + disbursementParameters = new HashSet<>(Arrays.asList("actualDisbursementDate", "externalId", "note", "locale", "dateFormat", + "paymentTypeId", "accountNumber", "checkNumber", "routingCode", "receiptNumber", "bankNumber", "adjustRepaymentDate", LoanApiConstants.principalDisbursedParameterName, LoanApiConstants.emiAmountParameterName)); } @@ -92,8 +93,8 @@ public final class LoanEventApiJsonValidator { final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); - final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanApiConstants.principalDisbursedParameterName, element); + final BigDecimal principal = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanApiConstants.principalDisbursedParameterName, element); baseDataValidator.reset().parameter(LoanApiConstants.principalDisbursedParameterName).value(principal).ignoreIfNull() .positiveAmount(); @@ -125,9 +126,8 @@ public final class LoanEventApiJsonValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set transactionParameters = new HashSet<>(Arrays.asList("transactionDate", "transactionAmount", "externalId", - "note", "locale", "dateFormat", "paymentTypeId", "accountNumber", "checkNumber", "routingCode", "receiptNumber", - "bankNumber")); + final Set transactionParameters = new HashSet<>(Arrays.asList("transactionDate", "transactionAmount", "externalId", "note", + "locale", "dateFormat", "paymentTypeId", "accountNumber", "checkNumber", "routingCode", "receiptNumber", "bankNumber")); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, transactionParameters); @@ -153,9 +153,9 @@ public final class LoanEventApiJsonValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set transactionParameters = new HashSet<>(Arrays.asList("transactionDate", "transactionAmount", "externalId", - "note", "locale", "dateFormat", "paymentTypeId", "accountNumber", "checkNumber", "routingCode", "receiptNumber", - "bankNumber","loanId")); + final Set transactionParameters = new HashSet<>( + Arrays.asList("transactionDate", "transactionAmount", "externalId", "note", "locale", "dateFormat", "paymentTypeId", + "accountNumber", "checkNumber", "routingCode", "receiptNumber", "bankNumber", "loanId")); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, transactionParameters); @@ -196,8 +196,8 @@ public final class LoanEventApiJsonValidator { // Validate all string payment detail fields for max length final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("paymentTypeId", element); baseDataValidator.reset().parameter("paymentTypeId").value(paymentTypeId).ignoreIfNull().integerGreaterThanZero(); - final Set paymentDetailParameters = new HashSet<>(Arrays.asList("accountNumber", "checkNumber", "routingCode", - "receiptNumber", "bankNumber")); + final Set paymentDetailParameters = new HashSet<>( + Arrays.asList("accountNumber", "checkNumber", "routingCode", "receiptNumber", "bankNumber")); for (final String paymentDetailParameterName : paymentDetailParameters) { final String paymentDetailParameterValue = this.fromApiJsonHelper.extractStringNamed(paymentDetailParameterName, element); baseDataValidator.reset().parameter(paymentDetailParameterName).value(paymentDetailParameterValue).ignoreIfNull() @@ -208,7 +208,8 @@ public final class LoanEventApiJsonValidator { public void validateTransactionWithNoAmount(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set disbursementParameters = new HashSet<>(Arrays.asList("transactionDate", "note", "locale", "dateFormat","writeoffReasonId")); + final Set disbursementParameters = new HashSet<>( + Arrays.asList("transactionDate", "note", "locale", "dateFormat", "writeoffReasonId")); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); @@ -229,8 +230,7 @@ public final class LoanEventApiJsonValidator { public void validateAddLoanCharge(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set disbursementParameters = new HashSet<>(Arrays.asList("chargeId", "amount", "dueDate", "locale", - "dateFormat")); + final Set disbursementParameters = new HashSet<>(Arrays.asList("chargeId", "amount", "dueDate", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); @@ -279,8 +279,8 @@ public final class LoanEventApiJsonValidator { public void validateUpdateOfLoanOfficer(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set disbursementParameters = new HashSet<>(Arrays.asList("assignmentDate", "fromLoanOfficerId", - "toLoanOfficerId", "locale", "dateFormat")); + final Set disbursementParameters = new HashSet<>( + Arrays.asList("assignmentDate", "fromLoanOfficerId", "toLoanOfficerId", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); @@ -307,8 +307,8 @@ public final class LoanEventApiJsonValidator { public void validateForBulkLoanReassignment(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set supportedParameters = new HashSet<>(Arrays.asList("assignmentDate", "fromLoanOfficerId", "toLoanOfficerId", - "loans", "locale", "dateFormat")); + final Set supportedParameters = new HashSet<>( + Arrays.asList("assignmentDate", "fromLoanOfficerId", "toLoanOfficerId", "loans", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); @@ -335,11 +335,10 @@ public final class LoanEventApiJsonValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } Set transactionParameters = null; if (isChargeIdIncluded) { - transactionParameters = new HashSet<>(Arrays.asList("transactionDate", "locale", "dateFormat", "chargeId", "dueDate", - "installmentNumber")); + transactionParameters = new HashSet<>( + Arrays.asList("transactionDate", "locale", "dateFormat", "chargeId", "dueDate", "installmentNumber")); } else { - transactionParameters = new HashSet<>(Arrays.asList("transactionDate", "locale", "dateFormat", "dueDate", - "installmentNumber")); + transactionParameters = new HashSet<>(Arrays.asList("transactionDate", "locale", "dateFormat", "dueDate", "installmentNumber")); } final Type typeOfMap = new TypeToken>() {}.getType(); @@ -385,9 +384,10 @@ public final class LoanEventApiJsonValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set disbursementParameters = new HashSet<>(Arrays.asList("locale", "dateFormat", LoanApiConstants.disbursementDataParameterName, - LoanApiConstants.approvedLoanAmountParameterName, LoanApiConstants.updatedDisbursementDateParameterName, LoanApiConstants.updatedDisbursementPrincipalParameterName, - LoanApiConstants.disbursementDateParameterName)); + final Set disbursementParameters = new HashSet<>( + Arrays.asList("locale", "dateFormat", LoanApiConstants.disbursementDataParameterName, + LoanApiConstants.approvedLoanAmountParameterName, LoanApiConstants.updatedDisbursementDateParameterName, + LoanApiConstants.updatedDisbursementPrincipalParameterName, LoanApiConstants.disbursementDateParameterName)); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); @@ -396,23 +396,22 @@ public final class LoanEventApiJsonValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.update.disbursement"); final JsonElement element = this.fromApiJsonHelper.parse(json); - final LocalDate actualDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed( - LoanApiConstants.disbursementDateParameterName, element); + final LocalDate actualDisbursementDate = this.fromApiJsonHelper + .extractLocalDateNamed(LoanApiConstants.disbursementDateParameterName, element); baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName).value(actualDisbursementDate).notNull(); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject()); - final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalNamed(LoanApiConstants.updatedDisbursementPrincipalParameterName, - element,locale); + final BigDecimal principal = this.fromApiJsonHelper + .extractBigDecimalNamed(LoanApiConstants.updatedDisbursementPrincipalParameterName, element, locale); baseDataValidator.reset().parameter(LoanApiConstants.disbursementPrincipalParameterName).value(principal).notNull(); final BigDecimal approvedPrincipal = this.fromApiJsonHelper.extractBigDecimalNamed(LoanApiConstants.approvedLoanAmountParameterName, - element,locale); + element, locale); if (loanDisbursementDetails.actualDisbursementDate() != null) { baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName) .failWithCode(LoanApiConstants.ALREADY_DISBURSED); } - fromApiJsonDeserializer.validateLoanMultiDisbursementdate(element, baseDataValidator, actualDisbursementDate, approvedPrincipal); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -422,9 +421,8 @@ public final class LoanEventApiJsonValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set transactionParameters = new HashSet<>(Arrays.asList("transactionDate", "transactionAmount", "externalId", - "note", "locale", "dateFormat", "paymentTypeId", "accountNumber", "checkNumber", "routingCode", "receiptNumber", - "bankNumber")); + final Set transactionParameters = new HashSet<>(Arrays.asList("transactionDate", "transactionAmount", "externalId", "note", + "locale", "dateFormat", "paymentTypeId", "accountNumber", "checkNumber", "routingCode", "receiptNumber", "bankNumber")); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, transactionParameters); @@ -468,4 +466,4 @@ public final class LoanEventApiJsonValidator { validatePaymentDetails(baseDataValidator, element); throwExceptionIfValidationWarningsExist(dataValidationErrors); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanUpdateCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanUpdateCommandFromApiJsonDeserializer.java index 2225356e1..7eea82d98 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanUpdateCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/LoanUpdateCommandFromApiJsonDeserializer.java @@ -62,4 +62,4 @@ public final class LoanUpdateCommandFromApiJsonDeserializer extends AbstractFrom return new LoanUpdateCommand(unassignedDate); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/VariableLoanScheduleFromApiJsonValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/VariableLoanScheduleFromApiJsonValidator.java index af2b17cc5..e5a2d2dc0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/VariableLoanScheduleFromApiJsonValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/serialization/VariableLoanScheduleFromApiJsonValidator.java @@ -49,9 +49,8 @@ public class VariableLoanScheduleFromApiJsonValidator { final Set variableSchedulesupportedParameters = new HashSet<>(Arrays.asList(LoanApiConstants.exceptionParamName, LoanApiConstants.localeParameterName, LoanApiConstants.dateFormatParameterName)); - final Set variableSchedulesupportedArrayParameters = new HashSet<>(Arrays.asList( - LoanApiConstants.modifiedinstallmentsParamName, LoanApiConstants.newinstallmentsParamName, - LoanApiConstants.deletedinstallmentsParamName)); + final Set variableSchedulesupportedArrayParameters = new HashSet<>(Arrays.asList(LoanApiConstants.modifiedinstallmentsParamName, + LoanApiConstants.newinstallmentsParamName, LoanApiConstants.deletedinstallmentsParamName)); final Set variableScheduleModifiedParameters = new HashSet<>(Arrays.asList(LoanApiConstants.dueDateParamName, LoanApiConstants.modifiedDueDateParamName, LoanApiConstants.principalParamName, LoanApiConstants.installmentAmountParamName)); final Set variableScheduleNewInstallmentParameters = new HashSet<>(Arrays.asList(LoanApiConstants.dueDateParamName, @@ -135,9 +134,8 @@ public class VariableLoanScheduleFromApiJsonValidator { List unsupportedParams = new ArrayList<>(1); unsupportedParams.add(LoanApiConstants.principalParamName); throw new UnsupportedParameterException(unsupportedParams); - } else if ((!loan.getLoanProductRelatedDetail().getInterestMethod().isDecliningBalnce() || loan.getLoanProductRelatedDetail() - .getAmortizationMethod().isEqualPrincipal()) - && installmentAmount != null) { + } else if ((!loan.getLoanProductRelatedDetail().getInterestMethod().isDecliningBalnce() + || loan.getLoanProductRelatedDetail().getAmortizationMethod().isEqualPrincipal()) && installmentAmount != null) { List unsupportedParams = new ArrayList<>(1); unsupportedParams.add(LoanApiConstants.installmentAmountParamName); throw new UnsupportedParameterException(unsupportedParams); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/BulkLoansReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/BulkLoansReadPlatformServiceImpl.java index 1bc184385..90dabd7fa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/BulkLoansReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/BulkLoansReadPlatformServiceImpl.java @@ -119,4 +119,4 @@ public class BulkLoansReadPlatformServiceImpl implements BulkLoansReadPlatformSe return new StaffAccountSummaryCollectionData.LoanAccountSummary(id, name); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoReadPlatformService.java index 7974ceff5..cf5960ea5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoReadPlatformService.java @@ -24,21 +24,21 @@ import org.apache.fineract.portfolio.loanaccount.data.GLIMContainer; import org.apache.fineract.portfolio.loanaccount.data.GlimRepaymentTemplate; import org.apache.fineract.portfolio.loanaccount.data.GroupLoanIndividualMonitoringAccountData; -public interface GLIMAccountInfoReadPlatformService -{ - Collection findGlimAccountsByGroupId(String groupId); +public interface GLIMAccountInfoReadPlatformService { - Collection findGlimAccountByGroupId(String groupId); + Collection findGlimAccountsByGroupId(String groupId); - Collection findGlimAccount(Long groupId); + Collection findGlimAccountByGroupId(String groupId); - Collection findGlimAccountByGroupIdandAccountNo(String groupId, String accountNo); + Collection findGlimAccount(Long groupId); - Collection findGlimAccountbyGroupAndAccount(Long groupId, String accountNo); + Collection findGlimAccountByGroupIdandAccountNo(String groupId, String accountNo); - Collection findGlimAccountByParentAccountId(String parentAccountIds); + Collection findGlimAccountbyGroupAndAccount(Long groupId, String accountNo); - Collection findGlimAccountsByGLIMId(Long glimId); + Collection findGlimAccountByParentAccountId(String parentAccountIds); - Collection findglimRepaymentTemplate(Long glimId); -} \ No newline at end of file + Collection findGlimAccountsByGLIMId(Long glimId); + + Collection findglimRepaymentTemplate(Long glimId); +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoReadPlatformServiceImpl.java index 3f1c64667..9f1ea5094 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoReadPlatformServiceImpl.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.fineract.portfolio.loanaccount.service; import java.math.BigDecimal; @@ -40,59 +39,56 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class GLIMAccountInfoReadPlatformServiceImpl implements GLIMAccountInfoReadPlatformService -{ +public class GLIMAccountInfoReadPlatformServiceImpl implements GLIMAccountInfoReadPlatformService { private final JdbcTemplate jdbcTemplate; private final PlatformSecurityContext context; private final AccountDetailsReadPlatformService accountDetailsReadPlatforService; - @Autowired public GLIMAccountInfoReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, final AccountDetailsReadPlatformService accountDetailsReadPlatforService) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); - this.accountDetailsReadPlatforService=accountDetailsReadPlatforService; + this.accountDetailsReadPlatforService = accountDetailsReadPlatforService; - } + } private static final class GLIMFieldsMapper implements RowMapper { + public String schema() { return "glim.id as glimId,ln.group_id as groupId,glim.account_number as accountNumber, ln.account_no as childAccountNumber,ln.principal_amount as childPrincipalAmount,glim.principal_amount as parentPrincipalAmount,glim.child_accounts_count as childAccountsCount," - +"glim.loan_status_id as loanStatus from glim_accounts glim,m_loan ln where glim.id=ln.glim_id"; + + "glim.loan_status_id as loanStatus from glim_accounts glim,m_loan ln where glim.id=ln.glim_id"; } @Override public GroupLoanIndividualMonitoringAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - final BigDecimal glimId=rs.getBigDecimal("glimId"); + final BigDecimal glimId = rs.getBigDecimal("glimId"); - final BigDecimal groupId=rs.getBigDecimal("groupId"); + final BigDecimal groupId = rs.getBigDecimal("groupId"); - final String accountNumber=rs.getString("accountNumber"); + final String accountNumber = rs.getString("accountNumber"); - final String childAccountNumber=rs.getString("childAccountNumber"); + final String childAccountNumber = rs.getString("childAccountNumber"); - final Long childAccountsCount=rs.getLong("childAccountsCount"); + final Long childAccountsCount = rs.getLong("childAccountsCount"); - final BigDecimal parentPrincipalAmount=rs.getBigDecimal("parentPrincipalAmount"); + final BigDecimal parentPrincipalAmount = rs.getBigDecimal("parentPrincipalAmount"); - final BigDecimal childPrincipalAmount=rs.getBigDecimal("childPrincipalAmount"); + final BigDecimal childPrincipalAmount = rs.getBigDecimal("childPrincipalAmount"); - final String loanStatus=LoanStatus.fromInt((int)rs.getLong("loanStatus")).toString(); + final String loanStatus = LoanStatus.fromInt((int) rs.getLong("loanStatus")).toString(); - - return GroupLoanIndividualMonitoringAccountData.getInstance(glimId,groupId,accountNumber,childAccountNumber,childPrincipalAmount,parentPrincipalAmount, - childAccountsCount,loanStatus); + return GroupLoanIndividualMonitoringAccountData.getInstance(glimId, groupId, accountNumber, childAccountNumber, + childPrincipalAmount, parentPrincipalAmount, childAccountsCount, loanStatus); } } - @Override - public Collection findGlimAccountsByGLIMId(final Long glimId) { + public Collection findGlimAccountsByGLIMId(final Long glimId) { this.context.authenticatedUser(); final GLIMFieldsMapper rm = new GLIMFieldsMapper(); @@ -102,7 +98,7 @@ public class GLIMAccountInfoReadPlatformServiceImpl implements GLIMAccountInfoRe } @Override - public Collection findGlimAccountsByGroupId(String groupId) { + public Collection findGlimAccountsByGroupId(String groupId) { this.context.authenticatedUser(); final GLIMFieldsMapper rm = new GLIMFieldsMapper(); @@ -111,21 +107,19 @@ public class GLIMAccountInfoReadPlatformServiceImpl implements GLIMAccountInfoRe return this.jdbcTemplate.query(sql, rm, new Object[] { groupId }); } - @Override - public Collection findGlimAccountByGroupId(String groupId) { + public Collection findGlimAccountByGroupId(String groupId) { this.context.authenticatedUser(); - GLIMMapper rm=new GLIMMapper(); + GLIMMapper rm = new GLIMMapper(); - final String sql="select "+rm.schema()+" where glim.group_id=?"; + final String sql = "select " + rm.schema() + " where glim.group_id=?"; return this.jdbcTemplate.query(sql, rm, new Object[] { groupId }); } - @Override - public Collection findGlimAccountByParentAccountId(String parentAccountIds) { + public Collection findGlimAccountByParentAccountId(String parentAccountIds) { this.context.authenticatedUser(); final GLIMFieldsMapper rm = new GLIMFieldsMapper(); @@ -135,128 +129,130 @@ public class GLIMAccountInfoReadPlatformServiceImpl implements GLIMAccountInfoRe } @Override - public Collection findGlimAccountByGroupIdandAccountNo(String groupId,String accountNo) { + public Collection findGlimAccountByGroupIdandAccountNo(String groupId, String accountNo) { this.context.authenticatedUser(); - GLIMMapper rm=new GLIMMapper(); + GLIMMapper rm = new GLIMMapper(); - final String sql="select "+rm.schema()+" where glim.group_id=? and glim.account_number=?"; + final String sql = "select " + rm.schema() + " where glim.group_id=? and glim.account_number=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { groupId,accountNo }); + return this.jdbcTemplate.query(sql, rm, new Object[] { groupId, accountNo }); } @Override - public Collection findGlimAccount(Long groupId) { + public Collection findGlimAccount(Long groupId) { this.context.authenticatedUser(); - Collection glimInfo=findGlimAccountByGroupId(groupId+""); + Collection glimInfo = findGlimAccountByGroupId(groupId + ""); - //List glimAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new Object[] { groupId }); + // List glimAccounts = + // retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new + // Object[] { groupId }); - List glimAccounts=new ArrayList(); - for(GroupLoanIndividualMonitoringAccountData glimAccount:glimInfo) - { + List glimAccounts = new ArrayList(); + for (GroupLoanIndividualMonitoringAccountData glimAccount : glimInfo) { - List childLoans=accountDetailsReadPlatforService.retrieveLoanAccountDetailsByGroupIdAndGlimAccountNumber(groupId,glimAccount.getAccountNumber()); - glimAccounts.add(new GLIMContainer(glimAccount.getGlimId(),glimAccount.getGroupId(), glimAccount.getAccountNumber(), - childLoans, glimAccount.getParentPrincipalAmount(),glimAccount.getLoanStatus())); + List childLoans = accountDetailsReadPlatforService + .retrieveLoanAccountDetailsByGroupIdAndGlimAccountNumber(groupId, glimAccount.getAccountNumber()); + glimAccounts.add(new GLIMContainer(glimAccount.getGlimId(), glimAccount.getGroupId(), glimAccount.getAccountNumber(), + childLoans, glimAccount.getParentPrincipalAmount(), glimAccount.getLoanStatus())); } return glimAccounts; } @Override - public Collection findGlimAccountbyGroupAndAccount(Long groupId,String accountNo) { + public Collection findGlimAccountbyGroupAndAccount(Long groupId, String accountNo) { this.context.authenticatedUser(); - Collection glimInfo=findGlimAccountByGroupIdandAccountNo(groupId+"", accountNo+""); + Collection glimInfo = findGlimAccountByGroupIdandAccountNo(groupId + "", accountNo + ""); - //List glimAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new Object[] { groupId }); + // List glimAccounts = + // retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new + // Object[] { groupId }); - List glimAccounts=new ArrayList(); - for(GroupLoanIndividualMonitoringAccountData glimAccount:glimInfo) - { + List glimAccounts = new ArrayList(); + for (GroupLoanIndividualMonitoringAccountData glimAccount : glimInfo) { - List childLoans=accountDetailsReadPlatforService.retrieveLoanAccountDetailsByGroupIdAndGlimAccountNumber(groupId,glimAccount.getAccountNumber()); - glimAccounts.add(new GLIMContainer(glimAccount.getGlimId(),glimAccount.getGroupId(), glimAccount.getAccountNumber(), - childLoans, glimAccount.getParentPrincipalAmount(),glimAccount.getLoanStatus())); + List childLoans = accountDetailsReadPlatforService + .retrieveLoanAccountDetailsByGroupIdAndGlimAccountNumber(groupId, glimAccount.getAccountNumber()); + glimAccounts.add(new GLIMContainer(glimAccount.getGlimId(), glimAccount.getGroupId(), glimAccount.getAccountNumber(), + childLoans, glimAccount.getParentPrincipalAmount(), glimAccount.getLoanStatus())); } return glimAccounts; } @Override - public Collection findglimRepaymentTemplate(final Long glimId) - { + public Collection findglimRepaymentTemplate(final Long glimId) { this.context.authenticatedUser(); - GLIMRepaymentMapper rm=new GLIMRepaymentMapper(); + GLIMRepaymentMapper rm = new GLIMRepaymentMapper(); - final String sql="select "+rm.schema()+" where glim.id=?"; + final String sql = "select " + rm.schema() + " where glim.id=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] {glimId}); + return this.jdbcTemplate.query(sql, rm, new Object[] { glimId }); } - private static final class GLIMMapper implements RowMapper { + public String schema() { - return "glim.id as glimId,glim.group_id as groupId,glim.account_number as accountNumber,glim.principal_amount as principalAmount,glim.child_accounts_count as childAccountsCount,"+ - "glim.loan_status_id as loanStatus from glim_accounts glim"; + return "glim.id as glimId,glim.group_id as groupId,glim.account_number as accountNumber,glim.principal_amount as principalAmount,glim.child_accounts_count as childAccountsCount," + + "glim.loan_status_id as loanStatus from glim_accounts glim"; } @Override public GroupLoanIndividualMonitoringAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - final BigDecimal glimId=rs.getBigDecimal("glimId"); + final BigDecimal glimId = rs.getBigDecimal("glimId"); - final BigDecimal groupId=rs.getBigDecimal("groupId"); + final BigDecimal groupId = rs.getBigDecimal("groupId"); - final String accountNumber=rs.getString("accountNumber"); + final String accountNumber = rs.getString("accountNumber"); - final BigDecimal principalAmount=rs.getBigDecimal("principalAmount"); + final BigDecimal principalAmount = rs.getBigDecimal("principalAmount"); - final String loanStatus=LoanStatus.fromInt((int)rs.getLong("loanStatus")).toString(); + final String loanStatus = LoanStatus.fromInt((int) rs.getLong("loanStatus")).toString(); - return GroupLoanIndividualMonitoringAccountData.getInstance1(glimId,groupId, accountNumber, principalAmount,loanStatus); + return GroupLoanIndividualMonitoringAccountData.getInstance1(glimId, groupId, accountNumber, principalAmount, loanStatus); } } - private static final class GLIMRepaymentMapper implements RowMapper { + public String schema() { - return "glim.id as glimId,loan.group_id as groupId,client.id as clientId,glim.account_number as parentLoanAccountNo,"+ - "glim.principal_amount as parentPrincipalAmount,loan.id as childLoanId,loan.account_no as childLoanAccountNo,loan.approved_principal as childPrincipalAmount,"+ - "client.display_name as clientName from glim_accounts glim left join m_loan loan on loan.glim_id=glim.id "+ - "left join m_client client on client.id=loan.client_id"; + return "glim.id as glimId,loan.group_id as groupId,client.id as clientId,glim.account_number as parentLoanAccountNo," + + "glim.principal_amount as parentPrincipalAmount,loan.id as childLoanId,loan.account_no as childLoanAccountNo,loan.approved_principal as childPrincipalAmount," + + "client.display_name as clientName from glim_accounts glim left join m_loan loan on loan.glim_id=glim.id " + + "left join m_client client on client.id=loan.client_id"; } @Override - public GlimRepaymentTemplate mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public GlimRepaymentTemplate mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - final BigDecimal glimId=rs.getBigDecimal("glimId"); + final BigDecimal glimId = rs.getBigDecimal("glimId"); - final BigDecimal groupId=rs.getBigDecimal("groupId"); + final BigDecimal groupId = rs.getBigDecimal("groupId"); - final BigDecimal clientId=rs.getBigDecimal("clientId"); + final BigDecimal clientId = rs.getBigDecimal("clientId"); - final String clientName=rs.getString("clientName"); + final String clientName = rs.getString("clientName"); - final BigDecimal childLoanId=rs.getBigDecimal("childLoanId"); + final BigDecimal childLoanId = rs.getBigDecimal("childLoanId"); - final String parentLoanAccountNo=rs.getString("parentLoanAccountNo"); + final String parentLoanAccountNo = rs.getString("parentLoanAccountNo"); - final BigDecimal parentPrincipalAmount=rs.getBigDecimal("parentPrincipalAmount"); + final BigDecimal parentPrincipalAmount = rs.getBigDecimal("parentPrincipalAmount"); - final String childLoanAccountNo=rs.getString("childLoanAccountNo"); + final String childLoanAccountNo = rs.getString("childLoanAccountNo"); - final BigDecimal childPrincipalAmount=rs.getBigDecimal("childPrincipalAmount"); + final BigDecimal childPrincipalAmount = rs.getBigDecimal("childPrincipalAmount"); - return GlimRepaymentTemplate.getInstance(glimId,groupId,clientId,clientName,childLoanId,parentLoanAccountNo, - parentPrincipalAmount,childLoanAccountNo,childPrincipalAmount); + return GlimRepaymentTemplate.getInstance(glimId, groupId, clientId, clientName, childLoanId, parentLoanAccountNo, + parentPrincipalAmount, childLoanAccountNo, childPrincipalAmount); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoWritePlatformService.java index 4c3d1b4f0..042a1ff2b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoWritePlatformService.java @@ -33,4 +33,4 @@ public interface GLIMAccountInfoWritePlatformService { void addGLIMAccountInfo(String accountNumber, Group group, BigDecimal principalAmount, Long childAccountsCount, Boolean isAcceptingChild, Integer loanStatus, BigDecimal applicationId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoWritePlatformServiceImpl.java index dbe32144f..b5e3c90e7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/GLIMAccountInfoWritePlatformServiceImpl.java @@ -29,8 +29,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class GLIMAccountInfoWritePlatformServiceImpl implements GLIMAccountInfoWritePlatformService -{ +public class GLIMAccountInfoWritePlatformServiceImpl implements GLIMAccountInfoWritePlatformService { private final PlatformSecurityContext context; @@ -39,56 +38,44 @@ public class GLIMAccountInfoWritePlatformServiceImpl implements GLIMAccountInfoW private final LoanRepository loanRepository; @Autowired - public GLIMAccountInfoWritePlatformServiceImpl(final PlatformSecurityContext context,final GLIMAccountInfoRepository glimAccountRepository, - final LoanRepository loanRepository) - { - this.context=context; - this.glimAccountRepository=glimAccountRepository; - this.loanRepository=loanRepository; + public GLIMAccountInfoWritePlatformServiceImpl(final PlatformSecurityContext context, + final GLIMAccountInfoRepository glimAccountRepository, final LoanRepository loanRepository) { + this.context = context; + this.glimAccountRepository = glimAccountRepository; + this.loanRepository = loanRepository; } @Override - public void addGLIMAccountInfo(String accountNumber,Group group,BigDecimal principalAmount,Long childAccountsCount, - Boolean isAcceptingChild,Integer loanStatus,BigDecimal applicationId) - { - childAccountsCount=2L; - GroupLoanIndividualMonitoringAccount glimAccountInfo=GroupLoanIndividualMonitoringAccount.getInstance(accountNumber,group,principalAmount,childAccountsCount, - isAcceptingChild,loanStatus,applicationId); - - this.glimAccountRepository.save(glimAccountInfo ); + public void addGLIMAccountInfo(String accountNumber, Group group, BigDecimal principalAmount, Long childAccountsCount, + Boolean isAcceptingChild, Integer loanStatus, BigDecimal applicationId) { + childAccountsCount = 2L; + GroupLoanIndividualMonitoringAccount glimAccountInfo = GroupLoanIndividualMonitoringAccount.getInstance(accountNumber, group, + principalAmount, childAccountsCount, isAcceptingChild, loanStatus, applicationId); + this.glimAccountRepository.save(glimAccountInfo); } - @Override - public void setIsAcceptingChild(GroupLoanIndividualMonitoringAccount glimAccount) - { + public void setIsAcceptingChild(GroupLoanIndividualMonitoringAccount glimAccount) { glimAccount.setIsAcceptingChild(true); glimAccountRepository.save(glimAccount); } - @Override - public void resetIsAcceptingChild(GroupLoanIndividualMonitoringAccount glimAccount) - { + public void resetIsAcceptingChild(GroupLoanIndividualMonitoringAccount glimAccount) { glimAccount.setIsAcceptingChild(false); glimAccountRepository.save(glimAccount); } - @Override - public void incrementChildAccountCount(GroupLoanIndividualMonitoringAccount glimAccount) - { - long count=glimAccount.getChildAccountsCount(); - glimAccount.setChildAccountsCount(count+1); + public void incrementChildAccountCount(GroupLoanIndividualMonitoringAccount glimAccount) { + long count = glimAccount.getChildAccountsCount(); + glimAccount.setChildAccountsCount(count + 1); glimAccountRepository.save(glimAccount); } - - - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualPlatformService.java index edcbf9402..143d2453e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualPlatformService.java @@ -33,6 +33,7 @@ public interface LoanAccrualPlatformService { void addAccrualAccounting() throws JobExecutionException; void addPeriodicAccruals() throws JobExecutionException; + void addPeriodicAccrualsForLoansWithIncomePostedAsTransactions() throws JobExecutionException; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualPlatformServiceImpl.java index 5798c962b..e78ccb892 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualPlatformServiceImpl.java @@ -93,7 +93,8 @@ public class LoanAccrualPlatformServiceImpl implements LoanAccrualPlatformServic } @Override - public void addPeriodicAccruals(final LocalDate tilldate, Collection loanScheduleAccrualDatas) throws JobExecutionException { + public void addPeriodicAccruals(final LocalDate tilldate, Collection loanScheduleAccrualDatas) + throws JobExecutionException { Map> loanDataMap = new HashMap<>(); for (final LoanScheduleAccrualData accrualData : loanScheduleAccrualDatas) { if (loanDataMap.containsKey(accrualData.getLoanId())) { @@ -121,7 +122,7 @@ public class LoanAccrualPlatformServiceImpl implements LoanAccrualPlatformServic @CronTarget(jobName = JobName.ADD_PERIODIC_ACCRUAL_ENTRIES_FOR_LOANS_WITH_INCOME_POSTED_AS_TRANSACTIONS) public void addPeriodicAccrualsForLoansWithIncomePostedAsTransactions() throws JobExecutionException { Collection loanIds = this.loanReadPlatformService.retrieveLoanIdsWithPendingIncomePostingTransactions(); - if(loanIds != null && loanIds.size() > 0){ + if (loanIds != null && loanIds.size() > 0) { List errors = new ArrayList<>(); for (Long loanId : loanIds) { try { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualWritePlatformService.java old mode 100755 new mode 100644 index fc725aa13..57aa0e325 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualWritePlatformService.java @@ -26,7 +26,8 @@ public interface LoanAccrualWritePlatformService { void addAccrualAccounting(Long loanId, Collection loanScheduleAccrualDatas) throws Exception; - void addPeriodicAccruals(LocalDate tilldate, Long loanId, Collection loanScheduleAccrualDatas) throws Exception; + void addPeriodicAccruals(LocalDate tilldate, Long loanId, Collection loanScheduleAccrualDatas) + throws Exception; void addIncomeAndAccrualTransactions(Long loanId) throws Exception; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualWritePlatformServiceImpl.java old mode 100755 new mode 100644 index 72bc8d441..f8a3049b4 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAccrualWritePlatformServiceImpl.java @@ -375,9 +375,8 @@ public class LoanAccrualWritePlatformServiceImpl implements LoanAccrualWritePlat } chargeAmount = accruableForInstallment; boolean canAddCharge = chargeAmount.compareTo(BigDecimal.ZERO) > 0; - if (canAddCharge - && (installmentChargeData.getAmountAccrued() == null || chargeAmount.compareTo(installmentChargeData - .getAmountAccrued()) != 0)) { + if (canAddCharge && (installmentChargeData.getAmountAccrued() == null + || chargeAmount.compareTo(installmentChargeData.getAmountAccrued()) != 0)) { BigDecimal amountForAccrual = chargeAmount; if (installmentChargeData.getAmountAccrued() != null) { amountForAccrual = chargeAmount.subtract(installmentChargeData.getAmountAccrued()); @@ -431,8 +430,8 @@ public class LoanAccrualWritePlatformServiceImpl implements LoanAccrualWritePlat final LocalDate tilldate) { BigDecimal interestIncome = BigDecimal.ZERO; - if(accrualData.getInterestIncome() != null) { - interestIncome = accrualData.getInterestIncome(); + if (accrualData.getInterestIncome() != null) { + interestIncome = accrualData.getInterestIncome(); } if (accrualData.getWaivedInterestIncome() != null) { BigDecimal recognized = BigDecimal.ZERO; @@ -443,8 +442,8 @@ public class LoanAccrualWritePlatformServiceImpl implements LoanAccrualWritePlat for (LoanTransactionData loanTransactionData : loanWaiverTansactions) { if (!loanTransactionData.dateOf().isAfter(accrualData.getFromDateAsLocaldate()) || (loanTransactionData.dateOf().isAfter(accrualData.getFromDateAsLocaldate()) - && !loanTransactionData.dateOf().isAfter(accrualData.getDueDateAsLocaldate()) && !loanTransactionData - .dateOf().isAfter(tilldate))) { + && !loanTransactionData.dateOf().isAfter(accrualData.getDueDateAsLocaldate()) + && !loanTransactionData.dateOf().isAfter(tilldate))) { loanTransactionDatas.add(loanTransactionData); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanApplicationWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanApplicationWritePlatformService.java index dac5507f1..510b8866b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanApplicationWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanApplicationWritePlatformService.java @@ -42,4 +42,4 @@ public interface LoanApplicationWritePlatformService { CommandProcessingResult undoGLIMLoanApplicationApproval(Long loanId, JsonCommand command); CommandProcessingResult rejectGLIMApplicationApproval(Long loanId, JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index da71211c7..4f6582e5a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java @@ -120,7 +120,6 @@ import org.apache.fineract.portfolio.loanaccount.serialization.LoanApplicationCo import org.apache.fineract.portfolio.loanaccount.serialization.LoanApplicationTransitionApiJsonValidator; import org.apache.fineract.portfolio.loanproduct.LoanProductConstants; import org.apache.fineract.portfolio.loanproduct.data.LoanProductData; -//import org.apache.fineract.portfolio.loanproduct.domain.*; import org.apache.fineract.portfolio.loanproduct.domain.LoanProduct; import org.apache.fineract.portfolio.loanproduct.domain.LoanProductRelatedDetail; import org.apache.fineract.portfolio.loanproduct.domain.LoanProductRepository; @@ -147,7 +146,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; - @Service public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements LoanApplicationWritePlatformService { @@ -202,26 +200,25 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa final LoanProductDataValidator loanProductCommandFromApiJsonDeserializer, final AprCalculator aprCalculator, final LoanAssembler loanAssembler, final LoanChargeAssembler loanChargeAssembler, final CollateralAssembler loanCollateralAssembler, final LoanRepositoryWrapper loanRepositoryWrapper, - final NoteRepository noteRepository, - final LoanScheduleCalculationPlatformService calculationPlatformService, final ClientRepositoryWrapper clientRepository, - final LoanProductRepository loanProductRepository, final AccountNumberGenerator accountNumberGenerator, - final LoanSummaryWrapper loanSummaryWrapper, final GroupRepositoryWrapper groupRepository, + final NoteRepository noteRepository, final LoanScheduleCalculationPlatformService calculationPlatformService, + final ClientRepositoryWrapper clientRepository, final LoanProductRepository loanProductRepository, + final AccountNumberGenerator accountNumberGenerator, final LoanSummaryWrapper loanSummaryWrapper, + final GroupRepositoryWrapper groupRepository, final LoanRepaymentScheduleTransactionProcessorFactory loanRepaymentScheduleTransactionProcessorFactory, final CalendarRepository calendarRepository, final CalendarInstanceRepository calendarInstanceRepository, final SavingsAccountAssembler savingsAccountAssembler, final AccountAssociationsRepository accountAssociationsRepository, final LoanRepaymentScheduleInstallmentRepository repaymentScheduleInstallmentRepository, - final LoanReadPlatformService loanReadPlatformService, - final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository, + final LoanReadPlatformService loanReadPlatformService, final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository, final BusinessEventNotifierService businessEventNotifierService, final ConfigurationDomainService configurationDomainService, final LoanScheduleAssembler loanScheduleAssembler, final LoanUtilService loanUtilService, - final CalendarReadPlatformService calendarReadPlatformService, final GlobalConfigurationRepositoryWrapper globalConfigurationRepository, - final FineractEntityToEntityMappingRepository repository, final FineractEntityRelationRepository fineractEntityRelationRepository, + final CalendarReadPlatformService calendarReadPlatformService, + final GlobalConfigurationRepositoryWrapper globalConfigurationRepository, + final FineractEntityToEntityMappingRepository repository, + final FineractEntityRelationRepository fineractEntityRelationRepository, final EntityDatatableChecksWritePlatformService entityDatatableChecksWritePlatformService, - final GLIMAccountInfoWritePlatformService glimAccountInfoWritePlatformService, - final GLIMAccountInfoRepository glimRepository,final LoanRepository loanRepository, - final GSIMReadPlatformService gsimReadPlatformService, final RateAssembler rateAssembler, - final LoanProductReadPlatformService loanProductReadPlatformService - ) { + final GLIMAccountInfoWritePlatformService glimAccountInfoWritePlatformService, final GLIMAccountInfoRepository glimRepository, + final LoanRepository loanRepository, final GSIMReadPlatformService gsimReadPlatformService, final RateAssembler rateAssembler, + final LoanProductReadPlatformService loanProductReadPlatformService) { this.context = context; this.fromJsonHelper = fromJsonHelper; this.loanApplicationTransitionApiJsonValidator = loanApplicationTransitionApiJsonValidator; @@ -231,7 +228,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa this.loanAssembler = loanAssembler; this.loanChargeAssembler = loanChargeAssembler; this.loanCollateralAssembler = loanCollateralAssembler; - this.loanRepositoryWrapper = loanRepositoryWrapper ; + this.loanRepositoryWrapper = loanRepositoryWrapper; this.noteRepository = noteRepository; this.calculationPlatformService = calculationPlatformService; this.clientRepository = clientRepository; @@ -258,10 +255,10 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa this.fineractEntityRelationRepository = fineractEntityRelationRepository; this.loanProductReadPlatformService = loanProductReadPlatformService; this.rateAssembler = rateAssembler; - this.glimAccountInfoWritePlatformService=glimAccountInfoWritePlatformService; - this.glimRepository=glimRepository; - this.loanRepository=loanRepository; - this.gsimReadPlatformService=gsimReadPlatformService; + this.glimAccountInfoWritePlatformService = glimAccountInfoWritePlatformService; + this.glimRepository = glimRepository; + this.loanRepository = loanRepository; + this.gsimReadPlatformService = gsimReadPlatformService; } private LoanLifecycleStateMachine defaultLoanLifecycleStateMachine() { @@ -281,15 +278,15 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa .orElseThrow(() -> new LoanProductNotFoundException(productId)); final Long clientId = this.fromJsonHelper.extractLongNamed("clientId", command.parsedJson()); - if(clientId !=null){ - Client client= this.clientRepository.findOneWithNotFoundDetection(clientId); - officeSpecificLoanProductValidation( productId,client.getOffice().getId()); - } - final Long groupId = this.fromJsonHelper.extractLongNamed("groupId", command.parsedJson()); - if(groupId != null){ - Group group= this.groupRepository.findOneWithNotFoundDetection(groupId); - officeSpecificLoanProductValidation( productId,group.getOffice().getId()); - } + if (clientId != null) { + Client client = this.clientRepository.findOneWithNotFoundDetection(clientId); + officeSpecificLoanProductValidation(productId, client.getOffice().getId()); + } + final Long groupId = this.fromJsonHelper.extractLongNamed("groupId", command.parsedJson()); + if (groupId != null) { + Group group = this.groupRepository.findOneWithNotFoundDetection(groupId); + officeSpecificLoanProductValidation(productId, group.getOffice().getId()); + } this.fromApiJsonDeserializer.validateForCreate(command.json(), isMeetingMandatoryForJLGLoans, loanProduct); @@ -314,7 +311,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa final Loan newLoanApplication = this.loanAssembler.assembleFrom(command, currentUser); - checkForProductMixRestrictions(newLoanApplication); + checkForProductMixRestrictions(newLoanApplication); validateSubmittedOnDate(newLoanApplication); @@ -329,48 +326,50 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa productRelatedDetail.getRepayEvery(), productRelatedDetail.getRepaymentPeriodFrequencyType().getValue(), newLoanApplication); - if(loanProduct.canUseForTopup() && clientId != null){ + if (loanProduct.canUseForTopup() && clientId != null) { final Boolean isTopup = command.booleanObjectValueOfParameterNamed(LoanApiConstants.isTopup); - if(null == isTopup){ + if (null == isTopup) { newLoanApplication.setIsTopup(false); - }else{ + } else { newLoanApplication.setIsTopup(isTopup); } - if(newLoanApplication.isTopup()){ + if (newLoanApplication.isTopup()) { final Long loanIdToClose = command.longValueOfParameterNamed(LoanApiConstants.loanIdToClose); final Loan loanToClose = this.loanRepositoryWrapper.findNonClosedLoanThatBelongsToClient(loanIdToClose, clientId); - if(loanToClose == null){ - throw new GeneralPlatformDomainRuleException("error.msg.loan.loanIdToClose.no.active.loan.associated.to.client.found", + if (loanToClose == null) { + throw new GeneralPlatformDomainRuleException( + "error.msg.loan.loanIdToClose.no.active.loan.associated.to.client.found", "loanIdToClose is invalid, No Active Loan associated with the given Client ID found."); } - if(loanToClose.isMultiDisburmentLoan() && !loanToClose.isInterestRecalculationEnabledForProduct()){ + if (loanToClose.isMultiDisburmentLoan() && !loanToClose.isInterestRecalculationEnabledForProduct()) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.topup.on.multi.tranche.loan.without.interest.recalculation.not.supported", "Topup on loan with multi-tranche disbursal and without interest recalculation is not supported."); } final LocalDate disbursalDateOfLoanToClose = loanToClose.getDisbursementDate(); - if(!newLoanApplication.getSubmittedOnDate().isAfter(disbursalDateOfLoanToClose)){ + if (!newLoanApplication.getSubmittedOnDate().isAfter(disbursalDateOfLoanToClose)) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.submitted.date.should.be.after.topup.loan.disbursal.date", - "Submitted date of this loan application "+newLoanApplication.getSubmittedOnDate() - +" should be after the disbursed date of loan to be closed "+ disbursalDateOfLoanToClose); + "Submitted date of this loan application " + newLoanApplication.getSubmittedOnDate() + + " should be after the disbursed date of loan to be closed " + disbursalDateOfLoanToClose); } - if(!loanToClose.getCurrencyCode().equals(newLoanApplication.getCurrencyCode())){ + if (!loanToClose.getCurrencyCode().equals(newLoanApplication.getCurrencyCode())) { throw new GeneralPlatformDomainRuleException("error.msg.loan.to.be.closed.has.different.currency", "loanIdToClose is invalid, Currency code is different."); } final LocalDate lastUserTransactionOnLoanToClose = loanToClose.getLastUserTransactionDate(); - if(newLoanApplication.getDisbursementDate().isBefore(lastUserTransactionOnLoanToClose)){ + if (newLoanApplication.getDisbursementDate().isBefore(lastUserTransactionOnLoanToClose)) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.disbursal.date.should.be.after.last.transaction.date.of.loan.to.be.closed", - "Disbursal date of this loan application "+newLoanApplication.getDisbursementDate() - +" should be after last transaction date of loan to be closed "+ lastUserTransactionOnLoanToClose); + "Disbursal date of this loan application " + newLoanApplication.getDisbursementDate() + + " should be after last transaction date of loan to be closed " + + lastUserTransactionOnLoanToClose); } - BigDecimal loanOutstanding = this.loanReadPlatformService.retrieveLoanPrePaymentTemplate(loanIdToClose, - newLoanApplication.getDisbursementDate()).getAmount(); + BigDecimal loanOutstanding = this.loanReadPlatformService + .retrieveLoanPrePaymentTemplate(loanIdToClose, newLoanApplication.getDisbursementDate()).getAmount(); final BigDecimal firstDisbursalAmount = newLoanApplication.getFirstDisbursalAmount(); - if(loanOutstanding.compareTo(firstDisbursalAmount) > 0){ + if (loanOutstanding.compareTo(firstDisbursalAmount) > 0) { throw new GeneralPlatformDomainRuleException("error.msg.loan.amount.less.than.outstanding.of.loan.to.be.closed", "Topup loan amount should be greater than outstanding amount of loan to be closed."); } @@ -387,105 +386,96 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa createAndPersistCalendarInstanceForInterestRecalculation(newLoanApplication); } - // loan account number generation - String accountNumber=""; + String accountNumber = ""; GroupLoanIndividualMonitoringAccount glimAccount; - BigDecimal applicationId=BigDecimal.ZERO; - Boolean isLastChildApplication=false; - + BigDecimal applicationId = BigDecimal.ZERO; + Boolean isLastChildApplication = false; if (newLoanApplication.isAccountNumberRequiresAutoGeneration()) { - final AccountNumberFormat accountNumberFormat = this.accountNumberFormatRepository.findByAccountType(EntityAccountType.LOAN); + final AccountNumberFormat accountNumberFormat = this.accountNumberFormatRepository + .findByAccountType(EntityAccountType.LOAN); // if application is of GLIM type - if(newLoanApplication.getLoanType()==4) - { - Group group= this.groupRepository.findOneWithNotFoundDetection(groupId); + if (newLoanApplication.getLoanType() == 4) { + Group group = this.groupRepository.findOneWithNotFoundDetection(groupId); - //GLIM specific parameters - if(command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("applicationId")!=null) - { - applicationId=command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("applicationId"); + // GLIM specific parameters + if (command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("applicationId") != null) { + applicationId = command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("applicationId"); } - if(command.booleanObjectValueOfParameterNamed("lastApplication")!=null) - { - isLastChildApplication=command.booleanPrimitiveValueOfParameterNamed("lastApplication"); + if (command.booleanObjectValueOfParameterNamed("lastApplication") != null) { + isLastChildApplication = command.booleanPrimitiveValueOfParameterNamed("lastApplication"); } - if(command.booleanObjectValueOfParameterNamed("isParentAccount")!=null) - { + if (command.booleanObjectValueOfParameterNamed("isParentAccount") != null) { - //empty table check - if(glimRepository.count()!=0) - { - //**************Parent-Not an empty table******************** - accountNumber=this.accountNumberGenerator.generate(newLoanApplication, accountNumberFormat); - newLoanApplication.updateAccountNo(accountNumber+"1"); - glimAccountInfoWritePlatformService.addGLIMAccountInfo(accountNumber,group, command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("totalLoan"),Long.valueOf(1),true, - LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue(),applicationId); - newLoanApplication.setGlim(glimRepository.findOneByAccountNumber(accountNumber)); - this.loanRepositoryWrapper.save(newLoanApplication); + // empty table check + if (glimRepository.count() != 0) { + // **************Parent-Not an empty + // table******************** + accountNumber = this.accountNumberGenerator.generate(newLoanApplication, accountNumberFormat); + newLoanApplication.updateAccountNo(accountNumber + "1"); + glimAccountInfoWritePlatformService.addGLIMAccountInfo(accountNumber, group, + command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("totalLoan"), Long.valueOf(1), true, + LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue(), applicationId); + newLoanApplication.setGlim(glimRepository.findOneByAccountNumber(accountNumber)); + this.loanRepositoryWrapper.save(newLoanApplication); - } - else - { - //************** Parent-empty table******************** + } else { + // ************** Parent-empty + // table******************** - accountNumber=this.accountNumberGenerator.generate(newLoanApplication, accountNumberFormat); - newLoanApplication.updateAccountNo(accountNumber+"1"); - glimAccountInfoWritePlatformService.addGLIMAccountInfo(accountNumber,group, command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("totalLoan"),Long.valueOf(1),true, - LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue(),applicationId); - newLoanApplication.setGlim(glimRepository.findOneByAccountNumber(accountNumber)); - this.loanRepositoryWrapper.save(newLoanApplication); + accountNumber = this.accountNumberGenerator.generate(newLoanApplication, accountNumberFormat); + newLoanApplication.updateAccountNo(accountNumber + "1"); + glimAccountInfoWritePlatformService.addGLIMAccountInfo(accountNumber, group, + command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("totalLoan"), Long.valueOf(1), true, + LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue(), applicationId); + newLoanApplication.setGlim(glimRepository.findOneByAccountNumber(accountNumber)); + this.loanRepositoryWrapper.save(newLoanApplication); - } + } - } - else - { + } else { - - if(glimRepository.count()!=0) - { + if (glimRepository.count() != 0) { // Child-Not an empty table - glimAccount=glimRepository.findOneByIsAcceptingChildAndApplicationId(true,applicationId); - accountNumber=glimAccount.getAccountNumber()+(glimAccount.getChildAccountsCount()+1); + glimAccount = glimRepository.findOneByIsAcceptingChildAndApplicationId(true, applicationId); + accountNumber = glimAccount.getAccountNumber() + (glimAccount.getChildAccountsCount() + 1); newLoanApplication.updateAccountNo(accountNumber); this.glimAccountInfoWritePlatformService.incrementChildAccountCount(glimAccount); newLoanApplication.setGlim(glimAccount); - this.loanRepositoryWrapper.save(newLoanApplication); + this.loanRepositoryWrapper.save(newLoanApplication); - } - else - { - //**************Child-empty table******************** - // if the glim info is empty set the current account as parent - accountNumber=this.accountNumberGenerator.generate(newLoanApplication, accountNumberFormat); - newLoanApplication.updateAccountNo(accountNumber+"1"); - glimAccountInfoWritePlatformService.addGLIMAccountInfo(accountNumber,group, command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("totalLoan"),Long.valueOf(1),true, - LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue(),applicationId); + } else { + // **************Child-empty + // table******************** + // if the glim info is empty set the current account + // as parent + accountNumber = this.accountNumberGenerator.generate(newLoanApplication, accountNumberFormat); + newLoanApplication.updateAccountNo(accountNumber + "1"); + glimAccountInfoWritePlatformService.addGLIMAccountInfo(accountNumber, group, + command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("totalLoan"), Long.valueOf(1), true, + LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue(), applicationId); newLoanApplication.setGlim(glimRepository.findOneByAccountNumber(accountNumber)); - this.loanRepositoryWrapper.save(newLoanApplication); + this.loanRepositoryWrapper.save(newLoanApplication); } // reset in cases of last child application of glim - if(isLastChildApplication) - { - this.glimAccountInfoWritePlatformService.resetIsAcceptingChild(glimRepository.findOneByIsAcceptingChildAndApplicationId(true,applicationId)); + if (isLastChildApplication) { + this.glimAccountInfoWritePlatformService + .resetIsAcceptingChild(glimRepository.findOneByIsAcceptingChildAndApplicationId(true, applicationId)); } - } - } - else // for applications other than GLIM + } else // for applications other than GLIM { - newLoanApplication.updateAccountNo(this.accountNumberGenerator.generate(newLoanApplication, accountNumberFormat)); - this.loanRepositoryWrapper.save(newLoanApplication); + newLoanApplication.updateAccountNo(this.accountNumberGenerator.generate(newLoanApplication, accountNumberFormat)); + this.loanRepositoryWrapper.save(newLoanApplication); } } @@ -500,8 +490,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa Calendar calendar = null; if (calendarId != null && calendarId != 0) { - calendar = this.calendarRepository.findById(calendarId) - .orElseThrow(() -> new CalendarNotFoundException(calendarId)); + calendar = this.calendarRepository.findById(calendarId).orElseThrow(() -> new CalendarNotFoundException(calendarId)); final CalendarInstance calendarInstance = new CalendarInstance(calendar, newLoanApplication.getId(), CalendarEntityType.LOANS.getValue()); @@ -530,62 +519,58 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa } } - // Save linked account information + // Save linked account information SavingsAccount savingsAccount; AccountAssociations accountAssociations; final Long savingsAccountId = command.longValueOfParameterNamed("linkAccountId"); if (savingsAccountId != null) { - if(newLoanApplication.getLoanType()==4) - { + if (newLoanApplication.getLoanType() == 4) { - List childSavings= (List)gsimReadPlatformService.findGSIMAccountsByGSIMId(savingsAccountId); - //List childSavings=gsimAccount.getChildGSIMAccounts(); - List gsimClientMembers=new ArrayList(); - Map clientAccountMappings=new HashMap<>(); - for(GroupSavingsIndividualMonitoringAccountData childSaving:childSavings) - { - gsimClientMembers.add(childSaving.getClientId()); - clientAccountMappings.put(childSaving.getClientId(), childSaving.getChildAccountId()); + List childSavings = (List) gsimReadPlatformService + .findGSIMAccountsByGSIMId(savingsAccountId); + // List + // childSavings=gsimAccount.getChildGSIMAccounts(); + List gsimClientMembers = new ArrayList(); + Map clientAccountMappings = new HashMap<>(); + for (GroupSavingsIndividualMonitoringAccountData childSaving : childSavings) { + gsimClientMembers.add(childSaving.getClientId()); + clientAccountMappings.put(childSaving.getClientId(), childSaving.getChildAccountId()); + } - } - - if(gsimClientMembers.contains(BigDecimal.valueOf(newLoanApplication.getClientId()))) - { - savingsAccount = this.savingsAccountAssembler.assembleFrom(clientAccountMappings.get(BigDecimal.valueOf(newLoanApplication.getClientId())).longValue()); + if (gsimClientMembers.contains(BigDecimal.valueOf(newLoanApplication.getClientId()))) { + savingsAccount = this.savingsAccountAssembler + .assembleFrom(clientAccountMappings.get(BigDecimal.valueOf(newLoanApplication.getClientId())).longValue()); this.fromApiJsonDeserializer.validatelinkedSavingsAccount(savingsAccount, newLoanApplication); - boolean isActive = true; - accountAssociations = AccountAssociations.associateSavingsAccount(newLoanApplication, - savingsAccount, AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue(), isActive); - this.accountAssociationsRepository.save(accountAssociations); + boolean isActive = true; + accountAssociations = AccountAssociations.associateSavingsAccount(newLoanApplication, savingsAccount, + AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue(), isActive); + this.accountAssociationsRepository.save(accountAssociations); - }else - { - throw new GroupMemberNotFoundInGSIMException(newLoanApplication.getClientId()); - } - } - else - { + } else { + throw new GroupMemberNotFoundInGSIMException(newLoanApplication.getClientId()); + } + } else { - savingsAccount = this.savingsAccountAssembler.assembleFrom(savingsAccountId); + savingsAccount = this.savingsAccountAssembler.assembleFrom(savingsAccountId); this.fromApiJsonDeserializer.validatelinkedSavingsAccount(savingsAccount, newLoanApplication); boolean isActive = true; - accountAssociations = AccountAssociations.associateSavingsAccount(newLoanApplication, - savingsAccount, AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue(), isActive); + accountAssociations = AccountAssociations.associateSavingsAccount(newLoanApplication, savingsAccount, + AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue(), isActive); this.accountAssociationsRepository.save(accountAssociations); + } } - } - if(command.parameterExists(LoanApiConstants.datatables)){ + if (command.parameterExists(LoanApiConstants.datatables)) { this.entityDatatableChecksWritePlatformService.saveDatatables(StatusEnum.CREATE.getCode().longValue(), EntityTables.LOAN.getName(), newLoanApplication.getId(), newLoanApplication.productId(), command.arrayOfParameterNamed(LoanApiConstants.datatables)); } - this.entityDatatableChecksWritePlatformService.runTheCheckForProduct(newLoanApplication.getId(), - EntityTables.LOAN.getName(), StatusEnum.CREATE.getCode().longValue(), - EntityTables.LOAN.getForeignKeyColumnNameOnDatatable(), newLoanApplication.productId()); + this.entityDatatableChecksWritePlatformService.runTheCheckForProduct(newLoanApplication.getId(), EntityTables.LOAN.getName(), + StatusEnum.CREATE.getCode().longValue(), EntityTables.LOAN.getForeignKeyColumnNameOnDatatable(), + newLoanApplication.productId()); this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_CREATE, constructEntityMap(BusinessEntity.LOAN, newLoanApplication)); @@ -596,21 +581,18 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa .withOfficeId(newLoanApplication.getOfficeId()) // .withClientId(newLoanApplication.getClientId()) // .withGroupId(newLoanApplication.getGroupId()) // - .withLoanId(newLoanApplication.getId()) - .withGlimId(newLoanApplication.getGlimId()) - .build(); + .withLoanId(newLoanApplication.getId()).withGlimId(newLoanApplication.getGlimId()).build(); } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } - -public void checkForProductMixRestrictions(final Loan loan) { + public void checkForProductMixRestrictions(final Loan loan) { final List activeLoansLoanProductIds; final Long productId = loan.loanProduct().getId(); @@ -625,13 +607,19 @@ public void checkForProductMixRestrictions(final Loan loan) { checkForProductMixRestrictions(activeLoansLoanProductIds, productId, loan.loanProduct().productName()); } - private void checkForProductMixRestrictions(final List activeLoansLoanProductIds, final Long productId, final String productName) { + private void checkForProductMixRestrictions(final List activeLoansLoanProductIds, final Long productId, + final String productName) { if (!CollectionUtils.isEmpty(activeLoansLoanProductIds)) { final Collection restrictedPrdouctsList = this.loanProductReadPlatformService .retrieveRestrictedProductsForMix(productId); for (final LoanProductData restrictedProduct : restrictedPrdouctsList) { - if (activeLoansLoanProductIds.contains(restrictedProduct.getId())) { throw new GeneralPlatformDomainRuleException("error.msg.loan.applied.or.to.be.disbursed.can.not.co-exist.with.the.loan.already.active.to.this.client", "This loan could not be applied/disbursed as the loan and `" + restrictedProduct + "` are not allowed to co-exist"); } + if (activeLoansLoanProductIds.contains(restrictedProduct.getId())) { + throw new GeneralPlatformDomainRuleException( + "error.msg.loan.applied.or.to.be.disbursed.can.not.co-exist.with.the.loan.already.active.to.this.client", + "This loan could not be applied/disbursed as the loan and `" + restrictedProduct + + "` are not allowed to co-exist"); + } } } } @@ -658,8 +646,8 @@ public void checkForProductMixRestrictions(final Loan loan) { productRelatedDetail.setGraceOnArrearsAgeing(loan.loanProduct().getLoanProductRelatedDetail().getGraceOnArrearsAgeing()); } if (!interestCalcPeriod) { - productRelatedDetail.setInterestCalculationPeriodMethod(loan.loanProduct().getLoanProductRelatedDetail() - .getInterestCalculationPeriodMethod()); + productRelatedDetail.setInterestCalculationPeriodMethod( + loan.loanProduct().getLoanProductRelatedDetail().getInterestCalculationPeriodMethod()); } if (!interestMethod) { productRelatedDetail.setInterestMethod(loan.loanProduct().getLoanProductRelatedDetail().getInterestMethod()); @@ -757,8 +745,9 @@ public void checkForProductMixRestrictions(final Loan loan) { try { AppUser currentUser = getAppUserIfPresent(); final Loan existingLoanApplication = retrieveLoanBy(loanId); - if (!existingLoanApplication.isSubmittedAndPendingApproval()) { throw new LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeModified( - loanId); } + if (!existingLoanApplication.isSubmittedAndPendingApproval()) { + throw new LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeModified(loanId); + } final String productIdParamName = "productId"; LoanProduct newLoanProduct = null; @@ -780,8 +769,8 @@ public void checkForProductMixRestrictions(final Loan loan) { LoanChargeData chargeData = new LoanChargeData(charge.getId(), charge.getDueLocalDate(), charge.amountOrPercentage()); chargesMap.put(charge.getId(), chargeData); } - List disbursementDetails = this.loanUtilService.fetchDisbursementData(command.parsedJson() - .getAsJsonObject()); + List disbursementDetails = this.loanUtilService + .fetchDisbursementData(command.parsedJson().getAsJsonObject()); /** * Stores all charges which are passed in during modify loan @@ -826,7 +815,6 @@ public void checkForProductMixRestrictions(final Loan loan) { final Set possiblyModifedLoanCollateralItems = this.loanCollateralAssembler .fromParsedJson(command.parsedJson()); - final Map changes = existingLoanApplication.loanApplicationModification(command, possiblyModifedLoanCharges, possiblyModifedLoanCollateralItems, this.aprCalculator, isChargeModified, loanProductForValidations); @@ -892,79 +880,80 @@ public void checkForProductMixRestrictions(final Loan loan) { updateProductRelatedDetails(productRelatedDetail, existingLoanApplication); } - if(existingLoanApplication.getLoanProduct().canUseForTopup() && existingLoanApplication.getClientId() != null){ + if (existingLoanApplication.getLoanProduct().canUseForTopup() && existingLoanApplication.getClientId() != null) { final Boolean isTopup = command.booleanObjectValueOfParameterNamed(LoanApiConstants.isTopup); - if(command.isChangeInBooleanParameterNamed(LoanApiConstants.isTopup, existingLoanApplication.isTopup())){ + if (command.isChangeInBooleanParameterNamed(LoanApiConstants.isTopup, existingLoanApplication.isTopup())) { existingLoanApplication.setIsTopup(isTopup); changes.put(LoanApiConstants.isTopup, isTopup); } - if(existingLoanApplication.isTopup()){ + if (existingLoanApplication.isTopup()) { final Long loanIdToClose = command.longValueOfParameterNamed(LoanApiConstants.loanIdToClose); LoanTopupDetails existingLoanTopupDetails = existingLoanApplication.getTopupLoanDetails(); - if(existingLoanTopupDetails == null + if (existingLoanTopupDetails == null || (existingLoanTopupDetails != null && !existingLoanTopupDetails.getLoanIdToClose().equals(loanIdToClose)) - || changes.containsKey("submittedOnDate") - || changes.containsKey("expectedDisbursementDate") - || changes.containsKey("principal") - || changes.containsKey(LoanApiConstants.disbursementDataParameterName)){ + || changes.containsKey("submittedOnDate") || changes.containsKey("expectedDisbursementDate") + || changes.containsKey("principal") || changes.containsKey(LoanApiConstants.disbursementDataParameterName)) { Long existingLoanIdToClose = null; - if(existingLoanTopupDetails != null){ + if (existingLoanTopupDetails != null) { existingLoanIdToClose = existingLoanTopupDetails.getLoanIdToClose(); } - final Loan loanToClose = this.loanRepositoryWrapper.findNonClosedLoanThatBelongsToClient(loanIdToClose, existingLoanApplication.getClientId()); - if(loanToClose == null){ - throw new GeneralPlatformDomainRuleException("error.msg.loan.loanIdToClose.no.active.loan.associated.to.client.found", + final Loan loanToClose = this.loanRepositoryWrapper.findNonClosedLoanThatBelongsToClient(loanIdToClose, + existingLoanApplication.getClientId()); + if (loanToClose == null) { + throw new GeneralPlatformDomainRuleException( + "error.msg.loan.loanIdToClose.no.active.loan.associated.to.client.found", "loanIdToClose is invalid, No Active Loan associated with the given Client ID found."); } - if(loanToClose.isMultiDisburmentLoan() && !loanToClose.isInterestRecalculationEnabledForProduct()){ - throw new GeneralPlatformDomainRuleException("error.msg.loan.topup.on.multi.tranche.loan.without.interest.recalculation.not.supported", + if (loanToClose.isMultiDisburmentLoan() && !loanToClose.isInterestRecalculationEnabledForProduct()) { + throw new GeneralPlatformDomainRuleException( + "error.msg.loan.topup.on.multi.tranche.loan.without.interest.recalculation.not.supported", "Topup on loan with multi-tranche disbursal and without interest recalculation is not supported."); } final LocalDate disbursalDateOfLoanToClose = loanToClose.getDisbursementDate(); - if(!existingLoanApplication.getSubmittedOnDate().isAfter(disbursalDateOfLoanToClose)){ + if (!existingLoanApplication.getSubmittedOnDate().isAfter(disbursalDateOfLoanToClose)) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.submitted.date.should.be.after.topup.loan.disbursal.date", - "Submitted date of this loan application "+existingLoanApplication.getSubmittedOnDate() - +" should be after the disbursed date of loan to be closed "+ disbursalDateOfLoanToClose); + "Submitted date of this loan application " + existingLoanApplication.getSubmittedOnDate() + + " should be after the disbursed date of loan to be closed " + disbursalDateOfLoanToClose); } - if(!loanToClose.getCurrencyCode().equals(existingLoanApplication.getCurrencyCode())){ + if (!loanToClose.getCurrencyCode().equals(existingLoanApplication.getCurrencyCode())) { throw new GeneralPlatformDomainRuleException("error.msg.loan.to.be.closed.has.different.currency", "loanIdToClose is invalid, Currency code is different."); } final LocalDate lastUserTransactionOnLoanToClose = loanToClose.getLastUserTransactionDate(); - if(existingLoanApplication.getDisbursementDate().isBefore(lastUserTransactionOnLoanToClose)){ + if (existingLoanApplication.getDisbursementDate().isBefore(lastUserTransactionOnLoanToClose)) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.disbursal.date.should.be.after.last.transaction.date.of.loan.to.be.closed", - "Disbursal date of this loan application "+existingLoanApplication.getDisbursementDate() - +" should be after last transaction date of loan to be closed "+ lastUserTransactionOnLoanToClose); + "Disbursal date of this loan application " + existingLoanApplication.getDisbursementDate() + + " should be after last transaction date of loan to be closed " + + lastUserTransactionOnLoanToClose); } - BigDecimal loanOutstanding = this.loanReadPlatformService.retrieveLoanPrePaymentTemplate(loanIdToClose, - existingLoanApplication.getDisbursementDate()).getAmount(); + BigDecimal loanOutstanding = this.loanReadPlatformService + .retrieveLoanPrePaymentTemplate(loanIdToClose, existingLoanApplication.getDisbursementDate()).getAmount(); final BigDecimal firstDisbursalAmount = existingLoanApplication.getFirstDisbursalAmount(); - if(loanOutstanding.compareTo(firstDisbursalAmount) > 0){ + if (loanOutstanding.compareTo(firstDisbursalAmount) > 0) { throw new GeneralPlatformDomainRuleException("error.msg.loan.amount.less.than.outstanding.of.loan.to.be.closed", "Topup loan amount should be greater than outstanding amount of loan to be closed."); } - if(!existingLoanIdToClose.equals(loanIdToClose)) { + if (!existingLoanIdToClose.equals(loanIdToClose)) { final LoanTopupDetails topupDetails = new LoanTopupDetails(existingLoanApplication, loanIdToClose); existingLoanApplication.setTopupLoanDetails(topupDetails); changes.put(LoanApiConstants.loanIdToClose, loanIdToClose); } } - }else{ + } else { existingLoanApplication.setTopupLoanDetails(null); } } else { - if(existingLoanApplication.isTopup()){ + if (existingLoanApplication.isTopup()) { existingLoanApplication.setIsTopup(false); existingLoanApplication.setTopupLoanDetails(null); changes.put(LoanApiConstants.isTopup, false); } } - final String fundIdParamName = "fundId"; if (changes.containsKey(fundIdParamName)) { final Long fundId = command.longValueOfParameterNamed(fundIdParamName); @@ -1017,12 +1006,11 @@ public void checkForProductMixRestrictions(final Loan loan) { existingLoanApplication.recalculateAllCharges(); } - //Changes to modify loan rates. + // Changes to modify loan rates. if (command.hasParameter(LoanProductConstants.RATES_PARAM_NAME)) { existingLoanApplication.updateLoanRates(rateAssembler.fromParsedJson(command.parsedJson())); } - this.fromApiJsonDeserializer.validateLoanTermAndRepaidEveryValues(existingLoanApplication.getTermFrequency(), existingLoanApplication.getTermPeriodFrequencyType(), productRelatedDetail.getNumberOfRepayments(), productRelatedDetail.getRepayEvery(), productRelatedDetail.getRepaymentPeriodFrequencyType().getValue(), @@ -1039,20 +1027,20 @@ public void checkForProductMixRestrictions(final Loan loan) { final Long calendarId = command.longValueOfParameterNamed("calendarId"); Calendar calendar = null; if (calendarId != null && calendarId != 0) { - calendar = this.calendarRepository.findById(calendarId) - .orElseThrow(() -> new CalendarNotFoundException(calendarId)); + calendar = this.calendarRepository.findById(calendarId).orElseThrow(() -> new CalendarNotFoundException(calendarId)); } - final List ciList = (List) this.calendarInstanceRepository.findByEntityIdAndEntityTypeId( - loanId, CalendarEntityType.LOANS.getValue()); + final List ciList = (List) this.calendarInstanceRepository + .findByEntityIdAndEntityTypeId(loanId, CalendarEntityType.LOANS.getValue()); if (calendar != null) { // For loans, allow to attach only one calendar instance per // loan if (ciList != null && !ciList.isEmpty()) { final CalendarInstance calendarInstance = ciList.get(0); - final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService.isCalendarAssociatedWithEntity(calendarInstance - .getEntityId(), calendarInstance.getCalendar().getId(), CalendarEntityType.LOANS.getValue().longValue()); + final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService.isCalendarAssociatedWithEntity( + calendarInstance.getEntityId(), calendarInstance.getCalendar().getId(), + CalendarEntityType.LOANS.getValue().longValue()); if (isCalendarAssociatedWithEntity && calendarId == null) { this.calendarRepository.delete(calendarInstance.getCalendar()); } @@ -1082,7 +1070,8 @@ public void checkForProductMixRestrictions(final Loan loan) { if (ciList != null && !ciList.isEmpty()) { final CalendarInstance calendarInstance = ciList.get(0); final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService.isCalendarAssociatedWithEntity( - calendarInstance.getEntityId(), calendarInstance.getCalendar().getId(), CalendarEntityType.LOANS.getValue().longValue()); + calendarInstance.getEntityId(), calendarInstance.getCalendar().getId(), + CalendarEntityType.LOANS.getValue().longValue()); if (isCalendarAssociatedWithEntity) { this.calendarInstanceRepository.delete(calendarInstance); this.calendarRepository.delete(calendarInstance.getCalendar()); @@ -1105,8 +1094,10 @@ public void checkForProductMixRestrictions(final Loan loan) { (Integer) changes.get("repaymentFrequencyNthDayType")); if (ciList != null && !ciList.isEmpty()) { final CalendarInstance calendarInstance = ciList.get(0); - final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService.isCalendarAssociatedWithEntity( - calendarInstance.getEntityId(), calendarInstance.getCalendar().getId(), CalendarEntityType.LOANS.getValue().longValue()); + final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService + .isCalendarAssociatedWithEntity(calendarInstance.getEntityId(), + calendarInstance.getCalendar().getId(), + CalendarEntityType.LOANS.getValue().longValue()); if (isCalendarAssociatedWithEntity) { final Calendar existingCalendar = calendarInstance.getCalendar(); if (existingCalendar != null) { @@ -1182,16 +1173,16 @@ public void checkForProductMixRestrictions(final Loan loan) { } if ((command.longValueOfParameterNamed(productIdParamName) != null) - || (command.longValueOfParameterNamed(clientIdParamName) != null) || (command.longValueOfParameterNamed(groupIdParamName) != null)) { - Long OfficeId = null; - if(existingLoanApplication.getClient() != null){ - OfficeId = existingLoanApplication.getClient().getOffice().getId(); - } - else if(existingLoanApplication.getGroup() != null){ - OfficeId = existingLoanApplication.getGroup().getOffice().getId(); - } - officeSpecificLoanProductValidation( existingLoanApplication.getLoanProduct().getId(),OfficeId); - } + || (command.longValueOfParameterNamed(clientIdParamName) != null) + || (command.longValueOfParameterNamed(groupIdParamName) != null)) { + Long OfficeId = null; + if (existingLoanApplication.getClient() != null) { + OfficeId = existingLoanApplication.getClient().getOffice().getId(); + } else if (existingLoanApplication.getGroup() != null) { + OfficeId = existingLoanApplication.getGroup().getOffice().getId(); + } + officeSpecificLoanProductValidation(existingLoanApplication.getLoanProduct().getId(), OfficeId); + } // updating loan interest recalculation details throwing null // pointer exception after saveAndFlush @@ -1217,10 +1208,10 @@ public void checkForProductMixRestrictions(final Loan loan) { } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -1230,15 +1221,17 @@ public void checkForProductMixRestrictions(final Loan loan) { */ private void handleDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { - if (realCause.getMessage().contains("loan_account_no_UNIQUE") || (realCause.getCause() != null && realCause.getCause().getMessage().contains("loan_account_no_UNIQUE"))) { + if (realCause.getMessage().contains("loan_account_no_UNIQUE") + || (realCause.getCause() != null && realCause.getCause().getMessage().contains("loan_account_no_UNIQUE"))) { final String accountNo = command.stringValueOfParameterNamed("accountNo"); - throw new PlatformDataIntegrityException("error.msg.loan.duplicate.accountNo", "Loan with accountNo `" + accountNo - + "` already exists", "accountNo", accountNo); - } else if (realCause.getMessage().contains("loan_externalid_UNIQUE") || (realCause.getCause() != null && realCause.getCause().getMessage().contains("loan_externalid_UNIQUE"))) { + throw new PlatformDataIntegrityException("error.msg.loan.duplicate.accountNo", + "Loan with accountNo `" + accountNo + "` already exists", "accountNo", accountNo); + } else if (realCause.getMessage().contains("loan_externalid_UNIQUE") + || (realCause.getCause() != null && realCause.getCause().getMessage().contains("loan_externalid_UNIQUE"))) { final String externalId = command.stringValueOfParameterNamed("externalId"); - throw new PlatformDataIntegrityException("error.msg.loan.duplicate.externalId", "Loan with externalId `" + externalId - + "` already exists", "externalId", externalId); + throw new PlatformDataIntegrityException("error.msg.loan.duplicate.externalId", + "Loan with externalId `" + externalId + "` already exists", "externalId", externalId); } logAsErrorUnexpectedDataIntegrityException(dve); @@ -1256,16 +1249,18 @@ public void checkForProductMixRestrictions(final Loan loan) { final Loan loan = retrieveLoanBy(loanId); checkClientOrGroupActive(loan); - if (loan.isNotSubmittedAndPendingApproval()) { throw new LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeDeleted(loanId); } + if (loan.isNotSubmittedAndPendingApproval()) { + throw new LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeDeleted(loanId); + } final List relatedNotes = this.noteRepository.findByLoanId(loan.getId()); this.noteRepository.deleteInBatch(relatedNotes); final AccountAssociations accountAssociations = this.accountAssociationsRepository.findByLoanIdAndType(loanId, - AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue()); - if (accountAssociations != null) { - this.accountAssociationsRepository.delete(accountAssociations); - } + AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue()); + if (accountAssociations != null) { + this.accountAssociationsRepository.delete(accountAssociations); + } this.loanRepositoryWrapper.delete(loanId); @@ -1289,61 +1284,52 @@ public void checkForProductMixRestrictions(final Loan loan) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - @Transactional @Override - public CommandProcessingResult approveGLIMLoanAppication(final Long loanId, final JsonCommand command) - { + public CommandProcessingResult approveGLIMLoanAppication(final Long loanId, final JsonCommand command) { - final Long parentLoanId=loanId; - GroupLoanIndividualMonitoringAccount parentLoan=glimRepository.findById(parentLoanId).get(); - JsonArray approvalFormData=command.arrayOfParameterNamed("approvalFormData"); + final Long parentLoanId = loanId; + GroupLoanIndividualMonitoringAccount parentLoan = glimRepository.findById(parentLoanId).get(); + JsonArray approvalFormData = command.arrayOfParameterNamed("approvalFormData"); - JsonObject jsonObject=null; - JsonCommand childCommand=null; - Long[] childLoanId=new Long[approvalFormData.size()]; - BigDecimal parentPrincipalAmount=command.bigDecimalValueOfParameterNamed("glimPrincipal"); + JsonObject jsonObject = null; + JsonCommand childCommand = null; + Long[] childLoanId = new Long[approvalFormData.size()]; + BigDecimal parentPrincipalAmount = command.bigDecimalValueOfParameterNamed("glimPrincipal"); for (int i = 0; i < approvalFormData.size(); i++) { - jsonObject=approvalFormData.get(i).getAsJsonObject(); + jsonObject = approvalFormData.get(i).getAsJsonObject(); - childLoanId[i]=jsonObject.get("loanId").getAsLong(); + childLoanId[i] = jsonObject.get("loanId").getAsLong(); } - - CommandProcessingResult result=null; + CommandProcessingResult result = null; int count = 0; int j = 0; - for(JsonElement approvals:approvalFormData) - { + for (JsonElement approvals : approvalFormData) { - childCommand=JsonCommand.fromExistingCommand(command,approvals); + childCommand = JsonCommand.fromExistingCommand(command, approvals); + result = approveApplication(childLoanId[j++], childCommand); - result=approveApplication(childLoanId[j++],childCommand); - - if(result.getLoanId()!=null) - { + if (result.getLoanId() != null) { count++; - // if all the child loans are approved, mark the parent loan as approved - if(count==parentLoan.getChildAccountsCount()) - { + // if all the child loans are approved, mark the parent loan as + // approved + if (count == parentLoan.getChildAccountsCount()) { parentLoan.setPrincipalAmount(parentPrincipalAmount); parentLoan.setLoanStatus(LoanStatus.APPROVED.getValue()); glimRepository.save(parentLoan); } - } - } return result; } - @Transactional @Override public CommandProcessingResult approveApplication(final Long loanId, final JsonCommand command) { @@ -1376,11 +1362,13 @@ public void checkForProductMixRestrictions(final Loan loan) { if (calendarInstance != null) { calendar = calendarInstance.getCalendar(); } - // final Calendar calendar = calendarInstance.getCalendar(); + // final Calendar calendar = calendarInstance.getCalendar(); boolean isSkipRepaymentOnFirstMonthEnabled = this.configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); if (isSkipRepaymentOnFirstMonthEnabled) { isSkipRepaymentOnFirstMonth = this.loanUtilService.isLoanRepaymentsSyncWithMeeting(loan.group(), calendar); - if(isSkipRepaymentOnFirstMonth) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } + if (isSkipRepaymentOnFirstMonth) { + numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); + } } this.loanScheduleAssembler.validateDisbursementDateWithMeetingDates(expectedDisbursementDate, calendar, isSkipRepaymentOnFirstMonth, numberOfDays); @@ -1390,8 +1378,6 @@ public void checkForProductMixRestrictions(final Loan loan) { final Map changes = loan.loanApplicationApproval(currentUser, command, disbursementDataArray, defaultLoanLifecycleStateMachine()); - - entityDatatableChecksWritePlatformService.runTheCheckForProduct(loanId, EntityTables.LOAN.getName(), StatusEnum.APPROVE.getCode().longValue(), EntityTables.LOAN.getForeignKeyColumnNameOnDatatable(), loan.productId()); @@ -1406,25 +1392,25 @@ public void checkForProductMixRestrictions(final Loan loan) { loan.regenerateRepaymentSchedule(scheduleGeneratorDTO, currentUser); } - if(loan.isTopup() && loan.getClientId() != null){ + if (loan.isTopup() && loan.getClientId() != null) { final Long loanIdToClose = loan.getTopupLoanDetails().getLoanIdToClose(); final Loan loanToClose = this.loanRepositoryWrapper.findNonClosedLoanThatBelongsToClient(loanIdToClose, loan.getClientId()); - if(loanToClose == null){ + if (loanToClose == null) { throw new GeneralPlatformDomainRuleException("error.msg.loan.to.be.closed.with.topup.is.not.active", "Loan to be closed with this topup is not active."); } final LocalDate lastUserTransactionOnLoanToClose = loanToClose.getLastUserTransactionDate(); - if(loan.getDisbursementDate().isBefore(lastUserTransactionOnLoanToClose)){ + if (loan.getDisbursementDate().isBefore(lastUserTransactionOnLoanToClose)) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.disbursal.date.should.be.after.last.transaction.date.of.loan.to.be.closed", - "Disbursal date of this loan application "+loan.getDisbursementDate() - +" should be after last transaction date of loan to be closed "+ lastUserTransactionOnLoanToClose); + "Disbursal date of this loan application " + loan.getDisbursementDate() + + " should be after last transaction date of loan to be closed " + lastUserTransactionOnLoanToClose); } - BigDecimal loanOutstanding = this.loanReadPlatformService.retrieveLoanPrePaymentTemplate(loanIdToClose, - expectedDisbursementDate).getAmount(); + BigDecimal loanOutstanding = this.loanReadPlatformService + .retrieveLoanPrePaymentTemplate(loanIdToClose, expectedDisbursementDate).getAmount(); final BigDecimal firstDisbursalAmount = loan.getFirstDisbursalAmount(); - if(loanOutstanding.compareTo(firstDisbursalAmount) > 0){ + if (loanOutstanding.compareTo(firstDisbursalAmount) > 0) { throw new GeneralPlatformDomainRuleException("error.msg.loan.amount.less.than.outstanding.of.loan.to.be.closed", "Topup loan amount should be greater than outstanding amount of loan to be closed."); } @@ -1454,37 +1440,32 @@ public void checkForProductMixRestrictions(final Loan loan) { .build(); } - @Transactional @Override - public CommandProcessingResult undoGLIMLoanApplicationApproval(final Long loanId, final JsonCommand command) - { + public CommandProcessingResult undoGLIMLoanApplicationApproval(final Long loanId, final JsonCommand command) { - //GroupLoanIndividualMonitoringAccount glimAccount=glimRepository.findOne(loanId); - final Long parentLoanId=loanId; - GroupLoanIndividualMonitoringAccount parentLoan=glimRepository.findById(parentLoanId).get(); - List childLoans=this.loanRepository.findByGlimId(loanId); + // GroupLoanIndividualMonitoringAccount + // glimAccount=glimRepository.findOne(loanId); + final Long parentLoanId = loanId; + GroupLoanIndividualMonitoringAccount parentLoan = glimRepository.findById(parentLoanId).get(); + List childLoans = this.loanRepository.findByGlimId(loanId); - CommandProcessingResult result=null; - int count=0; - for(Loan loan:childLoans) - { - result=undoApplicationApproval(loan.getId(),command); + CommandProcessingResult result = null; + int count = 0; + for (Loan loan : childLoans) { + result = undoApplicationApproval(loan.getId(), command); - if(result.getLoanId()!=null) - { + if (result.getLoanId() != null) { count++; - // if all the child loans are approved, mark the parent loan as approved - if(count==parentLoan.getChildAccountsCount()) - { + // if all the child loans are approved, mark the parent loan as + // approved + if (count == parentLoan.getChildAccountsCount()) { parentLoan.setLoanStatus(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL.getValue()); glimRepository.save(parentLoan); } - } - } return result; @@ -1538,34 +1519,30 @@ public void checkForProductMixRestrictions(final Loan loan) { @Transactional @Override - public CommandProcessingResult rejectGLIMApplicationApproval(final Long glimId, final JsonCommand command) - { + public CommandProcessingResult rejectGLIMApplicationApproval(final Long glimId, final JsonCommand command) { - //GroupLoanIndividualMonitoringAccount glimAccount=glimRepository.findOne(loanId); - final Long parentLoanId=glimId; - GroupLoanIndividualMonitoringAccount parentLoan=glimRepository.findById(parentLoanId).get(); - List childLoans=this.loanRepository.findByGlimId(glimId); + // GroupLoanIndividualMonitoringAccount + // glimAccount=glimRepository.findOne(loanId); + final Long parentLoanId = glimId; + GroupLoanIndividualMonitoringAccount parentLoan = glimRepository.findById(parentLoanId).get(); + List childLoans = this.loanRepository.findByGlimId(glimId); - CommandProcessingResult result=null; - int count=0; - for(Loan loan:childLoans) - { - result=rejectApplication(loan.getId(),command); + CommandProcessingResult result = null; + int count = 0; + for (Loan loan : childLoans) { + result = rejectApplication(loan.getId(), command); - if(result.getLoanId()!=null) - { + if (result.getLoanId() != null) { count++; - // if all the child loans are Rejected, mark the parent loan as rejected - if(count==parentLoan.getChildAccountsCount()) - { + // if all the child loans are Rejected, mark the parent loan as + // rejected + if (count == parentLoan.getChildAccountsCount()) { parentLoan.setLoanStatus(LoanStatus.REJECTED.getValue()); glimRepository.save(parentLoan); } - } - } return result; @@ -1584,7 +1561,7 @@ public void checkForProductMixRestrictions(final Loan loan) { checkClientOrGroupActive(loan); entityDatatableChecksWritePlatformService.runTheCheckForProduct(loanId, EntityTables.LOAN.getName(), - StatusEnum.REJECTED.getCode().longValue(), EntityTables.LOAN.getForeignKeyColumnNameOnDatatable(),loan.productId()); + StatusEnum.REJECTED.getCode().longValue(), EntityTables.LOAN.getForeignKeyColumnNameOnDatatable(), loan.productId()); final Map changes = loan.loanApplicationRejection(currentUser, command, defaultLoanLifecycleStateMachine()); if (!changes.isEmpty()) { @@ -1596,7 +1573,8 @@ public void checkForProductMixRestrictions(final Loan loan) { this.noteRepository.save(note); } } - this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_REJECTED, constructEntityMap(BusinessEntity.LOAN, loan)); + this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_REJECTED, + constructEntityMap(BusinessEntity.LOAN, loan)); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(loan.getId()) // @@ -1704,8 +1682,10 @@ public void checkForProductMixRestrictions(final Loan loan) { if (realCause.getMessage().toLowerCase().contains("external_id_unique")) { baseDataValidator.reset().parameter("externalId").failWithCode("value.must.be.unique"); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } @@ -1724,19 +1704,16 @@ public void checkForProductMixRestrictions(final Loan loan) { } private void officeSpecificLoanProductValidation(final Long productId, final Long officeId) { - final GlobalConfigurationProperty restrictToUserOfficeProperty = this.globalConfigurationRepository - .findOneByNameWithNotFoundDetection( - FineractEntityAccessConstants.GLOBAL_CONFIG_FOR_OFFICE_SPECIFIC_PRODUCTS); - if (restrictToUserOfficeProperty.isEnabled()) { - FineractEntityRelation fineractEntityRelation = fineractEntityRelationRepository - .findOneByCodeName(FineractEntityAccessType.OFFICE_ACCESS_TO_LOAN_PRODUCTS.toStr()); - FineractEntityToEntityMapping officeToLoanProductMappingList = this.repository.findListByProductId(fineractEntityRelation, productId, - officeId); - if (officeToLoanProductMappingList == null) { - throw new NotOfficeSpecificProductException(productId, officeId); - } + final GlobalConfigurationProperty restrictToUserOfficeProperty = this.globalConfigurationRepository + .findOneByNameWithNotFoundDetection(FineractEntityAccessConstants.GLOBAL_CONFIG_FOR_OFFICE_SPECIFIC_PRODUCTS); + if (restrictToUserOfficeProperty.isEnabled()) { + FineractEntityRelation fineractEntityRelation = fineractEntityRelationRepository + .findOneByCodeName(FineractEntityAccessType.OFFICE_ACCESS_TO_LOAN_PRODUCTS.toStr()); + FineractEntityToEntityMapping officeToLoanProductMappingList = this.repository.findListByProductId(fineractEntityRelation, + productId, officeId); + if (officeToLoanProductMappingList == null) { throw new NotOfficeSpecificProductException(productId, officeId); } - } - } + } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanArrearsAgingServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanArrearsAgingServiceImpl.java old mode 100755 new mode 100644 index 463339731..a88d255c4 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanArrearsAgingServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanArrearsAgingServiceImpl.java @@ -62,7 +62,8 @@ public class LoanArrearsAgingServiceImpl implements LoanArrearsAgingService, Bus private final JdbcTemplate jdbcTemplate; @Autowired - public LoanArrearsAgingServiceImpl(final RoutingDataSource dataSource, final BusinessEventNotifierService businessEventNotifierService) { + public LoanArrearsAgingServiceImpl(final RoutingDataSource dataSource, + final BusinessEventNotifierService businessEventNotifierService) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.businessEventNotifierService = businessEventNotifierService; } @@ -98,8 +99,8 @@ public class LoanArrearsAgingServiceImpl implements LoanArrearsAgingService, Bus final String penaltyChargesOverdueCalculationSql = "SUM(ifnull(mr.penalty_charges_amount, 0) - ifnull(mr.penalty_charges_writtenoff_derived, 0) - " + "ifnull(mr.penalty_charges_waived_derived, 0) - ifnull(mr.penalty_charges_completed_derived, 0))"; - updateSqlBuilder - .append("INSERT INTO m_loan_arrears_aging(`loan_id`,`principal_overdue_derived`,`interest_overdue_derived`,`fee_charges_overdue_derived`,`penalty_charges_overdue_derived`,`total_overdue_derived`,`overdue_since_date_derived`)"); + updateSqlBuilder.append( + "INSERT INTO m_loan_arrears_aging(`loan_id`,`principal_overdue_derived`,`interest_overdue_derived`,`fee_charges_overdue_derived`,`penalty_charges_overdue_derived`,`total_overdue_derived`,`overdue_since_date_derived`)"); updateSqlBuilder.append("select ml.id as loanId,"); updateSqlBuilder.append(principalOverdueCalculationSql + " as principal_overdue_derived,"); updateSqlBuilder.append(interestOverdueCalculationSql + " as interest_overdue_derived,"); @@ -201,10 +202,10 @@ public class LoanArrearsAgingServiceImpl implements LoanArrearsAgingService, Bus final StringBuilder loanIdentifier = new StringBuilder(); loanIdentifier.append("select ml.id as loanId FROM m_loan ml "); loanIdentifier.append("INNER JOIN m_loan_repayment_schedule mr on mr.loan_id = ml.id "); - loanIdentifier - .append("inner join m_product_loan_recalculation_details prd on prd.product_id = ml.product_id and prd.arrears_based_on_original_schedule = 1 "); - loanIdentifier - .append("WHERE ml.loan_status_id = 300 and mr.completed_derived is false and mr.duedate < SUBDATE(CURDATE(),INTERVAL ifnull(ml.grace_on_arrears_ageing,0) day) group by ml.id"); + loanIdentifier.append( + "inner join m_product_loan_recalculation_details prd on prd.product_id = ml.product_id and prd.arrears_based_on_original_schedule = 1 "); + loanIdentifier.append( + "WHERE ml.loan_status_id = 300 and mr.completed_derived is false and mr.duedate < SUBDATE(CURDATE(),INTERVAL ifnull(ml.grace_on_arrears_ageing,0) day) group by ml.id"); List loanIds = this.jdbcTemplate.queryForList(loanIdentifier.toString(), Long.class); if (!loanIds.isEmpty()) { String loanIdsAsString = loanIds.toString(); @@ -268,16 +269,15 @@ public class LoanArrearsAgingServiceImpl implements LoanArrearsAgingService, Bus for (LoanSchedulePeriodData loanSchedulePeriodData : entry.getValue()) { if (!loanSchedulePeriodData.getComplete()) { - principalOverdue = principalOverdue.add(loanSchedulePeriodData.principalDue().subtract( - loanSchedulePeriodData.principalPaid())); - interestOverdue = interestOverdue.add(loanSchedulePeriodData.interestDue().subtract( - loanSchedulePeriodData.interestPaid())); + principalOverdue = principalOverdue + .add(loanSchedulePeriodData.principalDue().subtract(loanSchedulePeriodData.principalPaid())); + interestOverdue = interestOverdue + .add(loanSchedulePeriodData.interestDue().subtract(loanSchedulePeriodData.interestPaid())); feeOverdue = feeOverdue.add(loanSchedulePeriodData.feeChargesDue().subtract(loanSchedulePeriodData.feeChargesPaid())); - penaltyOverdue = penaltyOverdue.add(loanSchedulePeriodData.penaltyChargesDue().subtract( - loanSchedulePeriodData.penaltyChargesPaid())); - if (overDueSince.isAfter(loanSchedulePeriodData.periodDueDate()) - && loanSchedulePeriodData.principalDue().subtract(loanSchedulePeriodData.principalPaid()) - .compareTo(BigDecimal.ZERO) > 0) { + penaltyOverdue = penaltyOverdue + .add(loanSchedulePeriodData.penaltyChargesDue().subtract(loanSchedulePeriodData.penaltyChargesPaid())); + if (overDueSince.isAfter(loanSchedulePeriodData.periodDueDate()) && loanSchedulePeriodData.principalDue() + .subtract(loanSchedulePeriodData.principalPaid()).compareTo(BigDecimal.ZERO) > 0) { overDueSince = loanSchedulePeriodData.periodDueDate(); } } @@ -300,8 +300,7 @@ public class LoanArrearsAgingServiceImpl implements LoanArrearsAgingService, Bus private String constructInsertStatement(final Long loanId, BigDecimal principalOverdue, BigDecimal interestOverdue, BigDecimal feeOverdue, BigDecimal penaltyOverdue, LocalDate overDueSince) { final StringBuilder insertStatementBuilder = new StringBuilder(900); - insertStatementBuilder - .append("INSERT INTO m_loan_arrears_aging(`loan_id`,`principal_overdue_derived`,`interest_overdue_derived`,") + insertStatementBuilder.append("INSERT INTO m_loan_arrears_aging(`loan_id`,`principal_overdue_derived`,`interest_overdue_derived`,") .append("`fee_charges_overdue_derived`,`penalty_charges_overdue_derived`,`total_overdue_derived`,`overdue_since_date_derived`) VALUES("); insertStatementBuilder.append(loanId).append(","); insertStatementBuilder.append(principalOverdue).append(","); @@ -329,10 +328,26 @@ public class LoanArrearsAgingServiceImpl implements LoanArrearsAgingService, Bus return insertStatementBuilder.toString(); } - private void updateSchheduleWithPaidDetail(Map> scheduleDate, List> loanSummary) { + private void updateSchheduleWithPaidDetail(Map> scheduleDate, + List> loanSummary) { for (Map transactionMap : loanSummary) { - String longValue = transactionMap.get("loanId").toString() ; //From JDBC Template API, we are getting BigInteger but in other call, we are getting Long - Long loanId = Long.parseLong(longValue) ; + String longValue = transactionMap.get("loanId").toString(); // From + // JDBC + // Template + // API, + // we + // are + // getting + // BigInteger + // but + // in + // other + // call, + // we + // are + // getting + // Long + Long loanId = Long.parseLong(longValue); BigDecimal principalAmtPaid = (BigDecimal) transactionMap.get("principalAmtPaid"); BigDecimal principalAmtWrittenoff = (BigDecimal) transactionMap.get("principalAmtWrittenoff"); BigDecimal interestAmtPaid = (BigDecimal) transactionMap.get("interestAmtPaid"); @@ -407,8 +422,8 @@ public class LoanArrearsAgingServiceImpl implements LoanArrearsAgingService, Bus public OriginalScheduleExtractor(final String loanIdsAsString) { final StringBuilder scheduleDetail = new StringBuilder(); scheduleDetail.append("select ml.id as loanId, mr.duedate as dueDate, mr.principal_amount as principalAmount, "); - scheduleDetail - .append("mr.interest_amount as interestAmount, mr.fee_charges_amount as feeAmount, mr.penalty_charges_amount as penaltyAmount "); + scheduleDetail.append( + "mr.interest_amount as interestAmount, mr.fee_charges_amount as feeAmount, mr.penalty_charges_amount as penaltyAmount "); scheduleDetail.append("from m_loan ml INNER JOIN m_loan_repayment_schedule_history mr on mr.loan_id = ml.id "); scheduleDetail.append("where mr.duedate < SUBDATE(CURDATE(),INTERVAL ifnull(ml.grace_on_arrears_ageing,0) day) and "); scheduleDetail.append("ml.id IN(").append(loanIdsAsString).append(") and mr.version = ("); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAssembler.java index eda4b92b4..c68b1bfba 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanAssembler.java @@ -148,7 +148,6 @@ public class LoanAssembler { return loanAccount; } - public void setHelpers(final Loan loanAccount) { loanAccount.setHelpers(defaultLoanLifecycleStateMachine(), this.loanSummaryWrapper, this.loanRepaymentScheduleTransactionProcessorFactory); @@ -172,15 +171,16 @@ public class LoanAssembler { final Long transactionProcessingStrategyId = this.fromApiJsonHelper.extractLongNamed("transactionProcessingStrategyId", element); final Long loanPurposeId = this.fromApiJsonHelper.extractLongNamed("loanPurposeId", element); final Boolean syncDisbursementWithMeeting = this.fromApiJsonHelper.extractBooleanNamed("syncDisbursementWithMeeting", element); - final Boolean createStandingInstructionAtDisbursement = this.fromApiJsonHelper.extractBooleanNamed( - "createStandingInstructionAtDisbursement", element); + final Boolean createStandingInstructionAtDisbursement = this.fromApiJsonHelper + .extractBooleanNamed("createStandingInstructionAtDisbursement", element); final LoanProduct loanProduct = this.loanProductRepository.findById(productId) .orElseThrow(() -> new LoanProductNotFoundException(productId)); final Fund fund = findFundByIdIfProvided(fundId); final Staff loanOfficer = findLoanOfficerByIdIfProvided(loanOfficerId); - final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy = findStrategyByIdIfProvided(transactionProcessingStrategyId); + final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy = findStrategyByIdIfProvided( + transactionProcessingStrategyId); CodeValue loanPurpose = null; if (loanPurposeId != null) { loanPurpose = this.codeValueRepository.findOneWithNotFoundDetection(loanPurposeId); @@ -208,7 +208,7 @@ public class LoanAssembler { } } final Set collateral = this.loanCollateralAssembler.fromParsedJson(element); - final Set loanCharges = this.loanChargeAssembler.fromParsedJson(element,disbursementDetails); + final Set loanCharges = this.loanChargeAssembler.fromParsedJson(element, disbursementDetails); for (final LoanCharge loanCharge : loanCharges) { if (!loanProduct.hasCurrencyCodeOf(loanCharge.currencyCode())) { final String errorMessage = "Charge and Loan must have the same currency."; @@ -227,27 +227,27 @@ public class LoanAssembler { Client client = null; Group group = null; - //Here we add Rates to LoanApplication + // Here we add Rates to LoanApplication final List rates = this.rateAssembler.fromParsedJson(element); final LoanProductRelatedDetail loanProductRelatedDetail = this.loanScheduleAssembler.assembleLoanProductRelatedDetail(element); - final BigDecimal interestRateDifferential = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(LoanApiConstants.interestRateDifferentialParameterName, element); - final Boolean isFloatingInterestRate = this.fromApiJsonHelper.extractBooleanNamed(LoanApiConstants.isFloatingInterestRateParameterName, element); + final BigDecimal interestRateDifferential = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanApiConstants.interestRateDifferentialParameterName, element); + final Boolean isFloatingInterestRate = this.fromApiJsonHelper + .extractBooleanNamed(LoanApiConstants.isFloatingInterestRateParameterName, element); final String loanTypeParameterName = "loanType"; final String loanTypeStr = this.fromApiJsonHelper.extractStringNamed(loanTypeParameterName, element); final EnumOptionData loanType = AccountEnumerations.loanType(loanTypeStr); - if (clientId != null) { client = this.clientRepository.findOneWithNotFoundDetection(clientId); if (client.isNotActive()) { throw new ClientNotActiveException(clientId); } } if (groupId != null) { - group = this.groupRepository.findById(groupId) - .orElseThrow(() -> new GroupNotFoundException(groupId)); + group = this.groupRepository.findById(groupId).orElseThrow(() -> new GroupNotFoundException(groupId)); if (group.isNotActive()) { throw new GroupNotActiveException(groupId); } } @@ -255,9 +255,9 @@ public class LoanAssembler { if (!group.hasClientAsMember(client)) { throw new ClientNotInGroupException(clientId, groupId); } - loanApplication = Loan.newIndividualLoanApplicationFromGroup(accountNo, client, group, loanType.getId().intValue(), - loanProduct, fund, loanOfficer, loanPurpose, loanTransactionProcessingStrategy, loanProductRelatedDetail, loanCharges, - collateral, syncDisbursementWithMeeting, fixedEmiAmount, disbursementDetails, maxOutstandingLoanBalance, + loanApplication = Loan.newIndividualLoanApplicationFromGroup(accountNo, client, group, loanType.getId().intValue(), loanProduct, + fund, loanOfficer, loanPurpose, loanTransactionProcessingStrategy, loanProductRelatedDetail, loanCharges, collateral, + syncDisbursementWithMeeting, fixedEmiAmount, disbursementDetails, maxOutstandingLoanBalance, createStandingInstructionAtDisbursement, isFloatingInterestRate, interestRateDifferential, rates); } else if (group != null) { @@ -265,7 +265,7 @@ public class LoanAssembler { loanApplication = Loan.newGroupLoanApplication(accountNo, group, loanType.getId().intValue(), loanProduct, fund, loanOfficer, loanPurpose, loanTransactionProcessingStrategy, loanProductRelatedDetail, loanCharges, collateral, syncDisbursementWithMeeting, fixedEmiAmount, disbursementDetails, maxOutstandingLoanBalance, - createStandingInstructionAtDisbursement,isFloatingInterestRate, interestRateDifferential, rates); + createStandingInstructionAtDisbursement, isFloatingInterestRate, interestRateDifferential, rates); } else if (client != null) { @@ -279,7 +279,9 @@ public class LoanAssembler { final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element); final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed("submittedOnDate", element); - if (loanApplication == null) { throw new IllegalStateException("No loan application exists for either a client or group (or both)."); } + if (loanApplication == null) { + throw new IllegalStateException("No loan application exists for either a client or group (or both)."); + } loanApplication.setHelpers(defaultLoanLifecycleStateMachine(), this.loanSummaryWrapper, this.loanRepaymentScheduleTransactionProcessorFactory); @@ -289,7 +291,6 @@ public class LoanAssembler { } } - final LoanApplicationTerms loanApplicationTerms = this.loanScheduleAssembler.assembleLoanTerms(element); final boolean isHolidayEnabled = this.configurationDomainService.isRescheduleRepaymentsOnHolidaysEnabled(); final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(loanApplication.getOfficeId(), @@ -298,7 +299,7 @@ public class LoanAssembler { final boolean allowTransactionsOnNonWorkingDay = this.configurationDomainService.allowTransactionsOnNonWorkingDayEnabled(); final boolean allowTransactionsOnHoliday = this.configurationDomainService.allowTransactionsOnHolidayEnabled(); final LoanScheduleModel loanScheduleModel = this.loanScheduleAssembler.assembleLoanScheduleFrom(loanApplicationTerms, - isHolidayEnabled, holidays, workingDays, element,disbursementDetails); + isHolidayEnabled, holidays, workingDays, element, disbursementDetails); loanApplication.loanApplicationSubmittal(currentUser, loanScheduleModel, loanApplicationTerms, defaultLoanLifecycleStateMachine(), submittedOnDate, externalId, allowTransactionsOnHoliday, holidays, workingDays, allowTransactionsOnNonWorkingDay); @@ -321,8 +322,7 @@ public class LoanAssembler { public Fund findFundByIdIfProvided(final Long fundId) { Fund fund = null; if (fundId != null) { - fund = this.fundRepository.findById(fundId) - .orElseThrow(() -> new FundNotFoundException(fundId)); + fund = this.fundRepository.findById(fundId).orElseThrow(() -> new FundNotFoundException(fundId)); } return fund; } @@ -330,8 +330,7 @@ public class LoanAssembler { public Staff findLoanOfficerByIdIfProvided(final Long loanOfficerId) { Staff staff = null; if (loanOfficerId != null) { - staff = this.staffRepository.findById(loanOfficerId) - .orElseThrow(() -> new StaffNotFoundException(loanOfficerId)); + staff = this.staffRepository.findById(loanOfficerId).orElseThrow(() -> new StaffNotFoundException(loanOfficerId)); if (staff.isNotLoanOfficer()) { throw new StaffRoleException(loanOfficerId, StaffRoleException.StaffRole.LOAN_OFFICER); } } return staff; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeAssembler.java index 95d83768c..257a235e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeAssembler.java @@ -112,8 +112,8 @@ public class LoanChargeAssembler { final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed("chargeTimeType", loanChargeElement, locale); final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed("chargeCalculationType", loanChargeElement, locale); - final LocalDate dueDate = this.fromApiJsonHelper - .extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale); + final LocalDate dueDate = this.fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, + locale); final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerNamed("chargePaymentMode", loanChargeElement, locale); if (id == null) { @@ -152,7 +152,7 @@ public class LoanChargeAssembler { } } - if ( ChargeTimeType.DISBURSEMENT.getValue().equals(chargeDefinition.getChargeTimeType())) { + if (ChargeTimeType.DISBURSEMENT.getValue().equals(chargeDefinition.getChargeTimeType())) { for (LoanDisbursementDetails disbursementDetail : disbursementDetails) { LoanTrancheDisbursementCharge loanTrancheDisbursementCharge = null; if (chargeDefinition.isPercentageOfApprovedAmount() @@ -203,8 +203,7 @@ public class LoanChargeAssembler { final Long loanChargeId = id; final LoanCharge loanCharge = this.loanChargeRepository.findById(loanChargeId).orElse(null); if (loanCharge != null) { - if(!loanCharge.isTrancheDisbursementCharge() - || disbursementChargeIds.contains(loanChargeId)){ + if (!loanCharge.isTrancheDisbursementCharge() || disbursementChargeIds.contains(loanChargeId)) { loanCharge.update(amount, dueDate, numberOfRepayments); loanCharges.add(loanCharge); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargePaidByReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargePaidByReadPlatformServiceImpl.java index 60cafe089..aee379f0e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargePaidByReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargePaidByReadPlatformServiceImpl.java @@ -32,51 +32,46 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class LoanChargePaidByReadPlatformServiceImpl implements - LoanChargePaidByReadPlatformService { +public class LoanChargePaidByReadPlatformServiceImpl implements LoanChargePaidByReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; - @Autowired - public LoanChargePaidByReadPlatformServiceImpl(final PlatformSecurityContext context, - final RoutingDataSource dataSource) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); + @Autowired + public LoanChargePaidByReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { + this.context = context; + this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Override - public List getLoanChargesPaidByTransactionId(Long transactionId) { - this.context.authenticatedUser(); - final LoanChargePaidByMapper rm = new LoanChargePaidByMapper(); - final String sql = "select " + rm.loanChargePaidBySchema() + " where lcpd.loan_transaction_id = ?"; - return this.jdbcTemplate.query(sql, rm, new Object[]{transactionId}); - } - - private static final class LoanChargePaidByMapper implements RowMapper { - - public String loanChargePaidBySchema() { - return "lcpd.id as id, lcpd.amount as amount, lcpd.installment_number as installmentNumber," + - " lcpd.loan_charge_id as chargeId, lcpd.loan_transaction_id as transactionId, " + - " c.name as chargeName" - + " from m_loan_charge_paid_by lcpd" - + " join m_loan_charge lc on lc.id=lcpd.loan_charge_Id" - + " join m_charge c on c.id=lc.charge_id"; } @Override - public LoanChargePaidByData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) - throws SQLException { - final Long id = rs.getLong("id"); - final BigDecimal amount = rs.getBigDecimal("amount"); - final Integer installmentNumber = rs.getInt("installmentNumber"); - final Long chargeId = rs.getLong("chargeId"); - final Long transactionId = rs.getLong("transactionId"); - final String chargeName = rs.getString("chargeName"); - return new LoanChargePaidByData(id, amount, installmentNumber, chargeId, transactionId, chargeName); + public List getLoanChargesPaidByTransactionId(Long transactionId) { + this.context.authenticatedUser(); + final LoanChargePaidByMapper rm = new LoanChargePaidByMapper(); + final String sql = "select " + rm.loanChargePaidBySchema() + " where lcpd.loan_transaction_id = ?"; + return this.jdbcTemplate.query(sql, rm, new Object[] { transactionId }); } - } + private static final class LoanChargePaidByMapper implements RowMapper { + + public String loanChargePaidBySchema() { + return "lcpd.id as id, lcpd.amount as amount, lcpd.installment_number as installmentNumber," + + " lcpd.loan_charge_id as chargeId, lcpd.loan_transaction_id as transactionId, " + " c.name as chargeName" + + " from m_loan_charge_paid_by lcpd" + " join m_loan_charge lc on lc.id=lcpd.loan_charge_Id" + + " join m_charge c on c.id=lc.charge_id"; + } + + @Override + public LoanChargePaidByData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { + final Long id = rs.getLong("id"); + final BigDecimal amount = rs.getBigDecimal("amount"); + final Integer installmentNumber = rs.getInt("installmentNumber"); + final Long chargeId = rs.getLong("chargeId"); + final Long transactionId = rs.getLong("transactionId"); + final String chargeName = rs.getString("chargeName"); + return new LoanChargePaidByData(id, amount, installmentNumber, chargeId, transactionId, chargeName); + } + + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeReadPlatformService.java index 1913f0a1d..b36cc54ec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeReadPlatformService.java @@ -41,5 +41,6 @@ public interface LoanChargeReadPlatformService { Collection retrieveLoanChargesForAccural(Long loanId); - Collection retriveLoanChargesPaidBy(Long chargeId, LoanTransactionType transactionType, Integer installmentNumber); + Collection retriveLoanChargesPaidBy(Long chargeId, LoanTransactionType transactionType, + Integer installmentNumber); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeReadPlatformServiceImpl.java old mode 100755 new mode 100644 index da030402e..684c33543 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanChargeReadPlatformServiceImpl.java @@ -156,8 +156,8 @@ public class LoanChargeReadPlatformServiceImpl implements LoanChargeReadPlatform final List feeFrequencyOptions = this.dropdownReadPlatformService.retrievePeriodFrequencyTypeOptions(); // this field is applicable only for client charges final Map> incomeOrLiabilityAccountOptions = null; - final List shareChargeCalculationTypeOptions = null ; - final List shareChargeTimeTypeOptions = null ; + final List shareChargeCalculationTypeOptions = null; + final List shareChargeTimeTypeOptions = null; final Collection taxGroupOptions = null; return ChargeData.template(null, allowedChargeCalculationTypeOptions, null, allowedChargeTimeOptions, null, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions, savingsChargeCalculationTypeOptions, @@ -397,7 +397,8 @@ public class LoanChargeReadPlatformServiceImpl implements LoanChargeReadPlatform private Collection retrieveInstallmentLoanChargesForAccrual(Long loanChargeId) { final LoanInstallmentChargeAccrualMapper rm = new LoanInstallmentChargeAccrualMapper(); - String sql = "select " + rm.schema() + " where lic.loan_charge_id= ? group by lsi.installment, lsi.duedate, lic.amount_outstanding_derived, lic.amount, lic.is_paid_derived, lic.amount_waived_derived, lic.waived"; + String sql = "select " + rm.schema() + + " where lic.loan_charge_id= ? group by lsi.installment, lsi.duedate, lic.amount_outstanding_derived, lic.amount, lic.is_paid_derived, lic.amount_waived_derived, lic.waived"; Collection chargeDatas = this.jdbcTemplate.query(sql, rm, new Object[] { LoanTransactionType.ACCRUAL.getValue(), loanChargeId }); final Map installmentChargeDatas = new HashMap<>(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformService.java index 99b2a554c..731c3a405 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformService.java @@ -45,7 +45,7 @@ public interface LoanReadPlatformService { LoanAccountData retrieveOne(Long loanId); LoanScheduleData retrieveRepaymentSchedule(Long loanId, RepaymentScheduleRelatedLoanData repaymentScheduleRelatedData, - Collection disbursementData, boolean isInterestRecalculationEnabled, BigDecimal totalPaidFeeCharges); + Collection disbursementData, boolean isInterestRecalculationEnabled, BigDecimal totalPaidFeeCharges); Collection retrieveLoanTransactions(Long loanId); @@ -89,7 +89,8 @@ public interface LoanReadPlatformService { * result overdue installments with this charge already applied are not * returned. */ - Collection retrieveAllLoansWithOverdueInstallments(final Long penaltyWaitPeriod, final Boolean backdatePenalties); + Collection retrieveAllLoansWithOverdueInstallments(final Long penaltyWaitPeriod, + final Boolean backdatePenalties); Integer retriveLoanCounter(Long groupId, Integer loanType, Long productId); @@ -143,4 +144,4 @@ public interface LoanReadPlatformService { List retrieveGLIMChildLoansByGLIMParentAccount(String parentloanAccountNumber); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java index d0b6039d9..6046a7348 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java @@ -134,7 +134,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { private final JdbcTemplate jdbcTemplate; private final PlatformSecurityContext context; - private final LoanRepositoryWrapper loanRepositoryWrapper ; + private final LoanRepositoryWrapper loanRepositoryWrapper; private final ApplicationCurrencyRepositoryWrapper applicationCurrencyRepository; private final LoanProductReadPlatformService loanProductReadPlatformService; private final ClientReadPlatformService clientReadPlatformService; @@ -158,20 +158,21 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { private final ColumnValidator columnValidator; @Autowired - public LoanReadPlatformServiceImpl(final PlatformSecurityContext context, final ApplicationCurrencyRepositoryWrapper applicationCurrencyRepository, - final LoanProductReadPlatformService loanProductReadPlatformService, final ClientReadPlatformService clientReadPlatformService, - final GroupReadPlatformService groupReadPlatformService, final LoanDropdownReadPlatformService loanDropdownReadPlatformService, - final FundReadPlatformService fundReadPlatformService, final ChargeReadPlatformService chargeReadPlatformService, - final CodeValueReadPlatformService codeValueReadPlatformService, final RoutingDataSource dataSource, - final CalendarReadPlatformService calendarReadPlatformService, final StaffReadPlatformService staffReadPlatformService, - final PaymentTypeReadPlatformService paymentTypeReadPlatformService, - final LoanRepaymentScheduleTransactionProcessorFactory loanRepaymentScheduleTransactionProcessorFactory, - final FloatingRatesReadPlatformService floatingRatesReadPlatformService, final LoanUtilService loanUtilService, - final ConfigurationDomainService configurationDomainService, - final AccountDetailsReadPlatformService accountDetailsReadPlatformService, - final LoanRepositoryWrapper loanRepositoryWrapper, final ColumnValidator columnValidator) { + public LoanReadPlatformServiceImpl(final PlatformSecurityContext context, + final ApplicationCurrencyRepositoryWrapper applicationCurrencyRepository, + final LoanProductReadPlatformService loanProductReadPlatformService, final ClientReadPlatformService clientReadPlatformService, + final GroupReadPlatformService groupReadPlatformService, final LoanDropdownReadPlatformService loanDropdownReadPlatformService, + final FundReadPlatformService fundReadPlatformService, final ChargeReadPlatformService chargeReadPlatformService, + final CodeValueReadPlatformService codeValueReadPlatformService, final RoutingDataSource dataSource, + final CalendarReadPlatformService calendarReadPlatformService, final StaffReadPlatformService staffReadPlatformService, + final PaymentTypeReadPlatformService paymentTypeReadPlatformService, + final LoanRepaymentScheduleTransactionProcessorFactory loanRepaymentScheduleTransactionProcessorFactory, + final FloatingRatesReadPlatformService floatingRatesReadPlatformService, final LoanUtilService loanUtilService, + final ConfigurationDomainService configurationDomainService, + final AccountDetailsReadPlatformService accountDetailsReadPlatformService, final LoanRepositoryWrapper loanRepositoryWrapper, + final ColumnValidator columnValidator) { this.context = context; - this.loanRepositoryWrapper = loanRepositoryWrapper ; + this.loanRepositoryWrapper = loanRepositoryWrapper; this.applicationCurrencyRepository = applicationCurrencyRepository; this.loanProductReadPlatformService = loanProductReadPlatformService; this.clientReadPlatformService = clientReadPlatformService; @@ -210,50 +211,45 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { sqlBuilder.append(" left join m_office transferToOffice on transferToOffice.id = c.transfer_to_office_id "); sqlBuilder.append(" where l.id=? and ( o.hierarchy like ? or transferToOffice.hierarchy like ?)"); - return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), rm, new Object[] { loanId, hierarchySearchString, - hierarchySearchString }); + return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), rm, + new Object[] { loanId, hierarchySearchString, hierarchySearchString }); } catch (final EmptyResultDataAccessException e) { throw new LoanNotFoundException(loanId); } } @Override - public LoanAccountData retrieveLoanByLoanAccount(String loanAccountNumber) - { + public LoanAccountData retrieveLoanByLoanAccount(String loanAccountNumber) { - - //final AppUser currentUser = this.context.authenticatedUser(); + // final AppUser currentUser = this.context.authenticatedUser(); this.context.authenticatedUser(); final LoanMapper rm = new LoanMapper(); - String sql="select "+rm.loanSchema()+" where l.account_no=?"; - + String sql = "select " + rm.loanSchema() + " where l.account_no=?"; return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { loanAccountNumber }); } @Override - public List retrieveGLIMChildLoansByGLIMParentAccount(String parentloanAccountNumber) - { + public List retrieveGLIMChildLoansByGLIMParentAccount(String parentloanAccountNumber) { + // final AppUser currentUser = this.context.authenticatedUser(); + this.context.authenticatedUser(); + final LoanMapper rm = new LoanMapper(); - //final AppUser currentUser = this.context.authenticatedUser(); - this.context.authenticatedUser(); - final LoanMapper rm = new LoanMapper(); + String sql = "select " + rm.loanSchema() + + " left join glim_parent_child_mapping as glim on glim.glim_child_account_id=l.account_no " + + "where glim.glim_parent_account_id=?"; - String sql="select "+rm.loanSchema()+" left join glim_parent_child_mapping as glim on glim.glim_child_account_id=l.account_no "+ - "where glim.glim_parent_account_id=?"; - - - return this.jdbcTemplate.query(sql, rm, new Object[] { parentloanAccountNumber }); + return this.jdbcTemplate.query(sql, rm, new Object[] { parentloanAccountNumber }); } @Override public LoanScheduleData retrieveRepaymentSchedule(final Long loanId, - final RepaymentScheduleRelatedLoanData repaymentScheduleRelatedLoanData, Collection disbursementData, - boolean isInterestRecalculationEnabled, BigDecimal totalPaidFeeCharges) { + final RepaymentScheduleRelatedLoanData repaymentScheduleRelatedLoanData, Collection disbursementData, + boolean isInterestRecalculationEnabled, BigDecimal totalPaidFeeCharges) { try { this.context.authenticatedUser(); @@ -268,8 +264,6 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { } } - - @Override public Collection retrieveLoanTransactions(final Long loanId) { try { @@ -284,8 +278,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { /*** * TODO Vishwas: Remove references to "Contra" from the codebase ***/ - final String sql = "select " - + rm.loanPaymentsSchema() + final String sql = "select " + rm.loanPaymentsSchema() + " where tr.loan_id = ? and tr.transaction_type_enum not in (0, 3) and (tr.is_reversed=0 or tr.manually_adjusted_or_reversed = 1) order by tr.transaction_date ASC,id "; return this.jdbcTemplate.query(sql, rm, new Object[] { loanId }); } catch (final EmptyResultDataAccessException e) { @@ -318,7 +311,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { extraCriterias.add(hierarchySearchString); extraCriterias.add(hierarchySearchString); - if (searchParameters!=null) { + if (searchParameters != null) { String sqlQueryCriteria = searchParameters.getSqlSearch(); if (StringUtils.isNotBlank(sqlQueryCriteria)) { @@ -333,7 +326,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { extraCriterias.add(searchParameters.getExternalId()); arrayPos = arrayPos + 1; } - if(searchParameters.getOfficeId()!=null){ + if (searchParameters.getOfficeId() != null) { sqlBuilder.append("and c.office_id =?"); extraCriterias.add(searchParameters.getOfficeId()); arrayPos = arrayPos + 1; @@ -369,7 +362,6 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { this.loaanLoanMapper); } - @Override public LoanAccountData retrieveTemplateWithClientAndProductDetails(final Long clientId, final Long productId) { @@ -469,29 +461,30 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { final BigDecimal unrecognizedIncomePortion = null; BigDecimal adjustedChargeAmount = adjustPrepayInstallmentCharge(loan, onDate); return new LoanTransactionData(null, null, null, transactionType, null, currencyData, earliestUnpaidInstallmentDate, - loanRepaymentScheduleInstallment.getTotalOutstanding(currency).getAmount().subtract(adjustedChargeAmount), loanRepaymentScheduleInstallment - .getPrincipalOutstanding(currency).getAmount(), loanRepaymentScheduleInstallment.getInterestOutstanding(currency) - .getAmount(), loanRepaymentScheduleInstallment.getFeeChargesOutstanding(currency).getAmount().subtract(adjustedChargeAmount), + loanRepaymentScheduleInstallment.getTotalOutstanding(currency).getAmount().subtract(adjustedChargeAmount), + loanRepaymentScheduleInstallment.getPrincipalOutstanding(currency).getAmount(), + loanRepaymentScheduleInstallment.getInterestOutstanding(currency).getAmount(), + loanRepaymentScheduleInstallment.getFeeChargesOutstanding(currency).getAmount().subtract(adjustedChargeAmount), loanRepaymentScheduleInstallment.getPenaltyChargesOutstanding(currency).getAmount(), null, unrecognizedIncomePortion, paymentOptions, null, null, null, outstandingLoanBalance, false); } private BigDecimal adjustPrepayInstallmentCharge(Loan loan, final LocalDate onDate) { BigDecimal chargeAmount = BigDecimal.ZERO; - /*for(LoanCharge loanCharge: loan.charges()){ - if(loanCharge.isInstalmentFee() && loanCharge.getCharge().getChargeCalculation()==ChargeCalculationType.FLAT.getValue()){ - for (LoanRepaymentScheduleInstallment installment : loan.getRepaymentScheduleInstallments()) { - if(onDate.isBefore(installment.getDueDate())){ - LoanInstallmentCharge loanInstallmentCharge = loanCharge.getInstallmentLoanCharge(installment.getInstallmentNumber()); - if(loanInstallmentCharge != null){ - chargeAmount = chargeAmount.add(loanInstallmentCharge.getAmountOutstanding()); - } - - break; - } - } - } - }*/ + /* + * for(LoanCharge loanCharge: loan.charges()){ + * if(loanCharge.isInstalmentFee() && + * loanCharge.getCharge().getChargeCalculation()==ChargeCalculationType. + * FLAT.getValue()){ for (LoanRepaymentScheduleInstallment installment : + * loan.getRepaymentScheduleInstallments()) { + * if(onDate.isBefore(installment.getDueDate())){ LoanInstallmentCharge + * loanInstallmentCharge = + * loanCharge.getInstallmentLoanCharge(installment.getInstallmentNumber( + * )); if(loanInstallmentCharge != null){ chargeAmount = + * chargeAmount.add(loanInstallmentCharge.getAmountOutstanding()); } + * + * break; } } } } + */ return chargeAmount; } @@ -546,8 +539,9 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { if (paymentDetailsRequired) { paymentOptions = this.paymentTypeReadPlatformService.retrieveAllPaymentTypes(); } - return LoanTransactionData.loanTransactionDataForDisbursalTemplate(transactionType, loan.getExpectedDisbursedOnLocalDateForTemplate(), loan.getDisburseAmountForTemplate(), - paymentOptions, loan.retriveLastEmiAmount(), loan.getNextPossibleRepaymentDateForRescheduling()); + return LoanTransactionData.loanTransactionDataForDisbursalTemplate(transactionType, + loan.getExpectedDisbursedOnLocalDateForTemplate(), loan.getDisburseAmountForTemplate(), paymentOptions, + loan.retriveLastEmiAmount(), loan.getNextPossibleRepaymentDateForRescheduling()); } @@ -596,19 +590,14 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { + " lps.name as transactionStrategyName, " + " l.currency_code as currencyCode, l.currency_digits as currencyDigits, l.currency_multiplesof as inMultiplesOf, rc.`name` as currencyName, rc.display_symbol as currencyDisplaySymbol, rc.internationalized_name_code as currencyNameCode, " + " l.loan_officer_id as loanOfficerId, s.display_name as loanOfficerName, " - + " l.principal_disbursed_derived as principalDisbursed," - + " l.principal_repaid_derived as principalPaid," + + " l.principal_disbursed_derived as principalDisbursed," + " l.principal_repaid_derived as principalPaid," + " l.principal_writtenoff_derived as principalWrittenOff," - + " l.principal_outstanding_derived as principalOutstanding," - + " l.interest_charged_derived as interestCharged," - + " l.interest_repaid_derived as interestPaid," - + " l.interest_waived_derived as interestWaived," - + " l.interest_writtenoff_derived as interestWrittenOff," - + " l.interest_outstanding_derived as interestOutstanding," + + " l.principal_outstanding_derived as principalOutstanding," + " l.interest_charged_derived as interestCharged," + + " l.interest_repaid_derived as interestPaid," + " l.interest_waived_derived as interestWaived," + + " l.interest_writtenoff_derived as interestWrittenOff," + " l.interest_outstanding_derived as interestOutstanding," + " l.fee_charges_charged_derived as feeChargesCharged," + " l.total_charges_due_at_disbursement_derived as feeChargesDueAtDisbursementCharged," - + " l.fee_charges_repaid_derived as feeChargesPaid," - + " l.fee_charges_waived_derived as feeChargesWaived," + + " l.fee_charges_repaid_derived as feeChargesPaid," + " l.fee_charges_waived_derived as feeChargesWaived," + " l.fee_charges_writtenoff_derived as feeChargesWrittenOff," + " l.fee_charges_outstanding_derived as feeChargesOutstanding," + " l.penalty_charges_charged_derived as penaltyChargesCharged," @@ -616,24 +605,15 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { + " l.penalty_charges_waived_derived as penaltyChargesWaived," + " l.penalty_charges_writtenoff_derived as penaltyChargesWrittenOff," + " l.penalty_charges_outstanding_derived as penaltyChargesOutstanding," - + " l.total_expected_repayment_derived as totalExpectedRepayment," - + " l.total_repayment_derived as totalRepayment," - + " l.total_expected_costofloan_derived as totalExpectedCostOfLoan," - + " l.total_costofloan_derived as totalCostOfLoan," - + " l.total_waived_derived as totalWaived," - + " l.total_writtenoff_derived as totalWrittenOff," - + " l.writeoff_reason_cv_id as writeoffReasonId," - + " codev.code_value as writeoffReason," - + " l.total_outstanding_derived as totalOutstanding," - + " l.total_overpaid_derived as totalOverpaid," - + " l.fixed_emi_amount as fixedEmiAmount," - + " l.max_outstanding_loan_balance as outstandingLoanBalance," - + " l.loan_sub_status_id as loanSubStatusId," - + " la.principal_overdue_derived as principalOverdue," - + " la.interest_overdue_derived as interestOverdue," - + " la.fee_charges_overdue_derived as feeChargesOverdue," - + " la.penalty_charges_overdue_derived as penaltyChargesOverdue," - + " la.total_overdue_derived as totalOverdue," + + " l.total_expected_repayment_derived as totalExpectedRepayment," + " l.total_repayment_derived as totalRepayment," + + " l.total_expected_costofloan_derived as totalExpectedCostOfLoan," + " l.total_costofloan_derived as totalCostOfLoan," + + " l.total_waived_derived as totalWaived," + " l.total_writtenoff_derived as totalWrittenOff," + + " l.writeoff_reason_cv_id as writeoffReasonId," + " codev.code_value as writeoffReason," + + " l.total_outstanding_derived as totalOutstanding," + " l.total_overpaid_derived as totalOverpaid," + + " l.fixed_emi_amount as fixedEmiAmount," + " l.max_outstanding_loan_balance as outstandingLoanBalance," + + " l.loan_sub_status_id as loanSubStatusId," + " la.principal_overdue_derived as principalOverdue," + + " la.interest_overdue_derived as interestOverdue," + " la.fee_charges_overdue_derived as feeChargesOverdue," + + " la.penalty_charges_overdue_derived as penaltyChargesOverdue," + " la.total_overdue_derived as totalOverdue," + " la.overdue_since_date_derived as overdueSinceDate," + " l.sync_disbursement_with_meeting as syncDisbursementWithMeeting," + " l.loan_counter as loanCounter, l.loan_product_counter as loanProductCounter," @@ -654,12 +634,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { + " l.interest_rate_differential as interestRateDifferential, " + " l.create_standing_instruction_at_disbursement as createStandingInstructionAtDisbursement, " + " lpvi.minimum_gap as minimuminstallmentgap, lpvi.maximum_gap as maximuminstallmentgap, " - + " lp.can_use_for_topup as canUseForTopup, " - + " l.is_topup as isTopup, " - + " topup.closure_loan_id as closureLoanId, " - + " topuploan.account_no as closureLoanAccountNo, " - + " topup.topup_amount as topupAmount " - + " from m_loan l" // + + " lp.can_use_for_topup as canUseForTopup, " + " l.is_topup as isTopup, " + " topup.closure_loan_id as closureLoanId, " + + " topuploan.account_no as closureLoanAccountNo, " + " topup.topup_amount as topupAmount " + " from m_loan l" // + " join m_product_loan lp on lp.id = l.product_id" // + " left join m_loan_recalculation_details lir on lir.loan_id = l.id " + " join m_currency rc on rc.`code` = l.currency_code" // @@ -672,8 +648,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { + " left join m_appuser rbu on rbu.id = l.rejectedon_userid" + " left join m_appuser wbu on wbu.id = l.withdrawnon_userid" + " left join m_appuser abu on abu.id = l.approvedon_userid" - + " left join m_appuser dbu on dbu.id = l.disbursedon_userid" - + " left join m_appuser cbu on cbu.id = l.closedon_userid" + + " left join m_appuser dbu on dbu.id = l.disbursedon_userid" + " left join m_appuser cbu on cbu.id = l.closedon_userid" + " left join m_code_value cv on cv.id = l.loanpurpose_cv_id" + " left join m_code_value codev on codev.id = l.writeoff_reason_cv_id" + " left join ref_loan_transaction_processing_strategy lps on lps.id = l.loan_transaction_strategy_id" @@ -796,7 +771,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { final boolean isFloatingInterestRate = rs.getBoolean("isFloatingInterestRate"); final Integer graceOnPrincipalPayment = JdbcSupport.getIntegerDefaultToNullIfZero(rs, "graceOnPrincipalPayment"); - final Integer recurringMoratoriumOnPrincipalPeriods = JdbcSupport.getIntegerDefaultToNullIfZero(rs, "recurringMoratoriumOnPrincipalPeriods"); + final Integer recurringMoratoriumOnPrincipalPeriods = JdbcSupport.getIntegerDefaultToNullIfZero(rs, + "recurringMoratoriumOnPrincipalPeriods"); final Integer graceOnInterestPayment = JdbcSupport.getIntegerDefaultToNullIfZero(rs, "graceOnInterestPayment"); final Integer graceOnInterestCharged = JdbcSupport.getIntegerDefaultToNullIfZero(rs, "graceOnInterestCharged"); final Integer graceOnArrearsAgeing = JdbcSupport.getIntegerDefaultToNullIfZero(rs, "graceOnArrearsAgeing"); @@ -893,7 +869,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { feeChargesWaived, feeChargesWrittenOff, feeChargesOutstanding, feeChargesOverdue, penaltyChargesCharged, penaltyChargesPaid, penaltyChargesWaived, penaltyChargesWrittenOff, penaltyChargesOutstanding, penaltyChargesOverdue, totalExpectedRepayment, totalRepayment, totalExpectedCostOfLoan, totalCostOfLoan, - totalWaived, totalWrittenOff, totalOutstanding, totalOverdue, overdueSinceDate,writeoffReasonId, writeoffReason); + totalWaived, totalWrittenOff, totalOutstanding, totalOverdue, overdueSinceDate, writeoffReasonId, writeoffReason); } GroupGeneralData groupData = null; @@ -988,11 +964,11 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { interestType, isFloatingInterestRate, interestRateDifferential, interestCalculationPeriodType, allowPartialPeriodInterestCalcualtion, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, - timeline, loanSummary, feeChargesDueAtDisbursementCharged, syncDisbursementWithMeeting, loanCounter, - loanProductCounter, multiDisburseLoan, canDefineInstallmentAmount, fixedEmiAmount, outstandingLoanBalance, inArrears, - graceOnArrearsAgeing, isNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, - interestRecalculationData, createStandingInstructionAtDisbursement, isvariableInstallmentsAllowed, minimumGap, - maximumGap, loanSubStatus, canUseForTopup, isTopup, closureLoanId, closureLoanAccountNo, topupAmount, isEqualAmortization); + timeline, loanSummary, feeChargesDueAtDisbursementCharged, syncDisbursementWithMeeting, loanCounter, loanProductCounter, + multiDisburseLoan, canDefineInstallmentAmount, fixedEmiAmount, outstandingLoanBalance, inArrears, graceOnArrearsAgeing, + isNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, interestRecalculationData, + createStandingInstructionAtDisbursement, isvariableInstallmentsAllowed, minimumGap, maximumGap, loanSubStatus, + canUseForTopup, isTopup, closureLoanId, closureLoanAccountNo, topupAmount, isEqualAmortization); } } @@ -1005,8 +981,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { + " ls.fee_charges_amount as feeChargesDue, ls.fee_charges_completed_derived as feeChargesPaid, ls.fee_charges_waived_derived as feeChargesWaived, ls.fee_charges_writtenoff_derived as feeChargesWrittenOff, " + " ls.penalty_charges_amount as penaltyChargesDue, ls.penalty_charges_completed_derived as penaltyChargesPaid, ls.penalty_charges_waived_derived as penaltyChargesWaived, ls.penalty_charges_writtenoff_derived as penaltyChargesWrittenOff, " + " ls.total_paid_in_advance_derived as totalPaidInAdvanceForPeriod, ls.total_paid_late_derived as totalPaidLateForPeriod, " - + " mc.amount,mc.id as chargeId " - + " from m_loan_repayment_schedule ls " + + " mc.amount,mc.id as chargeId " + " from m_loan_repayment_schedule ls " + " inner join m_loan ml on ml.id = ls.loan_id " + " join m_product_loan_charge plc on plc.product_loan_id = ml.product_id " + " join m_charge mc on mc.id = plc.charge_id "; @@ -1056,7 +1031,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { private BigDecimal totalPaidFeeCharges; public LoanScheduleResultSetExtractor(final RepaymentScheduleRelatedLoanData repaymentScheduleRelatedLoanData, - Collection disbursementData, boolean isInterestRecalculationEnabled, BigDecimal totalPaidFeeCharges) { + Collection disbursementData, boolean isInterestRecalculationEnabled, BigDecimal totalPaidFeeCharges) { this.currency = repaymentScheduleRelatedLoanData.getCurrency(); this.disbursement = repaymentScheduleRelatedLoanData.disbursementData(); this.totalFeeChargesDueAtDisbursement = repaymentScheduleRelatedLoanData.getTotalFeeChargesAtDisbursement(); @@ -1100,8 +1075,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { if (!this.disbursement.isDisbursed()) { excludePastUndisbursed = false; } - for(DisbursementData data : disbursementData){ - if(data.getChargeAmount() != null){ + for (DisbursementData data : disbursementData) { + if (data.getChargeAmount() != null) { disbursementChargeAmount = disbursementChargeAmount.subtract(data.getChargeAmount()); } } @@ -1148,7 +1123,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { disbursementChargeAmount, data.isDisbursed()); } else { periodData = LoanSchedulePeriodData.disbursementOnlyPeriod(data.disbursementDate(), data.amount(), - disbursementChargeAmount.add(data.getChargeAmount()).subtract(waivedChargeAmount), data.isDisbursed()); + disbursementChargeAmount.add(data.getChargeAmount()).subtract(waivedChargeAmount), + data.isDisbursed()); } if (periodData != null) { periods.add(periodData); @@ -1156,8 +1132,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { this.outstandingLoanPrincipalBalance = this.outstandingLoanPrincipalBalance.add(data.amount()); } } else if (data.isDueForDisbursement(fromDate, dueDate)) { - if (!excludePastUndisbursed - || (excludePastUndisbursed && (data.isDisbursed() || !data.disbursementDate().isBefore(LocalDate.now())))) { + if (!excludePastUndisbursed || (excludePastUndisbursed + && (data.isDisbursed() || !data.disbursementDate().isBefore(LocalDate.now())))) { principal = principal.add(data.amount()); LoanSchedulePeriodData periodData = null; if (data.getChargeAmount() == null) { @@ -1221,12 +1197,12 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { "totalPaidInAdvanceForPeriod"); final BigDecimal totalPaidLateForPeriod = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "totalPaidLateForPeriod"); - final BigDecimal penaltyChargesActualDue = penaltyChargesExpectedDue.subtract(penaltyChargesWaived).subtract( - penaltyChargesWrittenOff); + final BigDecimal penaltyChargesActualDue = penaltyChargesExpectedDue.subtract(penaltyChargesWaived) + .subtract(penaltyChargesWrittenOff); final BigDecimal penaltyChargesOutstanding = penaltyChargesActualDue.subtract(penaltyChargesPaid); - final BigDecimal totalExpectedCostOfLoanForPeriod = interestExpectedDue.add(feeChargesExpectedDue).add( - penaltyChargesExpectedDue); + final BigDecimal totalExpectedCostOfLoanForPeriod = interestExpectedDue.add(feeChargesExpectedDue) + .add(penaltyChargesExpectedDue); final BigDecimal totalDueForPeriod = principalDue.add(totalExpectedCostOfLoanForPeriod); final BigDecimal totalPaidForPeriod = principalPaid.add(interestPaid).add(feeChargesPaid).add(penaltyChargesPaid); @@ -1267,11 +1243,11 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { periods.add(periodData); } - return new LoanScheduleData(this.currency, periods, loanTermInDays, totalPrincipalDisbursed, - totalPrincipalExpected.getAmount(), totalPrincipalPaid.getAmount(), totalInterestCharged.getAmount(), - totalFeeChargesCharged.getAmount(), totalPenaltyChargesCharged.getAmount(), totalWaived.getAmount(), - totalWrittenOff.getAmount(), totalRepaymentExpected.getAmount(), totalRepayment.getAmount(), - totalPaidInAdvance.getAmount(), totalPaidLate.getAmount(), totalOutstanding.getAmount()); + return new LoanScheduleData(this.currency, periods, loanTermInDays, totalPrincipalDisbursed, totalPrincipalExpected.getAmount(), + totalPrincipalPaid.getAmount(), totalInterestCharged.getAmount(), totalFeeChargesCharged.getAmount(), + totalPenaltyChargesCharged.getAmount(), totalWaived.getAmount(), totalWrittenOff.getAmount(), + totalRepaymentExpected.getAmount(), totalRepayment.getAmount(), totalPaidInAdvance.getAmount(), + totalPaidLate.getAmount(), totalOutstanding.getAmount()); } } @@ -1284,8 +1260,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { + " tr.principal_portion_derived as principal, tr.interest_portion_derived as interest, " + " tr.fee_charges_portion_derived as fees, tr.penalty_charges_portion_derived as penalties, " + " tr.overpayment_portion_derived as overpayment, tr.outstanding_loan_balance_derived as outstandingLoanBalance, " - + " tr.unrecognized_income_portion as unrecognizedIncome," - + " tr.submitted_on_date as submittedOnDate, " + + " tr.unrecognized_income_portion as unrecognizedIncome," + " tr.submitted_on_date as submittedOnDate, " + " tr.manually_adjusted_or_reversed as manuallyReversed, " + " pd.payment_type_id as paymentType,pd.account_number as accountNumber,pd.check_number as checkNumber, " + " pd.receipt_number as receiptNumber, pd.bank_number as bankNumber,pd.routing_code as routingCode, " @@ -1415,8 +1390,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { chargeOptions = this.chargeReadPlatformService.retrieveLoanProductApplicableCharges(productId, new ChargeTimeType[] { ChargeTimeType.OVERDUE_INSTALLMENT }); } else { - chargeOptions = this.chargeReadPlatformService.retrieveLoanProductApplicableCharges(productId, new ChargeTimeType[] { - ChargeTimeType.OVERDUE_INSTALLMENT, ChargeTimeType.TRANCHE_DISBURSEMENT }); + chargeOptions = this.chargeReadPlatformService.retrieveLoanProductApplicableCharges(productId, + new ChargeTimeType[] { ChargeTimeType.OVERDUE_INSTALLMENT, ChargeTimeType.TRANCHE_DISBURSEMENT }); } Integer loanCycleCounter = null; @@ -1429,7 +1404,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { } Collection activeLoanOptions = null; - if(loanProduct.canUseForTopup() && clientId != null) { + if (loanProduct.canUseForTopup() && clientId != null) { activeLoanOptions = this.accountDetailsReadPlatformService.retrieveClientActiveLoanAccountSummary(clientId); } else if (loanProduct.canUseForTopup() && groupId != null) { activeLoanOptions = this.accountDetailsReadPlatformService.retrieveGroupActiveLoanAccountSummary(groupId); @@ -1483,8 +1458,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public Collection retrieveCalendars(final Long groupId) { Collection calendarsData = new ArrayList<>(); - calendarsData.addAll(this.calendarReadPlatformService.retrieveParentCalendarsByEntity(groupId, - CalendarEntityType.GROUPS.getValue(), null)); + calendarsData.addAll( + this.calendarReadPlatformService.retrieveParentCalendarsByEntity(groupId, CalendarEntityType.GROUPS.getValue(), null)); calendarsData .addAll(this.calendarReadPlatformService.retrieveCalendarsByEntity(groupId, CalendarEntityType.GROUPS.getValue(), null)); calendarsData = this.calendarReadPlatformService.updateWithRecurringDates(calendarsData); @@ -1514,7 +1489,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public Collection retrieveAllLoansWithOverdueInstallments(final Long penaltyWaitPeriod, - final Boolean backdatePenalties) { + final Boolean backdatePenalties) { final MusoniOverdueLoanScheduleMapper rm = new MusoniOverdueLoanScheduleMapper(); final StringBuilder sqlBuilder = new StringBuilder(400); @@ -1535,22 +1510,21 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public Integer retriveLoanCounter(final Long groupId, final Integer loanType, Long productId) { final String sql = "Select MAX(l.loan_product_counter) from m_loan l where l.group_id = ? and l.loan_type_enum = ? and l.product_id=?"; - return this.jdbcTemplate.queryForObject( - sql, new Object[]{groupId, loanType, productId}, Integer.class); + return this.jdbcTemplate.queryForObject(sql, new Object[] { groupId, loanType, productId }, Integer.class); } @SuppressWarnings("deprecation") @Override public Integer retriveLoanCounter(final Long clientId, Long productId) { final String sql = "Select MAX(l.loan_product_counter) from m_loan l where l.client_id = ? and l.product_id=?"; - return this.jdbcTemplate.queryForObject( - sql, new Object[]{clientId, productId}, Integer.class); + return this.jdbcTemplate.queryForObject(sql, new Object[] { clientId, productId }, Integer.class); } @Override public Collection retrieveLoanDisbursementDetails(final Long loanId) { final LoanDisbursementDetailMapper rm = new LoanDisbursementDetailMapper(); - final String sql = "select " + rm.schema() + " where dd.loan_id=? group by dd.id, lc.amount_waived_derived order by dd.expected_disburse_date"; + final String sql = "select " + rm.schema() + + " where dd.loan_id=? group by dd.id, lc.amount_waived_derived order by dd.expected_disburse_date"; return this.jdbcTemplate.query(sql, rm, new Object[] { loanId }); } @@ -1624,15 +1598,13 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { LoanScheduleAccrualMapper mapper = new LoanScheduleAccrualMapper(); Date organisationStartDate = this.configurationDomainService.retrieveOrganisationStartDate(); final StringBuilder sqlBuilder = new StringBuilder(400); - sqlBuilder - .append("select ") - .append(mapper.schema()) - .append(" where (recaldet.is_compounding_to_be_posted_as_transaction is null or recaldet.is_compounding_to_be_posted_as_transaction = 0) ") + sqlBuilder.append("select ").append(mapper.schema()).append( + " where (recaldet.is_compounding_to_be_posted_as_transaction is null or recaldet.is_compounding_to_be_posted_as_transaction = 0) ") .append(" and (((ls.fee_charges_amount <> if(ls.accrual_fee_charges_derived is null,0, ls.accrual_fee_charges_derived))") .append(" or ( ls.penalty_charges_amount <> if(ls.accrual_penalty_charges_derived is null,0,ls.accrual_penalty_charges_derived))") .append(" or ( ls.interest_amount <> if(ls.accrual_interest_derived is null,0,ls.accrual_interest_derived)))") .append(" and loan.loan_status_id=:active and mpl.accounting_type=:type and loan.is_npa=0 and ls.duedate <= CURDATE()) "); - if(organisationStartDate != null){ + if (organisationStartDate != null) { sqlBuilder.append(" and ls.duedate > :organisationstartdate "); } sqlBuilder.append(" order by loan.id,ls.duedate "); @@ -1650,16 +1622,14 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { LoanSchedulePeriodicAccrualMapper mapper = new LoanSchedulePeriodicAccrualMapper(); Date organisationStartDate = this.configurationDomainService.retrieveOrganisationStartDate(); final StringBuilder sqlBuilder = new StringBuilder(400); - sqlBuilder - .append("select ") - .append(mapper.schema()) - .append(" where (recaldet.is_compounding_to_be_posted_as_transaction is null or recaldet.is_compounding_to_be_posted_as_transaction = 0) ") + sqlBuilder.append("select ").append(mapper.schema()).append( + " where (recaldet.is_compounding_to_be_posted_as_transaction is null or recaldet.is_compounding_to_be_posted_as_transaction = 0) ") .append(" and (((ls.fee_charges_amount <> if(ls.accrual_fee_charges_derived is null,0, ls.accrual_fee_charges_derived))") .append(" or (ls.penalty_charges_amount <> if(ls.accrual_penalty_charges_derived is null,0,ls.accrual_penalty_charges_derived))") .append(" or (ls.interest_amount <> if(ls.accrual_interest_derived is null,0,ls.accrual_interest_derived)))") .append(" and loan.loan_status_id=:active and mpl.accounting_type=:type and (loan.closedon_date <= :tilldate or loan.closedon_date is null)") .append(" and loan.is_npa=0 and (ls.duedate <= :tilldate or (ls.duedate > :tilldate and ls.fromdate < :tilldate))) "); - if(organisationStartDate != null){ + if (organisationStartDate != null) { sqlBuilder.append(" and ls.duedate > :organisationstartdate "); } sqlBuilder.append(" order by loan.id,ls.duedate "); @@ -1676,16 +1646,13 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { public String schema() { final StringBuilder sqlBuilder = new StringBuilder(400); - sqlBuilder - .append("loan.id as loanId ,if(loan.client_id is null,mg.office_id,mc.office_id) as officeId,") + sqlBuilder.append("loan.id as loanId ,if(loan.client_id is null,mg.office_id,mc.office_id) as officeId,") .append("loan.accrued_till as accruedTill, loan.repayment_period_frequency_enum as frequencyEnum, ") - .append("loan.interest_calculated_from_date as interestCalculatedFrom, ") - .append("loan.repay_every as repayEvery,") + .append("loan.interest_calculated_from_date as interestCalculatedFrom, ").append("loan.repay_every as repayEvery,") .append("ls.installment as installmentNumber, ") .append("ls.duedate as duedate,ls.fromdate as fromdate ,ls.id as scheduleId,loan.product_id as productId,") .append("ls.interest_amount as interest, ls.interest_waived_derived as interestWaived,") - .append("ls.penalty_charges_amount as penalty, ") - .append("ls.fee_charges_amount as charges, ") + .append("ls.penalty_charges_amount as penalty, ").append("ls.fee_charges_amount as charges, ") .append("ls.accrual_interest_derived as accinterest,ls.accrual_fee_charges_derived as accfeecharege,ls.accrual_penalty_charges_derived as accpenalty,") .append(" loan.currency_code as currencyCode,loan.currency_digits as currencyDigits,loan.currency_multiplesof as inMultiplesOf,") .append("curr.display_symbol as currencyDisplaySymbol,curr.name as currencyName,curr.internationalized_name_code as currencyNameCode") @@ -1741,13 +1708,11 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { public String schema() { final StringBuilder sqlBuilder = new StringBuilder(400); - sqlBuilder - .append("loan.id as loanId ,if(loan.client_id is null,mg.office_id,mc.office_id) as officeId,") + sqlBuilder.append("loan.id as loanId ,if(loan.client_id is null,mg.office_id,mc.office_id) as officeId,") .append("ls.duedate as duedate,ls.fromdate as fromdate,ls.id as scheduleId,loan.product_id as productId,") .append("ls.installment as installmentNumber, ") .append("ls.interest_amount as interest, ls.interest_waived_derived as interestWaived,") - .append("ls.penalty_charges_amount as penalty, ") - .append("ls.fee_charges_amount as charges, ") + .append("ls.penalty_charges_amount as penalty, ").append("ls.fee_charges_amount as charges, ") .append("ls.accrual_interest_derived as accinterest,ls.accrual_fee_charges_derived as accfeecharege,ls.accrual_penalty_charges_derived as accpenalty,") .append(" loan.currency_code as currencyCode,loan.currency_digits as currencyDigits,loan.currency_multiplesof as inMultiplesOf,") .append("curr.display_symbol as currencyDisplaySymbol,curr.name as currencyName,curr.internationalized_name_code as currencyNameCode") @@ -1816,9 +1781,9 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { final BigDecimal unrecognizedIncomePortion = null; final List writeOffReasonOptions = new ArrayList<>( this.codeValueReadPlatformService.retrieveCodeValuesByCode(LoanApiConstants.WRITEOFFREASONS)); - LoanTransactionData loanTransactionData = new LoanTransactionData(null, null, null, transactionType, null, loan.currency(), DateUtils.getLocalDateOfTenant(), - loan.getTotalOutstandingAmount(), null, null, null, null, null, null, null, null, outstandingLoanBalance, - unrecognizedIncomePortion, false); + LoanTransactionData loanTransactionData = new LoanTransactionData(null, null, null, transactionType, null, loan.currency(), + DateUtils.getLocalDateOfTenant(), loan.getTotalOutstandingAmount(), null, null, null, null, null, null, null, null, + outstandingLoanBalance, unrecognizedIncomePortion, false); loanTransactionData.setWriteOffReasonOptions(writeOffReasonOptions); return loanTransactionData; } @@ -1830,8 +1795,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { sqlBuilder.append(" INNER JOIN m_loan_repayment_schedule mr on mr.loan_id = ml.id "); sqlBuilder.append(" LEFT JOIN m_loan_disbursement_detail dd on dd.loan_id=ml.id and dd.disbursedon_date is null "); // For Floating rate changes - sqlBuilder - .append(" left join m_product_loan_floating_rates pfr on ml.product_id = pfr.loan_product_id and ml.is_floating_interest_rate = 1"); + sqlBuilder.append( + " left join m_product_loan_floating_rates pfr on ml.product_id = pfr.loan_product_id and ml.is_floating_interest_rate = 1"); sqlBuilder.append(" left join m_floating_rates fr on pfr.floating_rates_id = fr.id"); sqlBuilder.append(" left join m_floating_rates_periods frp on fr.id = frp.floating_rates_id "); sqlBuilder.append(" left join m_loan_reschedule_request lrr on lrr.loan_id = ml.id"); @@ -1858,8 +1823,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { String currentdate = formatter.print(DateUtils.getLocalDateOfTenant()); // will look only for yesterday modified rates String yesterday = formatter.print(DateUtils.getLocalDateOfTenant().minusDays(1)); - return this.jdbcTemplate.queryForList(sqlBuilder.toString(), Long.class, new Object[] { yesterday, - LoanStatus.ACTIVE.getValue(), currentdate, currentdate, currentdate, yesterday }); + return this.jdbcTemplate.queryForList(sqlBuilder.toString(), Long.class, + new Object[] { yesterday, LoanStatus.ACTIVE.getValue(), currentdate, currentdate, currentdate, yesterday }); } catch (final EmptyResultDataAccessException e) { return null; } @@ -1874,8 +1839,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { sqlBuilder.append(" INNER JOIN m_loan_repayment_schedule mr on mr.loan_id = ml.id "); sqlBuilder.append(" LEFT JOIN m_loan_disbursement_detail dd on dd.loan_id=ml.id and dd.disbursedon_date is null "); // For Floating rate changes - sqlBuilder - .append(" left join m_product_loan_floating_rates pfr on ml.product_id = pfr.loan_product_id and ml.is_floating_interest_rate = 1"); + sqlBuilder.append( + " left join m_product_loan_floating_rates pfr on ml.product_id = pfr.loan_product_id and ml.is_floating_interest_rate = 1"); sqlBuilder.append(" left join m_floating_rates fr on pfr.floating_rates_id = fr.id"); sqlBuilder.append(" left join m_floating_rates_periods frp on fr.id = frp.floating_rates_id "); sqlBuilder.append(" left join m_loan_reschedule_request lrr on lrr.loan_id = ml.id"); @@ -1904,8 +1869,9 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { String currentdate = formatter.print(DateUtils.getLocalDateOfTenant()); // will look only for yesterday modified rates String yesterday = formatter.print(DateUtils.getLocalDateOfTenant().minusDays(1)); - return Collections.synchronizedList(this.jdbcTemplate.queryForList(sqlBuilder.toString(), Long.class, new Object[] { yesterday, - LoanStatus.ACTIVE.getValue(), currentdate, currentdate, currentdate, yesterday,maxLoanIdInList,officeHierarchy,pageSize })); + return Collections.synchronizedList(this.jdbcTemplate.queryForList(sqlBuilder.toString(), Long.class, + new Object[] { yesterday, LoanStatus.ACTIVE.getValue(), currentdate, currentdate, currentdate, yesterday, + maxLoanIdInList, officeHierarchy, pageSize })); } catch (final EmptyResultDataAccessException e) { return null; } @@ -2037,10 +2003,10 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { return LoanSchedulePeriodData.repaymentPeriodWithPayments(loanId, period, fromDate, dueDate, obligationsMetOnDate, complete, principalOriginalDue, principalPaid, principalWrittenOff, principalOutstanding, outstandingPrincipalBalanceOfLoan, - interestDueOnPrincipalOutstanding, interestPaid, interestWaived, interestWrittenOff, interestOutstanding, - feeChargesDue, feeChargesPaid, feeChargesWaived, feeChargesWrittenOff, feeChargesOutstanding, penaltyChargesDue, - penaltyChargesPaid, penaltyChargesWaived, penaltyChargesWrittenOff, penaltyChargesOutstanding, totalDueForPeriod, - totalPaid, totalPaidInAdvanceForPeriod, totalPaidLateForPeriod, totalWaived, totalWrittenOff, totalOutstanding, + interestDueOnPrincipalOutstanding, interestPaid, interestWaived, interestWrittenOff, interestOutstanding, feeChargesDue, + feeChargesPaid, feeChargesWaived, feeChargesWrittenOff, feeChargesOutstanding, penaltyChargesDue, penaltyChargesPaid, + penaltyChargesWaived, penaltyChargesWrittenOff, penaltyChargesOutstanding, totalDueForPeriod, totalPaid, + totalPaidInAdvanceForPeriod, totalPaidLateForPeriod, totalWaived, totalWrittenOff, totalOutstanding, totalActualCostOfLoanForPeriod, totalInstallmentAmount); } } @@ -2049,8 +2015,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { public Date retrieveMinimumDateOfRepaymentTransaction(Long loanId) { // TODO Auto-generated method stub Date date = this.jdbcTemplate.queryForObject( - "select min(transaction_date) from m_loan_transaction where loan_id=? and transaction_type_enum=2", - new Object[] { loanId }, Date.class); + "select min(transaction_date) from m_loan_transaction where loan_id=? and transaction_type_enum=2", new Object[] { loanId }, + Date.class); return date; } @@ -2093,8 +2059,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { final LoanTransactionEnumData transactionType = LoanEnumerations.transactionType(LoanTransactionType.REFUND_FOR_ACTIVE_LOAN); final Collection paymentOptions = this.paymentTypeReadPlatformService.retrieveAllPaymentTypes(); return new LoanTransactionData(null, null, null, transactionType, null, currencyData, earliestUnpaidInstallmentDate, - retrieveTotalPaidInAdvance(loan.getId()).getPaidInAdvance(), null, null, null, null, null, null, paymentOptions, null, - null, null, null, false); + retrieveTotalPaidInAdvance(loan.getId()).getPaidInAdvance(), null, null, null, null, null, null, paymentOptions, null, null, + null, null, false); } @Override @@ -2103,8 +2069,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { if (loanData.isLoanProductLinkedToFloatingRate()) { final Collection intRatePeriodData = new ArrayList<>(); - final Collection intRates = this.floatingRatesReadPlatformService.retrieveInterestRatePeriods(loanData - .loanProductId()); + final Collection intRates = this.floatingRatesReadPlatformService + .retrieveInterestRatePeriods(loanData.loanProductId()); for (final InterestRatePeriodData rate : intRates) { if (rate.getFromDate().compareTo(loanData.getDisbursementDate().toDate()) > 0 && loanData.isFloatingInterestRate()) { updateInterestRatePeriodData(rate, loanData); @@ -2142,17 +2108,13 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public Collection retrieveLoanIdsWithPendingIncomePostingTransactions() { - StringBuilder sqlBuilder = new StringBuilder() - .append(" select distinct loan.id ") - .append(" from m_loan as loan ") - .append(" inner join m_loan_recalculation_details as recdet on (recdet.loan_id = loan.id and recdet.is_compounding_to_be_posted_as_transaction is not null and recdet.is_compounding_to_be_posted_as_transaction = 1) ") + StringBuilder sqlBuilder = new StringBuilder().append(" select distinct loan.id ").append(" from m_loan as loan ").append( + " inner join m_loan_recalculation_details as recdet on (recdet.loan_id = loan.id and recdet.is_compounding_to_be_posted_as_transaction is not null and recdet.is_compounding_to_be_posted_as_transaction = 1) ") .append(" inner join m_loan_repayment_schedule as repsch on repsch.loan_id = loan.id ") .append(" inner join m_loan_interest_recalculation_additional_details as adddet on adddet.loan_repayment_schedule_id = repsch.id ") .append(" left join m_loan_transaction as trans on (trans.is_reversed <> 1 and trans.transaction_type_enum = 19 and trans.loan_id = loan.id and trans.transaction_date = adddet.effective_date) ") - .append(" where loan.loan_status_id = 300 ") - .append(" and loan.is_npa = 0 ") - .append(" and adddet.effective_date is not null ") - .append(" and trans.transaction_date is null ") + .append(" where loan.loan_status_id = 300 ").append(" and loan.is_npa = 0 ") + .append(" and adddet.effective_date is not null ").append(" and trans.transaction_date is null ") .append(" and adddet.effective_date < ? "); try { String currentdate = formatter.print(DateUtils.getLocalDateOfTenant()); @@ -2186,10 +2148,10 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { return new LoanTransactionData(null, null, null, transactionType, null, currencyData, earliestUnpaidInstallmentDate, outStandingAmount.getAmount(), loanRepaymentScheduleInstallment.getPrincipalOutstanding(currency).getAmount(), - loanRepaymentScheduleInstallment.getInterestOutstanding(currency).getAmount(), loanRepaymentScheduleInstallment - .getFeeChargesOutstanding(currency).getAmount(), loanRepaymentScheduleInstallment.getPenaltyChargesOutstanding( - currency).getAmount(), null, unrecognizedIncomePortion, paymentTypeOptions, null, null, null, - outstandingLoanBalance, isReversed); + loanRepaymentScheduleInstallment.getInterestOutstanding(currency).getAmount(), + loanRepaymentScheduleInstallment.getFeeChargesOutstanding(currency).getAmount(), + loanRepaymentScheduleInstallment.getPenaltyChargesOutstanding(currency).getAmount(), null, unrecognizedIncomePortion, + paymentTypeOptions, null, null, null, outstandingLoanBalance, isReversed); } private static final class CurrencyMapper implements RowMapper { @@ -2215,19 +2177,20 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("if(max(tr.transaction_date)>ls.dueDate,max(tr.transaction_date),ls.dueDate) as transactionDate,"); - sqlBuilder - .append("ls.principal_amount - IFNULL(ls.principal_writtenoff_derived,0) - IFNULL(ls.principal_completed_derived,0) as principalDue,"); - sqlBuilder - .append("ls.interest_amount - IFNULL(ls.interest_completed_derived,0) - IFNULL(ls.interest_waived_derived,0) - IFNULL(ls.interest_writtenoff_derived,0) as interestDue,"); - sqlBuilder - .append("ls.fee_charges_amount - IFNULL(ls.fee_charges_completed_derived,0) - IFNULL(ls.fee_charges_writtenoff_derived,0) - IFNULL(ls.fee_charges_waived_derived,0) as feeDue,"); - sqlBuilder - .append("ls.penalty_charges_amount - IFNULL(ls.penalty_charges_completed_derived,0) - IFNULL(ls.penalty_charges_writtenoff_derived,0) - IFNULL(ls.penalty_charges_waived_derived,0) as penaltyDue,"); - sqlBuilder - .append(" l.currency_code as currencyCode, l.currency_digits as currencyDigits, l.currency_multiplesof as inMultiplesOf, rc.`name` as currencyName, "); + sqlBuilder.append( + "ls.principal_amount - IFNULL(ls.principal_writtenoff_derived,0) - IFNULL(ls.principal_completed_derived,0) as principalDue,"); + sqlBuilder.append( + "ls.interest_amount - IFNULL(ls.interest_completed_derived,0) - IFNULL(ls.interest_waived_derived,0) - IFNULL(ls.interest_writtenoff_derived,0) as interestDue,"); + sqlBuilder.append( + "ls.fee_charges_amount - IFNULL(ls.fee_charges_completed_derived,0) - IFNULL(ls.fee_charges_writtenoff_derived,0) - IFNULL(ls.fee_charges_waived_derived,0) as feeDue,"); + sqlBuilder.append( + "ls.penalty_charges_amount - IFNULL(ls.penalty_charges_completed_derived,0) - IFNULL(ls.penalty_charges_writtenoff_derived,0) - IFNULL(ls.penalty_charges_waived_derived,0) as penaltyDue,"); + sqlBuilder.append( + " l.currency_code as currencyCode, l.currency_digits as currencyDigits, l.currency_multiplesof as inMultiplesOf, rc.`name` as currencyName, "); sqlBuilder.append(" rc.display_symbol as currencyDisplaySymbol, rc.internationalized_name_code as currencyNameCode "); sqlBuilder.append(" FROM m_loan l"); - sqlBuilder.append(" LEFT JOIN m_loan_transaction tr ON tr.loan_id = l.id AND tr.transaction_type_enum = ? and tr.is_reversed = 0"); + sqlBuilder.append( + " LEFT JOIN m_loan_transaction tr ON tr.loan_id = l.id AND tr.transaction_type_enum = ? and tr.is_reversed = 0"); sqlBuilder.append(" join m_currency rc on rc.`code` = l.currency_code "); sqlBuilder.append(" JOIN m_loan_repayment_schedule ls ON ls.loan_id = l.id AND ls.completed_derived = 0 "); sqlBuilder.append(" join( "); @@ -2269,8 +2232,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public Long retrieveLoanIdByAccountNumber(String loanAccountNumber) { try { - return this.jdbcTemplate.queryForObject("select l.id from m_loan l where l.account_no = ?", - new Object[] { loanAccountNumber }, Long.class); + return this.jdbcTemplate.queryForObject("select l.id from m_loan l where l.account_no = ?", new Object[] { loanAccountNumber }, + Long.class); } catch (final EmptyResultDataAccessException e) { return null; @@ -2287,11 +2250,9 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { } } - @Override public Integer retrieveNumberOfActiveLoans() { - final String sql="select count(*) from m_loan"; - return this.jdbcTemplate.queryForObject(sql,Integer.class); + final String sql = "select count(*) from m_loan"; + return this.jdbcTemplate.queryForObject(sql, Integer.class); } } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanSchedularService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanSchedularService.java index b6bfa2943..a85615bd4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanSchedularService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanSchedularService.java @@ -21,7 +21,6 @@ package org.apache.fineract.portfolio.loanaccount.service; import java.util.Map; import org.apache.fineract.infrastructure.jobs.exception.JobExecutionException; - public interface LoanSchedularService { void applyChargeForOverdueLoans() throws JobExecutionException; @@ -29,4 +28,4 @@ public interface LoanSchedularService { void recalculateInterest() throws JobExecutionException; void recalculateInterest(@SuppressWarnings("unused") final Map jobParameters); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanSchedularServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanSchedularServiceImpl.java index 20c660cf3..0004336d7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanSchedularServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanSchedularServiceImpl.java @@ -65,13 +65,12 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { @Autowired public LoanSchedularServiceImpl(final ConfigurationDomainService configurationDomainService, final LoanReadPlatformService loanReadPlatformService, final LoanWritePlatformService loanWritePlatformService, - final OfficeReadPlatformService officeReadPlatformService, - final ApplicationContext applicationContext) { + final OfficeReadPlatformService officeReadPlatformService, final ApplicationContext applicationContext) { this.configurationDomainService = configurationDomainService; this.loanReadPlatformService = loanReadPlatformService; this.loanWritePlatformService = loanWritePlatformService; this.officeReadPlatformService = officeReadPlatformService; - this.applicationContext=applicationContext; + this.applicationContext = applicationContext; } @Override @@ -81,7 +80,7 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { final Long penaltyWaitPeriodValue = this.configurationDomainService.retrievePenaltyWaitPeriod(); final Boolean backdatePenalties = this.configurationDomainService.isBackdatePenaltiesEnabled(); final Collection overdueLoanScheduledInstallments = this.loanReadPlatformService - .retrieveAllLoansWithOverdueInstallments(penaltyWaitPeriodValue,backdatePenalties); + .retrieveAllLoansWithOverdueInstallments(penaltyWaitPeriodValue, backdatePenalties); if (!overdueLoanScheduledInstallments.isEmpty()) { final Map> overdueScheduleData = new HashMap<>(); @@ -103,11 +102,13 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { } catch (final PlatformApiDataValidationException e) { final List errors = e.getErrors(); for (final ApiParameterError error : errors) { - LOG.error("Apply Charges due for overdue loans failed for account {} with message: {}", loanId, error.getDeveloperMessage(), e); + LOG.error("Apply Charges due for overdue loans failed for account {} with message: {}", loanId, + error.getDeveloperMessage(), e); } exceptions.add(e); } catch (final AbstractPlatformDomainRuleException e) { - LOG.error("Apply Charges due for overdue loans failed for account {} with message: {}", loanId, e.getDefaultUserMessage(), e); + LOG.error("Apply Charges due for overdue loans failed for account {} with message: {}", loanId, + e.getDefaultUserMessage(), e); exceptions.add(e); } catch (Exception e) { LOG.error("Apply Charges due for overdue loans failed for account {}", loanId, e); @@ -121,12 +122,9 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { @Override @CronTarget(jobName = JobName.RECALCULATE_INTEREST_FOR_LOAN) public void recalculateInterest() throws JobExecutionException { - Integer maxNumberOfRetries = ThreadLocalContextUtil.getTenant() - .getConnection().getMaxRetriesOnDeadlock(); - Integer maxIntervalBetweenRetries = ThreadLocalContextUtil.getTenant() - .getConnection().getMaxIntervalBetweenRetries(); - Collection loanIds = this.loanReadPlatformService - .fetchLoansForInterestRecalculation(); + Integer maxNumberOfRetries = ThreadLocalContextUtil.getTenant().getConnection().getMaxRetriesOnDeadlock(); + Integer maxIntervalBetweenRetries = ThreadLocalContextUtil.getTenant().getConnection().getMaxIntervalBetweenRetries(); + Collection loanIds = this.loanReadPlatformService.fetchLoansForInterestRecalculation(); int i = 0; if (!loanIds.isEmpty()) { List errors = new ArrayList<>(); @@ -137,23 +135,25 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { try { this.loanWritePlatformService.recalculateInterest(loanId); numberOfRetries = maxNumberOfRetries + 1; - } catch (CannotAcquireLockException - | ObjectOptimisticLockingFailureException exception) { + } catch (CannotAcquireLockException | ObjectOptimisticLockingFailureException exception) { LOG.info("Recalulate interest job has been retried {} time(s)", numberOfRetries); - // Fail if the transaction has been retried for maxNumberOfRetries + // Fail if the transaction has been retried for + // maxNumberOfRetries if (numberOfRetries >= maxNumberOfRetries) { - LOG.error("Recalulate interest job has been retried for the max allowed attempts of {} and will be rolled back", numberOfRetries); + LOG.error("Recalulate interest job has been retried for the max allowed attempts of {} and will be rolled back", + numberOfRetries); errors.add(exception); break; } - // Else sleep for a random time (between 1 to 10 seconds) and continue + // Else sleep for a random time (between 1 to 10 + // seconds) and continue try { Random random = new Random(); int randomNum = random.nextInt(maxIntervalBetweenRetries + 1); Thread.sleep(1000 + (randomNum * 1000)); numberOfRetries = numberOfRetries + 1; } catch (InterruptedException e) { - LOG.error("Interest recalculation for loans retry failed due to InterruptedException", e) ; + LOG.error("Interest recalculation for loans retry failed due to InterruptedException", e); errors.add(e); break; } @@ -181,13 +181,11 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { // gets the Office object final OfficeData office = this.officeReadPlatformService.retrieveOffice(officeIdLong); - if(office == null) { - throw new OfficeNotFoundException(officeIdLong); - } - final int threadPoolSize=Integer.parseInt(jobParameters.get("thread-pool-size")); - final int batchSize=Integer.parseInt(jobParameters.get("batch-size")); + if (office == null) { throw new OfficeNotFoundException(officeIdLong); } + final int threadPoolSize = Integer.parseInt(jobParameters.get("thread-pool-size")); + final int batchSize = Integer.parseInt(jobParameters.get("batch-size")); - recalculateInterest(office,threadPoolSize,batchSize); + recalculateInterest(office, threadPoolSize, batchSize); } private void recalculateInterest(OfficeData office, int threadPoolSize, int batchSize) { @@ -200,25 +198,25 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { final String officeHierarchy = office.getHierarchy() + "%"; // get the loanIds from service - List loanIds = Collections.synchronizedList(this.loanReadPlatformService - .fetchLoansForInterestRecalculation(pageSize, maxLoanIdInList, officeHierarchy)); + List loanIds = Collections.synchronizedList( + this.loanReadPlatformService.fetchLoansForInterestRecalculation(pageSize, maxLoanIdInList, officeHierarchy)); - // gets the loanIds data set iteratively and call addAccuruals for that paginated dataset + // gets the loanIds data set iteratively and call addAccuruals for that + // paginated dataset do { int totalFilteredRecords = loanIds.size(); LOG.info("Starting accrual - total filtered records - {}", totalFilteredRecords); recalculateInterest(loanIds, threadPoolSize, batchSize, executorService); - maxLoanIdInList+= pageSize+1; - loanIds = Collections.synchronizedList(this.loanReadPlatformService - .fetchLoansForInterestRecalculation(pageSize, maxLoanIdInList, officeHierarchy)); + maxLoanIdInList += pageSize + 1; + loanIds = Collections.synchronizedList( + this.loanReadPlatformService.fetchLoansForInterestRecalculation(pageSize, maxLoanIdInList, officeHierarchy)); } while (!CollectionUtils.isEmpty(loanIds)); // shutdown the executor when done executorService.shutdownNow(); } - private void recalculateInterest(List loanIds, - int threadPoolSize, int batchSize, final ExecutorService executorService) { + private void recalculateInterest(List loanIds, int threadPoolSize, int batchSize, final ExecutorService executorService) { List> posters = new ArrayList<>(); int fromIndex = 0; @@ -228,32 +226,30 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { double toGetCeilValue = size / threadPoolSize; batchSize = (int) Math.ceil(toGetCeilValue); - if(batchSize == 0) { - return; - } + if (batchSize == 0) { return; } - int toIndex = (batchSize > size - 1)? size : batchSize ; - while(toIndex < size && loanIds.get(toIndex - 1).equals(loanIds.get(toIndex))) { - toIndex ++; + int toIndex = (batchSize > size - 1) ? size : batchSize; + while (toIndex < size && loanIds.get(toIndex - 1).equals(loanIds.get(toIndex))) { + toIndex++; } boolean lastBatch = false; - int loopCount = size/batchSize+1; + int loopCount = size / batchSize + 1; - for (long i=0; i < loopCount; i++) { + for (long i = 0; i < loopCount; i++) { List subList = safeSubList(loanIds, fromIndex, toIndex); RecalculateInterestPoster poster = (RecalculateInterestPoster) this.applicationContext.getBean("recalculateInterestPoster"); poster.setLoanIds(subList); poster.setLoanWritePlatformService(loanWritePlatformService); posters.add(poster); - if(lastBatch) { + if (lastBatch) { break; } - if(toIndex + batchSize > size - 1) { + if (toIndex + batchSize > size - 1) { lastBatch = true; } fromIndex = fromIndex + (toIndex - fromIndex); - toIndex = (toIndex + batchSize > size - 1)? size : toIndex + batchSize; - while(toIndex < size && loanIds.get(toIndex - 1).equals(loanIds.get(toIndex))) { + toIndex = (toIndex + batchSize > size - 1) ? size : toIndex + batchSize; + while (toIndex < size && loanIds.get(toIndex - 1).equals(loanIds.get(toIndex))) { toIndex++; } } @@ -269,9 +265,7 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { // break the lists into sub lists private List safeSubList(List list, int fromIndex, int toIndex) { int size = list.size(); - if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) { - return Collections.emptyList(); - } + if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) { return Collections.emptyList(); } fromIndex = Math.max(0, fromIndex); toIndex = Math.min(size, toIndex); @@ -282,7 +276,7 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { // checks the execution of task by each thread in the executor service private void checkCompletion(List> responses) { try { - for(Future f : responses) { + for (Future f : responses) { f.get(); } boolean allThreadsExecuted = false; @@ -293,13 +287,13 @@ public class LoanSchedularServiceImpl implements LoanSchedularService { } } allThreadsExecuted = noOfThreadsExecuted == responses.size(); - if(!allThreadsExecuted) { + if (!allThreadsExecuted) { LOG.error("All threads could not execute."); } } catch (InterruptedException e1) { LOG.error("Interrupted while posting IR entries", e1); - } catch (ExecutionException e2) { + } catch (ExecutionException e2) { LOG.error("Execution exception while posting IR entries", e2); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanUtilService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanUtilService.java index ed3fbe513..d5c9b73f1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanUtilService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanUtilService.java @@ -121,27 +121,32 @@ public class LoanUtilService { if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) { restCalendarInstance = calendarInstanceRepository.findCalendarInstaneByEntityId(loan.loanInterestRecalculationDetailId(), CalendarEntityType.LOAN_RECALCULATION_REST_DETAIL.getValue()); - compoundingCalendarInstance = calendarInstanceRepository.findCalendarInstaneByEntityId( - loan.loanInterestRecalculationDetailId(), CalendarEntityType.LOAN_RECALCULATION_COMPOUNDING_DETAIL.getValue()); + compoundingCalendarInstance = calendarInstanceRepository.findCalendarInstaneByEntityId(loan.loanInterestRecalculationDetailId(), + CalendarEntityType.LOAN_RECALCULATION_COMPOUNDING_DETAIL.getValue()); overdurPenaltyWaitPeriod = this.configurationDomainService.retrievePenaltyWaitPeriod(); } - final Boolean isInterestChargedFromDateAsDisbursementDateEnabled = this.configurationDomainService.isInterestChargedFromDateSameAsDisbursementDate(); + final Boolean isInterestChargedFromDateAsDisbursementDateEnabled = this.configurationDomainService + .isInterestChargedFromDateSameAsDisbursementDate(); FloatingRateDTO floatingRateDTO = constructFloatingRateDTO(loan); Boolean isSkipRepaymentOnFirstMonth = false; Integer numberOfDays = 0; boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); - if(isSkipRepaymentOnFirstMonthEnabled){ + if (isSkipRepaymentOnFirstMonthEnabled) { isSkipRepaymentOnFirstMonth = isLoanRepaymentsSyncWithMeeting(loan.group(), calendar); - if(isSkipRepaymentOnFirstMonth) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } + if (isSkipRepaymentOnFirstMonth) { + numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); + } } - final Boolean isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled = this.configurationDomainService.isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled(); + final Boolean isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled = this.configurationDomainService + .isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled(); ScheduleGeneratorDTO scheduleGeneratorDTO = new ScheduleGeneratorDTO(loanScheduleFactory, applicationCurrency, calculatedRepaymentsStartingFromDate, holidayDetails, restCalendarInstance, compoundingCalendarInstance, recalculateFrom, - overdurPenaltyWaitPeriod, floatingRateDTO, calendar, calendarHistoryDataWrapper, isInterestChargedFromDateAsDisbursementDateEnabled, - numberOfDays, isSkipRepaymentOnFirstMonth, isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled); + overdurPenaltyWaitPeriod, floatingRateDTO, calendar, calendarHistoryDataWrapper, + isInterestChargedFromDateAsDisbursementDateEnabled, numberOfDays, isSkipRepaymentOnFirstMonth, + isChangeEmiIfRepaymentDateSameAsDisbursementDateEnabled); - return scheduleGeneratorDTO; + return scheduleGeneratorDTO; } public Boolean isLoanRepaymentsSyncWithMeeting(final Group group, final Calendar calendar) { @@ -159,15 +164,12 @@ public class LoanUtilService { } } - if (entityId == null || calendar == null) { - return isSkipRepaymentOnFirstMonth; - } - isSkipRepaymentOnFirstMonth = this.calendarReadPlatformService - .isCalendarAssociatedWithEntity(entityId, calendar.getId(), entityTypeId); + if (entityId == null || calendar == null) { return isSkipRepaymentOnFirstMonth; } + isSkipRepaymentOnFirstMonth = this.calendarReadPlatformService.isCalendarAssociatedWithEntity(entityId, calendar.getId(), + entityTypeId); return isSkipRepaymentOnFirstMonth; } - public LocalDate getCalculatedRepaymentsStartingFromDate(final Loan loan) { final CalendarInstance calendarInstance = this.calendarInstanceRepository.findCalendarInstaneByEntityId(loan.getId(), CalendarEntityType.LOANS.getValue()); @@ -177,8 +179,8 @@ public class LoanUtilService { private HolidayDetailDTO constructHolidayDTO(final Loan loan) { final boolean isHolidayEnabled = this.configurationDomainService.isRescheduleRepaymentsOnHolidaysEnabled(); - final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(loan.getOfficeId(), loan - .getDisbursementDate().toDate(), HolidayStatusType.ACTIVE.getValue()); + final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(loan.getOfficeId(), + loan.getDisbursementDate().toDate(), HolidayStatusType.ACTIVE.getValue()); final WorkingDays workingDays = this.workingDaysRepository.findOne(); final boolean allowTransactionsOnHoliday = this.configurationDomainService.allowTransactionsOnHolidayEnabled(); final boolean allowTransactionsOnNonWorkingDay = this.configurationDomainService.allowTransactionsOnNonWorkingDayEnabled(); @@ -225,10 +227,11 @@ public class LoanUtilService { LocalDate calculatedRepaymentsStartingFromDate = loan.getExpectedFirstRepaymentOnDate(); if (calendar != null) {// sync repayments - if (calculatedRepaymentsStartingFromDate == null && !calendar.getCalendarHistory().isEmpty() && - calendarHistoryDataWrapper != null) { + if (calculatedRepaymentsStartingFromDate == null && !calendar.getCalendarHistory().isEmpty() + && calendarHistoryDataWrapper != null) { // generate the first repayment date based on calendar history - calculatedRepaymentsStartingFromDate = generateCalculatedRepaymentStartDate(calendarHistoryDataWrapper, actualDisbursementDate, loan); + calculatedRepaymentsStartingFromDate = generateCalculatedRepaymentStartDate(calendarHistoryDataWrapper, + actualDisbursementDate, loan); return calculatedRepaymentsStartingFromDate; } @@ -243,12 +246,13 @@ public class LoanUtilService { if (repaymentScheduleDetails != null) {// Not expecting to be // null final Integer repayEvery = repaymentScheduleDetails.getRepayEvery(); - final String frequency = CalendarUtils.getMeetingFrequencyFromPeriodFrequencyType(repaymentScheduleDetails - .getRepaymentPeriodFrequencyType()); + final String frequency = CalendarUtils + .getMeetingFrequencyFromPeriodFrequencyType(repaymentScheduleDetails.getRepaymentPeriodFrequencyType()); Boolean isSkipRepaymentOnFirstMonth = false; Integer numberOfDays = 0; - boolean isSkipRepaymentOnFirstMonthEnabled = this.configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); - if(isSkipRepaymentOnFirstMonthEnabled){ + boolean isSkipRepaymentOnFirstMonthEnabled = this.configurationDomainService + .isSkippingMeetingOnFirstDayOfMonthEnabled(); + if (isSkipRepaymentOnFirstMonthEnabled) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); isSkipRepaymentOnFirstMonth = isLoanRepaymentsSyncWithMeeting(loan.group(), calendar); } @@ -266,24 +270,25 @@ public class LoanUtilService { final WorkingDays workingDays = this.workingDaysRepository.findOne(); LocalDate calculatedRepaymentsStartingFromDate = null; - List historyList = calendarHistoryDataWrapper.getCalendarHistoryList() ; + List historyList = calendarHistoryDataWrapper.getCalendarHistoryList(); - if( historyList!=null && historyList.size() > 0) { - if(repaymentScheduleDetails != null){ + if (historyList != null && historyList.size() > 0) { + if (repaymentScheduleDetails != null) { final Integer repayEvery = repaymentScheduleDetails.getRepayEvery(); - final String frequency = CalendarUtils.getMeetingFrequencyFromPeriodFrequencyType(repaymentScheduleDetails - .getRepaymentPeriodFrequencyType()); + final String frequency = CalendarUtils + .getMeetingFrequencyFromPeriodFrequencyType(repaymentScheduleDetails.getRepaymentPeriodFrequencyType()); Boolean isSkipRepaymentOnFirstMonth = false; Integer numberOfDays = 0; boolean isSkipRepaymentOnFirstMonthEnabled = this.configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); - if(isSkipRepaymentOnFirstMonthEnabled){ + if (isSkipRepaymentOnFirstMonthEnabled) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); isSkipRepaymentOnFirstMonth = isLoanRepaymentsSyncWithMeeting(loan.group(), historyList.get(0).getCalendar()); } - calculatedRepaymentsStartingFromDate = CalendarUtils.getNextRepaymentMeetingDate(historyList.get(0).getRecurrence(), historyList.get(0).getStartDateLocalDate(), - actualDisbursementDate, repayEvery, frequency, workingDays, isSkipRepaymentOnFirstMonth, numberOfDays); + calculatedRepaymentsStartingFromDate = CalendarUtils.getNextRepaymentMeetingDate(historyList.get(0).getRecurrence(), + historyList.get(0).getStartDateLocalDate(), actualDisbursementDate, repayEvery, frequency, workingDays, + isSkipRepaymentOnFirstMonth, numberOfDays); } - } + } return calculatedRepaymentsStartingFromDate; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformService.java old mode 100755 new mode 100644 index b2001a0b2..0391e4295 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformService.java @@ -114,4 +114,4 @@ public interface LoanWritePlatformService { CommandProcessingResult makeGLIMLoanRepayment(Long loanId, JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index 584882a3f..c64b8c23a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java @@ -193,8 +193,6 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - - @Service public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatformService { @@ -203,7 +201,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf private final PlatformSecurityContext context; private final LoanEventApiJsonValidator loanEventApiJsonValidator; private final LoanUpdateCommandFromApiJsonDeserializer loanUpdateCommandFromApiJsonDeserializer; - private final LoanRepositoryWrapper loanRepositoryWrapper ; + private final LoanRepositoryWrapper loanRepositoryWrapper; private final LoanAccountDomainService loanAccountDomainService; private final NoteRepository noteRepository; private final LoanTransactionRepository loanTransactionRepository; @@ -245,10 +243,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf public LoanWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final LoanEventApiJsonValidator loanEventApiJsonValidator, final LoanUpdateCommandFromApiJsonDeserializer loanUpdateCommandFromApiJsonDeserializer, final LoanAssembler loanAssembler, - final LoanAccountDomainService loanAccountDomainService, - final LoanTransactionRepository loanTransactionRepository, final NoteRepository noteRepository, - final ChargeRepositoryWrapper chargeRepository, final LoanChargeRepository loanChargeRepository, - final ApplicationCurrencyRepositoryWrapper applicationCurrencyRepository, + final LoanAccountDomainService loanAccountDomainService, final LoanTransactionRepository loanTransactionRepository, + final NoteRepository noteRepository, final ChargeRepositoryWrapper chargeRepository, + final LoanChargeRepository loanChargeRepository, final ApplicationCurrencyRepositoryWrapper applicationCurrencyRepository, final JournalEntryWritePlatformService journalEntryWritePlatformService, final CalendarInstanceRepository calendarInstanceRepository, final PaymentDetailWritePlatformService paymentDetailWritePlatformService, final HolidayRepositoryWrapper holidayRepository, @@ -268,16 +265,13 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final LoanUtilService loanUtilService, final LoanSummaryWrapper loanSummaryWrapper, final EntityDatatableChecksWritePlatformService entityDatatableChecksWritePlatformService, final LoanRepaymentScheduleTransactionProcessorFactory transactionProcessingStrategy, - final CodeValueRepositoryWrapper codeValueRepository, - final LoanRepositoryWrapper loanRepositoryWrapper, - final CashierTransactionDataValidator cashierTransactionDataValidator, - final GLIMAccountInfoRepository glimRepository, - final LoanRepository loanRepository - ) { + final CodeValueRepositoryWrapper codeValueRepository, final LoanRepositoryWrapper loanRepositoryWrapper, + final CashierTransactionDataValidator cashierTransactionDataValidator, final GLIMAccountInfoRepository glimRepository, + final LoanRepository loanRepository) { this.context = context; this.loanEventApiJsonValidator = loanEventApiJsonValidator; this.loanAssembler = loanAssembler; - this.loanRepositoryWrapper = loanRepositoryWrapper ; + this.loanRepositoryWrapper = loanRepositoryWrapper; this.loanAccountDomainService = loanAccountDomainService; this.loanTransactionRepository = loanTransactionRepository; this.noteRepository = noteRepository; @@ -312,8 +306,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf this.entityDatatableChecksWritePlatformService = entityDatatableChecksWritePlatformService; this.codeValueRepository = codeValueRepository; this.cashierTransactionDataValidator = cashierTransactionDataValidator; - this.loanRepository=loanRepository; - this.glimRepository=glimRepository; + this.loanRepository = loanRepository; + this.glimRepository = glimRepository; } private LoanLifecycleStateMachine defaultLoanLifecycleStateMachine() { @@ -323,22 +317,19 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf @Transactional @Override - public CommandProcessingResult disburseGLIMLoan(final Long loanId, final JsonCommand command) - { - final Long parentLoanId=loanId; - GroupLoanIndividualMonitoringAccount parentLoan=glimRepository.findById(parentLoanId).get(); - List childLoans=this.loanRepository.findByGlimId(loanId); - CommandProcessingResult result=null; - int count=0; - for(Loan loan:childLoans) - { - result=disburseLoan(loan.getId(),command,false); - if(result.getLoanId()!=null) - { + public CommandProcessingResult disburseGLIMLoan(final Long loanId, final JsonCommand command) { + final Long parentLoanId = loanId; + GroupLoanIndividualMonitoringAccount parentLoan = glimRepository.findById(parentLoanId).get(); + List childLoans = this.loanRepository.findByGlimId(loanId); + CommandProcessingResult result = null; + int count = 0; + for (Loan loan : childLoans) { + result = disburseLoan(loan.getId(), command, false); + if (result.getLoanId() != null) { count++; - // if all the child loans are approved, mark the parent loan as approved - if(count==parentLoan.getChildAccountsCount()) - { + // if all the child loans are approved, mark the parent loan as + // approved + if (count == parentLoan.getChildAccountsCount()) { parentLoan.setLoanStatus(LoanStatus.ACTIVE.getValue()); glimRepository.save(parentLoan); } @@ -361,7 +352,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf // validate ActualDisbursement Date Against Expected Disbursement Date LoanProduct loanProduct = loan.loanProduct(); - if(loanProduct.syncExpectedWithDisbursementDate()){ + if (loanProduct.syncExpectedWithDisbursementDate()) { syncExpectedDateWithActualDisbursementDate(loan, actualDisbursementDate); } checkClientOrGroupActive(loan); @@ -372,9 +363,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf entityDatatableChecksWritePlatformService.runTheCheckForProduct(loanId, EntityTables.LOAN.getName(), StatusEnum.DISBURSE.getCode().longValue(), EntityTables.LOAN.getForeignKeyColumnNameOnDatatable(), loan.productId()); - LocalDate recalculateFrom = null; - if(!loan.isMultiDisburmentLoan()){ + if (!loan.isMultiDisburmentLoan()) { loan.setActualDisbursementDate(actualDisbursementDate.toDate()); } ScheduleGeneratorDTO scheduleGeneratorDTO = this.loanUtilService.buildScheduleGeneratorDTO(loan, recalculateFrom); @@ -396,12 +386,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final Map changes = new LinkedHashMap<>(); final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService.createAndPersistPaymentDetail(command, changes); - if (paymentDetail != null && paymentDetail.getPaymentType() != null - && paymentDetail.getPaymentType().isCashPayment()) { - BigDecimal transactionAmount = command - .bigDecimalValueOfParameterNamed("transactionAmount"); - this.cashierTransactionDataValidator.validateOnLoanDisbursal( - currentUser, loan.getCurrencyCode(), transactionAmount); + if (paymentDetail != null && paymentDetail.getPaymentType() != null && paymentDetail.getPaymentType().isCashPayment()) { + BigDecimal transactionAmount = command.bigDecimalValueOfParameterNamed("transactionAmount"); + this.cashierTransactionDataValidator.validateOnLoanDisbursal(currentUser, loan.getCurrencyCode(), transactionAmount); } final Boolean isPaymnetypeApplicableforDisbursementCharge = configurationDomainService .isPaymnetypeApplicableforDisbursementCharge(); @@ -418,25 +405,25 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf boolean recalculateSchedule = amountBeforeAdjust.isNotEqualTo(loan.getPrincpal()); final String txnExternalId = command.stringValueOfParameterNamedAllowingNull("externalId"); - if(loan.isTopup() && loan.getClientId() != null){ + if (loan.isTopup() && loan.getClientId() != null) { final Long loanIdToClose = loan.getTopupLoanDetails().getLoanIdToClose(); final Loan loanToClose = this.loanRepositoryWrapper.findNonClosedLoanThatBelongsToClient(loanIdToClose, loan.getClientId()); - if(loanToClose == null){ + if (loanToClose == null) { throw new GeneralPlatformDomainRuleException("error.msg.loan.to.be.closed.with.topup.is.not.active", "Loan to be closed with this topup is not active."); } final LocalDate lastUserTransactionOnLoanToClose = loanToClose.getLastUserTransactionDate(); - if(loan.getDisbursementDate().isBefore(lastUserTransactionOnLoanToClose)){ + if (loan.getDisbursementDate().isBefore(lastUserTransactionOnLoanToClose)) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.disbursal.date.should.be.after.last.transaction.date.of.loan.to.be.closed", - "Disbursal date of this loan application "+loan.getDisbursementDate() - +" should be after last transaction date of loan to be closed "+ lastUserTransactionOnLoanToClose); + "Disbursal date of this loan application " + loan.getDisbursementDate() + + " should be after last transaction date of loan to be closed " + lastUserTransactionOnLoanToClose); } - BigDecimal loanOutstanding = this.loanReadPlatformService.retrieveLoanPrePaymentTemplate(loanIdToClose, - actualDisbursementDate).getAmount(); + BigDecimal loanOutstanding = this.loanReadPlatformService + .retrieveLoanPrePaymentTemplate(loanIdToClose, actualDisbursementDate).getAmount(); final BigDecimal firstDisbursalAmount = loan.getFirstDisbursalAmount(); - if(loanOutstanding.compareTo(firstDisbursalAmount) > 0){ + if (loanOutstanding.compareTo(firstDisbursalAmount) > 0) { throw new GeneralPlatformDomainRuleException("error.msg.loan.amount.less.than.outstanding.of.loan.to.be.closed", "Topup loan amount should be greater than outstanding amount of loan to be closed."); } @@ -459,7 +446,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf loan.addLoanTransaction(disbursementTransaction); } - regenerateScheduleOnDisbursement(command, loan, recalculateSchedule, scheduleGeneratorDTO, nextPossibleRepaymentDate, rescheduledRepaymentDate); + regenerateScheduleOnDisbursement(command, loan, recalculateSchedule, scheduleGeneratorDTO, nextPossibleRepaymentDate, + rescheduledRepaymentDate); if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) { createAndSaveLoanScheduleArchive(loan, scheduleGeneratorDTO); } @@ -535,8 +523,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf LoanRescheduleRequest loanRescheduleRequest = null; LoanScheduleModel loanScheduleModel = loan.regenerateScheduleModel(scheduleGeneratorDTO); List installments = retrieveRepaymentScheduleFromModel(loanScheduleModel); - this.loanScheduleHistoryWritePlatformService.createAndSaveLoanScheduleArchive(installments, - loan, loanRescheduleRequest); + this.loanScheduleHistoryWritePlatformService.createAndSaveLoanScheduleArchive(installments, loan, loanRescheduleRequest); } /** @@ -613,8 +600,10 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf if (realCause.getMessage().toLowerCase().contains("external_id_unique")) { baseDataValidator.reset().parameter("externalId").failWithCode("value.must.be.unique"); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } @@ -634,8 +623,10 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf if (realCause.getMessage().toLowerCase().contains("external_id_unique")) { baseDataValidator.reset().parameter("externalId").failWithCode("value.must.be.unique"); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } } @@ -662,9 +653,10 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final Loan loan = this.loanAssembler.assembleFrom(singleLoanDisbursalCommand.getLoanId()); final LocalDate actualDisbursementDate = command.localDateValueOfParameterNamed("actualDisbursementDate"); - // validate ActualDisbursement Date Against Expected Disbursement Date + // validate ActualDisbursement Date Against Expected Disbursement + // Date LoanProduct loanProduct = loan.loanProduct(); - if(loanProduct.syncExpectedWithDisbursementDate()){ + if (loanProduct.syncExpectedWithDisbursementDate()) { syncExpectedDateWithActualDisbursementDate(loan, actualDisbursementDate); } checkClientOrGroupActive(loan); @@ -727,7 +719,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf this.noteRepository.save(note); } if (changedTransactionDetail != null) { - for (final Map.Entry mapEntry : changedTransactionDetail.getNewTransactionMappings().entrySet()) { + for (final Map.Entry mapEntry : changedTransactionDetail.getNewTransactionMappings() + .entrySet()) { this.loanTransactionRepository.save(mapEntry.getValue()); this.accountTransfersWritePlatformService.updateLoanTransaction(mapEntry.getKey(), mapEntry.getValue()); } @@ -766,26 +759,23 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf return changes; } - @Transactional @Override - public CommandProcessingResult undoGLIMLoanDisbursal(final Long loanId, final JsonCommand command) - { - //GroupLoanIndividualMonitoringAccount glimAccount=glimRepository.findOne(loanId); - final Long parentLoanId=loanId; - GroupLoanIndividualMonitoringAccount parentLoan=glimRepository.findById(parentLoanId).get(); - List childLoans=this.loanRepository.findByGlimId(loanId); - CommandProcessingResult result=null; - int count=0; - for(Loan loan:childLoans) - { - result=undoLoanDisbursal(loan.getId(),command); - if(result.getLoanId()!=null) - { + public CommandProcessingResult undoGLIMLoanDisbursal(final Long loanId, final JsonCommand command) { + // GroupLoanIndividualMonitoringAccount + // glimAccount=glimRepository.findOne(loanId); + final Long parentLoanId = loanId; + GroupLoanIndividualMonitoringAccount parentLoan = glimRepository.findById(parentLoanId).get(); + List childLoans = this.loanRepository.findByGlimId(loanId); + CommandProcessingResult result = null; + int count = 0; + for (Loan loan : childLoans) { + result = undoLoanDisbursal(loan.getId(), command); + if (result.getLoanId() != null) { count++; - // if all the child loans are approved, mark the parent loan as approved - if(count==parentLoan.getChildAccountsCount()) - { + // if all the child loans are approved, mark the parent loan as + // approved + if (count == parentLoan.getChildAccountsCount()) { parentLoan.setLoanStatus(LoanStatus.APPROVED.getValue()); glimRepository.save(parentLoan); } @@ -814,8 +804,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf loan.setActualDisbursementDate(null); ScheduleGeneratorDTO scheduleGeneratorDTO = this.loanUtilService.buildScheduleGeneratorDTO(loan, recalculateFrom); - final Map changes = loan.undoDisbursal(scheduleGeneratorDTO, existingTransactionIds, - existingReversedTransactionIds, currentUser); + final Map changes = loan.undoDisbursal(scheduleGeneratorDTO, existingTransactionIds, existingReversedTransactionIds, + currentUser); if (!changes.isEmpty()) { saveAndFlushLoanWithDataIntegrityViolationChecks(loan); @@ -847,32 +837,29 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf .build(); } - @Transactional @Override - public CommandProcessingResult makeGLIMLoanRepayment(final Long loanId, final JsonCommand command) - { + public CommandProcessingResult makeGLIMLoanRepayment(final Long loanId, final JsonCommand command) { - final Long parentLoanId=loanId; + final Long parentLoanId = loanId; glimRepository.findById(parentLoanId).get(); - JsonArray repayments= command.arrayOfParameterNamed("formDataArray"); - JsonCommand childCommand=null; - CommandProcessingResult result=null; - JsonObject jsonObject=null; + JsonArray repayments = command.arrayOfParameterNamed("formDataArray"); + JsonCommand childCommand = null; + CommandProcessingResult result = null; + JsonObject jsonObject = null; - Long[] childLoanId=new Long[repayments.size()]; + Long[] childLoanId = new Long[repayments.size()]; for (int i = 0; i < repayments.size(); i++) { - jsonObject=repayments.get(i).getAsJsonObject(); - LOG.info("{}",jsonObject.toString()); - childLoanId[i]=jsonObject.get("loanId").getAsLong(); + jsonObject = repayments.get(i).getAsJsonObject(); + LOG.info("{}", jsonObject.toString()); + childLoanId[i] = jsonObject.get("loanId").getAsLong(); } - int j=0; - for(JsonElement element:repayments ) - { - childCommand=JsonCommand.fromExistingCommand(command,element); - result=makeLoanRepayment(childLoanId[j++],childCommand,false); + int j = 0; + for (JsonElement element : repayments) { + childCommand = JsonCommand.fromExistingCommand(command, element); + result = makeLoanRepayment(childLoanId[j++], childCommand, false); } return result; } @@ -904,8 +891,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final HolidayDetailDTO holidayDetailDto = null; boolean isAccountTransfer = false; final CommandProcessingResultBuilder commandProcessingResultBuilder = new CommandProcessingResultBuilder(); - this.loanAccountDomainService.makeRepayment(loan, commandProcessingResultBuilder, transactionDate, transactionAmount, - paymentDetail, noteText, txnExternalId, isRecoveryRepayment, isAccountTransfer, holidayDetailDto, isHolidayValidationDone); + this.loanAccountDomainService.makeRepayment(loan, commandProcessingResultBuilder, transactionDate, transactionAmount, paymentDetail, + noteText, txnExternalId, isRecoveryRepayment, isAccountTransfer, holidayDetailDto, isHolidayValidationDone); return commandProcessingResultBuilder.withCommandId(command.commandId()) // .withLoanId(loanId) // @@ -975,21 +962,24 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf this.loanEventApiJsonValidator.validateTransaction(command.json()); final Loan loan = this.loanAssembler.assembleFrom(loanId); - if(loan.status().isClosed() && loan.getLoanSubStatus() !=null && loan.getLoanSubStatus().equals(LoanSubStatus.FORECLOSED.getValue())) { + if (loan.status().isClosed() && loan.getLoanSubStatus() != null + && loan.getLoanSubStatus().equals(LoanSubStatus.FORECLOSED.getValue())) { final String defaultUserMessage = "The loan cannot reopend as it is foreclosed."; - throw new LoanForeclosureException("loan.cannot.be.reopened.as.it.is.foreclosured", defaultUserMessage, - loanId); + throw new LoanForeclosureException("loan.cannot.be.reopened.as.it.is.foreclosured", defaultUserMessage, loanId); } checkClientOrGroupActive(loan); final LoanTransaction transactionToAdjust = this.loanTransactionRepository.findById(transactionId) .orElseThrow(() -> new LoanTransactionNotFoundException(transactionId)); this.businessEventNotifierService.notifyBusinessEventToBeExecuted(BusinessEvents.LOAN_ADJUST_TRANSACTION, constructEntityMap(BusinessEntity.LOAN_ADJUSTED_TRANSACTION, transactionToAdjust)); - if (this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.LOAN)) { throw new PlatformServiceUnavailableException( - "error.msg.loan.transfer.transaction.update.not.allowed", "Loan transaction:" + transactionId - + " update not allowed as it involves in account transfer", transactionId); } - if (loan.isClosedWrittenOff()) { throw new PlatformServiceUnavailableException("error.msg.loan.written.off.update.not.allowed", - "Loan transaction:" + transactionId + " update not allowed as loan status is written off", transactionId); } + if (this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.LOAN)) { + throw new PlatformServiceUnavailableException("error.msg.loan.transfer.transaction.update.not.allowed", + "Loan transaction:" + transactionId + " update not allowed as it involves in account transfer", transactionId); + } + if (loan.isClosedWrittenOff()) { + throw new PlatformServiceUnavailableException("error.msg.loan.written.off.update.not.allowed", + "Loan transaction:" + transactionId + " update not allowed as loan status is written off", transactionId); + } final LocalDate transactionDate = command.localDateValueOfParameterNamed("transactionDate"); final BigDecimal transactionAmount = command.bigDecimalValueOfParameterNamed("transactionAmount"); @@ -1026,8 +1016,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf LocalDate recalculateFrom = null; if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) { - recalculateFrom = transactionToAdjust.getTransactionDate().isAfter(transactionDate) ? transactionDate : transactionToAdjust - .getTransactionDate(); + recalculateFrom = transactionToAdjust.getTransactionDate().isAfter(transactionDate) ? transactionDate + : transactionToAdjust.getTransactionDate(); } ScheduleGeneratorDTO scheduleGeneratorDTO = this.loanUtilService.buildScheduleGeneratorDTO(loan, recalculateFrom); @@ -1077,7 +1067,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } Collection transactionIds = new ArrayList<>(); - List transactions = loan.getLoanTransactions() ; + List transactions = loan.getLoanTransactions(); for (LoanTransaction transaction : transactions) { if (transaction.isRefund() && transaction.isNotReversed()) { transactionIds.add(transaction.getId()); @@ -1085,8 +1075,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } if (!transactionIds.isEmpty()) { - this.accountTransfersWritePlatformService - .reverseTransfersWithFromAccountTransactions(transactionIds, PortfolioAccountType.LOAN); + this.accountTransfersWritePlatformService.reverseTransfersWithFromAccountTransactions(transactionIds, + PortfolioAccountType.LOAN); loan.updateLoanSummarAndStatus(); } @@ -1099,15 +1089,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_ADJUST_TRANSACTION, entityMap); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withEntityId(transactionId) - .withOfficeId(loan.getOfficeId()) - .withClientId(loan.getClientId()) - .withGroupId(loan.getGroupId()) - .withLoanId(loanId) - .with(changes) - .build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(transactionId) + .withOfficeId(loan.getOfficeId()).withClientId(loan.getClientId()).withGroupId(loan.getGroupId()).withLoanId(loanId) + .with(changes).build(); } @Transactional @@ -1186,15 +1170,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf this.loanAccountDomainService.recalculateAccruals(loan); this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_WAIVE_INTEREST, constructEntityMap(BusinessEntity.LOAN_TRANSACTION, waiveInterestTransaction)); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withEntityId(waiveInterestTransaction.getId()) - .withOfficeId(loan.getOfficeId()) - .withClientId(loan.getClientId()) - .withGroupId(loan.getGroupId()) - .withLoanId(loanId) - .with(changes) - .build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(waiveInterestTransaction.getId()) + .withOfficeId(loan.getOfficeId()).withClientId(loan.getClientId()).withGroupId(loan.getGroupId()).withLoanId(loanId) + .with(changes).build(); } @Transactional @@ -1209,9 +1187,10 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf changes.put("locale", command.locale()); changes.put("dateFormat", command.dateFormat()); final Loan loan = this.loanAssembler.assembleFrom(loanId); - if(command.hasParameter("writeoffReasonId")){ + if (command.hasParameter("writeoffReasonId")) { Long writeoffReasonId = command.longValueOfParameterNamed("writeoffReasonId"); - CodeValue writeoffReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(LoanApiConstants.WRITEOFFREASONS, writeoffReasonId); + CodeValue writeoffReason = this.codeValueRepository + .findOneByCodeNameAndIdWithNotFoundDetection(LoanApiConstants.WRITEOFFREASONS, writeoffReasonId); changes.put("writeoffReasonId", writeoffReasonId); loan.updateWriteOffReason(writeoffReason); } @@ -1256,15 +1235,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf this.loanAccountDomainService.recalculateAccruals(loan); this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_WRITTEN_OFF, constructEntityMap(BusinessEntity.LOAN_TRANSACTION, writeoff)); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withEntityId(writeoff.getId()) - .withOfficeId(loan.getOfficeId()) - .withClientId(loan.getClientId()) - .withGroupId(loan.getGroupId()) - .withLoanId(loanId) - .with(changes) - .build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(writeoff.getId()) + .withOfficeId(loan.getOfficeId()).withClientId(loan.getClientId()).withGroupId(loan.getGroupId()).withLoanId(loanId) + .with(changes).build(); } @Transactional @@ -1328,25 +1301,13 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf CommandProcessingResult result = null; if (possibleClosingTransaction != null) { - result = new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withEntityId(possibleClosingTransaction.getId()) - .withOfficeId(loan.getOfficeId()) - .withClientId(loan.getClientId()) - .withGroupId(loan.getGroupId()) - .withLoanId(loanId) - .with(changes) - .build(); + result = new CommandProcessingResultBuilder().withCommandId(command.commandId()) + .withEntityId(possibleClosingTransaction.getId()).withOfficeId(loan.getOfficeId()).withClientId(loan.getClientId()) + .withGroupId(loan.getGroupId()).withLoanId(loanId).with(changes).build(); } else { - result = new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withEntityId(loanId) - .withOfficeId(loan.getOfficeId()) - .withClientId(loan.getClientId()) - .withGroupId(loan.getGroupId()) - .withLoanId(loanId) - .with(changes) - .build(); + result = new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(loanId) + .withOfficeId(loan.getOfficeId()).withClientId(loan.getClientId()).withGroupId(loan.getGroupId()).withLoanId(loanId) + .with(changes).build(); } return result; @@ -1404,9 +1365,10 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf break; } } - if (!pendingDisbursementAvailable) { throw new ChargeCannotBeUpdatedException( - "error.msg.charge.cannot.be.updated.no.pending.disbursements.in.loan", - "This charge cannot be added, No disbursement is pending"); } + if (!pendingDisbursementAvailable) { + throw new ChargeCannotBeUpdatedException("error.msg.charge.cannot.be.updated.no.pending.disbursements.in.loan", + "This charge cannot be added, No disbursement is pending"); + } } @Transactional @@ -1423,7 +1385,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final Charge chargeDefinition = this.chargeRepository.findOneWithNotFoundDetection(chargeDefinitionId); if (loan.isDisbursed() && chargeDefinition.isDisbursementCharge()) { - // validates whether any pending disbursements are available to apply this charge + // validates whether any pending disbursements are available to + // apply this charge validateAddingNewChargeAllowed(loanDisburseDetails); } final List existingTransactionIds = new ArrayList<>(loan.findExistingTransactionIds()); @@ -1495,20 +1458,16 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_ADD_CHARGE, constructEntityMap(BusinessEntity.LOAN_CHARGE, loanCharge)); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withEntityId(loanCharge.getId()) - .withOfficeId(loan.getOfficeId()) - .withClientId(loan.getClientId()) - .withGroupId(loan.getGroupId()) - .withLoanId(loanId) + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(loanCharge.getId()) + .withOfficeId(loan.getOfficeId()).withClientId(loan.getClientId()).withGroupId(loan.getGroupId()).withLoanId(loanId) .build(); } private void validateAddLoanCharge(final Loan loan, final Charge chargeDefinition, final LoanCharge loanCharge) { if (chargeDefinition.isOverdueInstallment()) { final String defaultUserMessage = "Installment charge cannot be added to the loan."; - throw new LoanChargeCannotBeAddedException("loanCharge", "overdue.charge", defaultUserMessage, null, chargeDefinition.getName()); + throw new LoanChargeCannotBeAddedException("loanCharge", "overdue.charge", defaultUserMessage, null, + chargeDefinition.getName()); } else if (loanCharge.getDueLocalDate() != null && loanCharge.getDueLocalDate().isBefore(loan.getLastUserTransactionForChargeCalc())) { final String defaultUserMessage = "charge with date before last transaction date can not be added to loan."; @@ -1534,8 +1493,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf AppUser currentUser = getAppUserIfPresent(); if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) { ScheduleGeneratorDTO generatorDTO = this.loanUtilService.buildScheduleGeneratorDTO(loan, recalculateFrom); - ChangedTransactionDetail changedTransactionDetail = loan.handleRegenerateRepaymentScheduleWithInterestRecalculation( - generatorDTO, currentUser); + ChangedTransactionDetail changedTransactionDetail = loan + .handleRegenerateRepaymentScheduleWithInterestRecalculation(generatorDTO, currentUser); saveLoanWithDataIntegrityViolationChecks(loan); if (changedTransactionDetail != null) { for (final Map.Entry mapEntry : changedTransactionDetail.getNewTransactionMappings().entrySet()) { @@ -1568,8 +1527,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } if (loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) { - final PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService.retriveLoanLinkedAssociation(loan - .getId()); + final PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService + .retriveLoanLinkedAssociation(loan.getId()); if (portfolioAccountData == null) { final String errorMessage = loanCharge.name() + "Charge requires linked savings account for payment"; throw new LinkedAccountRequiredException("loanCharge.add", errorMessage, loanCharge.name()); @@ -1608,8 +1567,10 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf // Charges may be edited only when the loan associated with them are // yet to be approved (are in submitted and pending status) - if (!loan.status().isSubmittedAndPendingApproval()) { throw new LoanChargeCannotBeUpdatedException( - LoanChargeCannotBeUpdatedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loanCharge.getId()); } + if (!loan.status().isSubmittedAndPendingApproval()) { + throw new LoanChargeCannotBeUpdatedException(LoanChargeCannotBeUpdatedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, + loanCharge.getId()); + } this.businessEventNotifierService.notifyBusinessEventToBeExecuted(BusinessEvents.LOAN_UPDATE_CHARGE, constructEntityMap(BusinessEntity.LOAN_CHARGE, loanCharge)); @@ -1643,14 +1604,16 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf // Charges may be waived only when the loan associated with them are // active - if (!loan.status().isActive()) { throw new LoanChargeCannotBeWaivedException(LoanChargeCannotBeWaivedReason.LOAN_INACTIVE, - loanCharge.getId()); } + if (!loan.status().isActive()) { + throw new LoanChargeCannotBeWaivedException(LoanChargeCannotBeWaivedReason.LOAN_INACTIVE, loanCharge.getId()); + } // validate loan charge is not already paid or waived if (loanCharge.isWaived()) { throw new LoanChargeCannotBeWaivedException(LoanChargeCannotBeWaivedReason.ALREADY_WAIVED, loanCharge.getId()); - } else if (loanCharge.isPaid()) { throw new LoanChargeCannotBeWaivedException(LoanChargeCannotBeWaivedReason.ALREADY_PAID, - loanCharge.getId()); } + } else if (loanCharge.isPaid()) { + throw new LoanChargeCannotBeWaivedException(LoanChargeCannotBeWaivedReason.ALREADY_PAID, loanCharge.getId()); + } this.businessEventNotifierService.notifyBusinessEventToBeExecuted(BusinessEvents.LOAN_WAIVE_CHARGE, constructEntityMap(BusinessEntity.LOAN_CHARGE, loanCharge)); Integer loanInstallmentNumber = null; @@ -1670,8 +1633,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } if (chargePerInstallment.isWaived()) { throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_WAIVED, loanCharge.getId()); - } else if (chargePerInstallment.isPaid()) { throw new LoanChargeCannotBePayedException( - LoanChargeCannotBePayedReason.ALREADY_PAID, loanCharge.getId()); } + } else if (chargePerInstallment.isPaid()) { + throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_PAID, loanCharge.getId()); + } loanInstallmentNumber = chargePerInstallment.getRepaymentInstallment().getInstallmentNumber(); } @@ -1684,8 +1648,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf Money accruedCharge = Money.zero(loan.getCurrency()); if (loan.isPeriodicAccrualAccountingEnabledOnLoanProduct()) { - Collection chargePaidByDatas = this.loanChargeReadPlatformService.retriveLoanChargesPaidBy( - loanCharge.getId(), LoanTransactionType.ACCRUAL, loanInstallmentNumber); + Collection chargePaidByDatas = this.loanChargeReadPlatformService + .retriveLoanChargesPaidBy(loanCharge.getId(), LoanTransactionType.ACCRUAL, loanInstallmentNumber); for (LoanChargePaidByData chargePaidByData : chargePaidByDatas) { accruedCharge = accruedCharge.plus(chargePaidByData.getAmount()); } @@ -1724,8 +1688,10 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf // Charges may be deleted only when the loan associated with them are // yet to be approved (are in submitted and pending status) - if (!loan.status().isSubmittedAndPendingApproval()) { throw new LoanChargeCannotBeDeletedException( - LoanChargeCannotBeDeletedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loanCharge.getId()); } + if (!loan.status().isSubmittedAndPendingApproval()) { + throw new LoanChargeCannotBeDeletedException(LoanChargeCannotBeDeletedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, + loanCharge.getId()); + } this.businessEventNotifierService.notifyBusinessEventToBeExecuted(BusinessEvents.LOAN_DELETE_CHARGE, constructEntityMap(BusinessEntity.LOAN_CHARGE, loanCharge)); @@ -1758,17 +1724,20 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf // Charges may be waived only when the loan associated with them are // active - if (!loan.status().isActive()) { throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.LOAN_INACTIVE, - loanCharge.getId()); } + if (!loan.status().isActive()) { + throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.LOAN_INACTIVE, loanCharge.getId()); + } // validate loan charge is not already paid or waived if (loanCharge.isWaived()) { throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_WAIVED, loanCharge.getId()); - } else if (loanCharge.isPaid()) { throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_PAID, - loanCharge.getId()); } + } else if (loanCharge.isPaid()) { + throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_PAID, loanCharge.getId()); + } - if (!loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) { throw new LoanChargeCannotBePayedException( - LoanChargeCannotBePayedReason.CHARGE_NOT_ACCOUNT_TRANSFER, loanCharge.getId()); } + if (!loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) { + throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.CHARGE_NOT_ACCOUNT_TRANSFER, loanCharge.getId()); + } final LocalDate transactionDate = command.localDateValueOfParameterNamed("transactionDate"); @@ -1790,8 +1759,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } if (chargePerInstallment.isWaived()) { throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_WAIVED, loanCharge.getId()); - } else if (chargePerInstallment.isPaid()) { throw new LoanChargeCannotBePayedException( - LoanChargeCannotBePayedReason.ALREADY_PAID, loanCharge.getId()); } + } else if (chargePerInstallment.isPaid()) { + throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_PAID, loanCharge.getId()); + } loanInstallmentNumber = chargePerInstallment.getRepaymentInstallment().getInstallmentNumber(); amount = chargePerInstallment.getAmountOutstanding(); } @@ -1827,10 +1797,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); - final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(transactionDate, amount, - PortfolioAccountType.LOAN, PortfolioAccountType.LOAN, loan.getId(), loan.getTopupLoanDetails().getLoanIdToClose(), - "Loan Topup", locale, fmt, LoanTransactionType.DISBURSEMENT.getValue(), LoanTransactionType.REPAYMENT.getValue(), - txnExternalId, loan, null); + final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(transactionDate, amount, PortfolioAccountType.LOAN, + PortfolioAccountType.LOAN, loan.getId(), loan.getTopupLoanDetails().getLoanIdToClose(), "Loan Topup", locale, fmt, + LoanTransactionType.DISBURSEMENT.getValue(), LoanTransactionType.REPAYMENT.getValue(), txnExternalId, loan, null); AccountTransferDetails accountTransferDetails = this.accountTransfersWritePlatformService.repayLoanWithTopup(accountTransferDTO); loan.getTopupLoanDetails().setAccountTransferDetails(accountTransferDetails.getId()); loan.getTopupLoanDetails().setTopupAmount(amount); @@ -1843,8 +1812,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); - final PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService.retriveLoanLinkedAssociation(loan - .getId()); + final PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService + .retriveLoanLinkedAssociation(loan.getId()); if (portfolioAccountData == null) { final String errorMessage = "Disburse Loan with id:" + loan.getId() + " requires linked savings account for payment"; throw new LinkedAccountRequiredException("loan.disburse.to.savings", errorMessage, loan.getId()); @@ -1852,9 +1821,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final SavingsAccount fromSavingsAccount = null; final boolean isExceptionForBalanceCheck = false; final boolean isRegularTransaction = true; - final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(transactionDate, amount.getAmount(), - PortfolioAccountType.LOAN, PortfolioAccountType.SAVINGS, loan.getId(), portfolioAccountData.accountId(), - "Loan Disbursement", locale, fmt, paymentDetail, LoanTransactionType.DISBURSEMENT.getValue(), null, null, null, + final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(transactionDate, amount.getAmount(), PortfolioAccountType.LOAN, + PortfolioAccountType.SAVINGS, loan.getId(), portfolioAccountData.accountId(), "Loan Disbursement", locale, fmt, + paymentDetail, LoanTransactionType.DISBURSEMENT.getValue(), null, null, null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null, null, txnExternalId, loan, null, fromSavingsAccount, isRegularTransaction, isExceptionForBalanceCheck); this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); @@ -1864,8 +1833,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf @Override @CronTarget(jobName = JobName.TRANSFER_FEE_CHARGE_FOR_LOANS) public void transferFeeCharges() throws JobExecutionException { - final Collection chargeDatas = this.loanChargeReadPlatformService.retrieveLoanChargesForFeePayment( - ChargePaymentMode.ACCOUNT_TRANSFER.getValue(), LoanStatus.ACTIVE.getValue()); + final Collection chargeDatas = this.loanChargeReadPlatformService + .retrieveLoanChargesForFeePayment(ChargePaymentMode.ACCOUNT_TRANSFER.getValue(), LoanStatus.ACTIVE.getValue()); final boolean isRegularTransaction = true; List errors = new ArrayList<>(); if (chargeDatas != null) { @@ -1877,17 +1846,17 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf for (final LoanInstallmentChargeData installmentChargeData : chargePerInstallments) { if (!installmentChargeData.getDueDate().isAfter(DateUtils.getLocalDateOfTenant())) { if (portfolioAccountData == null) { - portfolioAccountData = this.accountAssociationsReadPlatformService.retriveLoanLinkedAssociation(chargeData - .getLoanId()); + portfolioAccountData = this.accountAssociationsReadPlatformService + .retriveLoanLinkedAssociation(chargeData.getLoanId()); } final SavingsAccount fromSavingsAccount = null; final boolean isExceptionForBalanceCheck = false; final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(new LocalDate(), installmentChargeData.getAmountOutstanding(), PortfolioAccountType.SAVINGS, PortfolioAccountType.LOAN, - portfolioAccountData.accountId(), chargeData.getLoanId(), "Loan Charge Payment", null, null, null, - null, LoanTransactionType.CHARGE_PAYMENT.getValue(), chargeData.getId(), - installmentChargeData.getInstallmentNumber(), AccountTransferType.CHARGE_PAYMENT.getValue(), null, - null, null, null, null, fromSavingsAccount, isRegularTransaction, isExceptionForBalanceCheck); + portfolioAccountData.accountId(), chargeData.getLoanId(), "Loan Charge Payment", null, null, null, null, + LoanTransactionType.CHARGE_PAYMENT.getValue(), chargeData.getId(), + installmentChargeData.getInstallmentNumber(), AccountTransferType.CHARGE_PAYMENT.getValue(), null, null, + null, null, null, fromSavingsAccount, isRegularTransaction, isExceptionForBalanceCheck); transferFeeCharge(accountTransferDTO, errors); } } @@ -1896,9 +1865,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf .retriveLoanLinkedAssociation(chargeData.getLoanId()); final SavingsAccount fromSavingsAccount = null; final boolean isExceptionForBalanceCheck = false; - final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(new LocalDate(), - chargeData.getAmountOutstanding(), PortfolioAccountType.SAVINGS, PortfolioAccountType.LOAN, - portfolioAccountData.accountId(), chargeData.getLoanId(), "Loan Charge Payment", null, null, null, null, + final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(new LocalDate(), chargeData.getAmountOutstanding(), + PortfolioAccountType.SAVINGS, PortfolioAccountType.LOAN, portfolioAccountData.accountId(), + chargeData.getLoanId(), "Loan Charge Payment", null, null, null, null, LoanTransactionType.CHARGE_PAYMENT.getValue(), chargeData.getId(), null, AccountTransferType.CHARGE_PAYMENT.getValue(), null, null, null, null, null, fromSavingsAccount, isRegularTransaction, isExceptionForBalanceCheck); @@ -1913,7 +1882,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf try { this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); } catch (RuntimeException e) { - LOG.error("Exception while paying charge {} for loan id {}", accountTransferDTO.getChargeId(), accountTransferDTO.getToAccountId(), e); + LOG.error("Exception while paying charge {} for loan id {}", accountTransferDTO.getChargeId(), + accountTransferDTO.getToAccountId(), e); errors.add(e); } } @@ -1960,7 +1930,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf public LoanTransaction acceptLoanTransfer(final Loan loan, final LocalDate transferDate, final Office acceptedInOffice, final Staff loanOfficer) { AppUser currentUser = getAppUserIfPresent(); - this.loanAssembler.setHelpers(loan) ; + this.loanAssembler.setHelpers(loan); this.businessEventNotifierService.notifyBusinessEventToBeExecuted(BusinessEvents.LOAN_ACCEPT_TRANSFER, constructEntityMap(BusinessEntity.LOAN, loan)); final List existingTransactionIds = new ArrayList<>(loan.findExistingTransactionIds()); @@ -2187,12 +2157,13 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf Boolean isSkipRepaymentOnFirstMonth = false; Integer numberOfDays = 0; boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); - if(isSkipRepaymentOnFirstMonthEnabled){ + if (isSkipRepaymentOnFirstMonthEnabled) { isSkipRepaymentOnFirstMonth = this.loanUtilService.isLoanRepaymentsSyncWithMeeting(loan.group(), calendar); - if(isSkipRepaymentOnFirstMonth) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } + if (isSkipRepaymentOnFirstMonth) { + numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); + } } - holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(loan.getOfficeId(), loan.getDisbursementDate().toDate()); if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) { ScheduleGeneratorDTO scheduleGeneratorDTO = loanUtilService.buildScheduleGeneratorDTO(loan, recalculateFrom); @@ -2227,8 +2198,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } else { if (loan.loanProduct().isIncludeInBorrowerCycle()) { - loansToUpdate = this.loanRepositoryWrapper - .getClientOrJLGLoansToUpdateLoanCounter(loan.getCurrentLoanCounter(), loan.getClientId()); + loansToUpdate = this.loanRepositoryWrapper.getClientOrJLGLoansToUpdateLoanCounter(loan.getCurrentLoanCounter(), + loan.getClientId()); } else { loansToUpdate = this.loanRepositoryWrapper.getClientLoansToUpdateLoanProductCounter(loan.getLoanProductLoanCounter(), loan.getClientId()); @@ -2246,14 +2217,14 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf private void updateLoanCounters(final Loan loan, final LocalDate actualDisbursementDate) { if (loan.isGroupLoan()) { - final List loansToUpdateForLoanCounter = this.loanRepositoryWrapper.getGroupLoansDisbursedAfter(actualDisbursementDate.toDate(), - loan.getGroupId(), AccountType.GROUP.getValue()); + final List loansToUpdateForLoanCounter = this.loanRepositoryWrapper + .getGroupLoansDisbursedAfter(actualDisbursementDate.toDate(), loan.getGroupId(), AccountType.GROUP.getValue()); final Integer newLoanCounter = getNewGroupLoanCounter(loan); final Integer newLoanProductCounter = getNewGroupLoanProductCounter(loan); updateLoanCounter(loan, loansToUpdateForLoanCounter, newLoanCounter, newLoanProductCounter); } else { - final List loansToUpdateForLoanCounter = this.loanRepositoryWrapper.getClientOrJLGLoansDisbursedAfter( - actualDisbursementDate.toDate(), loan.getClientId()); + final List loansToUpdateForLoanCounter = this.loanRepositoryWrapper + .getClientOrJLGLoansDisbursedAfter(actualDisbursementDate.toDate(), loan.getClientId()); final Integer newLoanCounter = getNewClientOrJLGLoanCounter(loan); final Integer newLoanProductCounter = getNewClientOrJLGLoanProductCounter(loan); updateLoanCounter(loan, loansToUpdateForLoanCounter, newLoanCounter, newLoanProductCounter); @@ -2403,7 +2374,6 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf this.holidayRepository.save(holidays); } - private void checkClientOrGroupActive(final Loan loan) { final Client client = loan.client(); if (client != null) { @@ -2429,7 +2399,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final JsonElement parsedCommand = this.fromApiJsonHelper.parse(overdueInstallment.toString()); final JsonCommand command = JsonCommand.from(overdueInstallment.toString(), parsedCommand, this.fromApiJsonHelper, null, null, - null, null, null, loanId, null, null, null, null,null,null); + null, null, null, loanId, null, null, null, null, null, null); LoanOverdueDTO overdueDTO = applyChargeToOverdueLoanInstallment(loanId, overdueInstallment.getChargeId(), overdueInstallment.getPeriodNumber(), command, loan, existingTransactionIds, existingReversedTransactionIds); loan = overdueDTO.getLoan(); @@ -2460,7 +2430,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf addInstallmentIfPenaltyAppliedAfterLastDueDate(loan, lastChargeDate); ChangedTransactionDetail changedTransactionDetail = loan.reprocessTransactions(); if (changedTransactionDetail != null) { - for (final Map.Entry mapEntry : changedTransactionDetail.getNewTransactionMappings().entrySet()) { + for (final Map.Entry mapEntry : changedTransactionDetail.getNewTransactionMappings() + .entrySet()) { this.loanTransactionRepository.save(mapEntry.getValue()); // update loan with references to the newly created // transactions @@ -2507,7 +2478,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } public LoanOverdueDTO applyChargeToOverdueLoanInstallment(final Long loanId, final Long loanChargeId, final Integer periodNumber, - final JsonCommand command, Loan loan, final List existingTransactionIds, final List existingReversedTransactionIds) { + final JsonCommand command, Loan loan, final List existingTransactionIds, + final List existingReversedTransactionIds) { boolean runInterestRecalculation = false; final Charge chargeDefinition = this.chargeRepository.findOneWithNotFoundDetection(loanChargeId); @@ -2592,9 +2564,10 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf checkClientOrGroupActive(loan); final List existingTransactionIds = new ArrayList<>(); final List existingReversedTransactionIds = new ArrayList<>(); - if (!loan.isClosedWrittenOff()) { throw new PlatformServiceUnavailableException( - "error.msg.loan.status.not.written.off.update.not.allowed", "Loan :" + loanId - + " update not allowed as loan status is not written off", loanId); } + if (!loan.isClosedWrittenOff()) { + throw new PlatformServiceUnavailableException("error.msg.loan.status.not.written.off.update.not.allowed", + "Loan :" + loanId + " update not allowed as loan status is not written off", loanId); + } LocalDate recalculateFrom = null; LoanTransaction writeOffTransaction = loan.findWriteOffTransaction(); this.businessEventNotifierService.notifyBusinessEventToBeExecuted(BusinessEvents.LOAN_UNDO_WRITTEN_OFF, @@ -2689,8 +2662,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf if (loan.getDisbursementDetails().size() > loan.loanProduct().maxTrancheCount()) { final String errorMessage = "Number of tranche shouldn't be greter than " + loan.loanProduct().maxTrancheCount(); - throw new ExceedingTrancheCountException(LoanApiConstants.disbursementDataParameterName, errorMessage, loan.loanProduct() - .maxTrancheCount(), loan.getDisbursementDetails().size()); + throw new ExceedingTrancheCountException(LoanApiConstants.disbursementDataParameterName, errorMessage, + loan.loanProduct().maxTrancheCount(), loan.getDisbursementDetails().size()); } LoanDisbursementDetails updateDetails = null; return processLoanDisbursementDetail(loan, loanId, command, updateDetails); @@ -2783,17 +2756,20 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf // Charges may be waived only when the loan associated with them are // active - if (!loan.status().isActive()) { throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.LOAN_INACTIVE, - loanCharge.getId()); } + if (!loan.status().isActive()) { + throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.LOAN_INACTIVE, loanCharge.getId()); + } // validate loan charge is not already paid or waived if (loanCharge.isWaived()) { throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_WAIVED, loanCharge.getId()); - } else if (loanCharge.isPaid()) { throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_PAID, - loanCharge.getId()); } + } else if (loanCharge.isPaid()) { + throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_PAID, loanCharge.getId()); + } - if (!loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) { throw new LoanChargeCannotBePayedException( - LoanChargeCannotBePayedReason.CHARGE_NOT_ACCOUNT_TRANSFER, loanCharge.getId()); } + if (!loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) { + throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.CHARGE_NOT_ACCOUNT_TRANSFER, loanCharge.getId()); + } final LocalDate transactionDate = command.localDateValueOfParameterNamed("transactionDate"); @@ -2815,8 +2791,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } if (chargePerInstallment.isWaived()) { throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_WAIVED, loanCharge.getId()); - } else if (chargePerInstallment.isPaid()) { throw new LoanChargeCannotBePayedException( - LoanChargeCannotBePayedReason.ALREADY_PAID, loanCharge.getId()); } + } else if (chargePerInstallment.isPaid()) { + throw new LoanChargeCannotBePayedException(LoanChargeCannotBePayedReason.ALREADY_PAID, loanCharge.getId()); + } loanInstallmentNumber = chargePerInstallment.getRepaymentInstallment().getInstallmentNumber(); amount = chargePerInstallment.getAmountOutstanding(); } @@ -2893,7 +2870,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } private void regenerateScheduleOnDisbursement(final JsonCommand command, final Loan loan, final boolean recalculateSchedule, - final ScheduleGeneratorDTO scheduleGeneratorDTO, final LocalDate nextPossibleRepaymentDate, final Date rescheduledRepaymentDate) { + final ScheduleGeneratorDTO scheduleGeneratorDTO, final LocalDate nextPossibleRepaymentDate, + final Date rescheduledRepaymentDate) { AppUser currentUser = getAppUserIfPresent(); final LocalDate actualDisbursementDate = command.localDateValueOfParameterNamed("actualDisbursementDate"); BigDecimal emiAmount = command.bigDecimalValueOfParameterNamed(LoanApiConstants.emiAmountParameterName); @@ -2959,7 +2937,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf private void checkIfLoanIsPaidInAdvance(final Long loanId, final BigDecimal transactionAmount) { BigDecimal overpaid = this.loanReadPlatformService.retrieveTotalPaidInAdvance(loanId).getPaidInAdvance(); - if (overpaid == null || overpaid.compareTo(BigDecimal.ZERO) == 0 ? Boolean.TRUE:Boolean.FALSE || transactionAmount.floatValue() > overpaid.floatValue()) { + if (overpaid == null || overpaid.compareTo(BigDecimal.ZERO) == 0 ? Boolean.TRUE + : Boolean.FALSE || transactionAmount.floatValue() > overpaid.floatValue()) { if (overpaid == null) { overpaid = BigDecimal.ZERO; } @@ -3052,9 +3031,8 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf defaultUserMessage, transactionDate); } } - this.loanScheduleHistoryWritePlatformService.createAndSaveLoanScheduleArchive(loan.getRepaymentScheduleInstallments(), - loan, loanRescheduleRequest); - + this.loanScheduleHistoryWritePlatformService.createAndSaveLoanScheduleArchive(loan.getRepaymentScheduleInstallments(), loan, + loanRescheduleRequest); final Map modifications = this.loanAccountDomainService.foreCloseLoan(loan, transactionDate, noteText); changes.putAll(modifications); @@ -3083,10 +3061,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf } - private void syncExpectedDateWithActualDisbursementDate(final Loan loan, LocalDate actualDisbursementDate){ - if(!loan.getExpectedDisbursedOnLocalDate().equals(actualDisbursementDate)){ - throw new DateMismatchException(actualDisbursementDate, - loan.getExpectedDisbursedOnLocalDate()); + private void syncExpectedDateWithActualDisbursementDate(final Loan loan, LocalDate actualDisbursementDate) { + if (!loan.getExpectedDisbursedOnLocalDate().equals(actualDisbursementDate)) { + throw new DateMismatchException(actualDisbursementDate, loan.getExpectedDisbursedOnLocalDate()); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/RecalculateInterestPoster.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/RecalculateInterestPoster.java index 0bf994a37..30088dff1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/RecalculateInterestPoster.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/RecalculateInterestPoster.java @@ -51,10 +51,8 @@ public class RecalculateInterestPoster implements Callable { @Override public Void call() throws JobExecutionException { - Integer maxNumberOfRetries = ThreadLocalContextUtil.getTenant() - .getConnection().getMaxRetriesOnDeadlock(); - Integer maxIntervalBetweenRetries = ThreadLocalContextUtil.getTenant() - .getConnection().getMaxIntervalBetweenRetries(); + Integer maxNumberOfRetries = ThreadLocalContextUtil.getTenant().getConnection().getMaxRetriesOnDeadlock(); + Integer maxIntervalBetweenRetries = ThreadLocalContextUtil.getTenant().getConnection().getMaxIntervalBetweenRetries(); int i = 0; if (!loanIds.isEmpty()) { @@ -66,23 +64,25 @@ public class RecalculateInterestPoster implements Callable { try { this.loanWritePlatformService.recalculateInterest(loanId); numberOfRetries = maxNumberOfRetries + 1; - } catch (CannotAcquireLockException - | ObjectOptimisticLockingFailureException exception) { + } catch (CannotAcquireLockException | ObjectOptimisticLockingFailureException exception) { LOG.info("Recalulate interest job has been retried {} time(s)", numberOfRetries); - // Fail if the transaction has been retired for maxNumberOfRetries + // Fail if the transaction has been retired for + // maxNumberOfRetries if (numberOfRetries >= maxNumberOfRetries) { - LOG.error("Recalulate interest job has been retried for the max allowed attempts of {} and will be rolled back", numberOfRetries); + LOG.error("Recalulate interest job has been retried for the max allowed attempts of {} and will be rolled back", + numberOfRetries); errors.add(exception); break; } - // Else sleep for a random time (between 1 to 10 seconds) and continue + // Else sleep for a random time (between 1 to 10 + // seconds) and continue try { Random random = new Random(); int randomNum = random.nextInt(maxIntervalBetweenRetries + 1); Thread.sleep(1000 + (randomNum * 1000)); numberOfRetries = numberOfRetries + 1; } catch (InterruptedException e) { - LOG.error("Interest recalculation for loans retry failed due to InterruptedException", e) ; + LOG.error("Interest recalculation for loans retry failed due to InterruptedException", e); errors.add(e); break; } @@ -99,4 +99,4 @@ public class RecalculateInterestPoster implements Callable { } return null; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/LoanProductConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/LoanProductConstants.java old mode 100755 new mode 100644 index c18a89189..7ad88732d --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/LoanProductConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/LoanProductConstants.java @@ -111,7 +111,7 @@ public interface LoanProductConstants { public static final String canDefineEmiAmountParamName = "canDefineInstallmentAmount"; public static final String installmentAmountInMultiplesOfParamName = "installmentAmountInMultiplesOf"; - //Loan Configurable Attributes + // Loan Configurable Attributes public static final String allowAttributeOverridesParamName = "allowAttributeOverrides"; public static final String amortizationTypeParamName = "amortizationType"; public static final String interestTypeParamName = "interestType"; @@ -122,11 +122,10 @@ public interface LoanProductConstants { public static final String graceOnPrincipalAndInterestPaymentParamName = "graceOnPrincipalAndInterestPayment"; public static final String allowCompoundingOnEodParamName = "allowCompoundingOnEod"; - //Variable Installments Settings - public static final String allowVariableInstallmentsParamName = "allowVariableInstallments" ; - public static final String minimumGapBetweenInstallments = "minimumGap" ; - public static final String maximumGapBetweenInstallments = "maximumGap" ; - + // Variable Installments Settings + public static final String allowVariableInstallmentsParamName = "allowVariableInstallments"; + public static final String minimumGapBetweenInstallments = "minimumGap"; + public static final String maximumGapBetweenInstallments = "maximumGap"; public static final String ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME = "allowPartialPeriodInterestCalcualtion"; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/api/LoanProductsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/api/LoanProductsApiResource.java index c05d28268..a1f117cab 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/api/LoanProductsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/api/LoanProductsApiResource.java @@ -87,29 +87,29 @@ import org.springframework.stereotype.Component; @Path("/loanproducts") @Component @Scope("singleton") -@Api(tags = {"Loan Products"}) +@Api(tags = { "Loan Products" }) @SwaggerDefinition(tags = { - @Tag(name = "Loan Products", description = "A Loan product is a template that is used when creating a loan. Much of the template definition can be overridden during loan creation.") -}) + @Tag(name = "Loan Products", description = "A Loan product is a template that is used when creating a loan. Much of the template definition can be overridden during loan creation.") }) public class LoanProductsApiResource { - private final Set LOAN_PRODUCT_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "shortName", "description", - "fundId", "fundName", "includeInBorrowerCycle", "currency", "principal", "minPrincipal", "maxPrincipal", "numberOfRepayments", - "minNumberOfRepayments", "maxNumberOfRepayments", "repaymentEvery", "repaymentFrequencyType", "graceOnPrincipalPayment", "recurringMoratoriumOnPrincipalPeriods", - "graceOnInterestPayment", "graceOnInterestCharged", "interestRatePerPeriod", "minInterestRatePerPeriod", - "maxInterestRatePerPeriod", "interestRateFrequencyType", "annualInterestRate", "amortizationType", "interestType", - "interestCalculationPeriodType", LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, "inArrearsTolerance", - "transactionProcessingStrategyId", "transactionProcessingStrategyName", "charges", "accountingRule", "externalId", - "accountingMappings", "paymentChannelToFundSourceMappings", "fundOptions", "paymentTypeOptions", "currencyOptions", - "repaymentFrequencyTypeOptions", "interestRateFrequencyTypeOptions", "amortizationTypeOptions", "interestTypeOptions", - "interestCalculationPeriodTypeOptions", "transactionProcessingStrategyOptions", "chargeOptions", "accountingOptions", - "accountingRuleOptions", "accountingMappingOptions", "floatingRateOptions", "isLinkedToFloatingInterestRates", - "floatingRatesId", "interestRateDifferential", "minDifferentialLendingRate", "defaultDifferentialLendingRate", - "maxDifferentialLendingRate", "isFloatingInterestRateCalculationAllowed", LoanProductConstants.CAN_USE_FOR_TOPUP, LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM, + private final Set LOAN_PRODUCT_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "shortName", "description", "fundId", + "fundName", "includeInBorrowerCycle", "currency", "principal", "minPrincipal", "maxPrincipal", "numberOfRepayments", + "minNumberOfRepayments", "maxNumberOfRepayments", "repaymentEvery", "repaymentFrequencyType", "graceOnPrincipalPayment", + "recurringMoratoriumOnPrincipalPeriods", "graceOnInterestPayment", "graceOnInterestCharged", "interestRatePerPeriod", + "minInterestRatePerPeriod", "maxInterestRatePerPeriod", "interestRateFrequencyType", "annualInterestRate", "amortizationType", + "interestType", "interestCalculationPeriodType", LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, + "inArrearsTolerance", "transactionProcessingStrategyId", "transactionProcessingStrategyName", "charges", "accountingRule", + "externalId", "accountingMappings", "paymentChannelToFundSourceMappings", "fundOptions", "paymentTypeOptions", + "currencyOptions", "repaymentFrequencyTypeOptions", "interestRateFrequencyTypeOptions", "amortizationTypeOptions", + "interestTypeOptions", "interestCalculationPeriodTypeOptions", "transactionProcessingStrategyOptions", "chargeOptions", + "accountingOptions", "accountingRuleOptions", "accountingMappingOptions", "floatingRateOptions", + "isLinkedToFloatingInterestRates", "floatingRatesId", "interestRateDifferential", "minDifferentialLendingRate", + "defaultDifferentialLendingRate", "maxDifferentialLendingRate", "isFloatingInterestRateCalculationAllowed", + LoanProductConstants.CAN_USE_FOR_TOPUP, LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM, LoanProductConstants.RATES_PARAM_NAME)); - private final Set PRODUCT_MIX_DATA_PARAMETERS = new HashSet<>(Arrays.asList("productId", "productName", "restrictedProducts", - "allowedProducts", "productOptions")); + private final Set PRODUCT_MIX_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("productId", "productName", "restrictedProducts", "allowedProducts", "productOptions")); private final String resourceNameForPermissions = "LOANPRODUCT"; @@ -132,7 +132,6 @@ public class LoanProductsApiResource { private final RateReadService rateReadService; private final ConfigurationDomainService configurationDomainService; - @Autowired public LoanProductsApiResource(final PlatformSecurityContext context, final LoanProductReadPlatformService readPlatformService, final ChargeReadPlatformService chargeReadPlatformService, final CurrencyReadPlatformService currencyReadPlatformService, @@ -171,9 +170,22 @@ public class LoanProductsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Loan Product", httpMethod = "POST", notes = "Depending of the Accounting Rule (accountingRule) selected, additional fields with details of the appropriate Ledger Account identifiers would need to be passed in.\n" + "\n" + "Refer MifosX Accounting Specs Draft for more details regarding the significance of the selected accounting rule\n\n" + "Mandatory Fields: name, shortName, currencyCode, digitsAfterDecimal, inMultiplesOf, principal, numberOfRepayments, repaymentEvery, repaymentFrequencyType, interestRatePerPeriod, interestRateFrequencyType, amortizationType, interestType, interestCalculationPeriodType, transactionProcessingStrategyId, accountingRule, isInterestRecalculationEnabled, daysInYearType, daysInMonthType\n\n" + "Optional Fields: inArrearsTolerance, graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, graceOnArrearsAgeing, charges, paymentChannelToFundSourceMappings, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, includeInBorrowerCycle, useBorrowerCycle,principalVariationsForBorrowerCycle, numberOfRepaymentVariationsForBorrowerCycle, interestRateVariationsForBorrowerCycle, multiDisburseLoan,maxTrancheCount, outstandingLoanBalance,overdueDaysForNPA,holdGuaranteeFunds, principalThresholdForLastInstalment, accountMovesOutOfNPAOnlyOnArrearsCompletion, canDefineInstallmentAmount, installmentAmountInMultiplesOf, allowAttributeOverrides, allowPartialPeriodInterestCalcualtion\n\n" + "Additional Mandatory Fields for Cash(2) based accounting: fundSourceAccountId, loanPortfolioAccountId, interestOnLoanAccountId, incomeFromFeeAccountId, incomeFromPenaltyAccountId, writeOffAccountId, transfersInSuspenseAccountId, overpaymentLiabilityAccountId\n\n" + "Additional Mandatory Fields for periodic (3) and upfront (4)accrual accounting: fundSourceAccountId, loanPortfolioAccountId, interestOnLoanAccountId, incomeFromFeeAccountId, incomeFromPenaltyAccountId, writeOffAccountId, receivableInterestAccountId, receivableFeeAccountId, receivablePenaltyAccountId, transfersInSuspenseAccountId, overpaymentLiabilityAccountId\n\n" + "Additional Mandatory Fields if interest recalculation is enabled(true): interestRecalculationCompoundingMethod, rescheduleStrategyMethod, recalculationRestFrequencyType\n\n" + "Additional Optional Fields if interest recalculation is enabled(true): isArrearsBasedOnOriginalSchedule, preClosureInterestCalculationStrategy\n\n" + "Additional Optional Fields if interest recalculation is enabled(true) and recalculationRestFrequencyType is not same as repayment period: recalculationRestFrequencyInterval, recalculationRestFrequencyDate\n\n" + "Additional Optional Fields if interest recalculation is enabled(true) and interestRecalculationCompoundingMethod is enabled: recalculationCompoundingFrequencyType\n\n" + "Additional Optional Fields if interest recalculation is enabled(true) and interestRecalculationCompoundingMethod is enabled and recalculationCompoundingFrequencyType is not same as repayment period: recalculationCompoundingFrequencyInterval, recalculationCompoundingFrequencyDate\n\n" + "Additional Mandatory Fields if Hold Guarantee funds is enabled(true): mandatoryGuarantee\n\n" + "Additional Optional Fields if Hold Guarantee funds is enabled(true): minimumGuaranteeFromOwnFunds,minimumGuaranteeFromGuarantor") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanProductsApiResourceSwagger.PostLoanProductsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200,message = "OK", response = LoanProductsApiResourceSwagger.PostLoanProductsResponse.class)}) + @ApiOperation(value = "Create a Loan Product", httpMethod = "POST", notes = "Depending of the Accounting Rule (accountingRule) selected, additional fields with details of the appropriate Ledger Account identifiers would need to be passed in.\n" + + "\n" + "Refer MifosX Accounting Specs Draft for more details regarding the significance of the selected accounting rule\n\n" + + "Mandatory Fields: name, shortName, currencyCode, digitsAfterDecimal, inMultiplesOf, principal, numberOfRepayments, repaymentEvery, repaymentFrequencyType, interestRatePerPeriod, interestRateFrequencyType, amortizationType, interestType, interestCalculationPeriodType, transactionProcessingStrategyId, accountingRule, isInterestRecalculationEnabled, daysInYearType, daysInMonthType\n\n" + + "Optional Fields: inArrearsTolerance, graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, graceOnArrearsAgeing, charges, paymentChannelToFundSourceMappings, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, includeInBorrowerCycle, useBorrowerCycle,principalVariationsForBorrowerCycle, numberOfRepaymentVariationsForBorrowerCycle, interestRateVariationsForBorrowerCycle, multiDisburseLoan,maxTrancheCount, outstandingLoanBalance,overdueDaysForNPA,holdGuaranteeFunds, principalThresholdForLastInstalment, accountMovesOutOfNPAOnlyOnArrearsCompletion, canDefineInstallmentAmount, installmentAmountInMultiplesOf, allowAttributeOverrides, allowPartialPeriodInterestCalcualtion\n\n" + + "Additional Mandatory Fields for Cash(2) based accounting: fundSourceAccountId, loanPortfolioAccountId, interestOnLoanAccountId, incomeFromFeeAccountId, incomeFromPenaltyAccountId, writeOffAccountId, transfersInSuspenseAccountId, overpaymentLiabilityAccountId\n\n" + + "Additional Mandatory Fields for periodic (3) and upfront (4)accrual accounting: fundSourceAccountId, loanPortfolioAccountId, interestOnLoanAccountId, incomeFromFeeAccountId, incomeFromPenaltyAccountId, writeOffAccountId, receivableInterestAccountId, receivableFeeAccountId, receivablePenaltyAccountId, transfersInSuspenseAccountId, overpaymentLiabilityAccountId\n\n" + + "Additional Mandatory Fields if interest recalculation is enabled(true): interestRecalculationCompoundingMethod, rescheduleStrategyMethod, recalculationRestFrequencyType\n\n" + + "Additional Optional Fields if interest recalculation is enabled(true): isArrearsBasedOnOriginalSchedule, preClosureInterestCalculationStrategy\n\n" + + "Additional Optional Fields if interest recalculation is enabled(true) and recalculationRestFrequencyType is not same as repayment period: recalculationRestFrequencyInterval, recalculationRestFrequencyDate\n\n" + + "Additional Optional Fields if interest recalculation is enabled(true) and interestRecalculationCompoundingMethod is enabled: recalculationCompoundingFrequencyType\n\n" + + "Additional Optional Fields if interest recalculation is enabled(true) and interestRecalculationCompoundingMethod is enabled and recalculationCompoundingFrequencyType is not same as repayment period: recalculationCompoundingFrequencyInterval, recalculationCompoundingFrequencyDate\n\n" + + "Additional Mandatory Fields if Hold Guarantee funds is enabled(true): mandatoryGuarantee\n\n" + + "Additional Optional Fields if Hold Guarantee funds is enabled(true): minimumGuaranteeFromOwnFunds,minimumGuaranteeFromGuarantor") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanProductsApiResourceSwagger.PostLoanProductsRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = LoanProductsApiResourceSwagger.PostLoanProductsResponse.class) }) public String createLoanProduct(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createLoanProduct().withJson(apiRequestBodyAsJson).build(); @@ -186,8 +198,10 @@ public class LoanProductsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Loan Products", httpMethod = "GET", notes = "Lists Loan Products\n\n" + "Example Requests:\n" + "\n" + "loanproducts\n" + "\n" + "\n" + "loanproducts?fields=name,description,interestRateFrequencyType,amortizationType") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = LoanProductsApiResourceSwagger.GetLoanProductsResponse.class)}) + @ApiOperation(value = "List Loan Products", httpMethod = "GET", notes = "Lists Loan Products\n\n" + "Example Requests:\n" + "\n" + + "loanproducts\n" + "\n" + "\n" + "loanproducts?fields=name,description,interestRateFrequencyType,amortizationType") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = LoanProductsApiResourceSwagger.GetLoanProductsResponse.class) }) public String retrieveAllLoanProducts(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -211,9 +225,12 @@ public class LoanProductsApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Loan Product Details Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "loanproducts/template") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanProductsApiResourceSwagger.GetLoanProductsTemplateResponse.class)}) - public String retrieveTemplate(@Context final UriInfo uriInfo, @QueryParam("isProductMixTemplate") @ApiParam(value = "isProductMixTemplate") final boolean isProductMixTemplate) { + @ApiOperation(value = "Retrieve Loan Product Details Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "loanproducts/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanProductsApiResourceSwagger.GetLoanProductsTemplateResponse.class) }) + public String retrieveTemplate(@Context final UriInfo uriInfo, + @QueryParam("isProductMixTemplate") @ApiParam(value = "isProductMixTemplate") final boolean isProductMixTemplate) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -236,9 +253,13 @@ public class LoanProductsApiResource { @Path("{productId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Loan Product", httpMethod = "GET", notes = "Retrieves a Loan Product\n\n" + "Example Requests:\n" + "\n" + "loanproducts/1\n" + "\n" + "\n" + "loanproducts/1?template=true\n" + "\n" + "\n" + "loanproducts/1?fields=name,description,numberOfRepayments") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanProductsApiResourceSwagger.GetLoanProductsProductIdResponse.class)}) - public String retrieveLoanProductDetails(@PathParam("productId") @ApiParam(value = "productId") final Long productId, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Loan Product", httpMethod = "GET", notes = "Retrieves a Loan Product\n\n" + "Example Requests:\n" + + "\n" + "loanproducts/1\n" + "\n" + "\n" + "loanproducts/1?template=true\n" + "\n" + "\n" + + "loanproducts/1?fields=name,description,numberOfRepayments") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanProductsApiResourceSwagger.GetLoanProductsProductIdResponse.class) }) + public String retrieveLoanProductDetails(@PathParam("productId") @ApiParam(value = "productId") final Long productId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -251,8 +272,8 @@ public class LoanProductsApiResource { Collection feeToGLAccountMappings = null; Collection penaltyToGLAccountMappings = null; if (loanProduct.hasAccountingEnabled()) { - accountingMappings = this.accountMappingReadPlatformService.fetchAccountMappingDetailsForLoanProduct(productId, loanProduct - .accountingRuleType().getId().intValue()); + accountingMappings = this.accountMappingReadPlatformService.fetchAccountMappingDetailsForLoanProduct(productId, + loanProduct.accountingRuleType().getId().intValue()); paymentChannelToFundSourceMappings = this.accountMappingReadPlatformService .fetchPaymentTypeToFundSourceMappingsForLoanProduct(productId); feeToGLAccountMappings = this.accountMappingReadPlatformService @@ -274,9 +295,12 @@ public class LoanProductsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Loan Product", httpMethod = "PUT", notes = "Updates a Loan Product") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanProductsApiResourceSwagger.PutLoanProductsProductIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = LoanProductsApiResourceSwagger.PutLoanProductsProductIdResponse.class)}) - public String updateLoanProduct(@PathParam("productId") @ApiParam(value = "productId") final Long productId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = LoanProductsApiResourceSwagger.PutLoanProductsProductIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = LoanProductsApiResourceSwagger.PutLoanProductsProductIdResponse.class) }) + public String updateLoanProduct(@PathParam("productId") @ApiParam(value = "productId") final Long productId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateLoanProduct(productId).withJson(apiRequestBodyAsJson) .build(); @@ -300,7 +324,7 @@ public class LoanProductsApiResource { boolean isRatesEnabled = this.configurationDomainService.isSubRatesEnabled(); Collection rateOptions = this.rateReadService.retrieveLoanApplicableRates(); - if(rateOptions.isEmpty()){ + if (rateOptions.isEmpty()) { rateOptions = null; } @@ -345,13 +369,13 @@ public class LoanProductsApiResource { .retrivePreCloseInterestCalculationStrategyOptions(); final List floatingRateOptions = this.floatingRateReadPlatformService.retrieveLookupActive(); - return new LoanProductData(productData, chargeOptions, penaltyOptions, paymentTypeOptions, currencyOptions, - amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, repaymentFrequencyTypeOptions, - interestRateFrequencyTypeOptions, fundOptions, transactionProcessingStrategyOptions, rateOptions, accountOptions, - accountingRuleTypeOptions, loanCycleValueConditionTypeOptions, daysInMonthTypeOptions, daysInYearTypeOptions, + return new LoanProductData(productData, chargeOptions, penaltyOptions, paymentTypeOptions, currencyOptions, amortizationTypeOptions, + interestTypeOptions, interestCalculationPeriodTypeOptions, repaymentFrequencyTypeOptions, interestRateFrequencyTypeOptions, + fundOptions, transactionProcessingStrategyOptions, rateOptions, accountOptions, accountingRuleTypeOptions, + loanCycleValueConditionTypeOptions, daysInMonthTypeOptions, daysInYearTypeOptions, interestRecalculationCompoundingTypeOptions, rescheduleStrategyTypeOptions, interestRecalculationFrequencyTypeOptions, preCloseInterestCalculationStrategyOptions, floatingRateOptions, interestRecalculationNthDayTypeOptions, interestRecalculationDayOfWeekTypeOptions, isRatesEnabled); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/api/LoanProductsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/api/LoanProductsApiResourceSwagger.java index 83378abd2..d1a34774d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/api/LoanProductsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/api/LoanProductsApiResourceSwagger.java @@ -28,13 +28,13 @@ import java.util.Set; * Created by Chirag Gupta on 12/27/17. */ final class LoanProductsApiResourceSwagger { - private LoanProductsApiResourceSwagger() { - } + + private LoanProductsApiResourceSwagger() {} @ApiModel(value = "PostLoanProductsRequest") public final static class PostLoanProductsRequest { - private PostLoanProductsRequest() { - } + + private PostLoanProductsRequest() {} @ApiModelProperty(example = "LP Accrual Accounting") public String name; @@ -100,8 +100,8 @@ final class LoanProductsApiResourceSwagger { @ApiModel(value = "PostLoanProductsResponse") public final static class PostLoanProductsResponse { - private PostLoanProductsResponse() { - } + + private PostLoanProductsResponse() {} @ApiModelProperty(example = "3") public Integer resourceId; @@ -109,12 +109,12 @@ final class LoanProductsApiResourceSwagger { @ApiModel(value = "GetLoanProductsResponse") public final static class GetLoanProductsResponse { - private GetLoanProductsResponse() { - } + + private GetLoanProductsResponse() {} final class GetLoanProductsCurrency { - private GetLoanProductsCurrency() { - } + + private GetLoanProductsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -133,8 +133,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsRepaymentFrequencyType { - private GetLoanProductsRepaymentFrequencyType() { - } + + private GetLoanProductsRepaymentFrequencyType() {} @ApiModelProperty(example = "0") public Integer id; @@ -145,8 +145,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsInterestRateFrequencyType { - private GetLoanProductsInterestRateFrequencyType() { - } + + private GetLoanProductsInterestRateFrequencyType() {} @ApiModelProperty(example = "3") public Integer id; @@ -157,8 +157,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsAmortizationType { - private GetLoanProductsAmortizationType() { - } + + private GetLoanProductsAmortizationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -169,8 +169,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsInterestType { - private GetLoanProductsInterestType() { - } + + private GetLoanProductsInterestType() {} @ApiModelProperty(example = "1") public Integer id; @@ -181,8 +181,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoansProductsInterestCalculationPeriodType { - private GetLoansProductsInterestCalculationPeriodType() { - } + + private GetLoansProductsInterestCalculationPeriodType() {} @ApiModelProperty(example = "1") public Integer id; @@ -193,8 +193,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoansProductsDaysInMonthType { - private GetLoansProductsDaysInMonthType() { - } + + private GetLoansProductsDaysInMonthType() {} @ApiModelProperty(example = "30") public Integer id; @@ -205,8 +205,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoansProductsDaysInYearType { - private GetLoansProductsDaysInYearType() { - } + + private GetLoansProductsDaysInYearType() {} @ApiModelProperty(example = "360") public Integer id; @@ -217,12 +217,12 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsInterestRecalculationData { - private GetLoanProductsInterestRecalculationData() { - } + + private GetLoanProductsInterestRecalculationData() {} final class GetLoanProductsInterestRecalculationCompoundingType { - private GetLoanProductsInterestRecalculationCompoundingType() { - } + + private GetLoanProductsInterestRecalculationCompoundingType() {} @ApiModelProperty(example = "2") public Integer id; @@ -233,8 +233,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsInterestRecalculationCompoundingFrequencyType { - private GetLoanProductsInterestRecalculationCompoundingFrequencyType() { - } + + private GetLoanProductsInterestRecalculationCompoundingFrequencyType() {} @ApiModelProperty(example = "1") public Integer id; @@ -245,8 +245,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsRescheduleStrategyType { - private GetLoanProductsRescheduleStrategyType() { - } + + private GetLoanProductsRescheduleStrategyType() {} @ApiModelProperty(example = "2") public Integer id; @@ -257,8 +257,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsPreClosureInterestCalculationStrategy { - private GetLoanProductsPreClosureInterestCalculationStrategy() { - } + + private GetLoanProductsPreClosureInterestCalculationStrategy() {} @ApiModelProperty(example = "1") public Integer id; @@ -282,8 +282,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsAccountingRule { - private GetLoanProductsAccountingRule() { - } + + private GetLoanProductsAccountingRule() {} @ApiModelProperty(example = "2") public Integer id; @@ -355,12 +355,12 @@ final class LoanProductsApiResourceSwagger { @ApiModel(value = "GetLoanProductsTemplateResponse") public final static class GetLoanProductsTemplateResponse { - private GetLoanProductsTemplateResponse() { - } + + private GetLoanProductsTemplateResponse() {} final class GetLoanProductsTemplateCurrency { - private GetLoanProductsTemplateCurrency() { - } + + private GetLoanProductsTemplateCurrency() {} @ApiModelProperty(example = "") public String code; @@ -379,8 +379,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsRepaymentTemplateFrequencyType { - private GetLoanProductsRepaymentTemplateFrequencyType() { - } + + private GetLoanProductsRepaymentTemplateFrequencyType() {} @ApiModelProperty(example = "2") public Integer id; @@ -391,8 +391,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsInterestRateTemplateFrequencyType { - private GetLoanProductsInterestRateTemplateFrequencyType() { - } + + private GetLoanProductsInterestRateTemplateFrequencyType() {} @ApiModelProperty(example = "2") public Integer id; @@ -403,8 +403,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsInterestTemplateType { - private GetLoanProductsInterestTemplateType() { - } + + private GetLoanProductsInterestTemplateType() {} @ApiModelProperty(example = "0") public Integer id; @@ -415,8 +415,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsAccountingRule { - private GetLoanProductsAccountingRule() { - } + + private GetLoanProductsAccountingRule() {} @ApiModelProperty(example = "1") public Integer id; @@ -427,8 +427,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoansProductsDaysInMonthTemplateType { - private GetLoansProductsDaysInMonthTemplateType() { - } + + private GetLoansProductsDaysInMonthTemplateType() {} @ApiModelProperty(example = "1") public Integer id; @@ -439,8 +439,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsDaysInYearTemplateType { - private GetLoanProductsDaysInYearTemplateType() { - } + + private GetLoanProductsDaysInYearTemplateType() {} @ApiModelProperty(example = "1") public Integer id; @@ -451,12 +451,12 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsInterestRecalculationTemplateData { - private GetLoanProductsInterestRecalculationTemplateData() { - } + + private GetLoanProductsInterestRecalculationTemplateData() {} final class GetLoanProductsInterestRecalculationCompoundingType { - private GetLoanProductsInterestRecalculationCompoundingType() { - } + + private GetLoanProductsInterestRecalculationCompoundingType() {} @ApiModelProperty(example = "0") public Integer id; @@ -467,8 +467,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsRescheduleStrategyType { - private GetLoanProductsRescheduleStrategyType() { - } + + private GetLoanProductsRescheduleStrategyType() {} @ApiModelProperty(example = "3") public Integer id; @@ -484,8 +484,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsPaymentTypeOptions { - private GetLoanProductsPaymentTypeOptions() { - } + + private GetLoanProductsPaymentTypeOptions() {} @ApiModelProperty(example = "10") public Integer id; @@ -496,8 +496,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsCurrencyOptions { - private GetLoanProductsCurrencyOptions() { - } + + private GetLoanProductsCurrencyOptions() {} @ApiModelProperty(example = "USD") public String code; @@ -514,8 +514,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsTransactionProcessingStrategyOptions { - private GetLoanProductsTransactionProcessingStrategyOptions() { - } + + private GetLoanProductsTransactionProcessingStrategyOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -526,12 +526,12 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsChargeOptions { - private GetLoanProductsChargeOptions() { - } + + private GetLoanProductsChargeOptions() {} final class GetLoanChargeTimeType { - private GetLoanChargeTimeType() { - } + + private GetLoanChargeTimeType() {} @ApiModelProperty(example = "1") public Integer id; @@ -542,8 +542,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsChargeAppliesTo { - private GetLoanProductsChargeAppliesTo() { - } + + private GetLoanProductsChargeAppliesTo() {} @ApiModelProperty(example = "1 ") public Integer id; @@ -554,8 +554,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanChargeCalculationType { - private GetLoanChargeCalculationType() { - } + + private GetLoanChargeCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -566,8 +566,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoansChargePaymentMode { - private GetLoansChargePaymentMode() { - } + + private GetLoansChargePaymentMode() {} @ApiModelProperty(example = "0") public Integer id; @@ -595,16 +595,16 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsAccountingMappingOptions { - private GetLoanProductsAccountingMappingOptions() { - } + + private GetLoanProductsAccountingMappingOptions() {} final class GetLoanProductsLiabilityAccountOptions { - private GetLoanProductsLiabilityAccountOptions() { - } + + private GetLoanProductsLiabilityAccountOptions() {} final class GetLoanProductsLiabilityType { - private GetLoanProductsLiabilityType() { - } + + private GetLoanProductsLiabilityType() {} @ApiModelProperty(example = "2") public Integer id; @@ -615,8 +615,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsLiabilityUsage { - private GetLoanProductsLiabilityUsage() { - } + + private GetLoanProductsLiabilityUsage() {} @ApiModelProperty(example = "1") public Integer id; @@ -627,8 +627,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsLiabilityTagId { - private GetLoanProductsLiabilityTagId() { - } + + private GetLoanProductsLiabilityTagId() {} @ApiModelProperty(example = "0") public Integer id; @@ -654,8 +654,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsAssetAccountOptions { - private GetLoanProductsAssetAccountOptions() { - } + + private GetLoanProductsAssetAccountOptions() {} @ApiModelProperty(example = "2") public Integer id; @@ -677,12 +677,12 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsExpenseAccountOptions { - private GetLoanProductsExpenseAccountOptions() { - } + + private GetLoanProductsExpenseAccountOptions() {} final class GetLoanProductsExpenseType { - private GetLoanProductsExpenseType() { - } + + private GetLoanProductsExpenseType() {} @ApiModelProperty(example = "5") public Integer id; @@ -712,12 +712,12 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsIncomeAccountOptions { - private GetLoanProductsIncomeAccountOptions() { - } + + private GetLoanProductsIncomeAccountOptions() {} final class GetLoanProductsIncomeType { - private GetLoanProductsIncomeType() { - } + + private GetLoanProductsIncomeType() {} @ApiModelProperty(example = "4") public Integer id; @@ -753,8 +753,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsValueConditionTypeOptions { - private GetLoanProductsValueConditionTypeOptions() { - } + + private GetLoanProductsValueConditionTypeOptions() {} @ApiModelProperty(example = "2") public Integer id; @@ -808,12 +808,12 @@ final class LoanProductsApiResourceSwagger { @ApiModel(value = "GetLoanProductsProductIdResponse") public final static class GetLoanProductsProductIdResponse { - private GetLoanProductsProductIdResponse() { - } + + private GetLoanProductsProductIdResponse() {} final class GetLoanProductsInterestRateFrequencyType { - private GetLoanProductsInterestRateFrequencyType() { - } + + private GetLoanProductsInterestRateFrequencyType() {} @ApiModelProperty(example = "2") public Integer id; @@ -824,12 +824,12 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsPrincipalVariationsForBorrowerCycle { - private GetLoanProductsPrincipalVariationsForBorrowerCycle() { - } + + private GetLoanProductsPrincipalVariationsForBorrowerCycle() {} final class GetLoanProductsParamType { - private GetLoanProductsParamType() { - } + + private GetLoanProductsParamType() {} @ApiModelProperty(example = "1") public Integer id; @@ -840,8 +840,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanProductsValueConditionType { - private GetLoanProductsValueConditionType() { - } + + private GetLoanProductsValueConditionType() {} @ApiModelProperty(example = "2") public Integer id; @@ -866,12 +866,12 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanAccountingMappings { - private GetLoanAccountingMappings() { - } + + private GetLoanAccountingMappings() {} final class GetLoanFundSourceAccount { - private GetLoanFundSourceAccount() { - } + + private GetLoanFundSourceAccount() {} @ApiModelProperty(example = "1") public Integer id; @@ -882,8 +882,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanPortfolioAccount { - private GetLoanPortfolioAccount() { - } + + private GetLoanPortfolioAccount() {} @ApiModelProperty(example = "2") public Integer id; @@ -894,8 +894,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanTransfersInSuspenseAccount { - private GetLoanTransfersInSuspenseAccount() { - } + + private GetLoanTransfersInSuspenseAccount() {} @ApiModelProperty(example = "3") public Integer id; @@ -906,8 +906,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanInterestOnLoanAccount { - private GetLoanInterestOnLoanAccount() { - } + + private GetLoanInterestOnLoanAccount() {} @ApiModelProperty(example = "4") public Integer id; @@ -918,8 +918,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanIncomeFromFeeAccount { - private GetLoanIncomeFromFeeAccount() { - } + + private GetLoanIncomeFromFeeAccount() {} @ApiModelProperty(example = "8") public Integer id; @@ -930,8 +930,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanIncomeFromPenaltyAccount { - private GetLoanIncomeFromPenaltyAccount() { - } + + private GetLoanIncomeFromPenaltyAccount() {} @ApiModelProperty(example = "9") public Integer id; @@ -942,8 +942,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanWriteOffAccount { - private GetLoanWriteOffAccount() { - } + + private GetLoanWriteOffAccount() {} @ApiModelProperty(example = "10") public Integer id; @@ -954,8 +954,8 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanOverpaymentLiabilityAccount { - private GetLoanOverpaymentLiabilityAccount() { - } + + private GetLoanOverpaymentLiabilityAccount() {} @ApiModelProperty(example = "11") public Integer id; @@ -976,12 +976,12 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanPaymentChannelToFundSourceMappings { - private GetLoanPaymentChannelToFundSourceMappings() { - } + + private GetLoanPaymentChannelToFundSourceMappings() {} final class GetLoanPaymentType { - private GetLoanPaymentType() { - } + + private GetLoanPaymentType() {} @ApiModelProperty(example = "10") public Integer id; @@ -994,12 +994,12 @@ final class LoanProductsApiResourceSwagger { } final class GetLoanFeeToIncomeAccountMappings { - private GetLoanFeeToIncomeAccountMappings() { - } + + private GetLoanFeeToIncomeAccountMappings() {} final class GetLoanCharge { - private GetLoanCharge() { - } + + private GetLoanCharge() {} @ApiModelProperty(example = "1") public Integer id; @@ -1076,8 +1076,8 @@ final class LoanProductsApiResourceSwagger { @ApiModel(value = "PutLoanProductsProductIdRequest") public final static class PutLoanProductsProductIdRequest { - private PutLoanProductsProductIdRequest() { - } + + private PutLoanProductsProductIdRequest() {} @ApiModelProperty(example = "en_GB") public String locale; @@ -1087,12 +1087,12 @@ final class LoanProductsApiResourceSwagger { @ApiModel(value = "PutLoanProductsProductIdResponse") public final static class PutLoanProductsProductIdResponse { - private PutLoanProductsProductIdResponse() { - } + + private PutLoanProductsProductIdResponse() {} final class PutLoanChanges { - private PutLoanChanges() { - } + + private PutLoanChanges() {} @ApiModelProperty(example = "70,000.00") public Double principal; @@ -1105,4 +1105,3 @@ final class LoanProductsApiResourceSwagger { public PutLoanChanges changes; } } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanOverdueDTO.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanOverdueDTO.java old mode 100755 new mode 100644 index f97507b63..9fc96e0e8 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanOverdueDTO.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanOverdueDTO.java @@ -48,7 +48,6 @@ public class LoanOverdueDTO { return this.recalculateFrom; } - public LocalDate getLastChargeAppliedDate() { return this.lastChargeAppliedDate; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanProductData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanProductData.java index 12f74fc03..83e5ff1b7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanProductData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanProductData.java @@ -195,7 +195,7 @@ public class LoanProductData implements Serializable { /** * Used when returning lookup information about loan product for dropdowns. */ - public static LoanProductData lookup(final Long id, final String name, final Boolean multiDisburseLoan ) { + public static LoanProductData lookup(final Long id, final String name, final Boolean multiDisburseLoan) { final String shortName = null; final String description = null; final CurrencyData currency = null; @@ -269,21 +269,21 @@ public class LoanProductData implements Serializable { final boolean isEqualAmortization = false; final Collection rateOptions = null; final Collection rates = null; - final boolean isRatesEnabled= false; + final boolean isRatesEnabled = false; return new LoanProductData(id, name, shortName, description, currency, principal, minPrincipal, maxPrincipal, tolerance, numberOfRepayments, minNumberOfRepayments, maxNumberOfRepayments, repaymentEvery, interestRatePerPeriod, minInterestRatePerPeriod, maxInterestRatePerPeriod, annualInterestRate, repaymentFrequencyType, interestRateFrequencyType, amortizationType, interestType, interestCalculationPeriodType, allowPartialPeriodInterestCalcualtion, fundId, fundName, - transactionProcessingStrategyId, transactionProcessingStrategyName, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, - graceOnInterestCharged, charges, accountingType, includeInBorrowerCycle, useBorrowerCycle, startDate, closeDate, status, - externalId, principalVariations, interestRateVariations, numberOfRepaymentVariations, multiDisburseLoan, maxTrancheCount, - outstandingLoanBalance, graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, daysInYearType, - isInterestRecalculationEnabled, interestRecalculationData, minimumDaysBetweenDisbursalAndFirstRepayment, - holdGuaranteeFunds, productGuaranteeData, principalThresholdForLastInstallment, - accountMovesOutOfNPAOnlyOnArrearsCompletion, canDefineInstallmentAmount, installmentAmountInMultiplesOf, - loanProductConfigurableAttributes, isLinkedToFloatingInterestRates, floatingRateId, floatingRateName, - interestRateDifferential, minDifferentialLendingRate, defaultDifferentialLendingRate, maxDifferentialLendingRate, - isFloatingInterestRateCalculationAllowed, isVariableInstallmentsAllowed, minimumGap, maximumGap, + transactionProcessingStrategyId, transactionProcessingStrategyName, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, charges, accountingType, + includeInBorrowerCycle, useBorrowerCycle, startDate, closeDate, status, externalId, principalVariations, + interestRateVariations, numberOfRepaymentVariations, multiDisburseLoan, maxTrancheCount, outstandingLoanBalance, + graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, + interestRecalculationData, minimumDaysBetweenDisbursalAndFirstRepayment, holdGuaranteeFunds, productGuaranteeData, + principalThresholdForLastInstallment, accountMovesOutOfNPAOnlyOnArrearsCompletion, canDefineInstallmentAmount, + installmentAmountInMultiplesOf, loanProductConfigurableAttributes, isLinkedToFloatingInterestRates, floatingRateId, + floatingRateName, interestRateDifferential, minDifferentialLendingRate, defaultDifferentialLendingRate, + maxDifferentialLendingRate, isFloatingInterestRateCalculationAllowed, isVariableInstallmentsAllowed, minimumGap, maximumGap, syncExpectedWithDisbursementDate, canUseForTopup, isEqualAmortization, rateOptions, rates, isRatesEnabled); } @@ -370,16 +370,16 @@ public class LoanProductData implements Serializable { numberOfRepayments, minNumberOfRepayments, maxNumberOfRepayments, repaymentEvery, interestRatePerPeriod, minInterestRatePerPeriod, maxInterestRatePerPeriod, annualInterestRate, repaymentFrequencyType, interestRateFrequencyType, amortizationType, interestType, interestCalculationPeriodType, allowPartialPeriodInterestCalcualtion, fundId, fundName, - transactionProcessingStrategyId, transactionProcessingStrategyName, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, - graceOnInterestCharged, charges, accountingType, includeInBorrowerCycle, useBorrowerCycle, startDate, closeDate, status, - externalId, principalVariations, interestRateVariations, numberOfRepaymentVariations, multiDisburseLoan, maxTrancheCount, - outstandingLoanBalance, graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, daysInYearType, - isInterestRecalculationEnabled, interestRecalculationData, minimumDaysBetweenDisbursalAndFirstRepayment, - holdGuaranteeFunds, productGuaranteeData, principalThresholdForLastInstallment, - accountMovesOutOfNPAOnlyOnArrearsCompletion, canDefineInstallmentAmount, installmentAmountInMultiplesOf, - loanProductConfigurableAttributes, isLinkedToFloatingInterestRates, floatingRateId, floatingRateName, - interestRateDifferential, minDifferentialLendingRate, defaultDifferentialLendingRate, maxDifferentialLendingRate, - isFloatingInterestRateCalculationAllowed, isVariableInstallmentsAllowed, minimumGap, maximumGap, + transactionProcessingStrategyId, transactionProcessingStrategyName, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, charges, accountingType, + includeInBorrowerCycle, useBorrowerCycle, startDate, closeDate, status, externalId, principalVariations, + interestRateVariations, numberOfRepaymentVariations, multiDisburseLoan, maxTrancheCount, outstandingLoanBalance, + graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, + interestRecalculationData, minimumDaysBetweenDisbursalAndFirstRepayment, holdGuaranteeFunds, productGuaranteeData, + principalThresholdForLastInstallment, accountMovesOutOfNPAOnlyOnArrearsCompletion, canDefineInstallmentAmount, + installmentAmountInMultiplesOf, loanProductConfigurableAttributes, isLinkedToFloatingInterestRates, floatingRateId, + floatingRateName, interestRateDifferential, minDifferentialLendingRate, defaultDifferentialLendingRate, + maxDifferentialLendingRate, isFloatingInterestRateCalculationAllowed, isVariableInstallmentsAllowed, minimumGap, maximumGap, syncExpectedWithDisbursementDate, canUseForTopup, isEqualAmortization, rateOptions, rates, isRatesEnabled); } @@ -473,25 +473,26 @@ public class LoanProductData implements Serializable { numberOfRepayments, minNumberOfRepayments, maxNumberOfRepayments, repaymentEvery, interestRatePerPeriod, minInterestRatePerPeriod, maxInterestRatePerPeriod, annualInterestRate, repaymentFrequencyType, interestRateFrequencyType, amortizationType, interestType, interestCalculationPeriodType, allowPartialPeriodInterestCalcualtion, fundId, fundName, - transactionProcessingStrategyId, transactionProcessingStrategyName, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, - graceOnInterestCharged, charges, accountingType, includeInBorrowerCycle, useBorrowerCycle, startDate, closeDate, status, - externalId, principalVariationsForBorrowerCycle, interestRateVariationsForBorrowerCycle, - numberOfRepaymentVariationsForBorrowerCycle, multiDisburseLoan, maxTrancheCount, outstandingLoanBalance, - graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, - interestRecalculationData, minimumDaysBetweenDisbursalAndFirstRepayment, holdGuaranteeFunds, productGuaranteeData, - principalThresholdForLastInstallment, accountMovesOutOfNPAOnlyOnArrearsCompletion, canDefineInstallmentAmount, - installmentAmountInMultiplesOf, loanProductConfigurableAttributes, isLinkedToFloatingInterestRates, floatingRateId, - floatingRateName, interestRateDifferential, minDifferentialLendingRate, defaultDifferentialLendingRate, - maxDifferentialLendingRate, isFloatingInterestRateCalculationAllowed, isVariableInstallmentsAllowed, minimumGap, maximumGap, - syncExpectedWithDisbursementDate, canUseForTopup, isEqualAmortization, rateOptions, rates, isRatesEnabled); + transactionProcessingStrategyId, transactionProcessingStrategyName, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, charges, accountingType, + includeInBorrowerCycle, useBorrowerCycle, startDate, closeDate, status, externalId, principalVariationsForBorrowerCycle, + interestRateVariationsForBorrowerCycle, numberOfRepaymentVariationsForBorrowerCycle, multiDisburseLoan, maxTrancheCount, + outstandingLoanBalance, graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, daysInYearType, + isInterestRecalculationEnabled, interestRecalculationData, minimumDaysBetweenDisbursalAndFirstRepayment, holdGuaranteeFunds, + productGuaranteeData, principalThresholdForLastInstallment, accountMovesOutOfNPAOnlyOnArrearsCompletion, + canDefineInstallmentAmount, installmentAmountInMultiplesOf, loanProductConfigurableAttributes, + isLinkedToFloatingInterestRates, floatingRateId, floatingRateName, interestRateDifferential, minDifferentialLendingRate, + defaultDifferentialLendingRate, maxDifferentialLendingRate, isFloatingInterestRateCalculationAllowed, + isVariableInstallmentsAllowed, minimumGap, maximumGap, syncExpectedWithDisbursementDate, canUseForTopup, + isEqualAmortization, rateOptions, rates, isRatesEnabled); } public static LoanProductData loanProductWithFloatingRates(final Long id, final String name, - final boolean isLinkedToFloatingInterestRates, final Integer floatingRateId, final String floatingRateName, - final BigDecimal interestRateDifferential, final BigDecimal minDifferentialLendingRate, - final BigDecimal defaultDifferentialLendingRate, final BigDecimal maxDifferentialLendingRate, - final boolean isFloatingInterestRateCalculationAllowed) { + final boolean isLinkedToFloatingInterestRates, final Integer floatingRateId, final String floatingRateName, + final BigDecimal interestRateDifferential, final BigDecimal minDifferentialLendingRate, + final BigDecimal defaultDifferentialLendingRate, final BigDecimal maxDifferentialLendingRate, + final boolean isFloatingInterestRateCalculationAllowed) { final String shortName = null; final String description = null; final CurrencyData currency = CurrencyData.blank(); @@ -570,24 +571,25 @@ public class LoanProductData implements Serializable { numberOfRepayments, minNumberOfRepayments, maxNumberOfRepayments, repaymentEvery, interestRatePerPeriod, minInterestRatePerPeriod, maxInterestRatePerPeriod, annualInterestRate, repaymentFrequencyType, interestRateFrequencyType, amortizationType, interestType, interestCalculationPeriodType, allowPartialPeriodInterestCalcualtion, fundId, fundName, - transactionProcessingStrategyId, transactionProcessingStrategyName, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, - graceOnInterestCharged, charges, accountingType, includeInBorrowerCycle, useBorrowerCycle, startDate, closeDate, status, - externalId, principalVariationsForBorrowerCycle, interestRateVariationsForBorrowerCycle, - numberOfRepaymentVariationsForBorrowerCycle, multiDisburseLoan, maxTrancheCount, outstandingLoanBalance, - graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, - interestRecalculationData, minimumDaysBetweenDisbursalAndFirstRepayment, holdGuaranteeFunds, productGuaranteeData, - principalThresholdForLastInstallment, accountMovesOutOfNPAOnlyOnArrearsCompletion, canDefineInstallmentAmount, - installmentAmountInMultiplesOf, loanProductConfigurableAttributes, isLinkedToFloatingInterestRates, floatingRateId, - floatingRateName, interestRateDifferential, minDifferentialLendingRate, defaultDifferentialLendingRate, - maxDifferentialLendingRate, isFloatingInterestRateCalculationAllowed, isVariableInstallmentsAllowed, minimumGap, maximumGap, - syncExpectedWithDisbursementDate, canUseForTopup, isEqualAmortization, rateOptions, rates, isRatesEnabled); + transactionProcessingStrategyId, transactionProcessingStrategyName, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, charges, accountingType, + includeInBorrowerCycle, useBorrowerCycle, startDate, closeDate, status, externalId, principalVariationsForBorrowerCycle, + interestRateVariationsForBorrowerCycle, numberOfRepaymentVariationsForBorrowerCycle, multiDisburseLoan, maxTrancheCount, + outstandingLoanBalance, graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, daysInYearType, + isInterestRecalculationEnabled, interestRecalculationData, minimumDaysBetweenDisbursalAndFirstRepayment, holdGuaranteeFunds, + productGuaranteeData, principalThresholdForLastInstallment, accountMovesOutOfNPAOnlyOnArrearsCompletion, + canDefineInstallmentAmount, installmentAmountInMultiplesOf, loanProductConfigurableAttributes, + isLinkedToFloatingInterestRates, floatingRateId, floatingRateName, interestRateDifferential, minDifferentialLendingRate, + defaultDifferentialLendingRate, maxDifferentialLendingRate, isFloatingInterestRateCalculationAllowed, + isVariableInstallmentsAllowed, minimumGap, maximumGap, syncExpectedWithDisbursementDate, canUseForTopup, + isEqualAmortization, rateOptions, rates, isRatesEnabled); } public static LoanProductData withAccountingDetails(final LoanProductData productData, final Map accountingMappings, - final Collection paymentChannelToFundSourceMappings, - final Collection feeToGLAccountMappings, - final Collection penaltyToGLAccountMappings) { + final Collection paymentChannelToFundSourceMappings, + final Collection feeToGLAccountMappings, + final Collection penaltyToGLAccountMappings) { productData.accountingMappings = accountingMappings; productData.paymentChannelToFundSourceMappings = paymentChannelToFundSourceMappings; productData.feeToIncomeAccountMappings = feeToGLAccountMappings; @@ -596,31 +598,33 @@ public class LoanProductData implements Serializable { } public LoanProductData(final Long id, final String name, final String shortName, final String description, final CurrencyData currency, - final BigDecimal principal, final BigDecimal minPrincipal, final BigDecimal maxPrincipal, final BigDecimal tolerance, - final Integer numberOfRepayments, final Integer minNumberOfRepayments, final Integer maxNumberOfRepayments, - final Integer repaymentEvery, final BigDecimal interestRatePerPeriod, final BigDecimal minInterestRatePerPeriod, - final BigDecimal maxInterestRatePerPeriod, final BigDecimal annualInterestRate, final EnumOptionData repaymentFrequencyType, - final EnumOptionData interestRateFrequencyType, final EnumOptionData amortizationType, final EnumOptionData interestType, - final EnumOptionData interestCalculationPeriodType, final Boolean allowPartialPeriodInterestCalcualtion, final Long fundId, - final String fundName, final Long transactionProcessingStrategyId, final String transactionProcessingStrategyName, - final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, - final Collection charges, final EnumOptionData accountingType, final boolean includeInBorrowerCycle, boolean useBorrowerCycle, final LocalDate startDate, - final LocalDate closeDate, final String status, final String externalId, - Collection principalVariations, - Collection interestRateVariations, - Collection numberOfRepaymentVariations, Boolean multiDisburseLoan, - Integer maxTrancheCount, BigDecimal outstandingLoanBalance, final Integer graceOnArrearsAgeing, final Integer overdueDaysForNPA, - final EnumOptionData daysInMonthType, final EnumOptionData daysInYearType, final boolean isInterestRecalculationEnabled, final LoanProductInterestRecalculationData interestRecalculationData, - final Integer minimumDaysBetweenDisbursalAndFirstRepayment, boolean holdGuaranteeFunds, - final LoanProductGuaranteeData loanProductGuaranteeData, final BigDecimal principalThresholdForLastInstallment, - final boolean accountMovesOutOfNPAOnlyOnArrearsCompletion, boolean canDefineInstallmentAmount, - Integer installmentAmountInMultiplesOf, LoanProductConfigurableAttributes allowAttributeOverrides, - boolean isLinkedToFloatingInterestRates, Integer floatingRateId, String floatingRateName, BigDecimal interestRateDifferential, - BigDecimal minDifferentialLendingRate, BigDecimal defaultDifferentialLendingRate, BigDecimal maxDifferentialLendingRate, - boolean isFloatingInterestRateCalculationAllowed, final boolean isVariableInstallmentsAllowed, - final Integer minimumGapBetweenInstallments, final Integer maximumGapBetweenInstallments, - final boolean syncExpectedWithDisbursementDate, final boolean canUseForTopup, final boolean isEqualAmortization, Collection rateOptions, Collection rates, - final boolean isRatesEnabled) { + final BigDecimal principal, final BigDecimal minPrincipal, final BigDecimal maxPrincipal, final BigDecimal tolerance, + final Integer numberOfRepayments, final Integer minNumberOfRepayments, final Integer maxNumberOfRepayments, + final Integer repaymentEvery, final BigDecimal interestRatePerPeriod, final BigDecimal minInterestRatePerPeriod, + final BigDecimal maxInterestRatePerPeriod, final BigDecimal annualInterestRate, final EnumOptionData repaymentFrequencyType, + final EnumOptionData interestRateFrequencyType, final EnumOptionData amortizationType, final EnumOptionData interestType, + final EnumOptionData interestCalculationPeriodType, final Boolean allowPartialPeriodInterestCalcualtion, final Long fundId, + final String fundName, final Long transactionProcessingStrategyId, final String transactionProcessingStrategyName, + final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, + final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, final Collection charges, + final EnumOptionData accountingType, final boolean includeInBorrowerCycle, boolean useBorrowerCycle, final LocalDate startDate, + final LocalDate closeDate, final String status, final String externalId, + Collection principalVariations, + Collection interestRateVariations, + Collection numberOfRepaymentVariations, Boolean multiDisburseLoan, + Integer maxTrancheCount, BigDecimal outstandingLoanBalance, final Integer graceOnArrearsAgeing, final Integer overdueDaysForNPA, + final EnumOptionData daysInMonthType, final EnumOptionData daysInYearType, final boolean isInterestRecalculationEnabled, + final LoanProductInterestRecalculationData interestRecalculationData, + final Integer minimumDaysBetweenDisbursalAndFirstRepayment, boolean holdGuaranteeFunds, + final LoanProductGuaranteeData loanProductGuaranteeData, final BigDecimal principalThresholdForLastInstallment, + final boolean accountMovesOutOfNPAOnlyOnArrearsCompletion, boolean canDefineInstallmentAmount, + Integer installmentAmountInMultiplesOf, LoanProductConfigurableAttributes allowAttributeOverrides, + boolean isLinkedToFloatingInterestRates, Integer floatingRateId, String floatingRateName, BigDecimal interestRateDifferential, + BigDecimal minDifferentialLendingRate, BigDecimal defaultDifferentialLendingRate, BigDecimal maxDifferentialLendingRate, + boolean isFloatingInterestRateCalculationAllowed, final boolean isVariableInstallmentsAllowed, + final Integer minimumGapBetweenInstallments, final Integer maximumGapBetweenInstallments, + final boolean syncExpectedWithDisbursementDate, final boolean canUseForTopup, final boolean isEqualAmortization, + Collection rateOptions, Collection rates, final boolean isRatesEnabled) { this.id = id; this.name = name; this.shortName = shortName; @@ -732,18 +736,19 @@ public class LoanProductData implements Serializable { } public LoanProductData(final LoanProductData productData, final Collection chargeOptions, - final Collection penaltyOptions, final Collection paymentTypeOptions, - final Collection currencyOptions, final List amortizationTypeOptions, - final List interestTypeOptions, final List interestCalculationPeriodTypeOptions, - final List repaymentFrequencyTypeOptions, final List interestRateFrequencyTypeOptions, - final Collection fundOptions, final Collection transactionStrategyOptions, - final Collection rateOptions, final Map> accountingMappingOptions, final List accountingRuleOptions, - final List valueConditionTypeOptions, final List daysInMonthTypeOptions, - final List daysInYearTypeOptions, final List interestRecalculationCompoundingTypeOptions, - final List rescheduleStrategyTypeOptions, final List interestRecalculationFrequencyTypeOptions, - final List preCloseInterestCalculationStrategyOptions, final List floatingRateOptions, - final List interestRecalculationNthDayTypeOptions, - final List interestRecalculationDayOfWeekTypeOptions, final boolean isRatesEnabled) { + final Collection penaltyOptions, final Collection paymentTypeOptions, + final Collection currencyOptions, final List amortizationTypeOptions, + final List interestTypeOptions, final List interestCalculationPeriodTypeOptions, + final List repaymentFrequencyTypeOptions, final List interestRateFrequencyTypeOptions, + final Collection fundOptions, final Collection transactionStrategyOptions, + final Collection rateOptions, final Map> accountingMappingOptions, + final List accountingRuleOptions, final List valueConditionTypeOptions, + final List daysInMonthTypeOptions, final List daysInYearTypeOptions, + final List interestRecalculationCompoundingTypeOptions, + final List rescheduleStrategyTypeOptions, final List interestRecalculationFrequencyTypeOptions, + final List preCloseInterestCalculationStrategyOptions, final List floatingRateOptions, + final List interestRecalculationNthDayTypeOptions, + final List interestRecalculationDayOfWeekTypeOptions, final boolean isRatesEnabled) { this.id = productData.id; this.name = productData.name; this.shortName = productData.shortName; @@ -1024,9 +1029,7 @@ public class LoanProductData implements Serializable { @Override public boolean equals(final Object obj) { - if (!(obj instanceof LoanProductData)) { - return false; - } + if (!(obj instanceof LoanProductData)) { return false; } final LoanProductData loanProductData = (LoanProductData) obj; return loanProductData.id.equals(this.id); } @@ -1119,10 +1122,12 @@ public class LoanProductData implements Serializable { if (isInterestRecalculationEnabled()) { return this.interestRecalculationData.getRecalculationCompoundingFrequencyNthDay(); } return null; } + private EnumOptionData getInterestRecalculationCompoundingWeekDayType() { if (isInterestRecalculationEnabled()) { return this.interestRecalculationData.getRecalculationCompoundingFrequencyWeekday(); } return null; } + private Integer getInterestRecalculationCompoundingOnDayType() { if (isInterestRecalculationEnabled()) { return this.interestRecalculationData.getRecalculationCompoundingFrequencyOnDay(); } return null; @@ -1217,7 +1222,6 @@ public class LoanProductData implements Serializable { return this.maximumGap; } - public Boolean getAllowPartialPeriodInterestCalcualtion() { return this.allowPartialPeriodInterestCalcualtion; } @@ -1226,9 +1230,9 @@ public class LoanProductData implements Serializable { return syncExpectedWithDisbursementDate; } - public boolean canUseForTopup() { - return this.canUseForTopup; - } + public boolean canUseForTopup() { + return this.canUseForTopup; + } public BigDecimal getInterestRateDifferential() { return this.interestRateDifferential; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanProductInterestRecalculationData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanProductInterestRecalculationData.java index b90d35357..4fb5fa2b8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanProductInterestRecalculationData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/LoanProductInterestRecalculationData.java @@ -85,7 +85,8 @@ public class LoanProductInterestRecalculationData implements Serializable { public static LoanProductInterestRecalculationData sensibleDefaultsForNewLoanProductCreation() { final Long id = null; final Long productId = null; - final EnumOptionData interestRecalculationCompoundingType = interestRecalculationCompoundingType(InterestRecalculationCompoundingMethod.NONE); + final EnumOptionData interestRecalculationCompoundingType = interestRecalculationCompoundingType( + InterestRecalculationCompoundingMethod.NONE); final EnumOptionData rescheduleStrategyType = rescheduleStrategyType(LoanRescheduleStrategyMethod.REDUCE_EMI_AMOUNT); final EnumOptionData recalculationRestFrequencyType = null; final Integer recalculationRestFrequencyInterval = null; @@ -99,7 +100,8 @@ public class LoanProductInterestRecalculationData implements Serializable { final Integer recalculationCompoundingFrequencyOnDay = null; final boolean isArrearsBasedOnOriginalSchedule = false; final boolean isCompoundingToBePostedAsTransaction = false; - final EnumOptionData preCloseInterestCalculationStrategy = preCloseInterestCalculationStrategy(LoanPreClosureInterestCalculationStrategy.TILL_PRE_CLOSURE_DATE); + final EnumOptionData preCloseInterestCalculationStrategy = preCloseInterestCalculationStrategy( + LoanPreClosureInterestCalculationStrategy.TILL_PRE_CLOSURE_DATE); final boolean allowCompoundingOnEod = false; return new LoanProductInterestRecalculationData(id, productId, interestRecalculationCompoundingType, rescheduleStrategyType, recalculationRestFrequencyType, recalculationRestFrequencyInterval, recalculationRestFrequencyNthDay, @@ -137,12 +139,15 @@ public class LoanProductInterestRecalculationData implements Serializable { public EnumOptionData getRecalculationRestFrequencyNthDay() { return this.recalculationRestFrequencyNthDay; } + public EnumOptionData getRecalculationRestFrequencyWeekday() { return this.recalculationRestFrequencyWeekday; } + public Integer getRecalculationRestFrequencyOnDay() { return this.recalculationRestFrequencyOnDay; } + public EnumOptionData getRecalculationCompoundingFrequencyNthDay() { return this.recalculationCompoundingFrequencyNthDay; } @@ -150,12 +155,15 @@ public class LoanProductInterestRecalculationData implements Serializable { public EnumOptionData getRecalculationCompoundingFrequencyWeekday() { return this.recalculationCompoundingFrequencyWeekday; } + public Integer getRecalculationCompoundingFrequencyOnDay() { return this.recalculationCompoundingFrequencyOnDay; } + public boolean isCompoundingToBePostedAsTransaction() { return this.isCompoundingToBePostedAsTransaction; } + public boolean allowCompoundingOnEod() { return this.allowCompoundingOnEod; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/TransactionProcessingStrategyData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/TransactionProcessingStrategyData.java index 45f9dc94c..3f15fe8f8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/TransactionProcessingStrategyData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/data/TransactionProcessingStrategyData.java @@ -43,4 +43,4 @@ public final class TransactionProcessingStrategyData implements Serializable { public String name() { return this.name; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/AmortizationMethod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/AmortizationMethod.java index 122a223c7..30a9f8008 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/AmortizationMethod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/AmortizationMethod.java @@ -19,6 +19,7 @@ package org.apache.fineract.portfolio.loanproduct.domain; public enum AmortizationMethod { + EQUAL_PRINCIPAL(0, "amortizationType.equal.principal"), // EQUAL_INSTALLMENTS(1, "amortizationType.equal.installments"), // INVALID(2, "amortizationType.invalid"); @@ -65,4 +66,4 @@ public enum AmortizationMethod { public boolean isEqualPrincipal() { return this.value.equals(AmortizationMethod.EQUAL_PRINCIPAL.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestCalculationPeriodMethod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestCalculationPeriodMethod.java index 60c15bdcc..df814ee17 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestCalculationPeriodMethod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestCalculationPeriodMethod.java @@ -19,6 +19,7 @@ package org.apache.fineract.portfolio.loanproduct.domain; public enum InterestCalculationPeriodMethod { + DAILY(0, "interestCalculationPeriodType.daily"), // SAME_AS_REPAYMENT_PERIOD(1, "interestCalculationPeriodType.same.as.repayment.period"), // INVALID(2, "interestCalculationPeriodType.invalid"); @@ -60,4 +61,4 @@ public enum InterestCalculationPeriodMethod { return this.value.equals(InterestCalculationPeriodMethod.DAILY.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestMethod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestMethod.java index 118ed6dd6..6728ab964 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestMethod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestMethod.java @@ -18,8 +18,8 @@ */ package org.apache.fineract.portfolio.loanproduct.domain; - public enum InterestMethod { + DECLINING_BALANCE(0, "interestType.declining.balance"), FLAT(1, "interestType.flat"), INVALID(2, "interestType.invalid"); private final Integer value; @@ -58,4 +58,4 @@ public enum InterestMethod { public boolean isDecliningBalnce() { return this.value.equals(InterestMethod.DECLINING_BALANCE.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestRecalculationPeriodMethod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestRecalculationPeriodMethod.java index 9a63ee467..5e522789b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestRecalculationPeriodMethod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/InterestRecalculationPeriodMethod.java @@ -35,6 +35,7 @@ import java.util.Map; */ public enum InterestRecalculationPeriodMethod { + INVALID(0, "interestRecalculationPeriodMethod.invalid"), // DAILY(1, "interestRecalculationPeriodMethod.daily"), // WEEKLY(2, "interestRecalculationPeriodMethod.weekly"), // diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProduct.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProduct.java index a7d44da8f..b7b925e4f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProduct.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProduct.java @@ -133,7 +133,7 @@ public class LoanProduct extends AbstractPersistableCustom { @Column(name = "external_id", length = 100, nullable = true, unique = true) private String externalId; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loanProduct", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loanProduct", orphanRemoval = true, fetch = FetchType.EAGER) private Set borrowerCycleVariations = new HashSet<>(); @Column(name = "overdue_days_for_npa", nullable = true) @@ -142,13 +142,13 @@ public class LoanProduct extends AbstractPersistableCustom { @Column(name = "min_days_between_disbursal_and_first_repayment", nullable = true) private Integer minimumDaysBetweenDisbursalAndFirstRepayment; - @OneToOne(cascade = CascadeType.ALL, mappedBy = "loanProduct", optional = true, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToOne(cascade = CascadeType.ALL, mappedBy = "loanProduct", optional = true, orphanRemoval = true, fetch = FetchType.EAGER) private LoanProductInterestRecalculationDetails productInterestRecalculationDetails; @Column(name = "hold_guarantee_funds") private boolean holdGuaranteeFunds; - @OneToOne(cascade = CascadeType.ALL, mappedBy = "loanProduct", optional = true, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToOne(cascade = CascadeType.ALL, mappedBy = "loanProduct", optional = true, orphanRemoval = true, fetch = FetchType.EAGER) private LoanProductGuaranteeDetails loanProductGuaranteeDetails; @OneToOne(cascade = CascadeType.ALL, mappedBy = "loanProduct", optional = true, orphanRemoval = true) @@ -169,19 +169,18 @@ public class LoanProduct extends AbstractPersistableCustom { @Column(name = "is_linked_to_floating_interest_rates", nullable = false) private boolean isLinkedToFloatingInterestRate; - @OneToOne(cascade = CascadeType.ALL, mappedBy = "loanProduct", optional = true, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToOne(cascade = CascadeType.ALL, mappedBy = "loanProduct", optional = true, orphanRemoval = true, fetch = FetchType.EAGER) private LoanProductFloatingRates floatingRates; @Column(name = "allow_variabe_installments", nullable = false) private boolean allowVariabeInstallments; - @OneToOne(cascade = CascadeType.ALL, mappedBy = "loanProduct", optional = true, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToOne(cascade = CascadeType.ALL, mappedBy = "loanProduct", optional = true, orphanRemoval = true, fetch = FetchType.EAGER) private LoanProductVariableInstallmentConfig variableInstallmentConfig; @Column(name = "sync_expected_with_disbursement_date") private boolean syncExpectedWithDisbursementDate; - @Column(name = "can_use_for_topup", nullable = false) private boolean canUseForTopup = false; @@ -205,13 +204,13 @@ public class LoanProduct extends AbstractPersistableCustom { final BigDecimal maxPrincipal = command.bigDecimalValueOfParameterNamed("maxPrincipal"); final InterestMethod interestMethod = InterestMethod.fromInt(command.integerValueOfParameterNamed("interestType")); - final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.fromInt(command - .integerValueOfParameterNamed("interestCalculationPeriodType")); + final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod + .fromInt(command.integerValueOfParameterNamed("interestCalculationPeriodType")); final boolean allowPartialPeriodInterestCalcualtion = command .booleanPrimitiveValueOfParameterNamed(LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME); final AmortizationMethod amortizationMethod = AmortizationMethod.fromInt(command.integerValueOfParameterNamed("amortizationType")); - final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.fromInt(command - .integerValueOfParameterNamed("repaymentFrequencyType")); + final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType + .fromInt(command.integerValueOfParameterNamed("repaymentFrequencyType")); PeriodFrequencyType interestFrequencyType = PeriodFrequencyType.INVALID; BigDecimal interestRatePerPeriod = null; BigDecimal minInterestRatePerPeriod = null; @@ -226,7 +225,6 @@ public class LoanProduct extends AbstractPersistableCustom { Integer minimumGapBetweenInstallments = null; Integer maximumGapBetweenInstallments = null; - final Integer repaymentEvery = command.integerValueOfParameterNamed("repaymentEvery"); final Integer numberOfRepayments = command.integerValueOfParameterNamed("numberOfRepayments"); final Boolean isLinkedToFloatingInterestRates = command.booleanObjectValueOfParameterNamed("isLinkedToFloatingInterestRates"); @@ -242,7 +240,8 @@ public class LoanProduct extends AbstractPersistableCustom { interestRatePerPeriod = command.bigDecimalValueOfParameterNamed("interestRatePerPeriod"); minInterestRatePerPeriod = command.bigDecimalValueOfParameterNamed("minInterestRatePerPeriod"); maxInterestRatePerPeriod = command.bigDecimalValueOfParameterNamed("maxInterestRatePerPeriod"); - annualInterestRate = aprCalculator.calculateFrom(interestFrequencyType, interestRatePerPeriod, numberOfRepayments, repaymentEvery, repaymentFrequencyType); + annualInterestRate = aprCalculator.calculateFrom(interestFrequencyType, interestRatePerPeriod, numberOfRepayments, + repaymentEvery, repaymentFrequencyType); } @@ -272,7 +271,8 @@ public class LoanProduct extends AbstractPersistableCustom { final LocalDate closeDate = command.localDateValueOfParameterNamed("closeDate"); final String externalId = command.stringValueOfParameterNamedAllowingNull("externalId"); - final boolean useBorrowerCycle = command.booleanPrimitiveValueOfParameterNamed(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME); + final boolean useBorrowerCycle = command + .booleanPrimitiveValueOfParameterNamed(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME); final Set loanProductBorrowerCycleVariations = new HashSet<>(); if (useBorrowerCycle) { @@ -288,18 +288,19 @@ public class LoanProduct extends AbstractPersistableCustom { maxTrancheCount = command.integerValueOfParameterNamed(LoanProductConstants.MAX_TRANCHE_COUNT_PARAMETER_NAME); } - final Integer graceOnArrearsAgeing = command.integerValueOfParameterNamed(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME); + final Integer graceOnArrearsAgeing = command + .integerValueOfParameterNamed(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME); final Integer overdueDaysForNPA = command.integerValueOfParameterNamed(LoanProductConstants.OVERDUE_DAYS_FOR_NPA_PARAMETER_NAME); // Interest recalculation settings final boolean isInterestRecalculationEnabled = command .booleanPrimitiveValueOfParameterNamed(LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME); - final DaysInMonthType daysInMonthType = DaysInMonthType.fromInt(command - .integerValueOfParameterNamed(LoanProductConstants.DAYS_IN_YEAR_TYPE_PARAMETER_NAME)); + final DaysInMonthType daysInMonthType = DaysInMonthType + .fromInt(command.integerValueOfParameterNamed(LoanProductConstants.DAYS_IN_YEAR_TYPE_PARAMETER_NAME)); - final DaysInYearType daysInYearType = DaysInYearType.fromInt(command - .integerValueOfParameterNamed(LoanProductConstants.DAYS_IN_YEAR_TYPE_PARAMETER_NAME)); + final DaysInYearType daysInYearType = DaysInYearType + .fromInt(command.integerValueOfParameterNamed(LoanProductConstants.DAYS_IN_YEAR_TYPE_PARAMETER_NAME)); LoanProductInterestRecalculationDetails interestRecalculationSettings = null; @@ -324,7 +325,8 @@ public class LoanProduct extends AbstractPersistableCustom { .bigDecimalValueOfParameterNamed(LoanProductConstants.principalThresholdForLastInstallmentParamName); if (principalThresholdForLastInstallment == null) { - principalThresholdForLastInstallment = multiDisburseLoan ? LoanProductConstants.DEFAULT_PRINCIPAL_THRESHOLD_FOR_MULTI_DISBURSE_LOAN + principalThresholdForLastInstallment = multiDisburseLoan + ? LoanProductConstants.DEFAULT_PRINCIPAL_THRESHOLD_FOR_MULTI_DISBURSE_LOAN : LoanProductConstants.DEFAULT_PRINCIPAL_THRESHOLD_FOR_SINGLE_DISBURSE_LOAN; } final boolean accountMovesOutOfNPAOnlyOnArrearsCompletion = command @@ -335,28 +337,29 @@ public class LoanProduct extends AbstractPersistableCustom { final boolean syncExpectedWithDisbursementDate = command.booleanPrimitiveValueOfParameterNamed("syncExpectedWithDisbursementDate"); - final boolean canUseForTopup = command.parameterExists(LoanProductConstants.CAN_USE_FOR_TOPUP) ? command.booleanPrimitiveValueOfParameterNamed(LoanProductConstants.CAN_USE_FOR_TOPUP) : false; - final boolean isEqualAmortization = command.parameterExists(LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM) ? command - .booleanPrimitiveValueOfParameterNamed(LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM) : false; + final boolean isEqualAmortization = command.parameterExists(LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM) + ? command.booleanPrimitiveValueOfParameterNamed(LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM) + : false; return new LoanProduct(fund, loanTransactionProcessingStrategy, name, shortName, description, currency, principal, minPrincipal, maxPrincipal, interestRatePerPeriod, minInterestRatePerPeriod, maxInterestRatePerPeriod, interestFrequencyType, annualInterestRate, interestMethod, interestCalculationPeriodMethod, allowPartialPeriodInterestCalcualtion, repaymentEvery, - repaymentFrequencyType, numberOfRepayments, minNumberOfRepayments, maxNumberOfRepayments, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, - graceOnInterestPayment, graceOnInterestCharged, amortizationMethod, inArrearsTolerance, productCharges, accountingRuleType, - includeInBorrowerCycle, startDate, closeDate, externalId, useBorrowerCycle, loanProductBorrowerCycleVariations, - multiDisburseLoan, maxTrancheCount, outstandingLoanBalance, graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, - daysInYearType, isInterestRecalculationEnabled, interestRecalculationSettings, - minimumDaysBetweenDisbursalAndFirstRepayment, holdGuarantorFunds, loanProductGuaranteeDetails, - principalThresholdForLastInstallment, accountMovesOutOfNPAOnlyOnArrearsCompletion, canDefineEmiAmount, - installmentAmountInMultiplesOf, loanConfigurableAttributes, isLinkedToFloatingInterestRates, floatingRate, - interestRateDifferential, minDifferentialLendingRate, maxDifferentialLendingRate, defaultDifferentialLendingRate, - isFloatingInterestRateCalculationAllowed, isVariableInstallmentsAllowed, minimumGapBetweenInstallments, - maximumGapBetweenInstallments, syncExpectedWithDisbursementDate, canUseForTopup, isEqualAmortization, productRates); + repaymentFrequencyType, numberOfRepayments, minNumberOfRepayments, maxNumberOfRepayments, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, amortizationMethod, + inArrearsTolerance, productCharges, accountingRuleType, includeInBorrowerCycle, startDate, closeDate, externalId, + useBorrowerCycle, loanProductBorrowerCycleVariations, multiDisburseLoan, maxTrancheCount, outstandingLoanBalance, + graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, + interestRecalculationSettings, minimumDaysBetweenDisbursalAndFirstRepayment, holdGuarantorFunds, + loanProductGuaranteeDetails, principalThresholdForLastInstallment, accountMovesOutOfNPAOnlyOnArrearsCompletion, + canDefineEmiAmount, installmentAmountInMultiplesOf, loanConfigurableAttributes, isLinkedToFloatingInterestRates, + floatingRate, interestRateDifferential, minDifferentialLendingRate, maxDifferentialLendingRate, + defaultDifferentialLendingRate, isFloatingInterestRateCalculationAllowed, isVariableInstallmentsAllowed, + minimumGapBetweenInstallments, maximumGapBetweenInstallments, syncExpectedWithDisbursementDate, canUseForTopup, + isEqualAmortization, productRates); } @@ -448,7 +451,8 @@ public class LoanProduct extends AbstractPersistableCustom { } if (jsonObject.has(LoanProductConstants.VALUE_CONDITION_TYPE_PARAM_NAME) && jsonObject.get(LoanProductConstants.VALUE_CONDITION_TYPE_PARAM_NAME).isJsonPrimitive()) { - valueUsageCondition = jsonObject.getAsJsonPrimitive(LoanProductConstants.VALUE_CONDITION_TYPE_PARAM_NAME).getAsInt(); + valueUsageCondition = jsonObject.getAsJsonPrimitive(LoanProductConstants.VALUE_CONDITION_TYPE_PARAM_NAME) + .getAsInt(); } LoanProductBorrowerCycleVariations borrowerCycleVariations = new LoanProductBorrowerCycleVariations(cycleNumber, paramType, valueUsageCondition, minValue, maxValue, defaultValue); @@ -516,11 +520,12 @@ public class LoanProduct extends AbstractPersistableCustom { } if (jsonObject.has(LoanProductConstants.VALUE_CONDITION_TYPE_PARAM_NAME) && jsonObject.get(LoanProductConstants.VALUE_CONDITION_TYPE_PARAM_NAME).isJsonPrimitive()) { - valueUsageCondition = jsonObject.getAsJsonPrimitive(LoanProductConstants.VALUE_CONDITION_TYPE_PARAM_NAME).getAsInt(); + valueUsageCondition = jsonObject.getAsJsonPrimitive(LoanProductConstants.VALUE_CONDITION_TYPE_PARAM_NAME) + .getAsInt(); } if (jsonObject.has(LoanProductConstants.BORROWER_CYCLE_ID_PARAMETER_NAME) - && jsonObject.get(LoanProductConstants.BORROWER_CYCLE_ID_PARAMETER_NAME).isJsonPrimitive() - && StringUtils.isNotBlank(jsonObject.get(LoanProductConstants.BORROWER_CYCLE_ID_PARAMETER_NAME).getAsString())) { + && jsonObject.get(LoanProductConstants.BORROWER_CYCLE_ID_PARAMETER_NAME).isJsonPrimitive() && StringUtils + .isNotBlank(jsonObject.get(LoanProductConstants.BORROWER_CYCLE_ID_PARAMETER_NAME).getAsString())) { id = jsonObject.getAsJsonPrimitive(LoanProductConstants.BORROWER_CYCLE_ID_PARAMETER_NAME).getAsLong(); } LoanProductBorrowerCycleVariations borrowerCycleVariations = new LoanProductBorrowerCycleVariations(cycleNumber, @@ -571,12 +576,14 @@ public class LoanProduct extends AbstractPersistableCustom { final InterestCalculationPeriodMethod interestCalculationPeriodMethod, final boolean considerPartialPeriodInterest, final Integer repayEvery, final PeriodFrequencyType repaymentFrequencyType, final Integer defaultNumberOfInstallments, final Integer defaultMinNumberOfInstallments, final Integer defaultMaxNumberOfInstallments, - final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, - final AmortizationMethod amortizationMethod, final BigDecimal inArrearsTolerance, final List charges, final AccountingRuleType accountingRuleType, - final boolean includeInBorrowerCycle, final LocalDate startDate, final LocalDate closeDate, final String externalId, final boolean useBorrowerCycle, - final Set loanProductBorrowerCycleVariations, final boolean multiDisburseLoan, final Integer maxTrancheCount, final BigDecimal outstandingLoanBalance, - final Integer graceOnArrearsAgeing, final Integer overdueDaysForNPA, final DaysInMonthType daysInMonthType, final DaysInYearType daysInYearType, - final boolean isInterestRecalculationEnabled, + final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, + final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, final AmortizationMethod amortizationMethod, + final BigDecimal inArrearsTolerance, final List charges, final AccountingRuleType accountingRuleType, + final boolean includeInBorrowerCycle, final LocalDate startDate, final LocalDate closeDate, final String externalId, + final boolean useBorrowerCycle, final Set loanProductBorrowerCycleVariations, + final boolean multiDisburseLoan, final Integer maxTrancheCount, final BigDecimal outstandingLoanBalance, + final Integer graceOnArrearsAgeing, final Integer overdueDaysForNPA, final DaysInMonthType daysInMonthType, + final DaysInYearType daysInYearType, final boolean isInterestRecalculationEnabled, final LoanProductInterestRecalculationDetails productInterestRecalculationDetails, final Integer minimumDaysBetweenDisbursalAndFirstRepayment, final boolean holdGuarantorFunds, final LoanProductGuaranteeDetails loanProductGuaranteeDetails, final BigDecimal principalThresholdForLastInstallment, @@ -586,7 +593,8 @@ public class LoanProduct extends AbstractPersistableCustom { BigDecimal minDifferentialLendingRate, BigDecimal maxDifferentialLendingRate, BigDecimal defaultDifferentialLendingRate, Boolean isFloatingInterestRateCalculationAllowed, final Boolean isVariableInstallmentsAllowed, final Integer minimumGapBetweenInstallments, final Integer maximumGapBetweenInstallments, - final boolean syncExpectedWithDisbursementDate, final boolean canUseForTopup, final boolean isEqualAmortization, final List rates) { + final boolean syncExpectedWithDisbursementDate, final boolean canUseForTopup, final boolean isEqualAmortization, + final List rates) { this.fund = fund; this.transactionProcessingStrategy = transactionProcessingStrategy; this.name = name.trim(); @@ -616,9 +624,10 @@ public class LoanProduct extends AbstractPersistableCustom { this.loanProductRelatedDetail = new LoanProductRelatedDetail(currency, defaultPrincipal, defaultNominalInterestRatePerPeriod, interestPeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, - considerPartialPeriodInterest, repayEvery, repaymentFrequencyType, defaultNumberOfInstallments, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, - graceOnInterestPayment, graceOnInterestCharged, amortizationMethod, inArrearsTolerance, graceOnArrearsAgeing, - daysInMonthType.getValue(), daysInYearType.getValue(), isInterestRecalculationEnabled, isEqualAmortization); + considerPartialPeriodInterest, repayEvery, repaymentFrequencyType, defaultNumberOfInstallments, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, amortizationMethod, + inArrearsTolerance, graceOnArrearsAgeing, daysInMonthType.getValue(), daysInYearType.getValue(), + isInterestRecalculationEnabled, isEqualAmortization); this.loanProductRelatedDetail.validateRepaymentPeriodWithGraceSettings(); @@ -660,12 +669,11 @@ public class LoanProduct extends AbstractPersistableCustom { this.accountMovesOutOfNPAOnlyOnArrearsCompletion = accountMovesOutOfNPAOnlyOnArrearsCompletion; this.canDefineInstallmentAmount = canDefineEmiAmount; this.installmentAmountInMultiplesOf = installmentAmountInMultiplesOf; - this.syncExpectedWithDisbursementDate = - syncExpectedWithDisbursementDate; + this.syncExpectedWithDisbursementDate = syncExpectedWithDisbursementDate; this.canUseForTopup = canUseForTopup; this.isEqualAmortization = isEqualAmortization; - if(rates != null){ + if (rates != null) { this.rates = rates; } } @@ -764,7 +772,8 @@ public class LoanProduct extends AbstractPersistableCustom { this.floatingRates = null; } - if (command.isChangeInBooleanParameterNamed(LoanProductConstants.allowVariableInstallmentsParamName, this.allowVariabeInstallments)) { + if (command.isChangeInBooleanParameterNamed(LoanProductConstants.allowVariableInstallmentsParamName, + this.allowVariabeInstallments)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(LoanProductConstants.allowVariableInstallmentsParamName); actualChanges.put(LoanProductConstants.allowVariableInstallmentsParamName, newValue); this.allowVariabeInstallments = newValue; @@ -910,8 +919,7 @@ public class LoanProduct extends AbstractPersistableCustom { this.minimumDaysBetweenDisbursalAndFirstRepayment = newValue; } - if(command.isChangeInBooleanParameterNamed("syncExpectedWithDisbursementDate" - , this.syncExpectedWithDisbursementDate)){ + if (command.isChangeInBooleanParameterNamed("syncExpectedWithDisbursementDate", this.syncExpectedWithDisbursementDate)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed("syncExpectedWithDisbursementDate"); actualChanges.put("syncExpectedWithDisbursementDate", newValue); this.syncExpectedWithDisbursementDate = newValue; @@ -948,71 +956,72 @@ public class LoanProduct extends AbstractPersistableCustom { final String configurableAttributesChanges = LoanProductConstants.allowAttributeOverridesParamName; if (command.hasParameter(configurableAttributesChanges)) { - if (!command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName).isJsonNull()) { + if (!command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) + .isJsonNull()) { actualChanges.put(configurableAttributesChanges, command.jsonFragment(configurableAttributesChanges)); if (command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.amortizationTypeParamName).getAsBoolean() != this.loanConfigurableAttributes - .getAmortizationBoolean()) { - this.loanConfigurableAttributes.setAmortizationType(command.parsedJson().getAsJsonObject() - .getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.amortizationTypeParamName).getAsBoolean()); + .getAsJsonPrimitive(LoanProductConstants.amortizationTypeParamName) + .getAsBoolean() != this.loanConfigurableAttributes.getAmortizationBoolean()) { + this.loanConfigurableAttributes.setAmortizationType( + command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) + .getAsJsonPrimitive(LoanProductConstants.amortizationTypeParamName).getAsBoolean()); } if (command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.interestTypeParamName).getAsBoolean() != this.loanConfigurableAttributes - .getInterestMethodBoolean()) { - this.loanConfigurableAttributes.setInterestType(command.parsedJson().getAsJsonObject() - .getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.interestTypeParamName).getAsBoolean()); + .getAsJsonPrimitive(LoanProductConstants.interestTypeParamName) + .getAsBoolean() != this.loanConfigurableAttributes.getInterestMethodBoolean()) { + this.loanConfigurableAttributes.setInterestType( + command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) + .getAsJsonPrimitive(LoanProductConstants.interestTypeParamName).getAsBoolean()); } if (command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.transactionProcessingStrategyIdParamName).getAsBoolean() != this.loanConfigurableAttributes - .getTransactionProcessingStrategyBoolean()) { - this.loanConfigurableAttributes.setTransactionProcessingStrategyId(command.parsedJson().getAsJsonObject() - .getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.transactionProcessingStrategyIdParamName).getAsBoolean()); + .getAsJsonPrimitive(LoanProductConstants.transactionProcessingStrategyIdParamName) + .getAsBoolean() != this.loanConfigurableAttributes.getTransactionProcessingStrategyBoolean()) { + this.loanConfigurableAttributes.setTransactionProcessingStrategyId( + command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) + .getAsJsonPrimitive(LoanProductConstants.transactionProcessingStrategyIdParamName).getAsBoolean()); } if (command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.interestCalculationPeriodTypeParamName).getAsBoolean() != this.loanConfigurableAttributes - .getInterestCalcPeriodBoolean()) { - this.loanConfigurableAttributes.setInterestCalculationPeriodType(command.parsedJson().getAsJsonObject() - .getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.interestCalculationPeriodTypeParamName).getAsBoolean()); + .getAsJsonPrimitive(LoanProductConstants.interestCalculationPeriodTypeParamName) + .getAsBoolean() != this.loanConfigurableAttributes.getInterestCalcPeriodBoolean()) { + this.loanConfigurableAttributes.setInterestCalculationPeriodType( + command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) + .getAsJsonPrimitive(LoanProductConstants.interestCalculationPeriodTypeParamName).getAsBoolean()); } if (command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.inArrearsToleranceParamName).getAsBoolean() != this.loanConfigurableAttributes - .getArrearsToleranceBoolean()) { - this.loanConfigurableAttributes.setInArrearsTolerance(command.parsedJson().getAsJsonObject() - .getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.inArrearsToleranceParamName).getAsBoolean()); + .getAsJsonPrimitive(LoanProductConstants.inArrearsToleranceParamName) + .getAsBoolean() != this.loanConfigurableAttributes.getArrearsToleranceBoolean()) { + this.loanConfigurableAttributes.setInArrearsTolerance( + command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) + .getAsJsonPrimitive(LoanProductConstants.inArrearsToleranceParamName).getAsBoolean()); } if (command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.repaymentEveryParamName).getAsBoolean() != this.loanConfigurableAttributes - .getRepaymentEveryBoolean()) { - this.loanConfigurableAttributes.setRepaymentEvery(command.parsedJson().getAsJsonObject() - .getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.repaymentEveryParamName).getAsBoolean()); + .getAsJsonPrimitive(LoanProductConstants.repaymentEveryParamName) + .getAsBoolean() != this.loanConfigurableAttributes.getRepaymentEveryBoolean()) { + this.loanConfigurableAttributes.setRepaymentEvery( + command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) + .getAsJsonPrimitive(LoanProductConstants.repaymentEveryParamName).getAsBoolean()); } if (command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.graceOnPrincipalAndInterestPaymentParamName).getAsBoolean() != this.loanConfigurableAttributes - .getGraceOnPrincipalAndInterestPaymentBoolean()) { - this.loanConfigurableAttributes.setGraceOnPrincipalAndInterestPayment(command.parsedJson().getAsJsonObject() - .getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.graceOnPrincipalAndInterestPaymentParamName).getAsBoolean()); + .getAsJsonPrimitive(LoanProductConstants.graceOnPrincipalAndInterestPaymentParamName) + .getAsBoolean() != this.loanConfigurableAttributes.getGraceOnPrincipalAndInterestPaymentBoolean()) { + this.loanConfigurableAttributes.setGraceOnPrincipalAndInterestPayment( + command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) + .getAsJsonPrimitive(LoanProductConstants.graceOnPrincipalAndInterestPaymentParamName).getAsBoolean()); } if (command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME).getAsBoolean() != this.loanConfigurableAttributes - .getGraceOnArrearsAgingBoolean()) { - this.loanConfigurableAttributes.setGraceOnArrearsAgeing(command.parsedJson().getAsJsonObject() - .getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) - .getAsJsonPrimitive(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME).getAsBoolean()); + .getAsJsonPrimitive(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME) + .getAsBoolean() != this.loanConfigurableAttributes.getGraceOnArrearsAgingBoolean()) { + this.loanConfigurableAttributes.setGraceOnArrearsAgeing( + command.parsedJson().getAsJsonObject().getAsJsonObject(LoanProductConstants.allowAttributeOverridesParamName) + .getAsJsonPrimitive(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME).getAsBoolean()); } } else { this.loanConfigurableAttributes = LoanProductConfigurableAttributes.populateDefaultsForConfigurableAttributes(); @@ -1047,8 +1056,8 @@ public class LoanProduct extends AbstractPersistableCustom { } if (command.isChangeInBooleanParameterNamed(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, this.accountMovesOutOfNPAOnlyOnArrearsCompletion)) { - final boolean newValue = command - .booleanPrimitiveValueOfParameterNamed(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME); + final boolean newValue = command.booleanPrimitiveValueOfParameterNamed( + LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME); actualChanges.put(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, newValue); this.accountMovesOutOfNPAOnlyOnArrearsCompletion = newValue; } @@ -1158,8 +1167,9 @@ public class LoanProduct extends AbstractPersistableCustom { // If all min and max fields are null then loanProductMinMaxConstraints // initialising to null // Reset LoanProductMinMaxConstraints with null values. - this.loanProductMinMaxConstraints = this.loanProductMinMaxConstraints == null ? new LoanProductMinMaxConstraints(null, null, null, - null, null, null) : this.loanProductMinMaxConstraints; + this.loanProductMinMaxConstraints = this.loanProductMinMaxConstraints == null + ? new LoanProductMinMaxConstraints(null, null, null, null, null, null) + : this.loanProductMinMaxConstraints; return this.loanProductMinMaxConstraints; } @@ -1283,7 +1293,8 @@ public class LoanProduct extends AbstractPersistableCustom { interestCycleUsed = cycleVariation.getBorrowerCycleNumber(); break; case REPAYMENT: - borrowerCycleVariations.put(LoanProductConstants.MAX_INTEREST_RATE_PER_PERIOD, cycleVariation.getDefaultValue()); + borrowerCycleVariations.put(LoanProductConstants.MAX_INTEREST_RATE_PER_PERIOD, + cycleVariation.getDefaultValue()); borrowerCycleVariations.put(LoanProductConstants.MIN_NUMBER_OF_REPAYMENTS, cycleVariation.getMinValue()); borrowerCycleVariations.put(LoanProductConstants.MAX_NUMBER_OF_REPAYMENTS, cycleVariation.getMaxValue()); repaymentCycleUsed = cycleVariation.getBorrowerCycleNumber(); @@ -1304,15 +1315,19 @@ public class LoanProduct extends AbstractPersistableCustom { break; case INTERESTRATE: if (interestCycleUsed < cycleVariation.getBorrowerCycleNumber()) { - borrowerCycleVariations.put(LoanProductConstants.INTEREST_RATE_PER_PERIOD, cycleVariation.getDefaultValue()); - borrowerCycleVariations.put(LoanProductConstants.MIN_INTEREST_RATE_PER_PERIOD, cycleVariation.getMinValue()); - borrowerCycleVariations.put(LoanProductConstants.MAX_INTEREST_RATE_PER_PERIOD, cycleVariation.getMaxValue()); + borrowerCycleVariations.put(LoanProductConstants.INTEREST_RATE_PER_PERIOD, + cycleVariation.getDefaultValue()); + borrowerCycleVariations.put(LoanProductConstants.MIN_INTEREST_RATE_PER_PERIOD, + cycleVariation.getMinValue()); + borrowerCycleVariations.put(LoanProductConstants.MAX_INTEREST_RATE_PER_PERIOD, + cycleVariation.getMaxValue()); interestCycleUsed = cycleVariation.getBorrowerCycleNumber(); } break; case REPAYMENT: if (repaymentCycleUsed < cycleVariation.getBorrowerCycleNumber()) { - borrowerCycleVariations.put(LoanProductConstants.MAX_INTEREST_RATE_PER_PERIOD, cycleVariation.getDefaultValue()); + borrowerCycleVariations.put(LoanProductConstants.MAX_INTEREST_RATE_PER_PERIOD, + cycleVariation.getDefaultValue()); borrowerCycleVariations.put(LoanProductConstants.MIN_NUMBER_OF_REPAYMENTS, cycleVariation.getMinValue()); borrowerCycleVariations.put(LoanProductConstants.MAX_NUMBER_OF_REPAYMENTS, cycleVariation.getMaxValue()); repaymentCycleUsed = cycleVariation.getBorrowerCycleNumber(); @@ -1403,7 +1418,7 @@ public class LoanProduct extends AbstractPersistableCustom { return this.allowVariabeInstallments; } - public boolean canUseForTopup(){ + public boolean canUseForTopup() { return this.canUseForTopup; } @@ -1415,7 +1430,6 @@ public class LoanProduct extends AbstractPersistableCustom { this.isEqualAmortization = isEqualAmortization; } - public List getRates() { return rates; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductBorrowerCycleVariations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductBorrowerCycleVariations.java old mode 100755 new mode 100644 index de5de01e2..42b9dc57b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductBorrowerCycleVariations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductBorrowerCycleVariations.java @@ -53,8 +53,7 @@ public class LoanProductBorrowerCycleVariations extends AbstractPersistableCusto @Column(name = "default_value", scale = 6, precision = 19, nullable = false) private BigDecimal defaultValue; - protected LoanProductBorrowerCycleVariations() { - } + protected LoanProductBorrowerCycleVariations() {} public LoanProductBorrowerCycleVariations(final Integer borrowerCycleNumber, final Integer paramType, final Integer valueConditionType, final BigDecimal minValue, final BigDecimal maxValue, final BigDecimal defaultValue) { @@ -80,17 +79,12 @@ public class LoanProductBorrowerCycleVariations extends AbstractPersistableCusto @Override public boolean equals(final Object obj) { - if (!(obj instanceof LoanProductBorrowerCycleVariations)) { - return false; - } + if (!(obj instanceof LoanProductBorrowerCycleVariations)) { return false; } final LoanProductBorrowerCycleVariations other = (LoanProductBorrowerCycleVariations) obj; - return Objects.equals(loanProduct, other.loanProduct) - && Objects.equals(borrowerCycleNumber, other.borrowerCycleNumber) - && Objects.equals(paramType, other.paramType) - && Objects.equals(valueConditionType, other.valueConditionType) - && Objects.equals(minValue, other.minValue) - && Objects.equals(maxValue, other.maxValue) - && Objects.equals(defaultValue, other.defaultValue); + return Objects.equals(loanProduct, other.loanProduct) && Objects.equals(borrowerCycleNumber, other.borrowerCycleNumber) + && Objects.equals(paramType, other.paramType) && Objects.equals(valueConditionType, other.valueConditionType) + && Objects.equals(minValue, other.minValue) && Objects.equals(maxValue, other.maxValue) + && Objects.equals(defaultValue, other.defaultValue); } @Override diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductConfigurableAttributes.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductConfigurableAttributes.java index 24b0a9dff..f231c6213 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductConfigurableAttributes.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductConfigurableAttributes.java @@ -61,12 +61,11 @@ public class LoanProductConfigurableAttributes extends AbstractPersistableCustom @Column(name = "grace_on_arrears_ageing", nullable = true) private Boolean graceOnArrearsAgeing; - private static final String[] supportedloanConfigurableAttributes = {LoanProductConstants.amortizationTypeParamName, + private static final String[] supportedloanConfigurableAttributes = { LoanProductConstants.amortizationTypeParamName, LoanProductConstants.interestTypeParamName, LoanProductConstants.transactionProcessingStrategyIdParamName, - LoanProductConstants.interestCalculationPeriodTypeParamName, - LoanProductConstants.inArrearsToleranceParamName, LoanProductConstants.repaymentEveryParamName, - LoanProductConstants.graceOnPrincipalAndInterestPaymentParamName, - LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME}; + LoanProductConstants.interestCalculationPeriodTypeParamName, LoanProductConstants.inArrearsToleranceParamName, + LoanProductConstants.repaymentEveryParamName, LoanProductConstants.graceOnPrincipalAndInterestPaymentParamName, + LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME }; public static LoanProductConfigurableAttributes createFrom(JsonCommand command) { @@ -212,29 +211,24 @@ public class LoanProductConfigurableAttributes extends AbstractPersistableCustom @Override public boolean equals(Object o) { - if (this == o) { - return true; - } + if (this == o) { return true; } - if (!(o instanceof LoanProductConfigurableAttributes)) { - return false; - } + if (!(o instanceof LoanProductConfigurableAttributes)) { return false; } LoanProductConfigurableAttributes that = (LoanProductConfigurableAttributes) o; - return Objects.equals(loanProduct, that.loanProduct) && - Objects.equals(amortizationType, that.amortizationType) && - Objects.equals(interestType, that.interestType) && - Objects.equals(transactionProcessingStrategyId, that.transactionProcessingStrategyId) && - Objects.equals(interestCalculationPeriodType, that.interestCalculationPeriodType) && - Objects.equals(inArrearsTolerance, that.inArrearsTolerance) && - Objects.equals(repaymentEvery, that.repaymentEvery) && - Objects.equals(graceOnPrincipalAndInterestPayment, that.graceOnPrincipalAndInterestPayment) && - Objects.equals(graceOnArrearsAgeing, that.graceOnArrearsAgeing); + return Objects.equals(loanProduct, that.loanProduct) && Objects.equals(amortizationType, that.amortizationType) + && Objects.equals(interestType, that.interestType) + && Objects.equals(transactionProcessingStrategyId, that.transactionProcessingStrategyId) + && Objects.equals(interestCalculationPeriodType, that.interestCalculationPeriodType) + && Objects.equals(inArrearsTolerance, that.inArrearsTolerance) && Objects.equals(repaymentEvery, that.repaymentEvery) + && Objects.equals(graceOnPrincipalAndInterestPayment, that.graceOnPrincipalAndInterestPayment) + && Objects.equals(graceOnArrearsAgeing, that.graceOnArrearsAgeing); } @Override public int hashCode() { - return Objects.hash(loanProduct, amortizationType, interestType, transactionProcessingStrategyId, interestCalculationPeriodType, inArrearsTolerance, repaymentEvery, graceOnPrincipalAndInterestPayment, graceOnArrearsAgeing); + return Objects.hash(loanProduct, amortizationType, interestType, transactionProcessingStrategyId, interestCalculationPeriodType, + inArrearsTolerance, repaymentEvery, graceOnPrincipalAndInterestPayment, graceOnArrearsAgeing); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductFloatingRates.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductFloatingRates.java index cb430d366..aaccf253f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductFloatingRates.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductFloatingRates.java @@ -61,12 +61,13 @@ public class LoanProductFloatingRates extends AbstractPersistableCustom { @Column(name = "is_floating_interest_rate_calculation_allowed", nullable = false) private boolean isFloatingInterestRateCalculationAllowed; - public LoanProductFloatingRates(){ + public LoanProductFloatingRates() { } + public LoanProductFloatingRates(FloatingRate floatingRate, LoanProduct loanProduct, BigDecimal interestRateDifferential, BigDecimal minDifferentialLendingRate, BigDecimal maxDifferentialLendingRate, BigDecimal defaultDifferentialLendingRate, - boolean isFloatingInterestRateCalculationAllowed){ + boolean isFloatingInterestRateCalculationAllowed) { this.floatingRate = floatingRate; this.loanProduct = loanProduct; this.interestRateDifferential = interestRateDifferential; @@ -140,8 +141,8 @@ public class LoanProductFloatingRates extends AbstractPersistableCustom { this.maxDifferentialLendingRate = newValue; } final String isFloatingInterestRateCalculationAllowed = "isFloatingInterestRateCalculationAllowed"; - if (command - .isChangeInBooleanParameterNamed(isFloatingInterestRateCalculationAllowed, this.isFloatingInterestRateCalculationAllowed)) { + if (command.isChangeInBooleanParameterNamed(isFloatingInterestRateCalculationAllowed, + this.isFloatingInterestRateCalculationAllowed)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(isFloatingInterestRateCalculationAllowed); actualChanges.put(isFloatingInterestRateCalculationAllowed, newValue); this.isFloatingInterestRateCalculationAllowed = newValue; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductInterestRecalculationDetails.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductInterestRecalculationDetails.java index c3088c1c7..cdfa4dae7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductInterestRecalculationDetails.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductInterestRecalculationDetails.java @@ -102,11 +102,12 @@ public class LoanProductInterestRecalculationDetails extends AbstractPersistable public static LoanProductInterestRecalculationDetails createFrom(final JsonCommand command) { - final Integer interestRecalculationCompoundingMethod = InterestRecalculationCompoundingMethod.fromInt( - command.integerValueOfParameterNamed(LoanProductConstants.interestRecalculationCompoundingMethodParameterName)).getValue(); + final Integer interestRecalculationCompoundingMethod = InterestRecalculationCompoundingMethod + .fromInt(command.integerValueOfParameterNamed(LoanProductConstants.interestRecalculationCompoundingMethodParameterName)) + .getValue(); - final Integer loanRescheduleStrategyMethod = LoanRescheduleStrategyMethod.fromInt( - command.integerValueOfParameterNamed(LoanProductConstants.rescheduleStrategyMethodParameterName)).getValue(); + final Integer loanRescheduleStrategyMethod = LoanRescheduleStrategyMethod + .fromInt(command.integerValueOfParameterNamed(LoanProductConstants.rescheduleStrategyMethodParameterName)).getValue(); final Integer recurrenceFrequency = command .integerValueOfParameterNamed(LoanProductConstants.recalculationRestFrequencyTypeParameterName); @@ -148,8 +149,7 @@ public class LoanProductInterestRecalculationDetails extends AbstractPersistable compoundingRecurrenceOnWeekday = command .integerValueOfParameterNamed(LoanProductConstants.recalculationCompoundingFrequencyWeekdayParamName); if (!compoundingFrequencyType.isDaily()) { - allowCompoundingOnEod = command - .booleanPrimitiveValueOfParameterNamed(LoanProductConstants.allowCompoundingOnEodParamName); + allowCompoundingOnEod = command.booleanPrimitiveValueOfParameterNamed(LoanProductConstants.allowCompoundingOnEodParamName); } } @@ -278,7 +278,7 @@ public class LoanProductInterestRecalculationDetails extends AbstractPersistable this.restFrequencyNthDay = null; this.restFrequencyOnDay = null; } else if (frequencyType.isMonthly()) { - if(command.integerValueOfParameterNamed(LoanProductConstants.recalculationRestFrequencyOnDayParamName) != null) { + if (command.integerValueOfParameterNamed(LoanProductConstants.recalculationRestFrequencyOnDayParamName) != null) { this.restFrequencyNthDay = null; this.restFrequencyWeekday = null; } else { @@ -350,7 +350,8 @@ public class LoanProductInterestRecalculationDetails extends AbstractPersistable this.compoundingFrequencyNthDay = null; this.compoundingFrequencyOnDay = null; } else if (compoundingfrequencyType.isMonthly()) { - if(command.integerValueOfParameterNamed(LoanProductConstants.recalculationCompoundingFrequencyOnDayParamName) != null) { + if (command + .integerValueOfParameterNamed(LoanProductConstants.recalculationCompoundingFrequencyOnDayParamName) != null) { this.compoundingFrequencyNthDay = null; this.compoundingFrequencyWeekday = null; } else { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductMinMaxConstraints.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductMinMaxConstraints.java index 1e8ece97b..fa8d6deec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductMinMaxConstraints.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductMinMaxConstraints.java @@ -112,8 +112,8 @@ public class LoanProductMinMaxConstraints { } final String minInterestRatePerPeriodParamName = "minInterestRatePerPeriod"; - if (command - .isChangeInBigDecimalParameterNamedWithNullCheck(minInterestRatePerPeriodParamName, this.minNominalInterestRatePerPeriod)) { + if (command.isChangeInBigDecimalParameterNamedWithNullCheck(minInterestRatePerPeriodParamName, + this.minNominalInterestRatePerPeriod)) { final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(minInterestRatePerPeriodParamName); actualChanges.put(minInterestRatePerPeriodParamName, newValue); actualChanges.put("locale", localeAsInput); @@ -121,8 +121,8 @@ public class LoanProductMinMaxConstraints { } final String maxInterestRatePerPeriodParamName = "maxInterestRatePerPeriod"; - if (command - .isChangeInBigDecimalParameterNamedWithNullCheck(maxInterestRatePerPeriodParamName, this.maxNominalInterestRatePerPeriod)) { + if (command.isChangeInBigDecimalParameterNamedWithNullCheck(maxInterestRatePerPeriodParamName, + this.maxNominalInterestRatePerPeriod)) { final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(maxInterestRatePerPeriodParamName); actualChanges.put(maxInterestRatePerPeriodParamName, newValue); actualChanges.put("locale", localeAsInput); @@ -141,13 +141,13 @@ public class LoanProductMinMaxConstraints { } public BigDecimal getMinNominalInterestRatePerPeriod() { - return this.minNominalInterestRatePerPeriod == null ? null : BigDecimal.valueOf(Double.valueOf(this.minNominalInterestRatePerPeriod - .stripTrailingZeros().toString())); + return this.minNominalInterestRatePerPeriod == null ? null + : BigDecimal.valueOf(Double.valueOf(this.minNominalInterestRatePerPeriod.stripTrailingZeros().toString())); } public BigDecimal getMaxNominalInterestRatePerPeriod() { - return this.maxNominalInterestRatePerPeriod == null ? null : BigDecimal.valueOf(Double.valueOf(this.maxNominalInterestRatePerPeriod - .stripTrailingZeros().toString())); + return this.maxNominalInterestRatePerPeriod == null ? null + : BigDecimal.valueOf(Double.valueOf(this.maxNominalInterestRatePerPeriod.stripTrailingZeros().toString())); } public Integer getMinNumberOfRepayments() { @@ -163,7 +163,6 @@ public class LoanProductMinMaxConstraints { this.maxNominalInterestRatePerPeriod = null; } - public void setMinNominalInterestRatePerPeriod(BigDecimal minNominalInterestRatePerPeriod) { this.minNominalInterestRatePerPeriod = minNominalInterestRatePerPeriod; } @@ -171,4 +170,4 @@ public class LoanProductMinMaxConstraints { public void setMaxNominalInterestRatePerPeriod(BigDecimal maxNominalInterestRatePerPeriod) { this.maxNominalInterestRatePerPeriod = maxNominalInterestRatePerPeriod; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductParamType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductParamType.java old mode 100755 new mode 100644 index d9146bd59..dd403917f --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductParamType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductParamType.java @@ -74,4 +74,4 @@ public enum LoanProductParamType { return LoanProductParamType.REPAYMENT.getValue().equals(this.value); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductRelatedDetail.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductRelatedDetail.java index a9877693d..9f334225e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductRelatedDetail.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductRelatedDetail.java @@ -134,15 +134,17 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche final BigDecimal nominalAnnualInterestRate, final InterestMethod interestMethod, final InterestCalculationPeriodMethod interestCalculationPeriodMethod, final boolean allowPartialPeriodInterestCalcualtion, final Integer repaymentEvery, final PeriodFrequencyType repaymentPeriodFrequencyType, final Integer numberOfRepayments, - final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, - final AmortizationMethod amortizationMethod, final BigDecimal inArrearsTolerance, final Integer graceOnArrearsAgeing, - final Integer daysInMonthType, final Integer daysInYearType, final boolean isInterestRecalculationEnabled, final boolean isEqualAmortization) { + final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, + final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, final AmortizationMethod amortizationMethod, + final BigDecimal inArrearsTolerance, final Integer graceOnArrearsAgeing, final Integer daysInMonthType, + final Integer daysInYearType, final boolean isInterestRecalculationEnabled, final boolean isEqualAmortization) { return new LoanProductRelatedDetail(currency, principal, nominalInterestRatePerPeriod, interestRatePeriodFrequencyType, nominalAnnualInterestRate, interestMethod, interestCalculationPeriodMethod, allowPartialPeriodInterestCalcualtion, - repaymentEvery, repaymentPeriodFrequencyType, numberOfRepayments, graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, - graceOnInterestCharged, amortizationMethod, inArrearsTolerance, graceOnArrearsAgeing, daysInMonthType, daysInYearType, - isInterestRecalculationEnabled, isEqualAmortization); + repaymentEvery, repaymentPeriodFrequencyType, numberOfRepayments, graceOnPrincipalPayment, + recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, amortizationMethod, + inArrearsTolerance, graceOnArrearsAgeing, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, + isEqualAmortization); } protected LoanProductRelatedDetail() { @@ -154,9 +156,10 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche final BigDecimal defaultAnnualNominalInterestRate, final InterestMethod interestMethod, final InterestCalculationPeriodMethod interestCalculationPeriodMethod, final boolean allowPartialPeriodInterestCalcualtion, final Integer repayEvery, final PeriodFrequencyType repaymentFrequencyType, final Integer defaultNumberOfRepayments, - final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, - final AmortizationMethod amortizationMethod, final BigDecimal inArrearsTolerance, final Integer graceOnArrearsAgeing, - final Integer daysInMonthType, final Integer daysInYearType, final boolean isInterestRecalculationEnabled, final boolean isEqualAmortization) { + final Integer graceOnPrincipalPayment, final Integer recurringMoratoriumOnPrincipalPeriods, + final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, final AmortizationMethod amortizationMethod, + final BigDecimal inArrearsTolerance, final Integer graceOnArrearsAgeing, final Integer daysInMonthType, + final Integer daysInYearType, final boolean isInterestRecalculationEnabled, final boolean isEqualAmortization) { this.currency = currency; this.principal = defaultPrincipal; this.nominalInterestRatePerPeriod = defaultNominalInterestRatePerPeriod; @@ -234,8 +237,8 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche @Override public BigDecimal getNominalInterestRatePerPeriod() { - return this.nominalInterestRatePerPeriod == null ? null : BigDecimal.valueOf(Double.valueOf(this.nominalInterestRatePerPeriod - .stripTrailingZeros().toString())); + return this.nominalInterestRatePerPeriod == null ? null + : BigDecimal.valueOf(Double.valueOf(this.nominalInterestRatePerPeriod.stripTrailingZeros().toString())); } @Override @@ -245,8 +248,8 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche @Override public BigDecimal getAnnualNominalInterestRate() { - return this.annualNominalInterestRate == null ? null : BigDecimal.valueOf(Double.valueOf(this.annualNominalInterestRate - .stripTrailingZeros().toString())); + return this.annualNominalInterestRate == null ? null + : BigDecimal.valueOf(Double.valueOf(this.annualNominalInterestRate.stripTrailingZeros().toString())); } @Override @@ -349,17 +352,17 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche actualChanges.put("locale", localeAsInput); this.repaymentPeriodFrequencyType = PeriodFrequencyType.fromInt(newValue); } - if (this.repaymentPeriodFrequencyType == PeriodFrequencyType.MONTHS) { + if (this.repaymentPeriodFrequencyType == PeriodFrequencyType.MONTHS) { Integer newValue = null; - final String repaymentFrequencyNthDayTypeParamName = "repaymentFrequencyNthDayType"; - newValue = command.integerValueOfParameterNamed(repaymentFrequencyNthDayTypeParamName); - actualChanges.put(repaymentFrequencyNthDayTypeParamName, newValue); + final String repaymentFrequencyNthDayTypeParamName = "repaymentFrequencyNthDayType"; + newValue = command.integerValueOfParameterNamed(repaymentFrequencyNthDayTypeParamName); + actualChanges.put(repaymentFrequencyNthDayTypeParamName, newValue); - final String repaymentFrequencyDayOfWeekTypeParamName = "repaymentFrequencyDayOfWeekType"; - newValue = command.integerValueOfParameterNamed(repaymentFrequencyDayOfWeekTypeParamName); - actualChanges.put(repaymentFrequencyDayOfWeekTypeParamName, newValue); + final String repaymentFrequencyDayOfWeekTypeParamName = "repaymentFrequencyDayOfWeekType"; + newValue = command.integerValueOfParameterNamed(repaymentFrequencyDayOfWeekTypeParamName); + actualChanges.put(repaymentFrequencyDayOfWeekTypeParamName, newValue); - actualChanges.put("locale", localeAsInput); + actualChanges.put("locale", localeAsInput); } final String numberOfRepaymentsParamName = "numberOfRepayments"; @@ -415,8 +418,8 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche } final String interestCalculationPeriodTypeParamName = "interestCalculationPeriodType"; - if (command - .isChangeInIntegerParameterNamed(interestCalculationPeriodTypeParamName, this.interestCalculationPeriodMethod.getValue())) { + if (command.isChangeInIntegerParameterNamed(interestCalculationPeriodTypeParamName, + this.interestCalculationPeriodMethod.getValue())) { final Integer newValue = command.integerValueOfParameterNamed(interestCalculationPeriodTypeParamName); actualChanges.put(interestCalculationPeriodTypeParamName, newValue); actualChanges.put("locale", localeAsInput); @@ -444,7 +447,8 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche } final String recurringMoratoriumOnPrincipalPeriodsParamName = "recurringMoratoriumOnPrincipalPeriods"; - if (command.isChangeInIntegerParameterNamed(recurringMoratoriumOnPrincipalPeriodsParamName, this.recurringMoratoriumOnPrincipalPeriods)) { + if (command.isChangeInIntegerParameterNamed(recurringMoratoriumOnPrincipalPeriodsParamName, + this.recurringMoratoriumOnPrincipalPeriods)) { final Integer newValue = command.integerValueOfParameterNamed(recurringMoratoriumOnPrincipalPeriodsParamName); actualChanges.put(recurringMoratoriumOnPrincipalPeriodsParamName, newValue); actualChanges.put("locale", localeAsInput); @@ -467,7 +471,8 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche this.graceOnInterestCharged = newValue; } - if (command.isChangeInIntegerParameterNamed(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, this.graceOnArrearsAgeing)) { + if (command.isChangeInIntegerParameterNamed(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, + this.graceOnArrearsAgeing)) { final Integer newValue = command.integerValueOfParameterNamed(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME); actualChanges.put(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, newValue); actualChanges.put("locale", localeAsInput); @@ -508,7 +513,7 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche } public void updateCurrency(final MonetaryCurrency currency) { - this.currency = currency ; + this.currency = currency; } public void validateRepaymentPeriodWithGraceSettings() { @@ -539,11 +544,9 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche recurMoratoriumOnPrincipal = this.recurringMoratoriumOnPrincipalPeriods().intValue(); } - if ( ( recurMoratoriumOnPrincipal > 0 ) - && ( (this.numberOfRepayments - graceOnPrincipal) % ( recurMoratoriumOnPrincipal + 1) != 1) ) { + if ((recurMoratoriumOnPrincipal > 0) && ((this.numberOfRepayments - graceOnPrincipal) % (recurMoratoriumOnPrincipal + 1) != 1)) { baseDataValidator.reset().parameter("graceOnPrincipalPayments.and.recurringMoratoriumOnPrincipalPeriods") - .value(graceOnPrincipal) - .value(recurMoratoriumOnPrincipal) + .value(graceOnPrincipal).value(recurMoratoriumOnPrincipal) .failWithCode("causes.principal.moratorium.for.last.installment"); } @@ -559,7 +562,8 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche } private void updateInterestRateDerivedFields(final AprCalculator aprCalculator) { - this.annualNominalInterestRate = aprCalculator.calculateFrom(this.interestPeriodFrequencyType, this.nominalInterestRatePerPeriod, this.numberOfRepayments, this.repayEvery, this.repaymentPeriodFrequencyType); + this.annualNominalInterestRate = aprCalculator.calculateFrom(this.interestPeriodFrequencyType, this.nominalInterestRatePerPeriod, + this.numberOfRepayments, this.repayEvery, this.repaymentPeriodFrequencyType); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductRepository.java index cba8f8e50..143802d33 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductRepository.java @@ -28,4 +28,4 @@ public interface LoanProductRepository extends JpaRepository, @Query("select loanProduct from LoanProduct loanProduct, IN(loanProduct.charges) charge where charge.id = :chargeId") List retrieveLoanProductsByChargeId(@Param("chargeId") Long chargeId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductTrancheDetails.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductTrancheDetails.java index e95fd0f0c..3db3f43d8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductTrancheDetails.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductTrancheDetails.java @@ -41,7 +41,8 @@ public class LoanProductTrancheDetails { // TODO Auto-generated constructor stub } - public LoanProductTrancheDetails(final boolean multiDisburseLoan, final Integer maxTrancheCount, final BigDecimal outstandingLoanBalance) { + public LoanProductTrancheDetails(final boolean multiDisburseLoan, final Integer maxTrancheCount, + final BigDecimal outstandingLoanBalance) { this.multiDisburseLoan = multiDisburseLoan; this.maxTrancheCount = maxTrancheCount; this.outstandingLoanBalance = outstandingLoanBalance; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductValueConditionType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductValueConditionType.java old mode 100755 new mode 100644 index 5c701a944..5ff421386 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductValueConditionType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanProductValueConditionType.java @@ -67,4 +67,4 @@ public enum LoanProductValueConditionType { return LoanProductValueConditionType.GREATERTHAN.getValue().equals(this.value); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanRescheduleStrategyMethod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanRescheduleStrategyMethod.java index a74a26b1c..1ac347758 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanRescheduleStrategyMethod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanRescheduleStrategyMethod.java @@ -22,8 +22,8 @@ import java.util.HashMap; import java.util.Map; /*** - * * People typically use either of the following settings when defining interest - * recalculation method: + * * People typically use either of the following settings when defining + * interest recalculation method: *

      *
    • RESCHEDULE_NEXT_REPAYMENTS
    • *
    • REDUCE_NUMBER_OF_INSTALLMENTS
    • diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanTransactionProcessingStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanTransactionProcessingStrategy.java index f5c3168bc..606770ef5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanTransactionProcessingStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/LoanTransactionProcessingStrategy.java @@ -35,7 +35,9 @@ public class LoanTransactionProcessingStrategy extends AbstractPersistableCustom private String name; @Column(name = "sort_order") - private Integer sortOrder ; //Don't change this name as this property name is used as sort order while retrieving this objects + private Integer sortOrder; // Don't change this name as this property name + // is used as sort order while retrieving this + // objects protected LoanTransactionProcessingStrategy() { // @@ -72,4 +74,4 @@ public class LoanTransactionProcessingStrategy extends AbstractPersistableCustom public boolean isInterestPrincipalPenaltiesFeesOrderStrategy() { return "interest-principal-penalties-fees-order-strategy".equalsIgnoreCase(this.code); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/RecalculationFrequencyType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/RecalculationFrequencyType.java index 6c505c362..6984d0bde 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/RecalculationFrequencyType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/domain/RecalculationFrequencyType.java @@ -23,6 +23,7 @@ import java.util.Map; import org.apache.fineract.portfolio.common.domain.PeriodFrequencyType; public enum RecalculationFrequencyType { + INVALID(0, "interestRecalculationFrequencyType.invalid"), // SAME_AS_REPAYMENT_PERIOD(1, "interestRecalculationFrequencyType.same.as.repayment.period"), // DAILY(2, "interestRecalculationFrequencyType.daily"), // diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/InvalidCurrencyException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/InvalidCurrencyException.java index 545f41d01..b81b6cb16 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/InvalidCurrencyException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/InvalidCurrencyException.java @@ -30,4 +30,4 @@ public class InvalidCurrencyException extends AbstractPlatformDomainRuleExceptio final Object... defaultUserMessageArgs) { super("error.msg." + entity + "." + postFix + ".invalid.currency", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/InvalidLendingStrategy.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/InvalidLendingStrategy.java index 7d4853d10..38fae3f6b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/InvalidLendingStrategy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/InvalidLendingStrategy.java @@ -29,4 +29,4 @@ public class InvalidLendingStrategy extends AbstractPlatformDomainRuleException public InvalidLendingStrategy(final Integer strategyId) { super("error.msg.unsupported.lending.strategy", "Stratagy code [" + strategyId + "] passed is not valid."); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/LoanProductCannotBeModifiedDueToNonClosedLoansException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/LoanProductCannotBeModifiedDueToNonClosedLoansException.java index 67b5cc201..f0bb5574f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/LoanProductCannotBeModifiedDueToNonClosedLoansException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/LoanProductCannotBeModifiedDueToNonClosedLoansException.java @@ -20,7 +20,8 @@ package org.apache.fineract.portfolio.loanproduct.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; -public class LoanProductCannotBeModifiedDueToNonClosedLoansException extends AbstractPlatformDomainRuleException { +public class LoanProductCannotBeModifiedDueToNonClosedLoansException extends AbstractPlatformDomainRuleException { + public LoanProductCannotBeModifiedDueToNonClosedLoansException(final Long id) { super("error.msg.loanproduct.not.modifiable.due.to.non.closed.loans", "Loan product with identifier " + id + " cannot be modified due to non closed loans associated with it.", id); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/LoanProductNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/LoanProductNotFoundException.java index 94830378c..aa004c128 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/LoanProductNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/LoanProductNotFoundException.java @@ -28,4 +28,4 @@ public class LoanProductNotFoundException extends AbstractPlatformResourceNotFou public LoanProductNotFoundException(final Long id) { super("error.msg.loanproduct.id.invalid", "Loan product with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/NotInMinMaxRangeException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/NotInMinMaxRangeException.java index 528853be1..5569d705c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/NotInMinMaxRangeException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/exception/NotInMinMaxRangeException.java @@ -31,4 +31,4 @@ public class NotInMinMaxRangeException extends AbstractPlatformDomainRuleExcepti final Object... defaultUserMessageArgs) { super("validation.msg." + entity + "." + postFix + ".is.not.within.min.max.range", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/handler/CreateLoanProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/handler/CreateLoanProductCommandHandler.java index 0561ceff6..72d6dbd17 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/handler/CreateLoanProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/handler/CreateLoanProductCommandHandler.java @@ -44,4 +44,4 @@ public class CreateLoanProductCommandHandler implements NewCommandSourceHandler return this.writePlatformService.createLoanProduct(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/handler/UpdateLoanProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/handler/UpdateLoanProductCommandHandler.java index 9cafd8ee1..3f7a39c28 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/handler/UpdateLoanProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/handler/UpdateLoanProductCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateLoanProductCommandHandler implements NewCommandSourceHandler return this.writePlatformService.updateLoanProduct(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/api/ProductMixApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/api/ProductMixApiResource.java index be624589a..4eb8094d7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/api/ProductMixApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/api/ProductMixApiResource.java @@ -56,8 +56,8 @@ public class ProductMixApiResource { private final String resourceNameForPermissions = "PRODUCTMIX"; - private final Set PRODUCT_MIX_DATA_PARAMETERS = new HashSet<>(Arrays.asList("productId", "productName", - "restrictedProducts", "allowedProducts", "productOptions")); + private final Set PRODUCT_MIX_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("productId", "productName", "restrictedProducts", "allowedProducts", "productOptions")); private final PlatformSecurityContext context; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @@ -70,8 +70,7 @@ public class ProductMixApiResource { @Autowired public ProductMixApiResource(final PlatformSecurityContext context, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final ApiRequestParameterHelper apiRequestParameterHelper, - final DefaultToApiJsonSerializer toApiJsonSerializer, + final ApiRequestParameterHelper apiRequestParameterHelper, final DefaultToApiJsonSerializer toApiJsonSerializer, final ProductMixReadPlatformService productMixReadPlatformService, final LoanProductReadPlatformService loanProductReadPlatformService) { this.context = context; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/data/ProductMixData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/data/ProductMixData.java index 6c1bdfb52..88d9bc576 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/data/ProductMixData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/data/ProductMixData.java @@ -43,7 +43,8 @@ public class ProductMixData { return new ProductMixData(null, null, null, null, productOptions); } - public static ProductMixData withTemplateOptions(final ProductMixData productMixData, final Collection productOptions) { + public static ProductMixData withTemplateOptions(final ProductMixData productMixData, + final Collection productOptions) { return new ProductMixData(productMixData.productId, productMixData.productName, productMixData.restrictedProducts, productMixData.allowedProducts, productOptions); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/serialization/ProductMixDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/serialization/ProductMixDataValidator.java index 32eedbce6..45d83ff41 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/serialization/ProductMixDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/serialization/ProductMixDataValidator.java @@ -78,8 +78,10 @@ public final class ProductMixDataValidator { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForUpdate(final String json) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/service/ProductMixWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/service/ProductMixWritePlatformServiceJpaRepositoryImpl.java index c318f2798..7e7bd125d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/service/ProductMixWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/productmix/service/ProductMixWritePlatformServiceJpaRepositoryImpl.java @@ -171,8 +171,7 @@ public class ProductMixWritePlatformServiceJpaRepositoryImpl implements ProductM } private LoanProduct findByProductIdIfProvided(final Long productId) { - return this.productRepository.findById(productId) - .orElseThrow(() -> new LoanProductNotFoundException(productId)); + return this.productRepository.findById(productId).orElseThrow(() -> new LoanProductNotFoundException(productId)); } private Map getRestrictedProducts(final Set restrictedIds) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/serialization/LoanProductDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/serialization/LoanProductDataValidator.java old mode 100755 new mode 100644 index bc3870908..235a853d3 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/serialization/LoanProductDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/serialization/LoanProductDataValidator.java @@ -64,11 +64,12 @@ public final class LoanProductDataValidator { "currencyCode", "digitsAfterDecimal", "inMultiplesOf", "principal", "minPrincipal", "maxPrincipal", "repaymentEvery", "numberOfRepayments", "minNumberOfRepayments", "maxNumberOfRepayments", "repaymentFrequencyType", "interestRatePerPeriod", "minInterestRatePerPeriod", "maxInterestRatePerPeriod", "interestRateFrequencyType", "amortizationType", "interestType", - "interestCalculationPeriodType", LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, "inArrearsTolerance", - "transactionProcessingStrategyId", "graceOnPrincipalPayment", "recurringMoratoriumOnPrincipalPeriods", "graceOnInterestPayment", "graceOnInterestCharged", "charges", - "accountingRule", "includeInBorrowerCycle", "startDate", "closeDate", "externalId", "isLinkedToFloatingInterestRates", - "floatingRatesId", "interestRateDifferential", "minDifferentialLendingRate", "defaultDifferentialLendingRate", - "maxDifferentialLendingRate", "isFloatingInterestRateCalculationAllowed", "syncExpectedWithDisbursementDate", + "interestCalculationPeriodType", LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, + "inArrearsTolerance", "transactionProcessingStrategyId", "graceOnPrincipalPayment", "recurringMoratoriumOnPrincipalPeriods", + "graceOnInterestPayment", "graceOnInterestCharged", "charges", "accountingRule", "includeInBorrowerCycle", "startDate", + "closeDate", "externalId", "isLinkedToFloatingInterestRates", "floatingRatesId", "interestRateDifferential", + "minDifferentialLendingRate", "defaultDifferentialLendingRate", "maxDifferentialLendingRate", + "isFloatingInterestRateCalculationAllowed", "syncExpectedWithDisbursementDate", LoanProductAccountingParams.FEES_RECEIVABLE.getValue(), LoanProductAccountingParams.FUND_SOURCE.getValue(), LoanProductAccountingParams.INCOME_FROM_FEES.getValue(), LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), LoanProductAccountingParams.INTEREST_ON_LOANS.getValue(), LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), @@ -76,8 +77,7 @@ public final class LoanProductDataValidator { LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), - LoanProductAccountingParams.FEE_INCOME_ACCOUNT_MAPPING.getValue(), - LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), + LoanProductAccountingParams.FEE_INCOME_ACCOUNT_MAPPING.getValue(), LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), LoanProductAccountingParams.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(), LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME, LoanProductConstants.PRINCIPAL_VARIATIONS_FOR_BORROWER_CYCLE_PARAMETER_NAME, LoanProductConstants.INTEREST_RATE_VARIATIONS_FOR_BORROWER_CYCLE_PARAMETER_NAME, @@ -96,25 +96,24 @@ public final class LoanProductDataValidator { LoanProductConstants.MINIMUM_DAYS_BETWEEN_DISBURSAL_AND_FIRST_REPAYMENT, LoanProductConstants.mandatoryGuaranteeParamName, LoanProductConstants.holdGuaranteeFundsParamName, LoanProductConstants.minimumGuaranteeFromGuarantorParamName, LoanProductConstants.minimumGuaranteeFromOwnFundsParamName, LoanProductConstants.principalThresholdForLastInstallmentParamName, - LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, LoanProductConstants.canDefineEmiAmountParamName, - LoanProductConstants.installmentAmountInMultiplesOfParamName, + LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, + LoanProductConstants.canDefineEmiAmountParamName, LoanProductConstants.installmentAmountInMultiplesOfParamName, LoanProductConstants.preClosureInterestCalculationStrategyParamName, LoanProductConstants.allowAttributeOverridesParamName, LoanProductConstants.allowVariableInstallmentsParamName, LoanProductConstants.minimumGapBetweenInstallments, LoanProductConstants.maximumGapBetweenInstallments, LoanProductConstants.recalculationCompoundingFrequencyWeekdayParamName, LoanProductConstants.recalculationCompoundingFrequencyNthDayParamName, LoanProductConstants.recalculationCompoundingFrequencyOnDayParamName, - LoanProductConstants.recalculationRestFrequencyWeekdayParamName, - LoanProductConstants.recalculationRestFrequencyNthDayParamName, LoanProductConstants.recalculationRestFrequencyOnDayParamName, + LoanProductConstants.recalculationRestFrequencyWeekdayParamName, LoanProductConstants.recalculationRestFrequencyNthDayParamName, + LoanProductConstants.recalculationRestFrequencyOnDayParamName, LoanProductConstants.isCompoundingToBePostedAsTransactionParamName, LoanProductConstants.allowCompoundingOnEodParamName, LoanProductConstants.CAN_USE_FOR_TOPUP, LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM, LoanProductConstants.RATES_PARAM_NAME)); - private static final String[] supportedloanConfigurableAttributes = {LoanProductConstants.amortizationTypeParamName, + private static final String[] supportedloanConfigurableAttributes = { LoanProductConstants.amortizationTypeParamName, LoanProductConstants.interestTypeParamName, LoanProductConstants.transactionProcessingStrategyIdParamName, - LoanProductConstants.interestCalculationPeriodTypeParamName, - LoanProductConstants.inArrearsToleranceParamName, LoanProductConstants.repaymentEveryParamName, - LoanProductConstants.graceOnPrincipalAndInterestPaymentParamName, - LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME}; + LoanProductConstants.interestCalculationPeriodTypeParamName, LoanProductConstants.inArrearsToleranceParamName, + LoanProductConstants.repaymentEveryParamName, LoanProductConstants.graceOnPrincipalAndInterestPaymentParamName, + LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME }; private final FromJsonHelper fromApiJsonHelper; @@ -156,8 +155,8 @@ public final class LoanProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.MINIMUM_DAYS_BETWEEN_DISBURSAL_AND_FIRST_REPAYMENT, element)) { - final Long minimumDaysBetweenDisbursalAndFirstRepayment = this.fromApiJsonHelper.extractLongNamed( - LoanProductConstants.MINIMUM_DAYS_BETWEEN_DISBURSAL_AND_FIRST_REPAYMENT, element); + final Long minimumDaysBetweenDisbursalAndFirstRepayment = this.fromApiJsonHelper + .extractLongNamed(LoanProductConstants.MINIMUM_DAYS_BETWEEN_DISBURSAL_AND_FIRST_REPAYMENT, element); baseDataValidator.reset().parameter(LoanProductConstants.MINIMUM_DAYS_BETWEEN_DISBURSAL_AND_FIRST_REPAYMENT) .value(minimumDaysBetweenDisbursalAndFirstRepayment).ignoreIfNull().integerGreaterThanZero(); } @@ -198,8 +197,8 @@ public final class LoanProductDataValidator { if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) >= 0) { baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).notLessThanMin(minPrincipalAmount); if (minPrincipalAmount.compareTo(maxPrincipalAmount) <= 0 && principal != null) { - baseDataValidator.reset().parameter("principal").value(principal) - .inMinAndMaxAmountRange(minPrincipalAmount, maxPrincipalAmount); + baseDataValidator.reset().parameter("principal").value(principal).inMinAndMaxAmountRange(minPrincipalAmount, + maxPrincipalAmount); } } else if (principal != null) { baseDataValidator.reset().parameter("principal").value(principal).notGreaterThanMax(maxPrincipalAmount); @@ -232,8 +231,8 @@ public final class LoanProductDataValidator { baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments) .notLessThanMin(minNumberOfRepayments); if (minNumberOfRepayments.compareTo(maxNumberOfRepayments) <= 0) { - baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments) - .inMinMaxRange(minNumberOfRepayments, maxNumberOfRepayments); + baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).inMinMaxRange(minNumberOfRepayments, + maxNumberOfRepayments); } } else { baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments) @@ -259,8 +258,8 @@ public final class LoanProductDataValidator { final Integer interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerNamed("interestCalculationPeriodType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("interestCalculationPeriodType").value(interestCalculationPeriodType).notNull() - .inMinMaxRange(0, 1); + baseDataValidator.reset().parameter("interestCalculationPeriodType").value(interestCalculationPeriodType).notNull().inMinMaxRange(0, + 1); final BigDecimal inArrearsTolerance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element); baseDataValidator.reset().parameter("inArrearsTolerance").value(inArrearsTolerance).ignoreIfNull().zeroOrPositiveAmount(); @@ -279,13 +278,13 @@ public final class LoanProductDataValidator { final Integer graceOnInterestCharged = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged).zeroOrPositiveAmount(); - final Integer graceOnArrearsAgeing = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element); + final Integer graceOnArrearsAgeing = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME).value(graceOnArrearsAgeing) .integerZeroOrGreater(); - final Integer overdueDaysForNPA = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - LoanProductConstants.OVERDUE_DAYS_FOR_NPA_PARAMETER_NAME, element); + final Integer overdueDaysForNPA = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(LoanProductConstants.OVERDUE_DAYS_FOR_NPA_PARAMETER_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.OVERDUE_DAYS_FOR_NPA_PARAMETER_NAME).value(overdueDaysForNPA) .integerZeroOrGreater(); @@ -305,23 +304,25 @@ public final class LoanProductDataValidator { baseDataValidator.reset().parameter(LoanProductConstants.DAYS_IN_MONTH_TYPE_PARAMETER_NAME).value(daysInMonthType).notNull() .isOneOfTheseValues(1, 30); - if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, element)) { - Boolean npaChangeConfig = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, element); + if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, + element)) { + Boolean npaChangeConfig = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME) .value(npaChangeConfig).notNull().isOneOfTheseValues(true, false); } // Interest recalculation settings - final Boolean isInterestRecalculationEnabled = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME, element); + final Boolean isInterestRecalculationEnabled = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME) .value(isInterestRecalculationEnabled).notNull().isOneOfTheseValues(true, false); if (isInterestRecalculationEnabled != null) { if (isInterestRecalculationEnabled) { - if (isEqualAmortization) { throw new EqualAmortizationUnsupportedFeatureException("interest.recalculation", - "interest recalculation"); } + if (isEqualAmortization) { + throw new EqualAmortizationUnsupportedFeatureException("interest.recalculation", "interest recalculation"); + } validateInterestRecalculationParams(element, baseDataValidator, null); } } @@ -329,46 +330,37 @@ public final class LoanProductDataValidator { // interest rates if (this.fromApiJsonHelper.parameterExists("isLinkedToFloatingInterestRates", element) && this.fromApiJsonHelper.extractBooleanNamed("isLinkedToFloatingInterestRates", element) == true) { - if (isEqualAmortization) { throw new EqualAmortizationUnsupportedFeatureException("floating.interest.rate", - "floating interest rate"); } + if (isEqualAmortization) { + throw new EqualAmortizationUnsupportedFeatureException("floating.interest.rate", "floating interest rate"); + } if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) { - baseDataValidator - .reset() - .parameter("interestRatePerPeriod") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.true", - "interestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); + baseDataValidator.reset().parameter("interestRatePerPeriod").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.true", + "interestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); } if (this.fromApiJsonHelper.parameterExists("minInterestRatePerPeriod", element)) { - baseDataValidator - .reset() - .parameter("minInterestRatePerPeriod") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.true", - "minInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); + baseDataValidator.reset().parameter("minInterestRatePerPeriod").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.true", + "minInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); } if (this.fromApiJsonHelper.parameterExists("maxInterestRatePerPeriod", element)) { - baseDataValidator - .reset() - .parameter("maxInterestRatePerPeriod") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.true", - "maxInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); + baseDataValidator.reset().parameter("maxInterestRatePerPeriod").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.true", + "maxInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); } if (this.fromApiJsonHelper.parameterExists("interestRateFrequencyType", element)) { - baseDataValidator - .reset() - .parameter("interestRateFrequencyType") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.true", - "interestRateFrequencyType param is not supported when isLinkedToFloatingInterestRates is true"); + baseDataValidator.reset().parameter("interestRateFrequencyType").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.true", + "interestRateFrequencyType param is not supported when isLinkedToFloatingInterestRates is true"); } if ((interestType == null || !interestType.equals(InterestMethod.DECLINING_BALANCE.getValue())) || (isInterestRecalculationEnabled == null || isInterestRecalculationEnabled == false)) { - baseDataValidator - .reset() - .parameter("isLinkedToFloatingInterestRates") - .failWithCode("supported.only.for.declining.balance.interest.recalculation.enabled", - "Floating interest rates are supported only for declining balance and interest recalculation enabled loan products"); + baseDataValidator.reset().parameter("isLinkedToFloatingInterestRates").failWithCode( + "supported.only.for.declining.balance.interest.recalculation.enabled", + "Floating interest rates are supported only for declining balance and interest recalculation enabled loan products"); } final Integer floatingRatesId = this.fromApiJsonHelper.extractIntegerNamed("floatingRatesId", element, Locale.getDefault()); @@ -380,20 +372,20 @@ public final class LoanProductDataValidator { .zeroOrPositiveAmount(); final String minDifferentialLendingRateParameterName = "minDifferentialLendingRate"; - BigDecimal minDifferentialLendingRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minDifferentialLendingRateParameterName, element); + BigDecimal minDifferentialLendingRate = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(minDifferentialLendingRateParameterName, element); baseDataValidator.reset().parameter(minDifferentialLendingRateParameterName).value(minDifferentialLendingRate).notNull() .zeroOrPositiveAmount(); final String defaultDifferentialLendingRateParameterName = "defaultDifferentialLendingRate"; - BigDecimal defaultDifferentialLendingRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - defaultDifferentialLendingRateParameterName, element); - baseDataValidator.reset().parameter(defaultDifferentialLendingRateParameterName).value(defaultDifferentialLendingRate) - .notNull().zeroOrPositiveAmount(); + BigDecimal defaultDifferentialLendingRate = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(defaultDifferentialLendingRateParameterName, element); + baseDataValidator.reset().parameter(defaultDifferentialLendingRateParameterName).value(defaultDifferentialLendingRate).notNull() + .zeroOrPositiveAmount(); final String maxDifferentialLendingRateParameterName = "maxDifferentialLendingRate"; - BigDecimal maxDifferentialLendingRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - maxDifferentialLendingRateParameterName, element); + BigDecimal maxDifferentialLendingRate = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(maxDifferentialLendingRateParameterName, element); baseDataValidator.reset().parameter(maxDifferentialLendingRateParameterName).value(maxDifferentialLendingRate).notNull() .zeroOrPositiveAmount(); @@ -418,57 +410,45 @@ public final class LoanProductDataValidator { } } - final Boolean isFloatingInterestRateCalculationAllowed = this.fromApiJsonHelper.extractBooleanNamed( - "isFloatingInterestRateCalculationAllowed", element); + final Boolean isFloatingInterestRateCalculationAllowed = this.fromApiJsonHelper + .extractBooleanNamed("isFloatingInterestRateCalculationAllowed", element); baseDataValidator.reset().parameter("isFloatingInterestRateCalculationAllowed").value(isFloatingInterestRateCalculationAllowed) .notNull().isOneOfTheseValues(true, false); } else { if (this.fromApiJsonHelper.parameterExists("floatingRatesId", element)) { - baseDataValidator - .reset() - .parameter("floatingRatesId") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "floatingRatesId param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("floatingRatesId").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "floatingRatesId param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists("interestRateDifferential", element)) { - baseDataValidator - .reset() - .parameter("interestRateDifferential") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "interestRateDifferential param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("interestRateDifferential").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "interestRateDifferential param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists("minDifferentialLendingRate", element)) { - baseDataValidator - .reset() - .parameter("minDifferentialLendingRate") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "minDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("minDifferentialLendingRate").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "minDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists("defaultDifferentialLendingRate", element)) { - baseDataValidator - .reset() - .parameter("defaultDifferentialLendingRate") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "defaultDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("defaultDifferentialLendingRate").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "defaultDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists("maxDifferentialLendingRate", element)) { - baseDataValidator - .reset() - .parameter("maxDifferentialLendingRate") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "maxDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("maxDifferentialLendingRate").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "maxDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists("isFloatingInterestRateCalculationAllowed", element)) { - baseDataValidator - .reset() - .parameter("isFloatingInterestRateCalculationAllowed") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "isFloatingInterestRateCalculationAllowed param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("isFloatingInterestRateCalculationAllowed").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "isFloatingInterestRateCalculationAllowed param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", @@ -529,20 +509,20 @@ public final class LoanProductDataValidator { } } - BigDecimal principalThresholdForLastInstallment = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanProductConstants.principalThresholdForLastInstallmentParamName, element); + BigDecimal principalThresholdForLastInstallment = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanProductConstants.principalThresholdForLastInstallmentParamName, element); baseDataValidator.reset().parameter(LoanProductConstants.principalThresholdForLastInstallmentParamName) .value(principalThresholdForLastInstallment).notLessThanMin(BigDecimal.ZERO).notGreaterThanMax(BigDecimal.valueOf(100)); if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.canDefineEmiAmountParamName, element)) { - final Boolean canDefineInstallmentAmount = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.canDefineEmiAmountParamName, element); + final Boolean canDefineInstallmentAmount = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.canDefineEmiAmountParamName, element); baseDataValidator.reset().parameter(LoanProductConstants.canDefineEmiAmountParamName).value(canDefineInstallmentAmount) .isOneOfTheseValues(true, false); } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.installmentAmountInMultiplesOfParamName, element)) { - final Integer installmentAmountInMultiplesOf = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - LoanProductConstants.installmentAmountInMultiplesOfParamName, element); + final Integer installmentAmountInMultiplesOf = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(LoanProductConstants.installmentAmountInMultiplesOfParamName, element); baseDataValidator.reset().parameter(LoanProductConstants.installmentAmountInMultiplesOfParamName) .value(installmentAmountInMultiplesOf).ignoreIfNull().integerGreaterThanZero(); } @@ -553,50 +533,49 @@ public final class LoanProductDataValidator { if (isCashBasedAccounting(accountingRuleType) || isAccrualBasedAccounting(accountingRuleType)) { - final Long fundAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.FUND_SOURCE.getValue(), - element); + final Long fundAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.FUND_SOURCE.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.FUND_SOURCE.getValue()).value(fundAccountId).notNull() .integerGreaterThanZero(); - final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.LOAN_PORTFOLIO.getValue(), element); + final Long loanPortfolioAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.LOAN_PORTFOLIO.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.LOAN_PORTFOLIO.getValue()).value(loanPortfolioAccountId) .notNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero(); - final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INTEREST_ON_LOANS.getValue(), element); + final Long incomeFromInterestId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INTEREST_ON_LOANS.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.INTEREST_ON_LOANS.getValue()).value(incomeFromInterestId) .notNull().integerGreaterThanZero(); - final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_FROM_FEES.getValue(), element); - baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) - .notNull().integerGreaterThanZero(); + final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.INCOME_FROM_FEES.getValue(), + element); + baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId).notNull() + .integerGreaterThanZero(); - final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); + final Long incomeFromPenaltyId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .notNull().integerGreaterThanZero(); - final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), element); + final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue()) .value(incomeFromRecoveryAccountId).notNull().integerGreaterThanZero(); - final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), element); + final Long writeOffAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue()).value(writeOffAccountId) .notNull().integerGreaterThanZero(); - final Long overpaymentAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.OVERPAYMENT.getValue(), element); - baseDataValidator.reset().parameter(LoanProductAccountingParams.OVERPAYMENT.getValue()).value(overpaymentAccountId) - .notNull().integerGreaterThanZero(); + final Long overpaymentAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.OVERPAYMENT.getValue(), + element); + baseDataValidator.reset().parameter(LoanProductAccountingParams.OVERPAYMENT.getValue()).value(overpaymentAccountId).notNull() + .integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(baseDataValidator, element); validateChargeToIncomeAccountMappings(baseDataValidator, element); @@ -605,27 +584,27 @@ public final class LoanProductDataValidator { if (isAccrualBasedAccounting(accountingRuleType)) { - final Long receivableInterestAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), element); + final Long receivableInterestAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue()) .value(receivableInterestAccountId).notNull().integerGreaterThanZero(); - final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.FEES_RECEIVABLE.getValue(), element); + final Long receivableFeeAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.FEES_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.FEES_RECEIVABLE.getValue()).value(receivableFeeAccountId) .notNull().integerGreaterThanZero(); - final Long receivablePenaltyAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), element); + final Long receivablePenaltyAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue()) .value(receivablePenaltyAccountId).notNull().integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME, element)) { - final Boolean useBorrowerCycle = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME, - element); - baseDataValidator.reset().parameter(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME).value(useBorrowerCycle).ignoreIfNull() - .validateForBooleanValue(); + final Boolean useBorrowerCycle = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME, element); + baseDataValidator.reset().parameter(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME).value(useBorrowerCycle) + .ignoreIfNull().validateForBooleanValue(); if (useBorrowerCycle) { validateBorrowerCycleVariations(element, baseDataValidator); } @@ -639,9 +618,8 @@ public final class LoanProductDataValidator { validatePartialPeriodSupport(interestCalculationPeriodType, baseDataValidator, element, null); - if(this.fromApiJsonHelper.parameterExists(LoanProductConstants.CAN_USE_FOR_TOPUP, element)){ - final Boolean canUseForTopup = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.CAN_USE_FOR_TOPUP, - element); + if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.CAN_USE_FOR_TOPUP, element)) { + final Boolean canUseForTopup = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.CAN_USE_FOR_TOPUP, element); baseDataValidator.reset().parameter(LoanProductConstants.CAN_USE_FOR_TOPUP).value(canUseForTopup).validateForBooleanValue(); } @@ -656,47 +634,42 @@ public final class LoanProductDataValidator { if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM, element)) { isEqualAmortization = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM, element); } - if (isEqualAmortization) { throw new EqualAmortizationUnsupportedFeatureException("variable.installment", - "variable installment"); } + if (isEqualAmortization) { + throw new EqualAmortizationUnsupportedFeatureException("variable.installment", "variable installment"); + } Long minimumGapBetweenInstallments = null; if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.minimumGapBetweenInstallments, element)) { minimumGapBetweenInstallments = this.fromApiJsonHelper.extractLongNamed(LoanProductConstants.minimumGapBetweenInstallments, element); - baseDataValidator.reset().parameter(LoanProductConstants.minimumGapBetweenInstallments) - .value(minimumGapBetweenInstallments).notNull(); + baseDataValidator.reset().parameter(LoanProductConstants.minimumGapBetweenInstallments).value(minimumGapBetweenInstallments) + .notNull(); } else { - baseDataValidator - .reset() - .parameter(LoanProductConstants.minimumGapBetweenInstallments) - .failWithCode("is.mandatory.when.allowVariableInstallments.is.true", - "minimumGap param is mandatory when allowVariableInstallments is true"); + baseDataValidator.reset().parameter(LoanProductConstants.minimumGapBetweenInstallments).failWithCode( + "is.mandatory.when.allowVariableInstallments.is.true", + "minimumGap param is mandatory when allowVariableInstallments is true"); } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.maximumGapBetweenInstallments, element)) { - final Long maximumGapBetweenInstallments = this.fromApiJsonHelper.extractLongNamed( - LoanProductConstants.maximumGapBetweenInstallments, element); - baseDataValidator.reset().parameter(LoanProductConstants.minimumGapBetweenInstallments) - .value(maximumGapBetweenInstallments).notNull(); - baseDataValidator.reset().parameter(LoanProductConstants.maximumGapBetweenInstallments) - .value(maximumGapBetweenInstallments).notNull().longGreaterThanNumber(minimumGapBetweenInstallments); + final Long maximumGapBetweenInstallments = this.fromApiJsonHelper + .extractLongNamed(LoanProductConstants.maximumGapBetweenInstallments, element); + baseDataValidator.reset().parameter(LoanProductConstants.minimumGapBetweenInstallments).value(maximumGapBetweenInstallments) + .notNull(); + baseDataValidator.reset().parameter(LoanProductConstants.maximumGapBetweenInstallments).value(maximumGapBetweenInstallments) + .notNull().longGreaterThanNumber(minimumGapBetweenInstallments); } } else { if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.minimumGapBetweenInstallments, element)) { - baseDataValidator - .reset() - .parameter(LoanProductConstants.minimumGapBetweenInstallments) - .failWithCode("not.supported.when.allowVariableInstallments.is.false", - "minimumGap param is not supported when allowVariableInstallments is not supplied or false"); + baseDataValidator.reset().parameter(LoanProductConstants.minimumGapBetweenInstallments).failWithCode( + "not.supported.when.allowVariableInstallments.is.false", + "minimumGap param is not supported when allowVariableInstallments is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.maximumGapBetweenInstallments, element)) { - baseDataValidator - .reset() - .parameter(LoanProductConstants.maximumGapBetweenInstallments) - .failWithCode("not.supported.when.allowVariableInstallments.is.false", - "maximumGap param is not supported when allowVariableInstallments is not supplied or false"); + baseDataValidator.reset().parameter(LoanProductConstants.maximumGapBetweenInstallments).failWithCode( + "not.supported.when.allowVariableInstallments.is.false", + "maximumGap param is not supported when allowVariableInstallments is not supplied or false"); } } @@ -718,10 +691,9 @@ public final class LoanProductDataValidator { for (int i = 0; i < length; i++) { /* Validate the attribute names */ - if (this.fromApiJsonHelper - .parameterExists(supportedloanConfigurableAttributes[i], object)) { - Boolean loanConfigurationAttributeValue = this.fromApiJsonHelper.extractBooleanNamed( - supportedloanConfigurableAttributes[i], object); + if (this.fromApiJsonHelper.parameterExists(supportedloanConfigurableAttributes[i], object)) { + Boolean loanConfigurationAttributeValue = this.fromApiJsonHelper + .extractBooleanNamed(supportedloanConfigurableAttributes[i], object); /* Validate the boolean value */ baseDataValidator.reset().parameter(LoanProductConstants.allowAttributeOverridesParamName) .value(loanConfigurationAttributeValue).notNull().validateForBooleanValue(); @@ -734,7 +706,8 @@ public final class LoanProductDataValidator { private void validateMultiDisburseLoanData(final DataValidatorBuilder baseDataValidator, final JsonElement element) { Boolean multiDisburseLoan = false; if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.MULTI_DISBURSE_LOAN_PARAMETER_NAME, element)) { - multiDisburseLoan = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.MULTI_DISBURSE_LOAN_PARAMETER_NAME, element); + multiDisburseLoan = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.MULTI_DISBURSE_LOAN_PARAMETER_NAME, + element); baseDataValidator.reset().parameter(LoanProductConstants.MULTI_DISBURSE_LOAN_PARAMETER_NAME).value(multiDisburseLoan) .ignoreIfNull().validateForBooleanValue(); } @@ -743,19 +716,20 @@ public final class LoanProductDataValidator { if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM, element)) { isEqualAmortization = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM, element); } - if (isEqualAmortization && multiDisburseLoan) { throw new EqualAmortizationUnsupportedFeatureException("tranche.disbursal", - "tranche disbursal"); } + if (isEqualAmortization && multiDisburseLoan) { + throw new EqualAmortizationUnsupportedFeatureException("tranche.disbursal", "tranche disbursal"); + } if (multiDisburseLoan) { if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.OUTSTANDING_LOAN_BALANCE_PARAMETER_NAME, element)) { - final BigDecimal outstandingLoanBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanProductConstants.OUTSTANDING_LOAN_BALANCE_PARAMETER_NAME, element); - baseDataValidator.reset().parameter(LoanProductConstants.OUTSTANDING_LOAN_BALANCE_PARAMETER_NAME).value(outstandingLoanBalance) - .ignoreIfNull().zeroOrPositiveAmount(); + final BigDecimal outstandingLoanBalance = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanProductConstants.OUTSTANDING_LOAN_BALANCE_PARAMETER_NAME, element); + baseDataValidator.reset().parameter(LoanProductConstants.OUTSTANDING_LOAN_BALANCE_PARAMETER_NAME) + .value(outstandingLoanBalance).ignoreIfNull().zeroOrPositiveAmount(); } - final Integer maxTrancheCount = this.fromApiJsonHelper.extractIntegerNamed(LoanProductConstants.MAX_TRANCHE_COUNT_PARAMETER_NAME, - element, Locale.getDefault()); + final Integer maxTrancheCount = this.fromApiJsonHelper + .extractIntegerNamed(LoanProductConstants.MAX_TRANCHE_COUNT_PARAMETER_NAME, element, Locale.getDefault()); baseDataValidator.reset().parameter(LoanProductConstants.MAX_TRANCHE_COUNT_PARAMETER_NAME).value(maxTrancheCount).notNull() .integerGreaterThanZero(); @@ -773,9 +747,8 @@ public final class LoanProductDataValidator { */ InterestRecalculationCompoundingMethod compoundingMethod = null; - if (loanProduct == null - || this.fromApiJsonHelper - .parameterExists(LoanProductConstants.interestRecalculationCompoundingMethodParameterName, element)) { + if (loanProduct == null || this.fromApiJsonHelper + .parameterExists(LoanProductConstants.interestRecalculationCompoundingMethodParameterName, element)) { final Integer interestRecalculationCompoundingMethod = this.fromApiJsonHelper.extractIntegerNamed( LoanProductConstants.interestRecalculationCompoundingMethodParameterName, element, Locale.getDefault()); baseDataValidator.reset().parameter(LoanProductConstants.interestRecalculationCompoundingMethodParameterName) @@ -789,8 +762,8 @@ public final class LoanProductDataValidator { if (loanProduct == null) { compoundingMethod = InterestRecalculationCompoundingMethod.NONE; } else { - compoundingMethod = InterestRecalculationCompoundingMethod.fromInt(loanProduct.getProductInterestRecalculationDetails() - .getInterestRecalculationCompoundingMethod()); + compoundingMethod = InterestRecalculationCompoundingMethod + .fromInt(loanProduct.getProductInterestRecalculationDetails().getInterestRecalculationCompoundingMethod()); } } @@ -799,8 +772,8 @@ public final class LoanProductDataValidator { */ if (loanProduct == null || this.fromApiJsonHelper.parameterExists(LoanProductConstants.rescheduleStrategyMethodParameterName, element)) { - final Integer rescheduleStrategyMethod = this.fromApiJsonHelper.extractIntegerNamed( - LoanProductConstants.rescheduleStrategyMethodParameterName, element, Locale.getDefault()); + final Integer rescheduleStrategyMethod = this.fromApiJsonHelper + .extractIntegerNamed(LoanProductConstants.rescheduleStrategyMethodParameterName, element, Locale.getDefault()); baseDataValidator.reset().parameter(LoanProductConstants.rescheduleStrategyMethodParameterName).value(rescheduleStrategyMethod) .notNull().inMinMaxRange(1, 3); } @@ -809,8 +782,8 @@ public final class LoanProductDataValidator { if (loanProduct == null || this.fromApiJsonHelper.parameterExists(LoanProductConstants.recalculationRestFrequencyTypeParameterName, element)) { - final Integer recalculationRestFrequencyType = this.fromApiJsonHelper.extractIntegerNamed( - LoanProductConstants.recalculationRestFrequencyTypeParameterName, element, Locale.getDefault()); + final Integer recalculationRestFrequencyType = this.fromApiJsonHelper + .extractIntegerNamed(LoanProductConstants.recalculationRestFrequencyTypeParameterName, element, Locale.getDefault()); baseDataValidator.reset().parameter(LoanProductConstants.recalculationRestFrequencyTypeParameterName) .value(recalculationRestFrequencyType).notNull().inMinMaxRange(1, 4); if (recalculationRestFrequencyType != null) { @@ -827,9 +800,8 @@ public final class LoanProductDataValidator { } if (!frequencyType.isSameAsRepayment()) { - if (loanProduct == null - || this.fromApiJsonHelper - .parameterExists(LoanProductConstants.recalculationRestFrequencyIntervalParameterName, element)) { + if (loanProduct == null || this.fromApiJsonHelper + .parameterExists(LoanProductConstants.recalculationRestFrequencyIntervalParameterName, element)) { final Integer recurrenceInterval = this.fromApiJsonHelper.extractIntegerNamed( LoanProductConstants.recalculationRestFrequencyIntervalParameterName, element, Locale.getDefault()); baseDataValidator.reset().parameter(LoanProductConstants.recalculationRestFrequencyIntervalParameterName) @@ -844,8 +816,8 @@ public final class LoanProductDataValidator { } if (loanProduct == null || this.fromApiJsonHelper.parameterExists(LoanProductConstants.recalculationRestFrequencyOnDayParamName, element)) { - final Integer recalculationRestFrequencyOnDay = this.fromApiJsonHelper.extractIntegerNamed( - LoanProductConstants.recalculationRestFrequencyOnDayParamName, element, Locale.getDefault()); + final Integer recalculationRestFrequencyOnDay = this.fromApiJsonHelper + .extractIntegerNamed(LoanProductConstants.recalculationRestFrequencyOnDayParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(LoanProductConstants.recalculationRestFrequencyOnDayParamName) .value(recalculationRestFrequencyOnDay).ignoreIfNull().inMinMaxRange(1, 28); } @@ -854,9 +826,8 @@ public final class LoanProductDataValidator { if (compoundingMethod.isCompoundingEnabled()) { RecalculationFrequencyType compoundingfrequencyType = null; - if (loanProduct == null - || this.fromApiJsonHelper.parameterExists(LoanProductConstants.recalculationCompoundingFrequencyTypeParameterName, - element)) { + if (loanProduct == null || this.fromApiJsonHelper + .parameterExists(LoanProductConstants.recalculationCompoundingFrequencyTypeParameterName, element)) { final Integer recalculationCompoundingFrequencyType = this.fromApiJsonHelper.extractIntegerNamed( LoanProductConstants.recalculationCompoundingFrequencyTypeParameterName, element, Locale.getDefault()); baseDataValidator.reset().parameter(LoanProductConstants.recalculationCompoundingFrequencyTypeParameterName) @@ -889,9 +860,8 @@ public final class LoanProductDataValidator { } if (!compoundingfrequencyType.isSameAsRepayment()) { - if (loanProduct == null - || this.fromApiJsonHelper.parameterExists( - LoanProductConstants.recalculationCompoundingFrequencyIntervalParameterName, element)) { + if (loanProduct == null || this.fromApiJsonHelper + .parameterExists(LoanProductConstants.recalculationCompoundingFrequencyIntervalParameterName, element)) { final Integer recurrenceInterval = this.fromApiJsonHelper.extractIntegerNamed( LoanProductConstants.recalculationCompoundingFrequencyIntervalParameterName, element, Locale.getDefault()); Integer repaymentEvery = null; @@ -913,9 +883,8 @@ public final class LoanProductDataValidator { LoanProductConstants.recalculationCompoundingFrequencyNthDayParamName, LoanProductConstants.recalculationCompoundingFrequencyWeekdayParamName, element, this.fromApiJsonHelper); } - if (loanProduct == null - || this.fromApiJsonHelper.parameterExists(LoanProductConstants.recalculationCompoundingFrequencyOnDayParamName, - element)) { + if (loanProduct == null || this.fromApiJsonHelper + .parameterExists(LoanProductConstants.recalculationCompoundingFrequencyOnDayParamName, element)) { final Integer recalculationRestFrequencyOnDay = this.fromApiJsonHelper.extractIntegerNamed( LoanProductConstants.recalculationCompoundingFrequencyOnDayParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(LoanProductConstants.recalculationCompoundingFrequencyOnDayParamName) @@ -925,27 +894,23 @@ public final class LoanProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.isArrearsBasedOnOriginalScheduleParamName, element)) { - final Boolean isArrearsBasedOnOriginalSchedule = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.isArrearsBasedOnOriginalScheduleParamName, element); + final Boolean isArrearsBasedOnOriginalSchedule = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.isArrearsBasedOnOriginalScheduleParamName, element); baseDataValidator.reset().parameter(LoanProductConstants.isArrearsBasedOnOriginalScheduleParamName) .value(isArrearsBasedOnOriginalSchedule).notNull().isOneOfTheseValues(true, false); } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.isCompoundingToBePostedAsTransactionParamName, element)) { - final Boolean isCompoundingToBePostedAsTransactions = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.isCompoundingToBePostedAsTransactionParamName, element); + final Boolean isCompoundingToBePostedAsTransactions = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.isCompoundingToBePostedAsTransactionParamName, element); baseDataValidator.reset().parameter(LoanProductConstants.isCompoundingToBePostedAsTransactionParamName) .value(isCompoundingToBePostedAsTransactions).notNull().isOneOfTheseValues(true, false); } - final Integer preCloseInterestCalculationStrategy = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - LoanProductConstants.preClosureInterestCalculationStrategyParamName, element); - baseDataValidator - .reset() - .parameter(LoanProductConstants.preClosureInterestCalculationStrategyParamName) - .value(preCloseInterestCalculationStrategy) - .ignoreIfNull() - .inMinMaxRange(LoanPreClosureInterestCalculationStrategy.getMinValue(), - LoanPreClosureInterestCalculationStrategy.getMaxValue()); + final Integer preCloseInterestCalculationStrategy = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(LoanProductConstants.preClosureInterestCalculationStrategyParamName, element); + baseDataValidator.reset().parameter(LoanProductConstants.preClosureInterestCalculationStrategyParamName) + .value(preCloseInterestCalculationStrategy).ignoreIfNull().inMinMaxRange( + LoanPreClosureInterestCalculationStrategy.getMinValue(), LoanPreClosureInterestCalculationStrategy.getMaxValue()); } public void validateForUpdate(final String json, final LoanProduct loanProduct) { @@ -1057,16 +1022,16 @@ public final class LoanProductDataValidator { } if (this.fromApiJsonHelper.parameterExists("transactionProcessingStrategyId", element)) { - final Long transactionProcessingStrategyId = this.fromApiJsonHelper - .extractLongNamed("transactionProcessingStrategyId", element); + final Long transactionProcessingStrategyId = this.fromApiJsonHelper.extractLongNamed("transactionProcessingStrategyId", + element); baseDataValidator.reset().parameter("transactionProcessingStrategyId").value(transactionProcessingStrategyId).notNull() .integerGreaterThanZero(); } // grace validation if (this.fromApiJsonHelper.parameterExists("graceOnPrincipalPayment", element)) { - final Integer graceOnPrincipalPayment = this.fromApiJsonHelper - .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); + final Integer graceOnPrincipalPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", + element); baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment).zeroOrPositiveAmount(); } @@ -1081,15 +1046,15 @@ public final class LoanProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element)) { - final Integer graceOnArrearsAgeing = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element); + final Integer graceOnArrearsAgeing = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.GRACE_ON_ARREARS_AGEING_PARAMETER_NAME).value(graceOnArrearsAgeing) .integerZeroOrGreater(); } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.OVERDUE_DAYS_FOR_NPA_PARAMETER_NAME, element)) { - final Integer overdueDaysForNPA = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - LoanProductConstants.OVERDUE_DAYS_FOR_NPA_PARAMETER_NAME, element); + final Integer overdueDaysForNPA = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(LoanProductConstants.OVERDUE_DAYS_FOR_NPA_PARAMETER_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.OVERDUE_DAYS_FOR_NPA_PARAMETER_NAME).value(overdueDaysForNPA) .integerZeroOrGreater(); } @@ -1126,15 +1091,16 @@ public final class LoanProductDataValidator { * { @link DaysInMonthType } */ if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.DAYS_IN_YEAR_TYPE_PARAMETER_NAME, element)) { - final Integer daysInMonthType = this.fromApiJsonHelper.extractIntegerNamed(LoanProductConstants.DAYS_IN_MONTH_TYPE_PARAMETER_NAME, - element, Locale.getDefault()); + final Integer daysInMonthType = this.fromApiJsonHelper + .extractIntegerNamed(LoanProductConstants.DAYS_IN_MONTH_TYPE_PARAMETER_NAME, element, Locale.getDefault()); baseDataValidator.reset().parameter(LoanProductConstants.DAYS_IN_MONTH_TYPE_PARAMETER_NAME).value(daysInMonthType).notNull() .isOneOfTheseValues(1, 30); } - if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, element)) { - Boolean npaChangeConfig = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, element); + if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, + element)) { + Boolean npaChangeConfig = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.ACCOUNT_MOVES_OUT_OF_NPA_ONLY_ON_ARREARS_COMPLETION_PARAM_NAME) .value(npaChangeConfig).notNull().isOneOfTheseValues(true, false); } @@ -1149,16 +1115,17 @@ public final class LoanProductDataValidator { // Interest recalculation settings Boolean isInterestRecalculationEnabled = loanProduct.isInterestRecalculationEnabled(); if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME, element)) { - isInterestRecalculationEnabled = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME, element); + isInterestRecalculationEnabled = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME) .value(isInterestRecalculationEnabled).notNull().isOneOfTheseValues(true, false); } if (isInterestRecalculationEnabled != null) { if (isInterestRecalculationEnabled) { - if (isEqualAmortization) { throw new EqualAmortizationUnsupportedFeatureException("interest.recalculation", - "interest recalculation"); } + if (isEqualAmortization) { + throw new EqualAmortizationUnsupportedFeatureException("interest.recalculation", "interest recalculation"); + } validateInterestRecalculationParams(element, baseDataValidator, loanProduct); } } @@ -1169,51 +1136,41 @@ public final class LoanProductDataValidator { isLinkedToFloatingInterestRates = this.fromApiJsonHelper.extractBooleanNamed("isLinkedToFloatingInterestRates", element); } if (isLinkedToFloatingInterestRates) { - if(isEqualAmortization){ + if (isEqualAmortization) { throw new EqualAmortizationUnsupportedFeatureException("floating.interest.rate", "floating interest rate"); } if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) { - baseDataValidator - .reset() - .parameter("interestRatePerPeriod") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.true", - "interestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); + baseDataValidator.reset().parameter("interestRatePerPeriod").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.true", + "interestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); } if (this.fromApiJsonHelper.parameterExists("minInterestRatePerPeriod", element)) { - baseDataValidator - .reset() - .parameter("minInterestRatePerPeriod") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.true", - "minInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); + baseDataValidator.reset().parameter("minInterestRatePerPeriod").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.true", + "minInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); } if (this.fromApiJsonHelper.parameterExists("maxInterestRatePerPeriod", element)) { - baseDataValidator - .reset() - .parameter("maxInterestRatePerPeriod") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.true", - "maxInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); + baseDataValidator.reset().parameter("maxInterestRatePerPeriod").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.true", + "maxInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true"); } if (this.fromApiJsonHelper.parameterExists("interestRateFrequencyType", element)) { - baseDataValidator - .reset() - .parameter("interestRateFrequencyType") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.true", - "interestRateFrequencyType param is not supported when isLinkedToFloatingInterestRates is true"); + baseDataValidator.reset().parameter("interestRateFrequencyType").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.true", + "interestRateFrequencyType param is not supported when isLinkedToFloatingInterestRates is true"); } - Integer interestType = this.fromApiJsonHelper.parameterExists("interestType", element) ? this.fromApiJsonHelper - .extractIntegerNamed("interestType", element, Locale.getDefault()) : loanProduct.getLoanProductRelatedDetail() - .getInterestMethod().getValue(); + Integer interestType = this.fromApiJsonHelper.parameterExists("interestType", element) + ? this.fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()) + : loanProduct.getLoanProductRelatedDetail().getInterestMethod().getValue(); if ((interestType == null || !interestType.equals(InterestMethod.DECLINING_BALANCE.getValue())) || (isInterestRecalculationEnabled == null || isInterestRecalculationEnabled == false)) { - baseDataValidator - .reset() - .parameter("isLinkedToFloatingInterestRates") - .failWithCode("supported.only.for.declining.balance.interest.recalculation.enabled", - "Floating interest rates are supported only for declining balance and interest recalculation enabled loan products"); + baseDataValidator.reset().parameter("isLinkedToFloatingInterestRates").failWithCode( + "supported.only.for.declining.balance.interest.recalculation.enabled", + "Floating interest rates are supported only for declining balance and interest recalculation enabled loan products"); } Long floatingRatesId = loanProduct.getFloatingRates() == null ? null : loanProduct.getFloatingRates().getFloatingRate().getId(); @@ -1222,8 +1179,8 @@ public final class LoanProductDataValidator { } baseDataValidator.reset().parameter("floatingRatesId").value(floatingRatesId).notNull(); - BigDecimal interestRateDifferential = loanProduct.getFloatingRates() == null ? null : loanProduct.getFloatingRates() - .getInterestRateDifferential(); + BigDecimal interestRateDifferential = loanProduct.getFloatingRates() == null ? null + : loanProduct.getFloatingRates().getInterestRateDifferential(); if (this.fromApiJsonHelper.parameterExists("interestRateDifferential", element)) { interestRateDifferential = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRateDifferential", element); } @@ -1231,31 +1188,31 @@ public final class LoanProductDataValidator { .zeroOrPositiveAmount(); final String minDifferentialLendingRateParameterName = "minDifferentialLendingRate"; - BigDecimal minDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null : loanProduct.getFloatingRates() - .getMinDifferentialLendingRate(); + BigDecimal minDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null + : loanProduct.getFloatingRates().getMinDifferentialLendingRate(); if (this.fromApiJsonHelper.parameterExists(minDifferentialLendingRateParameterName, element)) { - minDifferentialLendingRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minDifferentialLendingRateParameterName, element); + minDifferentialLendingRate = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(minDifferentialLendingRateParameterName, element); } baseDataValidator.reset().parameter(minDifferentialLendingRateParameterName).value(minDifferentialLendingRate).notNull() .zeroOrPositiveAmount(); final String defaultDifferentialLendingRateParameterName = "defaultDifferentialLendingRate"; - BigDecimal defaultDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null : loanProduct.getFloatingRates() - .getDefaultDifferentialLendingRate(); + BigDecimal defaultDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null + : loanProduct.getFloatingRates().getDefaultDifferentialLendingRate(); if (this.fromApiJsonHelper.parameterExists(defaultDifferentialLendingRateParameterName, element)) { - defaultDifferentialLendingRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - defaultDifferentialLendingRateParameterName, element); + defaultDifferentialLendingRate = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(defaultDifferentialLendingRateParameterName, element); } - baseDataValidator.reset().parameter(defaultDifferentialLendingRateParameterName).value(defaultDifferentialLendingRate) - .notNull().zeroOrPositiveAmount(); + baseDataValidator.reset().parameter(defaultDifferentialLendingRateParameterName).value(defaultDifferentialLendingRate).notNull() + .zeroOrPositiveAmount(); final String maxDifferentialLendingRateParameterName = "maxDifferentialLendingRate"; - BigDecimal maxDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null : loanProduct.getFloatingRates() - .getMaxDifferentialLendingRate(); + BigDecimal maxDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null + : loanProduct.getFloatingRates().getMaxDifferentialLendingRate(); if (this.fromApiJsonHelper.parameterExists(maxDifferentialLendingRateParameterName, element)) { - maxDifferentialLendingRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - maxDifferentialLendingRateParameterName, element); + maxDifferentialLendingRate = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(maxDifferentialLendingRateParameterName, element); } baseDataValidator.reset().parameter(maxDifferentialLendingRateParameterName).value(maxDifferentialLendingRate).notNull() .zeroOrPositiveAmount(); @@ -1281,61 +1238,49 @@ public final class LoanProductDataValidator { } } - Boolean isFloatingInterestRateCalculationAllowed = loanProduct.getFloatingRates() == null ? null : loanProduct - .getFloatingRates().isFloatingInterestRateCalculationAllowed(); + Boolean isFloatingInterestRateCalculationAllowed = loanProduct.getFloatingRates() == null ? null + : loanProduct.getFloatingRates().isFloatingInterestRateCalculationAllowed(); if (this.fromApiJsonHelper.parameterExists("isFloatingInterestRateCalculationAllowed", element)) { - isFloatingInterestRateCalculationAllowed = this.fromApiJsonHelper.extractBooleanNamed( - "isFloatingInterestRateCalculationAllowed", element); + isFloatingInterestRateCalculationAllowed = this.fromApiJsonHelper + .extractBooleanNamed("isFloatingInterestRateCalculationAllowed", element); } baseDataValidator.reset().parameter("isFloatingInterestRateCalculationAllowed").value(isFloatingInterestRateCalculationAllowed) .notNull().isOneOfTheseValues(true, false); } else { if (this.fromApiJsonHelper.parameterExists("floatingRatesId", element)) { - baseDataValidator - .reset() - .parameter("floatingRatesId") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "floatingRatesId param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("floatingRatesId").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "floatingRatesId param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists("interestRateDifferential", element)) { - baseDataValidator - .reset() - .parameter("interestRateDifferential") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "interestRateDifferential param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("interestRateDifferential").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "interestRateDifferential param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists("minDifferentialLendingRate", element)) { - baseDataValidator - .reset() - .parameter("minDifferentialLendingRate") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "minDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("minDifferentialLendingRate").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "minDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists("defaultDifferentialLendingRate", element)) { - baseDataValidator - .reset() - .parameter("defaultDifferentialLendingRate") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "defaultDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("defaultDifferentialLendingRate").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "defaultDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists("maxDifferentialLendingRate", element)) { - baseDataValidator - .reset() - .parameter("maxDifferentialLendingRate") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "maxDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("maxDifferentialLendingRate").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "maxDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } if (this.fromApiJsonHelper.parameterExists("isFloatingInterestRateCalculationAllowed", element)) { - baseDataValidator - .reset() - .parameter("isFloatingInterestRateCalculationAllowed") - .failWithCode("not.supported.when.isLinkedToFloatingInterestRates.is.false", - "isFloatingInterestRateCalculationAllowed param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); + baseDataValidator.reset().parameter("isFloatingInterestRateCalculationAllowed").failWithCode( + "not.supported.when.isLinkedToFloatingInterestRates.is.false", + "isFloatingInterestRateCalculationAllowed param is not supported when isLinkedToFloatingInterestRates is not supplied or false"); } final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod"; @@ -1385,22 +1330,22 @@ public final class LoanProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.principalThresholdForLastInstallmentParamName, element)) { - BigDecimal principalThresholdForLastInstallment = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanProductConstants.principalThresholdForLastInstallmentParamName, element); + BigDecimal principalThresholdForLastInstallment = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanProductConstants.principalThresholdForLastInstallmentParamName, element); baseDataValidator.reset().parameter(LoanProductConstants.principalThresholdForLastInstallmentParamName) .value(principalThresholdForLastInstallment).notNull().notLessThanMin(BigDecimal.ZERO) .notGreaterThanMax(BigDecimal.valueOf(100)); } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.canDefineEmiAmountParamName, element)) { - final Boolean canDefineInstallmentAmount = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.canDefineEmiAmountParamName, element); + final Boolean canDefineInstallmentAmount = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.canDefineEmiAmountParamName, element); baseDataValidator.reset().parameter(LoanProductConstants.canDefineEmiAmountParamName).value(canDefineInstallmentAmount) .isOneOfTheseValues(true, false); } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.installmentAmountInMultiplesOfParamName, element)) { - final Integer installmentAmountInMultiplesOf = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - LoanProductConstants.installmentAmountInMultiplesOfParamName, element); + final Integer installmentAmountInMultiplesOf = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(LoanProductConstants.installmentAmountInMultiplesOfParamName, element); baseDataValidator.reset().parameter(LoanProductConstants.installmentAmountInMultiplesOfParamName) .value(installmentAmountInMultiplesOf).ignoreIfNull().integerGreaterThanZero(); } @@ -1412,60 +1357,60 @@ public final class LoanProductDataValidator { baseDataValidator.reset().parameter(LoanProductAccountingParams.FUND_SOURCE.getValue()).value(fundAccountId).ignoreIfNull() .integerGreaterThanZero(); - final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.LOAN_PORTFOLIO.getValue(), element); + final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.LOAN_PORTFOLIO.getValue(), + element); baseDataValidator.reset().parameter(LoanProductAccountingParams.LOAN_PORTFOLIO.getValue()).value(loanPortfolioAccountId) .ignoreIfNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); - baseDataValidator.reset().parameter(LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue()) - .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); + baseDataValidator.reset().parameter(LoanProductAccountingParams.TRANSFERS_SUSPENSE.getValue()).value(transfersInSuspenseAccountId) + .ignoreIfNull().integerGreaterThanZero(); - final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INTEREST_ON_LOANS.getValue(), element); + final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.INTEREST_ON_LOANS.getValue(), + element); baseDataValidator.reset().parameter(LoanProductAccountingParams.INTEREST_ON_LOANS.getValue()).value(incomeFromInterestId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.INCOME_FROM_FEES.getValue(), element); - baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) - .ignoreIfNull().integerGreaterThanZero(); + baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId).ignoreIfNull() + .integerGreaterThanZero(); - final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); + final Long incomeFromPenaltyId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); - final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), element); - baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue()) - .value(incomeFromRecoveryAccountId).ignoreIfNull().integerGreaterThanZero(); + final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue(), element); + baseDataValidator.reset().parameter(LoanProductAccountingParams.INCOME_FROM_RECOVERY.getValue()).value(incomeFromRecoveryAccountId) + .ignoreIfNull().integerGreaterThanZero(); - final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), element); + final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), + element); baseDataValidator.reset().parameter(LoanProductAccountingParams.LOSSES_WRITTEN_OFF.getValue()).value(writeOffAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long overpaymentAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.OVERPAYMENT.getValue(), element); - baseDataValidator.reset().parameter(LoanProductAccountingParams.OVERPAYMENT.getValue()).value(overpaymentAccountId) + baseDataValidator.reset().parameter(LoanProductAccountingParams.OVERPAYMENT.getValue()).value(overpaymentAccountId).ignoreIfNull() + .integerGreaterThanZero(); + + final Long receivableInterestAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), element); + baseDataValidator.reset().parameter(LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue()).value(receivableInterestAccountId) .ignoreIfNull().integerGreaterThanZero(); - final Long receivableInterestAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue(), element); - baseDataValidator.reset().parameter(LoanProductAccountingParams.INTEREST_RECEIVABLE.getValue()) - .value(receivableInterestAccountId).ignoreIfNull().integerGreaterThanZero(); - - final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.FEES_RECEIVABLE.getValue(), element); + final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.FEES_RECEIVABLE.getValue(), + element); baseDataValidator.reset().parameter(LoanProductAccountingParams.FEES_RECEIVABLE.getValue()).value(receivableFeeAccountId) .ignoreIfNull().integerGreaterThanZero(); - final Long receivablePenaltyAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), element); - baseDataValidator.reset().parameter(LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue()) - .value(receivablePenaltyAccountId).ignoreIfNull().integerGreaterThanZero(); + final Long receivablePenaltyAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue(), element); + baseDataValidator.reset().parameter(LoanProductAccountingParams.PENALTIES_RECEIVABLE.getValue()).value(receivablePenaltyAccountId) + .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(baseDataValidator, element); validateChargeToIncomeAccountMappings(baseDataValidator, element); @@ -1473,10 +1418,10 @@ public final class LoanProductDataValidator { validateMinMaxConstraints(element, baseDataValidator, loanProduct); if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME, element)) { - final Boolean useBorrowerCycle = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME, - element); - baseDataValidator.reset().parameter(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME).value(useBorrowerCycle).ignoreIfNull() - .validateForBooleanValue(); + final Boolean useBorrowerCycle = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME, element); + baseDataValidator.reset().parameter(LoanProductConstants.USE_BORROWER_CYCLE_PARAMETER_NAME).value(useBorrowerCycle) + .ignoreIfNull().validateForBooleanValue(); if (useBorrowerCycle) { validateBorrowerCycleVariations(element, baseDataValidator); } @@ -1490,9 +1435,8 @@ public final class LoanProductDataValidator { validatePartialPeriodSupport(interestCalculationPeriodType, baseDataValidator, element, loanProduct); - if(this.fromApiJsonHelper.parameterExists(LoanProductConstants.CAN_USE_FOR_TOPUP, element)){ - final Boolean canUseForTopup = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.CAN_USE_FOR_TOPUP, - element); + if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.CAN_USE_FOR_TOPUP, element)) { + final Boolean canUseForTopup = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.CAN_USE_FOR_TOPUP, element); baseDataValidator.reset().parameter(LoanProductConstants.CAN_USE_FOR_TOPUP).value(canUseForTopup).validateForBooleanValue(); } @@ -1504,29 +1448,25 @@ public final class LoanProductDataValidator { */ private void validatePaymentChannelFundSourceMappings(final DataValidatorBuilder baseDataValidator, final JsonElement element) { if (this.fromApiJsonHelper.parameterExists(LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element)) { - final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( - LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); + final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper + .extractJsonArrayNamed(LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); if (paymentChannelMappingArray != null && paymentChannelMappingArray.size() > 0) { int i = 0; do { final JsonObject jsonObject = paymentChannelMappingArray.get(i).getAsJsonObject(); - final Long paymentTypeId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.PAYMENT_TYPE.getValue(), jsonObject); - final Long paymentSpecificFundAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.FUND_SOURCE.getValue(), jsonObject); + final Long paymentTypeId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.PAYMENT_TYPE.getValue(), + jsonObject); + final Long paymentSpecificFundAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.FUND_SOURCE.getValue(), jsonObject); - baseDataValidator - .reset() - .parameter( - LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." - + LoanProductAccountingParams.PAYMENT_TYPE.getValue()).value(paymentTypeId).notNull() - .integerGreaterThanZero(); - baseDataValidator - .reset() - .parameter( - LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." - + LoanProductAccountingParams.FUND_SOURCE.getValue()).value(paymentSpecificFundAccountId) - .notNull().integerGreaterThanZero(); + baseDataValidator.reset() + .parameter(LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." + + LoanProductAccountingParams.PAYMENT_TYPE.getValue()) + .value(paymentTypeId).notNull().integerGreaterThanZero(); + baseDataValidator.reset() + .parameter(LoanProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." + + LoanProductAccountingParams.FUND_SOURCE.getValue()) + .value(paymentSpecificFundAccountId).notNull().integerGreaterThanZero(); i++; } while (i < paymentChannelMappingArray.size()); } @@ -1556,10 +1496,9 @@ public final class LoanProductDataValidator { final JsonObject jsonObject = chargeToIncomeAccountMappingArray.get(i).getAsJsonObject(); final Long chargeId = this.fromApiJsonHelper.extractLongNamed(LoanProductAccountingParams.CHARGE_ID.getValue(), jsonObject); - final Long incomeAccountId = this.fromApiJsonHelper.extractLongNamed( - LoanProductAccountingParams.INCOME_ACCOUNT_ID.getValue(), jsonObject); - baseDataValidator.reset() - .parameter(parameterName + "[" + i + "]." + LoanProductAccountingParams.CHARGE_ID.getValue()) + final Long incomeAccountId = this.fromApiJsonHelper + .extractLongNamed(LoanProductAccountingParams.INCOME_ACCOUNT_ID.getValue(), jsonObject); + baseDataValidator.reset().parameter(parameterName + "[" + i + "]." + LoanProductAccountingParams.CHARGE_ID.getValue()) .value(chargeId).notNull().integerGreaterThanZero(); baseDataValidator.reset() .parameter(parameterName + "[" + i + "]." + LoanProductAccountingParams.INCOME_ACCOUNT_ID.getValue()) @@ -1596,8 +1535,8 @@ public final class LoanProductDataValidator { if ((minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) > 0) && (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) > 0)) { - baseDataValidator.reset().parameter(principalParameterName).value(principalAmount) - .inMinAndMaxAmountRange(minPrincipalAmount, maxPrincipalAmount); + baseDataValidator.reset().parameter(principalParameterName).value(principalAmount).inMinAndMaxAmountRange(minPrincipalAmount, + maxPrincipalAmount); } else { if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) > 0) { baseDataValidator.reset().parameter(principalParameterName).value(principalAmount).notLessThanMin(minPrincipalAmount); @@ -1777,8 +1716,11 @@ public final class LoanProductDataValidator { private void validateNominalInterestRatePerPeriodMinMaxConstraint(final JsonElement element, final LoanProduct loanProduct, final DataValidatorBuilder baseDataValidator) { - if ((this.fromApiJsonHelper.parameterExists("isLinkedToFloatingInterestRates", element) && this.fromApiJsonHelper - .extractBooleanNamed("isLinkedToFloatingInterestRates", element) == true) || loanProduct.isLinkedToFloatingInterestRate()) { return; } + if ((this.fromApiJsonHelper.parameterExists("isLinkedToFloatingInterestRates", element) + && this.fromApiJsonHelper.extractBooleanNamed("isLinkedToFloatingInterestRates", element) == true) + || loanProduct.isLinkedToFloatingInterestRate()) { + return; + } boolean iRPUpdated = false; boolean minIRPUpdated = false; boolean maxIRPUpdated = false; @@ -1855,8 +1797,10 @@ public final class LoanProductDataValidator { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } private void validateBorrowerCycleVariations(final JsonElement element, final DataValidatorBuilder baseDataValidator) { @@ -1867,10 +1811,11 @@ public final class LoanProductDataValidator { private void validateBorrowerCyclePrincipalVariations(final JsonElement element, final DataValidatorBuilder baseDataValidator) { - validateBorrowerCycleVariations(element, baseDataValidator, LoanProductConstants.PRINCIPAL_VARIATIONS_FOR_BORROWER_CYCLE_PARAMETER_NAME, + validateBorrowerCycleVariations(element, baseDataValidator, + LoanProductConstants.PRINCIPAL_VARIATIONS_FOR_BORROWER_CYCLE_PARAMETER_NAME, LoanProductConstants.PRINCIPAL_PER_CYCLE_PARAMETER_NAME, LoanProductConstants.MIN_PRINCIPAL_PER_CYCLE_PARAMETER_NAME, - LoanProductConstants.MIN_PRINCIPAL_PER_CYCLE_PARAMETER_NAME, LoanProductConstants.PRINCIPAL_VALUE_USAGE_CONDITION_PARAM_NAME, - LoanProductConstants.PRINCIPAL_CYCLE_NUMBERS_PARAM_NAME); + LoanProductConstants.MIN_PRINCIPAL_PER_CYCLE_PARAMETER_NAME, + LoanProductConstants.PRINCIPAL_VALUE_USAGE_CONDITION_PARAM_NAME, LoanProductConstants.PRINCIPAL_CYCLE_NUMBERS_PARAM_NAME); } private void validateBorrowerCycleRepaymentVariations(final JsonElement element, final DataValidatorBuilder baseDataValidator) { @@ -1888,7 +1833,8 @@ public final class LoanProductDataValidator { LoanProductConstants.INTEREST_RATE_PER_PERIOD_PER_CYCLE_PARAMETER_NAME, LoanProductConstants.MIN_INTEREST_RATE_PER_PERIOD_PER_CYCLE_PARAMETER_NAME, LoanProductConstants.MAX_INTEREST_RATE_PER_PERIOD_PER_CYCLE_PARAMETER_NAME, - LoanProductConstants.INTEREST_RATE_VALUE_USAGE_CONDITION_PARAM_NAME, LoanProductConstants.INTEREST_RATE_VALUE_USAGE_CONDITION_PARAM_NAME); + LoanProductConstants.INTEREST_RATE_VALUE_USAGE_CONDITION_PARAM_NAME, + LoanProductConstants.INTEREST_RATE_VALUE_USAGE_CONDITION_PARAM_NAME); } private void validateBorrowerCycleVariations(final JsonElement element, final DataValidatorBuilder baseDataValidator, @@ -1905,16 +1851,16 @@ public final class LoanProductDataValidator { do { final JsonObject jsonObject = variationArray.get(i).getAsJsonObject(); - BigDecimal defaultValue = this.fromApiJsonHelper.extractBigDecimalNamed(LoanProductConstants.DEFAULT_VALUE_PARAMETER_NAME, - jsonObject, locale); + BigDecimal defaultValue = this.fromApiJsonHelper + .extractBigDecimalNamed(LoanProductConstants.DEFAULT_VALUE_PARAMETER_NAME, jsonObject, locale); BigDecimal minValue = this.fromApiJsonHelper.extractBigDecimalNamed(LoanProductConstants.MIN_VALUE_PARAMETER_NAME, jsonObject, locale); BigDecimal maxValue = this.fromApiJsonHelper.extractBigDecimalNamed(LoanProductConstants.MAX_VALUE_PARAMETER_NAME, jsonObject, locale); Integer cycleNumber = this.fromApiJsonHelper.extractIntegerNamed(LoanProductConstants.BORROWER_CYCLE_NUMBER_PARAM_NAME, jsonObject, locale); - Integer valueUsageCondition = this.fromApiJsonHelper.extractIntegerNamed( - LoanProductConstants.VALUE_CONDITION_TYPE_PARAM_NAME, jsonObject, locale); + Integer valueUsageCondition = this.fromApiJsonHelper + .extractIntegerNamed(LoanProductConstants.VALUE_CONDITION_TYPE_PARAM_NAME, jsonObject, locale); baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue).notBlank(); if (minValue != null) { @@ -1926,8 +1872,8 @@ public final class LoanProductDataValidator { } if ((minValue != null && minValue.compareTo(BigDecimal.ZERO) > 0) && (maxValue != null && maxValue.compareTo(BigDecimal.ZERO) > 0)) { - baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue) - .inMinAndMaxAmountRange(minValue, maxValue); + baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue).inMinAndMaxAmountRange(minValue, + maxValue); } else { if (minValue != null && minValue.compareTo(BigDecimal.ZERO) > 0) { baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue).notLessThanMin(minValue); @@ -1940,13 +1886,8 @@ public final class LoanProductDataValidator { if (valueUsageCondition != null) { conditionType = LoanProductValueConditionType.fromInt(valueUsageCondition); } - baseDataValidator - .reset() - .parameter(valueUsageConditionParamName) - .value(valueUsageCondition) - .notNull() - .inMinMaxRange(LoanProductValueConditionType.EQUAL.getValue(), - LoanProductValueConditionType.GREATERTHAN.getValue()); + baseDataValidator.reset().parameter(valueUsageConditionParamName).value(valueUsageCondition).notNull().inMinMaxRange( + LoanProductValueConditionType.EQUAL.getValue(), LoanProductValueConditionType.GREATERTHAN.getValue()); if (lastConditionType.equals(LoanProductValueConditionType.EQUAL) && conditionType.equals(LoanProductValueConditionType.GREATERTHAN)) { if (lastCycleNumber == 0) { @@ -2003,8 +1944,8 @@ public final class LoanProductDataValidator { if (loanProduct == null || this.fromApiJsonHelper.parameterExists(LoanProductConstants.minimumGuaranteeFromGuarantorParamName, element)) { - minimumGuaranteeFromGuarantor = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanProductConstants.minimumGuaranteeFromGuarantorParamName, element); + minimumGuaranteeFromGuarantor = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanProductConstants.minimumGuaranteeFromGuarantorParamName, element); if (minimumGuaranteeFromGuarantor == null) { minimumGuaranteeFromGuarantor = BigDecimal.ZERO; } @@ -2012,16 +1953,16 @@ public final class LoanProductDataValidator { if (loanProduct == null || this.fromApiJsonHelper.parameterExists(LoanProductConstants.minimumGuaranteeFromOwnFundsParamName, element)) { - minimumGuaranteeFromOwnFunds = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - LoanProductConstants.minimumGuaranteeFromOwnFundsParamName, element); + minimumGuaranteeFromOwnFunds = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(LoanProductConstants.minimumGuaranteeFromOwnFundsParamName, element); if (minimumGuaranteeFromOwnFunds == null) { minimumGuaranteeFromOwnFunds = BigDecimal.ZERO; } } if (mandatoryGuarantee.compareTo(minimumGuaranteeFromOwnFunds.add(minimumGuaranteeFromGuarantor)) < 0) { - baseDataValidator.parameter(LoanProductConstants.mandatoryGuaranteeParamName).failWithCode( - "must.be.greter.than.sum.of.min.funds"); + baseDataValidator.parameter(LoanProductConstants.mandatoryGuaranteeParamName) + .failWithCode("must.be.greter.than.sum.of.min.funds"); } } @@ -2033,9 +1974,10 @@ public final class LoanProductDataValidator { .fromInt(interestCalculationPeriodType); boolean considerPartialPeriodUpdates = interestCalculationPeriodMethod.isDaily(); - if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, element)) { - final Boolean considerPartialInterestEnabled = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, element); + if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, + element)) { + final Boolean considerPartialInterestEnabled = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, element); baseDataValidator.reset().parameter(LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME) .value(considerPartialInterestEnabled).notNull().isOneOfTheseValues(true, false); final boolean considerPartialPeriods = considerPartialInterestEnabled == null ? false : considerPartialInterestEnabled; @@ -2051,9 +1993,10 @@ public final class LoanProductDataValidator { if (!considerPartialPeriodUpdates) { Boolean isInterestRecalculationEnabled = null; - if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME, element)) { - isInterestRecalculationEnabled = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME, element); + if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME, + element)) { + isInterestRecalculationEnabled = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.IS_INTEREST_RECALCULATION_ENABLED_PARAMETER_NAME, element); } else if (loanProduct != null) { isInterestRecalculationEnabled = loanProduct.isInterestRecalculationEnabled(); } @@ -2076,8 +2019,8 @@ public final class LoanProductDataValidator { Boolean variableInstallments = null; if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.allowVariableInstallmentsParamName, element)) { - variableInstallments = this.fromApiJsonHelper.extractBooleanNamed( - LoanProductConstants.allowVariableInstallmentsParamName, element); + variableInstallments = this.fromApiJsonHelper + .extractBooleanNamed(LoanProductConstants.allowVariableInstallmentsParamName, element); } else if (loanProduct != null) { isInterestRecalculationEnabled = loanProduct.allowVariabeInstallments(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanDropdownReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanDropdownReadPlatformService.java index 11216b863..4a4ad1c8a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanDropdownReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanDropdownReadPlatformService.java @@ -46,7 +46,9 @@ public interface LoanDropdownReadPlatformService { List retrieveLoanCycleValueConditionTypeOptions(); List retrieveInterestRecalculationCompoundingTypeOptions(); + List retrieveInterestRecalculationNthDayTypeOptions(); + List retrieveInterestRecalculationDayOfWeekTypeOptions(); List retrieveRescheduleStrategyTypeOptions(); @@ -55,4 +57,4 @@ public interface LoanDropdownReadPlatformService { List retrivePreCloseInterestCalculationStrategyOptions(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanDropdownReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanDropdownReadPlatformServiceImpl.java index fc68a143a..ef788c6e4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanDropdownReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanDropdownReadPlatformServiceImpl.java @@ -63,7 +63,8 @@ public class LoanDropdownReadPlatformServiceImpl implements LoanDropdownReadPlat private final LoanTransactionProcessingStrategyRepository loanTransactionProcessingStrategyRepository; @Autowired - public LoanDropdownReadPlatformServiceImpl(final LoanTransactionProcessingStrategyRepository loanTransactionProcessingStrategyRepository) { + public LoanDropdownReadPlatformServiceImpl( + final LoanTransactionProcessingStrategyRepository loanTransactionProcessingStrategyRepository) { this.loanTransactionProcessingStrategyRepository = loanTransactionProcessingStrategyRepository; } @@ -131,7 +132,7 @@ public class LoanDropdownReadPlatformServiceImpl implements LoanDropdownReadPlat public List retrieveInterestRateFrequencyTypeOptions() { // support for monthly and annual percentage rate (MPR) and (APR) final List interestRateFrequencyTypeOptions = Arrays.asList(interestRateFrequencyType(PeriodFrequencyType.MONTHS), - interestRateFrequencyType(PeriodFrequencyType.YEARS), interestRateFrequencyType(PeriodFrequencyType.WHOLE_TERM)); + interestRateFrequencyType(PeriodFrequencyType.YEARS), interestRateFrequencyType(PeriodFrequencyType.WHOLE_TERM)); return interestRateFrequencyTypeOptions; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanEnumerations.java index 9e4f4e048..4f429cbe4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanEnumerations.java @@ -88,20 +88,20 @@ public class LoanEnumerations { EnumOptionData optionData = null; switch (type) { case DAYS: - optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + PeriodFrequencyType.DAYS.getCode(), "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"); + 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"); + 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"); + optionData = new EnumOptionData(PeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + PeriodFrequencyType.YEARS.getCode(), "Years"); break; default: optionData = new EnumOptionData(PeriodFrequencyType.INVALID.getValue().longValue(), PeriodFrequencyType.INVALID.getCode(), @@ -120,20 +120,20 @@ public class LoanEnumerations { EnumOptionData optionData = null; switch (type) { case DAYS: - optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + PeriodFrequencyType.DAYS.getCode(), "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"); + 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"); + 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"); + optionData = new EnumOptionData(PeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + PeriodFrequencyType.YEARS.getCode(), "Years"); break; default: optionData = new EnumOptionData(PeriodFrequencyType.INVALID.getValue().longValue(), PeriodFrequencyType.INVALID.getCode(), @@ -200,20 +200,20 @@ public class LoanEnumerations { EnumOptionData optionData = null; switch (type) { case DAYS: - optionData = new EnumOptionData(PeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + PeriodFrequencyType.DAYS.getCode(), "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"); + 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"); + 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"); + optionData = new EnumOptionData(PeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + PeriodFrequencyType.YEARS.getCode(), "Years"); break; default: optionData = new EnumOptionData(PeriodFrequencyType.INVALID.getValue().longValue(), PeriodFrequencyType.INVALID.getCode(), @@ -232,16 +232,16 @@ public class LoanEnumerations { EnumOptionData optionData = null; switch (type) { case MONTHS: - optionData = new EnumOptionData(PeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix - + PeriodFrequencyType.MONTHS.getCode(), "Per month"); + 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"); + optionData = new EnumOptionData(PeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + PeriodFrequencyType.YEARS.getCode(), "Per year"); break; case WHOLE_TERM: - optionData = new EnumOptionData(PeriodFrequencyType.WHOLE_TERM.getValue().longValue(), codePrefix - + PeriodFrequencyType.WHOLE_TERM.getCode(), "Whole term"); + optionData = new EnumOptionData(PeriodFrequencyType.WHOLE_TERM.getValue().longValue(), + codePrefix + PeriodFrequencyType.WHOLE_TERM.getCode(), "Whole term"); break; default: optionData = new EnumOptionData(PeriodFrequencyType.INVALID.getValue().longValue(), PeriodFrequencyType.INVALID.getCode(), @@ -517,8 +517,8 @@ public class LoanEnumerations { LoanProductParamType.REPAYMENT.getCode(), "repayment"); break; default: - optionData = new EnumOptionData(LoanProductParamType.INVALID.getValue().longValue(), - LoanProductParamType.INVALID.getCode(), "Invalid"); + optionData = new EnumOptionData(LoanProductParamType.INVALID.getValue().longValue(), LoanProductParamType.INVALID.getCode(), + "Invalid"); break; } return optionData; @@ -605,10 +605,12 @@ public class LoanEnumerations { } return optionData; } + public static EnumOptionData interestRecalculationCompoundingNthDayType(final Integer id) { if (id == null) { return null; } return interestRecalculationCompoundingNthDayType(NthDayType.fromInt(id)); } + public static EnumOptionData interestRecalculationCompoundingNthDayType(final NthDayType type) { final String codePrefix = "interestRecalculationCompounding."; long nthDayValue = type.getValue().longValue(); @@ -638,10 +640,12 @@ public class LoanEnumerations { } return optionData; } + public static EnumOptionData interestRecalculationCompoundingDayOfWeekType(final Integer id) { if (id == null) { return null; } return interestRecalculationCompoundingDayOfWeekType(DayOfWeekType.fromInt(id)); } + public static EnumOptionData interestRecalculationCompoundingDayOfWeekType(final DayOfWeekType type) { final String codePrefix = "interestRecalculationCompounding."; EnumOptionData optionData = new EnumOptionData(type.getValue().longValue(), codePrefix + type.getCode(), type.toString()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductReadPlatformService.java index 1dc801f27..54df64fc7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductReadPlatformService.java @@ -47,4 +47,4 @@ public interface LoanProductReadPlatformService { Collection retrieveLoanProductBorrowerCycleVariations(Long loanProductId); LoanProductData retrieveLoanProductFloatingDetails(Long loanProductId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductReadPlatformServiceImpl.java index 093adcfd1..f4acbe60c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductReadPlatformServiceImpl.java @@ -68,7 +68,7 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo this.chargeReadPlatformService = chargeReadPlatformService; this.jdbcTemplate = new JdbcTemplate(dataSource); this.fineractEntityAccessUtil = fineractEntityAccessUtil; - this.rateReadService=rateReadService; + this.rateReadService = rateReadService; } @Override @@ -77,7 +77,8 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo try { final Collection charges = this.chargeReadPlatformService.retrieveLoanProductCharges(loanProductId); final Collection rates = this.rateReadService.retrieveProductLoanRates(loanProductId); - final Collection borrowerCycleVariationDatas = retrieveLoanProductBorrowerCycleVariations(loanProductId); + final Collection borrowerCycleVariationDatas = retrieveLoanProductBorrowerCycleVariations( + loanProductId); final LoanProductMapper rm = new LoanProductMapper(charges, borrowerCycleVariationDatas, rates); final String sql = "select " + rm.loanProductSchema() + " where lp.id = ?"; @@ -125,9 +126,9 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo String sql = "select " + rm.schema(); if (inClause != null && !inClause.trim().isEmpty()) { - sql += " where lp.id in ("+inClause+") "; - //Here no need to check injection as this is internal where clause - // SQLInjectionValidator.validateSQLInput(inClause); + sql += " where lp.id in (" + inClause + ") "; + // Here no need to check injection as this is internal where clause + // SQLInjectionValidator.validateSQLInput(inClause); } return this.jdbcTemplate.query(sql, rm, new Object[] {}); @@ -204,16 +205,14 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo + "lpr.id as lprId, lpr.product_id as productId, lpr.compound_type_enum as compoundType, lpr.reschedule_strategy_enum as rescheduleStrategy, " + "lpr.rest_frequency_type_enum as restFrequencyEnum, lpr.rest_frequency_interval as restFrequencyInterval, " + "lpr.rest_frequency_nth_day_enum as restFrequencyNthDayEnum, " - + "lpr.rest_frequency_weekday_enum as restFrequencyWeekDayEnum, " - + "lpr.rest_frequency_on_day as restFrequencyOnDay, " + + "lpr.rest_frequency_weekday_enum as restFrequencyWeekDayEnum, " + "lpr.rest_frequency_on_day as restFrequencyOnDay, " + "lpr.arrears_based_on_original_schedule as isArrearsBasedOnOriginalSchedule, " + "lpr.compounding_frequency_type_enum as compoundingFrequencyTypeEnum, lpr.compounding_frequency_interval as compoundingInterval, " + "lpr.compounding_frequency_nth_day_enum as compoundingFrequencyNthDayEnum, " + "lpr.compounding_frequency_weekday_enum as compoundingFrequencyWeekDayEnum, " + "lpr.compounding_frequency_on_day as compoundingFrequencyOnDay, " + "lpr.is_compounding_to_be_posted_as_transaction as isCompoundingToBePostedAsTransaction, " - + "lpr.allow_compounding_on_eod as allowCompoundingOnEod, " - + "lp.hold_guarantee_funds as holdGuaranteeFunds, " + + "lpr.allow_compounding_on_eod as allowCompoundingOnEod, " + "lp.hold_guarantee_funds as holdGuaranteeFunds, " + "lp.principal_threshold_for_last_installment as principalThresholdForLastInstallment, " + "lp.sync_expected_with_disbursement_date as syncExpectedWithDisbursementDate, " + "lpg.id as lpgId, lpg.mandatory_guarantee as mandatoryGuarantee, " @@ -224,19 +223,16 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo + "lca.loan_transaction_strategy_id as transactionProcessingStrategyBoolean,lca.interest_calculated_in_period_enum as interestCalcPeriodBoolean, lca.arrearstolerance_amount as arrearsToleranceBoolean, " + "lca.repay_every as repaymentFrequencyBoolean, lca.moratorium as graceOnPrincipalAndInterestBoolean, lca.grace_on_arrears_ageing as graceOnArrearsAgingBoolean, " + "lp.is_linked_to_floating_interest_rates as isLinkedToFloatingInterestRates, " - + "lfr.floating_rates_id as floatingRateId, " - + "fr.name as floatingRateName, " + + "lfr.floating_rates_id as floatingRateId, " + "fr.name as floatingRateName, " + "lfr.interest_rate_differential as interestRateDifferential, " + "lfr.min_differential_lending_rate as minDifferentialLendingRate, " + "lfr.default_differential_lending_rate as defaultDifferentialLendingRate, " + "lfr.max_differential_lending_rate as maxDifferentialLendingRate, " + "lfr.is_floating_interest_rate_calculation_allowed as isFloatingInterestRateCalculationAllowed, " - + "lp.allow_variabe_installments as isVariableIntallmentsAllowed, " - + "lvi.minimum_gap as minimumGap, " + + "lp.allow_variabe_installments as isVariableIntallmentsAllowed, " + "lvi.minimum_gap as minimumGap, " + "lvi.maximum_gap as maximumGap, " + "lp.can_use_for_topup as canUseForTopup, lp.is_equal_amortization as isEqualAmortization " - + " from m_product_loan lp " - + " left join m_fund f on f.id = lp.fund_id " + + " from m_product_loan lp " + " left join m_fund f on f.id = lp.fund_id " + " left join m_product_loan_recalculation_details lpr on lpr.product_id=lp.id " + " left join m_product_loan_guarantee_details lpg on lpg.loan_product_id=lp.id " + " left join ref_loan_transaction_processing_strategy ltps on ltps.id = lp.loan_transaction_strategy_id" @@ -267,8 +263,8 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final BigDecimal principal = rs.getBigDecimal("principal"); final BigDecimal minPrincipal = rs.getBigDecimal("minPrincipal"); @@ -281,7 +277,8 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo final Integer repaymentEvery = JdbcSupport.getInteger(rs, "repaidEvery"); final Integer graceOnPrincipalPayment = JdbcSupport.getIntegerDefaultToNullIfZero(rs, "graceOnPrincipalPayment"); - final Integer recurringMoratoriumOnPrincipalPeriods = JdbcSupport.getIntegerDefaultToNullIfZero(rs, "recurringMoratoriumOnPrincipalPeriods"); + final Integer recurringMoratoriumOnPrincipalPeriods = JdbcSupport.getIntegerDefaultToNullIfZero(rs, + "recurringMoratoriumOnPrincipalPeriods"); final Integer graceOnInterestPayment = JdbcSupport.getIntegerDefaultToNullIfZero(rs, "graceOnInterestPayment"); final Integer graceOnInterestCharged = JdbcSupport.getIntegerDefaultToNullIfZero(rs, "graceOnInterestCharged"); final Integer graceOnArrearsAgeing = JdbcSupport.getIntegerDefaultToNullIfZero(rs, "graceOnArrearsAgeing"); @@ -418,12 +415,11 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo .preCloseInterestCalculationStrategy(preCloseInterestCalculationStrategyEnumValue); final boolean allowCompoundingOnEod = rs.getBoolean("allowCompoundingOnEod"); - interestRecalculationData = new LoanProductInterestRecalculationData(lprId, productId, - interestRecalculationCompoundingType, rescheduleStrategyType, restFrequencyType, restFrequencyInterval, - restFrequencyNthDayEnum, restFrequencyWeekDayEnum, restFrequencyOnDay, compoundingFrequencyType, - compoundingInterval, compoundingFrequencyNthDayEnum, compoundingFrequencyWeekDayEnum, compoundingFrequencyOnDay, - isArrearsBasedOnOriginalSchedule, isCompoundingToBePostedAsTransaction, preCloseInterestCalculationStrategy, - allowCompoundingOnEod); + interestRecalculationData = new LoanProductInterestRecalculationData(lprId, productId, interestRecalculationCompoundingType, + rescheduleStrategyType, restFrequencyType, restFrequencyInterval, restFrequencyNthDayEnum, restFrequencyWeekDayEnum, + restFrequencyOnDay, compoundingFrequencyType, compoundingInterval, compoundingFrequencyNthDayEnum, + compoundingFrequencyWeekDayEnum, compoundingFrequencyOnDay, isArrearsBasedOnOriginalSchedule, + isCompoundingToBePostedAsTransaction, preCloseInterestCalculationStrategy, allowCompoundingOnEod); } final boolean amortization = rs.getBoolean("amortizationBoolean"); @@ -456,7 +452,7 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo final boolean syncExpectedWithDisbursementDate = rs.getBoolean("syncExpectedWithDisbursementDate"); final boolean canUseForTopup = rs.getBoolean("canUseForTopup"); - final Collection rateOptions= null; + final Collection rateOptions = null; final boolean isRatesEnabled = false; return new LoanProductData(id, name, shortName, description, currency, principal, minPrincipal, maxPrincipal, tolerance, @@ -464,8 +460,8 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo minInterestRatePerPeriod, maxInterestRatePerPeriod, annualInterestRate, repaymentFrequencyType, interestRateFrequencyType, amortizationType, interestType, interestCalculationPeriodType, allowPartialPeriodInterestCalcualtion, fundId, fundName, transactionStrategyId, transactionStrategyName, - graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, this.charges, accountingRuleType, - includeInBorrowerCycle, useBorrowerCycle, startDate, closeDate, status, externalId, + graceOnPrincipalPayment, recurringMoratoriumOnPrincipalPeriods, graceOnInterestPayment, graceOnInterestCharged, + this.charges, accountingRuleType, includeInBorrowerCycle, useBorrowerCycle, startDate, closeDate, status, externalId, principalVariationsForBorrowerCycle, interestRateVariationsForBorrowerCycle, numberOfRepaymentVariationsForBorrowerCycle, multiDisburseLoan, maxTrancheCount, outstandingLoanBalance, graceOnArrearsAgeing, overdueDaysForNPA, daysInMonthType, daysInYearType, isInterestRecalculationEnabled, @@ -474,7 +470,8 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo installmentAmountInMultiplesOf, allowAttributeOverrides, isLinkedToFloatingInterestRates, floatingRateId, floatingRateName, interestRateDifferential, minDifferentialLendingRate, defaultDifferentialLendingRate, maxDifferentialLendingRate, isFloatingInterestRateCalculationAllowed, isVariableIntallmentsAllowed, minimumGap, - maximumGap, syncExpectedWithDisbursementDate, canUseForTopup, isEqualAmortization, rateOptions, this.rates, isRatesEnabled); + maximumGap, syncExpectedWithDisbursementDate, canUseForTopup, isEqualAmortization, rateOptions, this.rates, + isRatesEnabled); } } @@ -556,7 +553,7 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo sql += " and id in (" + inClause + ") "; } - return this.jdbcTemplate.query(sql, rm, new Object[] {currencyCode}); + return this.jdbcTemplate.query(sql, rm, new Object[] { currencyCode }); } @Override @@ -645,14 +642,12 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo } } - private static final class LoanProductFloatingRateMapper implements RowMapper { public LoanProductFloatingRateMapper() {} public String schema() { - return "lp.id as id, lp.name as name," - + "lp.is_linked_to_floating_interest_rates as isLinkedToFloatingInterestRates, " + return "lp.id as id, lp.name as name," + "lp.is_linked_to_floating_interest_rates as isLinkedToFloatingInterestRates, " + "lfr.floating_rates_id as floatingRateId, " + "fr.name as floatingRateName, " + "lfr.interest_rate_differential as interestRateDifferential, " + "lfr.min_differential_lending_rate as minDifferentialLendingRate, " @@ -678,9 +673,9 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo final BigDecimal maxDifferentialLendingRate = rs.getBigDecimal("maxDifferentialLendingRate"); final boolean isFloatingInterestRateCalculationAllowed = rs.getBoolean("isFloatingInterestRateCalculationAllowed"); - return LoanProductData.loanProductWithFloatingRates(id, name, isLinkedToFloatingInterestRates, floatingRateId, - floatingRateName, interestRateDifferential, minDifferentialLendingRate, defaultDifferentialLendingRate, - maxDifferentialLendingRate, isFloatingInterestRateCalculationAllowed); + return LoanProductData.loanProductWithFloatingRates(id, name, isLinkedToFloatingInterestRates, floatingRateId, floatingRateName, + interestRateDifferential, minDifferentialLendingRate, defaultDifferentialLendingRate, maxDifferentialLendingRate, + isFloatingInterestRateCalculationAllowed); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductWritePlatformService.java index 16acb1de5..d95de8fda 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductWritePlatformService.java @@ -26,4 +26,4 @@ public interface LoanProductWritePlatformService { CommandProcessingResult createLoanProduct(JsonCommand command); CommandProcessingResult updateLoanProduct(Long loanProductId, JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductWritePlatformServiceJpaRepositoryImpl.java index 38b6c8e59..25dccc1ec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/service/LoanProductWritePlatformServiceJpaRepositoryImpl.java @@ -93,10 +93,8 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro final LoanTransactionProcessingStrategyRepository loanTransactionProcessingStrategyRepository, final ChargeRepositoryWrapper chargeRepository, final RateRepositoryWrapper rateRepository, final ProductToGLAccountMappingWritePlatformService accountMappingWritePlatformService, - final FineractEntityAccessUtil fineractEntityAccessUtil, - final FloatingRateRepositoryWrapper floatingRateRepository, - final LoanRepositoryWrapper loanRepositoryWrapper, - final BusinessEventNotifierService businessEventNotifierService) { + final FineractEntityAccessUtil fineractEntityAccessUtil, final FloatingRateRepositoryWrapper floatingRateRepository, + final LoanRepositoryWrapper loanRepositoryWrapper, final BusinessEventNotifierService businessEventNotifierService) { this.context = context; this.fromApiJsonDeserializer = fromApiJsonDeserializer; this.loanProductRepository = loanProductRepository; @@ -126,14 +124,15 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro final Fund fund = findFundByIdIfProvided(command.longValueOfParameterNamed("fundId")); final Long transactionProcessingStrategyId = command.longValueOfParameterNamed("transactionProcessingStrategyId"); - final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy = findStrategyByIdIfProvided(transactionProcessingStrategyId); + final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy = findStrategyByIdIfProvided( + transactionProcessingStrategyId); final String currencyCode = command.stringValueOfParameterNamed("currencyCode"); final List charges = assembleListOfProductCharges(command, currencyCode); final List rates = assembleListOfProductRates(command); FloatingRate floatingRate = null; - if(command.parameterExists("floatingRatesId")){ + if (command.parameterExists("floatingRatesId")) { floatingRate = this.floatingRateRepository .findOneWithNotFoundDetection(command.longValueOfParameterNamed("floatingRatesId")); } @@ -145,11 +144,11 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro // save accounting mappings this.accountMappingWritePlatformService.createLoanProductToGLAccountMapping(loanproduct.getId(), command); - // check if the office specific products are enabled. If yes, then save this savings product against a specific office + // check if the office specific products are enabled. If yes, then + // save this savings product against a specific office // i.e. this savings product is specific for this office. fineractEntityAccessUtil.checkConfigurationAndAddProductResrictionsForUserOffice( - FineractEntityAccessType.OFFICE_ACCESS_TO_LOAN_PRODUCTS, - loanproduct.getId()); + FineractEntityAccessType.OFFICE_ACCESS_TO_LOAN_PRODUCTS, loanproduct.getId()); this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_PRODUCT_CREATE, constructEntityMap(BusinessEntity.LOAN_PRODUCT, loanproduct)); @@ -165,10 +164,10 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } @@ -185,8 +184,7 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro private Fund findFundByIdIfProvided(final Long fundId) { Fund fund = null; if (fundId != null) { - fund = this.fundRepository.findById(fundId) - .orElseThrow(() -> new FundNotFoundException(fundId)); + fund = this.fundRepository.findById(fundId).orElseThrow(() -> new FundNotFoundException(fundId)); } return fund; } @@ -204,13 +202,13 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro this.fromApiJsonDeserializer.validateForUpdate(command.json(), product); validateInputDates(command); - if(anyChangeInCriticalFloatingRateLinkedParams(command, product) - && this.loanRepositoryWrapper.doNonClosedLoanAccountsExistForProduct(product.getId())){ + if (anyChangeInCriticalFloatingRateLinkedParams(command, product) + && this.loanRepositoryWrapper.doNonClosedLoanAccountsExistForProduct(product.getId())) { throw new LoanProductCannotBeModifiedDueToNonClosedLoansException(product.getId()); } FloatingRate floatingRate = null; - if(command.parameterExists("floatingRatesId")){ + if (command.parameterExists("floatingRatesId")) { floatingRate = this.floatingRateRepository .findOneWithNotFoundDetection(command.longValueOfParameterNamed("floatingRatesId")); } @@ -225,7 +223,8 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro if (changes.containsKey("transactionProcessingStrategyId")) { final Long transactionProcessingStrategyId = (Long) changes.get("transactionProcessingStrategyId"); - final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy = findStrategyByIdIfProvided(transactionProcessingStrategyId); + final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy = findStrategyByIdIfProvided( + transactionProcessingStrategyId); product.update(loanTransactionProcessingStrategy); } @@ -264,19 +263,21 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return new CommandProcessingResult(Long.valueOf(-1)); - }catch(final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); - return CommandProcessingResult.empty(); + return CommandProcessingResult.empty(); } } private boolean anyChangeInCriticalFloatingRateLinkedParams(JsonCommand command, LoanProduct product) { - final boolean isChangeFromFloatingToFlatOrViceVersa = command.isChangeInBooleanParameterNamed("isLinkedToFloatingInterestRates", product.isLinkedToFloatingInterestRate()); + final boolean isChangeFromFloatingToFlatOrViceVersa = command.isChangeInBooleanParameterNamed("isLinkedToFloatingInterestRates", + product.isLinkedToFloatingInterestRate()); final boolean isChangeInCriticalFloatingRateParams = product.getFloatingRates() != null && (command.isChangeInLongParameterNamed("floatingRatesId", product.getFloatingRates().getFloatingRate().getId()) - || command.isChangeInBigDecimalParameterNamed("interestRateDifferential", product.getFloatingRates().getInterestRateDifferential())); + || command.isChangeInBigDecimalParameterNamed("interestRateDifferential", + product.getFloatingRates().getInterestRateDifferential())); return isChangeFromFloatingToFlatOrViceVersa || isChangeInCriticalFloatingRateParams; } @@ -344,18 +345,18 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro if (realCause.getMessage().contains("'external_id'")) { final String externalId = command.stringValueOfParameterNamed("externalId"); - throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.externalId", "Loan Product with externalId `" - + externalId + "` already exists", "externalId", externalId); + throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.externalId", + "Loan Product with externalId `" + externalId + "` already exists", "externalId", externalId); } else if (realCause.getMessage().contains("'unq_name'")) { final String name = command.stringValueOfParameterNamed("name"); - throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.name", "Loan product with name `" + name - + "` already exists", "name", name); + throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.name", + "Loan product with name `" + name + "` already exists", "name", name); } else if (realCause.getMessage().contains("'unq_short_name'")) { final String shortName = command.stringValueOfParameterNamed("shortName"); - throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.short.name", "Loan product with short name `" - + shortName + "` already exists", "shortName", shortName); + throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.short.name", + "Loan product with short name `" + shortName + "` already exists", "shortName", shortName); } else if (realCause.getMessage().contains("Duplicate entry")) { final Object[] args = null; throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.charge", @@ -380,7 +381,8 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro LOG.error("Error occured.", dve); } - private Map constructEntityMap(final BusinessEventNotificationConstants.BusinessEntity entityEvent, Object entity) { + private Map constructEntityMap( + final BusinessEventNotificationConstants.BusinessEntity entityEvent, Object entity) { Map map = new HashMap<>(1); map.put(entityEvent, entity); return map; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/MeetingApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/MeetingApiConstants.java index 92f2e8e37..2b95eff3e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/MeetingApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/MeetingApiConstants.java @@ -44,4 +44,4 @@ public class MeetingApiConstants { public static final String calendarData = "calendarData"; public static final String attendanceTypeOptions = "attendanceTypeOptions"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/api/MeetingsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/api/MeetingsApiResource.java index 98dc69276..20d50bb9d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/api/MeetingsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/api/MeetingsApiResource.java @@ -80,9 +80,8 @@ public class MeetingsApiResource { private final ApiRequestParameterHelper apiRequestParameterHelper; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private static final Set MEETING_RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(MeetingApiConstants.idParamName, MeetingApiConstants.meetingDateParamName, - MeetingApiConstants.clientsAttendance, MeetingApiConstants.clients, - MeetingApiConstants.calendarData, MeetingApiConstants.attendanceTypeOptions)); + Arrays.asList(MeetingApiConstants.idParamName, MeetingApiConstants.meetingDateParamName, MeetingApiConstants.clientsAttendance, + MeetingApiConstants.clients, MeetingApiConstants.calendarData, MeetingApiConstants.attendanceTypeOptions)); @Autowired public MeetingsApiResource(final PlatformSecurityContext context, final MeetingReadPlatformService readPlatformService, @@ -151,8 +150,8 @@ public class MeetingsApiResource { this.context.authenticatedUser().validateHasReadPermission(MEETING_RESOURCE_NAME); - final Collection meetingsData = this.readPlatformService.retrieveMeetingsByEntity(entityId, CalendarEntityType - .valueOf(entityType.toUpperCase()).getValue(), limit); + final Collection meetingsData = this.readPlatformService.retrieveMeetingsByEntity(entityId, + CalendarEntityType.valueOf(entityType.toUpperCase()).getValue(), limit); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, meetingsData, MEETING_RESPONSE_DATA_PARAMETERS); @@ -278,4 +277,4 @@ public class MeetingsApiResource { return resourceDetails.build(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/AttendanceType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/AttendanceType.java index 941d26d43..523a4d332 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/AttendanceType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/AttendanceType.java @@ -73,4 +73,4 @@ public enum AttendanceType { return attendanceType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/domain/ClientAttendance.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/domain/ClientAttendance.java index e28a859f0..3778e7405 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/domain/ClientAttendance.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/domain/ClientAttendance.java @@ -29,7 +29,8 @@ import org.apache.fineract.portfolio.client.domain.Client; import org.apache.fineract.portfolio.meeting.domain.Meeting; @Entity -@Table(name = "m_client_attendance", uniqueConstraints = { @UniqueConstraint(columnNames = { "client_id", "meeting_id" }, name = "unique_client_meeting_attendance") }) +@Table(name = "m_client_attendance", uniqueConstraints = { + @UniqueConstraint(columnNames = { "client_id", "meeting_id" }, name = "unique_client_meeting_attendance") }) public class ClientAttendance extends AbstractPersistableCustom { @ManyToOne diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/AttendanceDropdownReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/AttendanceDropdownReadPlatformService.java index daf808f81..360fda24d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/AttendanceDropdownReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/AttendanceDropdownReadPlatformService.java @@ -24,4 +24,4 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; public interface AttendanceDropdownReadPlatformService { List retrieveAttendanceTypeOptions(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/AttendanceEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/AttendanceEnumerations.java index ba4871bfa..118ea926f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/AttendanceEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/AttendanceEnumerations.java @@ -68,4 +68,4 @@ public class AttendanceEnumerations { } return optionDatas; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformServiceImpl.java index 3dfaba0f6..c8551b8ef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformServiceImpl.java @@ -68,4 +68,4 @@ public class ClientAttendanceReadPlatformServiceImpl implements ClientAttendance return this.jdbcTemplate.query(sql, rm, new Object[] { meetingId }); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/data/MeetingDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/data/MeetingDataValidator.java index e09436f1d..51ebe38c8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/data/MeetingDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/data/MeetingDataValidator.java @@ -52,10 +52,9 @@ import org.springframework.stereotype.Component; public class MeetingDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set MEETING_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(MeetingApiConstants.meetingDateParamName, MeetingApiConstants.localeParamName, - MeetingApiConstants.dateFormatParamName, MeetingApiConstants.calendarIdParamName, - MeetingApiConstants.clientsAttendanceParamName)); + private static final Set MEETING_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(MeetingApiConstants.meetingDateParamName, + MeetingApiConstants.localeParamName, MeetingApiConstants.dateFormatParamName, MeetingApiConstants.calendarIdParamName, + MeetingApiConstants.clientsAttendanceParamName)); @Autowired public MeetingDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -157,4 +156,4 @@ public class MeetingDataValidator { } } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/domain/Meeting.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/domain/Meeting.java index 104b19af1..60c97b590 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/domain/Meeting.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/domain/Meeting.java @@ -52,7 +52,8 @@ import org.apache.fineract.portfolio.meeting.exception.MeetingDateException; import org.joda.time.LocalDate; @Entity -@Table(name = "m_meeting", uniqueConstraints = { @UniqueConstraint(columnNames = { "calendar_instance_id", "meeting_date" }, name = "unique_calendar_instance_id_meeting_date") }) +@Table(name = "m_meeting", uniqueConstraints = { + @UniqueConstraint(columnNames = { "calendar_instance_id", "meeting_date" }, name = "unique_calendar_instance_id_meeting_date") }) public class Meeting extends AbstractPersistableCustom { @ManyToOne @@ -75,12 +76,13 @@ public class Meeting extends AbstractPersistableCustom { this.meetingDate = meetingDate; } - public static Meeting createNew(final CalendarInstance calendarInstance, final Date meetingDate, Boolean isTransactionDateOnNonMeetingDate, - final boolean isSkipRepaymentOnFirstMonth, final int numberOfDays) { + public static Meeting createNew(final CalendarInstance calendarInstance, final Date meetingDate, + Boolean isTransactionDateOnNonMeetingDate, final boolean isSkipRepaymentOnFirstMonth, final int numberOfDays) { - if (!isTransactionDateOnNonMeetingDate && !isValidMeetingDate(calendarInstance, meetingDate,isSkipRepaymentOnFirstMonth, numberOfDays)) - { throw new NotValidRecurringDateException("meeting", "The date '" - + meetingDate + "' is not a valid meeting date.", meetingDate); } + if (!isTransactionDateOnNonMeetingDate + && !isValidMeetingDate(calendarInstance, meetingDate, isSkipRepaymentOnFirstMonth, numberOfDays)) { + throw new NotValidRecurringDateException("meeting", "The date '" + meetingDate + "' is not a valid meeting date.", meetingDate); + } return new Meeting(calendarInstance, meetingDate); } @@ -106,8 +108,9 @@ public class Meeting extends AbstractPersistableCustom { actualChanges.put("locale", localeAsInput); this.meetingDate = newValue.toDate(); - if (!isValidMeetingDate(this.calendarInstance, this.meetingDate, isSkipRepaymentOnFirstMonth, numberOfDays)) { throw new NotValidRecurringDateException("meeting", - "Not a valid meeting date", this.meetingDate); } + if (!isValidMeetingDate(this.calendarInstance, this.meetingDate, isSkipRepaymentOnFirstMonth, numberOfDays)) { + throw new NotValidRecurringDateException("meeting", "Not a valid meeting date", this.meetingDate); + } } @@ -185,7 +188,10 @@ public class Meeting extends AbstractPersistableCustom { meetingDateLocalDate = LocalDate.fromDateFields(meetingDate); } - if (meetingDateLocalDate == null || !calendar.isValidRecurringDate(meetingDateLocalDate, isSkipRepaymentOnFirstMonth, numberOfDays)) { return false; } + if (meetingDateLocalDate == null + || !calendar.isValidRecurringDate(meetingDateLocalDate, isSkipRepaymentOnFirstMonth, numberOfDays)) { + return false; + } return true; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/domain/MeetingRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/domain/MeetingRepositoryWrapper.java index db13f5df3..e9b50f060 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/domain/MeetingRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/domain/MeetingRepositoryWrapper.java @@ -45,8 +45,7 @@ public class MeetingRepositoryWrapper { } public Meeting findOneWithNotFoundDetection(final Long meetingId) { - return this.repository.findById(meetingId) - .orElseThrow(() -> new MeetingNotFoundException(meetingId)); + return this.repository.findById(meetingId).orElseThrow(() -> new MeetingNotFoundException(meetingId)); } public void save(final Meeting meeting) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingDateException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingDateException.java index 854b0c41c..b9d80a1f9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingDateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingDateException.java @@ -28,4 +28,4 @@ public class MeetingDateException extends AbstractPlatformDomainRuleException { public MeetingDateException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.meeting.date." + postFix, defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingNotFoundException.java index fa85f3da7..3609795b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingNotFoundException.java @@ -28,4 +28,4 @@ public class MeetingNotFoundException extends AbstractPlatformResourceNotFoundEx public MeetingNotFoundException(final Long id) { super("error.msg.meeting.id.invalid", "Meeting with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingNotSupportedResourceException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingNotSupportedResourceException.java index a986678c4..be3712c9f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingNotSupportedResourceException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/exception/MeetingNotSupportedResourceException.java @@ -29,4 +29,4 @@ public class MeetingNotSupportedResourceException extends AbstractPlatformDomain public MeetingNotSupportedResourceException(final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.meeting.not.supported.resource", defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/handler/DeleteMeetingCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/handler/DeleteMeetingCommandHandler.java index 8405ca829..1496e17de 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/handler/DeleteMeetingCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/handler/DeleteMeetingCommandHandler.java @@ -43,4 +43,4 @@ public class DeleteMeetingCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.deleteMeeting(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/service/MeetingReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/service/MeetingReadPlatformServiceImpl.java index 8e70b809f..630bc1efd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/service/MeetingReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/service/MeetingReadPlatformServiceImpl.java @@ -113,4 +113,4 @@ public class MeetingReadPlatformServiceImpl implements MeetingReadPlatformServic } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/service/MeetingWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/service/MeetingWritePlatformServiceJpaRepositoryImpl.java index f75d6fe8c..1c1af3263 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/service/MeetingWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/meeting/service/MeetingWritePlatformServiceJpaRepositoryImpl.java @@ -78,8 +78,8 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit public MeetingWritePlatformServiceJpaRepositoryImpl(final MeetingRepositoryWrapper meetingRepositoryWrapper, final MeetingRepository meetingRepository, final MeetingDataValidator meetingDataValidator, final CalendarInstanceRepository calendarInstanceRepository, final CalendarRepository calendarRepository, - final ClientRepositoryWrapper clientRepositoryWrapper, final GroupRepository groupRepository, final FromJsonHelper fromApiJsonHelper, - final ConfigurationDomainService configurationDomainService) { + final ClientRepositoryWrapper clientRepositoryWrapper, final GroupRepository groupRepository, + final FromJsonHelper fromApiJsonHelper, final ConfigurationDomainService configurationDomainService) { this.meetingRepositoryWrapper = meetingRepositoryWrapper; this.meetingRepository = meetingRepository; this.meetingDataValidator = meetingDataValidator; @@ -98,13 +98,17 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit final Date meetingDate = command.dateValueOfParameterNamed(meetingDateParamName); final Boolean isTransactionDateOnNonMeetingDate = false; - /*Boolean isSkipRepaymentOnFirstMonth = false; - Integer numberOfDays = 0; - boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); - if(isSkipRepaymentOnFirstMonthEnabled){ - isSkipRepaymentOnFirstMonth = isLoanRepaymentsSyncWithMeeting(loan.group(), calendar); - if(isSkipRepaymentOnFirstMonth) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } - }*/ + /* + * Boolean isSkipRepaymentOnFirstMonth = false; Integer numberOfDays = + * 0; boolean isSkipRepaymentOnFirstMonthEnabled = + * configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled( + * ); if(isSkipRepaymentOnFirstMonthEnabled){ + * isSkipRepaymentOnFirstMonth = + * isLoanRepaymentsSyncWithMeeting(loan.group(), calendar); + * if(isSkipRepaymentOnFirstMonth) { numberOfDays = + * configurationDomainService. + * retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } } + */ try { final CalendarInstance calendarInstance = getCalendarInstance(command); @@ -112,11 +116,16 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit Boolean isSkipRepaymentOnFirstMonth = false; Integer numberOfDays = 0; boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); - if(isSkipRepaymentOnFirstMonthEnabled){ - if(calendarInstance != null){isSkipRepaymentOnFirstMonth = true;} - if(isSkipRepaymentOnFirstMonth) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } + if (isSkipRepaymentOnFirstMonthEnabled) { + if (calendarInstance != null) { + isSkipRepaymentOnFirstMonth = true; + } + if (isSkipRepaymentOnFirstMonth) { + numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); + } } - final Meeting newMeeting = Meeting.createNew(calendarInstance, meetingDate, isTransactionDateOnNonMeetingDate, isSkipRepaymentOnFirstMonth, numberOfDays); + final Meeting newMeeting = Meeting.createNew(calendarInstance, meetingDate, isTransactionDateOnNonMeetingDate, + isSkipRepaymentOnFirstMonth, numberOfDays); final Collection clientsAttendance = getClientsAttendance(newMeeting, command); if (clientsAttendance != null && !clientsAttendance.isEmpty()) { @@ -166,8 +175,8 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit } } - final CalendarInstance calendarInstance = this.calendarInstanceRepository.findByCalendarIdAndEntityIdAndEntityTypeId( - calendarForUpdate.getId(), entityId, entityType.getValue()); + final CalendarInstance calendarInstance = this.calendarInstanceRepository + .findByCalendarIdAndEntityIdAndEntityTypeId(calendarForUpdate.getId(), entityId, entityType.getValue()); if (calendarInstance == null) { final String postFix = "for." + entityType.name().toLowerCase() + "not.found"; final String defaultUserMessage = "No Calendar Instance details found for group with identifier " + entityId @@ -237,8 +246,7 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit Boolean isSkipRepaymentOnFirstMonth = false; Integer numberOfDays = 0; - boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService - .isSkippingMeetingOnFirstDayOfMonthEnabled(); + boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); if (isSkipRepaymentOnFirstMonthEnabled) { if (calendarInstance != null) { isSkipRepaymentOnFirstMonth = true; @@ -295,8 +303,8 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("unique_calendar_instance_id_meeting_date")) { final LocalDate meetingDateLocal = LocalDate.fromDateFields(meetingDate); - throw new PlatformDataIntegrityException("error.msg.meeting.duplicate", "A meeting with date '" + meetingDateLocal - + "' already exists", meetingDateParamName, meetingDateLocal); + throw new PlatformDataIntegrityException("error.msg.meeting.duplicate", + "A meeting with date '" + meetingDateLocal + "' already exists", meetingDateParamName, meetingDateLocal); } throw new PlatformDataIntegrityException("error.msg.meeting.unknown.data.integrity.issue", @@ -306,27 +314,26 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit @Override public void updateCollectionSheetAttendance(final JsonCommand command) { final Date meetingDate = command.dateValueOfParameterNamed(transactionDateParamName); - final Boolean isTransactionDateOnNonMeetingDate = command.booleanPrimitiveValueOfParameterNamed(isTransactionDateOnNonMeetingDateParamName); + final Boolean isTransactionDateOnNonMeetingDate = command + .booleanPrimitiveValueOfParameterNamed(isTransactionDateOnNonMeetingDateParamName); try { final CalendarInstance calendarInstance = getCalendarInstance(command); - final Meeting meeting = this.meetingRepository - .findByCalendarInstanceIdAndMeetingDate(calendarInstance.getId(), meetingDate); + final Meeting meeting = this.meetingRepository.findByCalendarInstanceIdAndMeetingDate(calendarInstance.getId(), meetingDate); Boolean isSkipRepaymentOnFirstMonth = false; Integer numberOfDays = 0; - boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService - .isSkippingMeetingOnFirstDayOfMonthEnabled(); + boolean isSkipRepaymentOnFirstMonthEnabled = configurationDomainService.isSkippingMeetingOnFirstDayOfMonthEnabled(); if (isSkipRepaymentOnFirstMonthEnabled) { - isSkipRepaymentOnFirstMonth = true; + isSkipRepaymentOnFirstMonth = true; if (isSkipRepaymentOnFirstMonth) { - numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate() - .intValue(); + numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate().intValue(); } } // create new meeting - final Meeting newMeeting = (meeting != null) ? meeting : Meeting.createNew(calendarInstance, meetingDate, isTransactionDateOnNonMeetingDate, - isSkipRepaymentOnFirstMonth, numberOfDays); + final Meeting newMeeting = (meeting != null) ? meeting + : Meeting.createNew(calendarInstance, meetingDate, isTransactionDateOnNonMeetingDate, isSkipRepaymentOnFirstMonth, + numberOfDays); final Collection clientsAttendance = getClientsAttendance(newMeeting, command); if (clientsAttendance != null && !clientsAttendance.isEmpty()) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/api/NotesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/api/NotesApiResource.java index 3a2984a64..11cdf834d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/api/NotesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/api/NotesApiResource.java @@ -61,15 +61,13 @@ import org.springframework.stereotype.Component; @Path("/{resourceType}/{resourceId}/notes") @Component @Scope("singleton") -@Api(tags = {"Notes"}) -@SwaggerDefinition(tags = { - @Tag(name = "Notes", description = "Notes API allows to enter notes for supported resources.") -}) +@Api(tags = { "Notes" }) +@SwaggerDefinition(tags = { @Tag(name = "Notes", description = "Notes API allows to enter notes for supported resources.") }) public class NotesApiResource { - private final Set NOTE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "clientId", "groupId", "loanId", - "loanTransactionId", "depositAccountId", "savingAccountId", "noteType", "note", "createdById", "createdByUsername", - "createdOn", "updatedById", "updatedByUsername", "updatedOn")); + private final Set NOTE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList("id", "clientId", "groupId", "loanId", "loanTransactionId", "depositAccountId", "savingAccountId", "noteType", + "note", "createdById", "createdByUsername", "createdOn", "updatedById", "updatedByUsername", "updatedOn")); private final PlatformSecurityContext context; private final NoteReadPlatformService readPlatformService; @@ -91,8 +89,11 @@ public class NotesApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Resource's Notes", httpMethod = "GET", notes = "Retrieves a Resource's Notes\n\n" + "Note: Notes are returned in descending createOn order.\n" + "\n" + "Example Requests:\n" + "\n" + "clients/2/notes\n" + "\n" + "\n" + "groups/2/notes?fields=note,createdOn,createdByUsername") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = NotesApiResourceSwagger.GetResourceTypeResourceIdNotesResponse.class)}) + @ApiOperation(value = "Retrieve a Resource's Notes", httpMethod = "GET", notes = "Retrieves a Resource's Notes\n\n" + + "Note: Notes are returned in descending createOn order.\n" + "\n" + "Example Requests:\n" + "\n" + "clients/2/notes\n" + "\n" + + "\n" + "groups/2/notes?fields=note,createdOn,createdByUsername") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = NotesApiResourceSwagger.GetResourceTypeResourceIdNotesResponse.class) }) public String retrieveNotesByResource(@PathParam("resourceType") @ApiParam(value = "resourceType") final String resourceType, @PathParam("resourceId") @ApiParam(value = "resourceId") final Long resourceId, @Context final UriInfo uriInfo) { @@ -114,9 +115,14 @@ public class NotesApiResource { @Path("{noteId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Resource Note", httpMethod = "GET", notes = "Retrieves a Resource Note\n\n" + "Example Requests:\n" + "\n" + "clients/1/notes/76\n" + "\n" + "\n" + "groups/1/notes/20\n" + "\n" + "\n" + "clients/1/notes/76?fields=note,createdOn,createdByUsername\n" + "\n" + "\n" + "groups/1/notes/20?fields=note,createdOn,createdByUsername") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = NotesApiResourceSwagger.GetResourceTypeResourceIdNotesNoteIdResponse.class)}) - public String retrieveNote(@PathParam("resourceType") @ApiParam(value = "resourceType")final String resourceType, @PathParam("resourceId") @ApiParam(value = "resourceId")final Long resourceId, + @ApiOperation(value = "Retrieve a Resource Note", httpMethod = "GET", notes = "Retrieves a Resource Note\n\n" + "Example Requests:\n" + + "\n" + "clients/1/notes/76\n" + "\n" + "\n" + "groups/1/notes/20\n" + "\n" + "\n" + + "clients/1/notes/76?fields=note,createdOn,createdByUsername\n" + "\n" + "\n" + + "groups/1/notes/20?fields=note,createdOn,createdByUsername") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = NotesApiResourceSwagger.GetResourceTypeResourceIdNotesNoteIdResponse.class) }) + public String retrieveNote(@PathParam("resourceType") @ApiParam(value = "resourceType") final String resourceType, + @PathParam("resourceId") @ApiParam(value = "resourceId") final Long resourceId, @PathParam("noteId") @ApiParam(value = "noteId") final Long noteId, @Context final UriInfo uriInfo) { final NoteType noteType = NoteType.fromApiUrl(resourceType); @@ -136,10 +142,14 @@ public class NotesApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Add a Resource Note", httpMethod = "POST", notes = "Adds a new note to a supported resource.\n\n" + "Example Requests:\n" + "\n" + "clients/1/notes\n" + "\n" + "\n" + "groups/1/notes") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = NotesApiResourceSwagger.PostResourceTypeResourceIdNotesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = NotesApiResourceSwagger.PostResourceTypeResourceIdNotesResponse.class)}) - public String addNewNote(@PathParam("resourceType") @ApiParam(value = "resourceType")final String resourceType, @PathParam("resourceId") @ApiParam(value = "resourceId")final Long resourceId, + @ApiOperation(value = "Add a Resource Note", httpMethod = "POST", notes = "Adds a new note to a supported resource.\n\n" + + "Example Requests:\n" + "\n" + "clients/1/notes\n" + "\n" + "\n" + "groups/1/notes") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = NotesApiResourceSwagger.PostResourceTypeResourceIdNotesRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = NotesApiResourceSwagger.PostResourceTypeResourceIdNotesResponse.class) }) + public String addNewNote(@PathParam("resourceType") @ApiParam(value = "resourceType") final String resourceType, + @PathParam("resourceId") @ApiParam(value = "resourceId") final Long resourceId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final NoteType noteType = NoteType.fromApiUrl(resourceType); @@ -160,10 +170,14 @@ public class NotesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Resource Note", httpMethod = "PUT", notes = "Updates a Resource Note") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = NotesApiResourceSwagger.PutResourceTypeResourceIdNotesNoteIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = NotesApiResourceSwagger.PutResourceTypeResourceIdNotesNoteIdResponse.class)}) - public String updateNote(@PathParam("resourceType") @ApiParam(value = "resourceType") final String resourceType, @PathParam("resourceId") @ApiParam(value = "resourceId") final Long resourceId, - @PathParam("noteId") @ApiParam(value = "noteId") final Long noteId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = NotesApiResourceSwagger.PutResourceTypeResourceIdNotesNoteIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = NotesApiResourceSwagger.PutResourceTypeResourceIdNotesNoteIdResponse.class) }) + public String updateNote(@PathParam("resourceType") @ApiParam(value = "resourceType") final String resourceType, + @PathParam("resourceId") @ApiParam(value = "resourceId") final Long resourceId, + @PathParam("noteId") @ApiParam(value = "noteId") final Long noteId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final NoteType noteType = NoteType.fromApiUrl(resourceType); @@ -184,9 +198,11 @@ public class NotesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Resource Note", httpMethod = "DELETE", notes = "Deletes a Resource Note") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = NotesApiResourceSwagger.DeleteResourceTypeResourceIdNotesNoteIdResponse.class)}) - public String deleteNote(@PathParam("resourceType") @ApiParam(value = "resourceType")final String resourceType, @PathParam("resourceId") @ApiParam(value = "resourceId")final Long resourceId, - @PathParam("noteId") @ApiParam(value = "noteId")final Long noteId) { + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = NotesApiResourceSwagger.DeleteResourceTypeResourceIdNotesNoteIdResponse.class) }) + public String deleteNote(@PathParam("resourceType") @ApiParam(value = "resourceType") final String resourceType, + @PathParam("resourceId") @ApiParam(value = "resourceId") final Long resourceId, + @PathParam("noteId") @ApiParam(value = "noteId") final Long noteId) { final NoteType noteType = NoteType.fromApiUrl(resourceType); @@ -216,7 +232,8 @@ public class NotesApiResource { break; case LOAN_TRANSACTION: resourceNameForPermissions = "LOANTRANSACTIONNOTE"; - // updating loanId, to distinguish saving transaction note and loan transaction note as we are using subEntityId for both. + // updating loanId, to distinguish saving transaction note and + // loan transaction note as we are using subEntityId for both. resourceDetails.withLoanId(resourceId); resourceDetails.withSubEntityId(resourceId); break; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/api/NotesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/api/NotesApiResourceSwagger.java index ff99c4f95..6f7b86da3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/api/NotesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/api/NotesApiResourceSwagger.java @@ -26,17 +26,17 @@ import org.joda.time.DateTime; * Created by Chirag Gupta on 12/29/17. */ final class NotesApiResourceSwagger { - private NotesApiResourceSwagger() { - } + + private NotesApiResourceSwagger() {} @ApiModel(value = "GetResourceTypeResourceIdNotesResponse") public final static class GetResourceTypeResourceIdNotesResponse { - private GetResourceTypeResourceIdNotesResponse() { - } + + private GetResourceTypeResourceIdNotesResponse() {} final class GetNotesNoteType { - private GetNotesNoteType() { - } + + private GetNotesNoteType() {} @ApiModelProperty(example = "100") public Integer id; @@ -69,8 +69,8 @@ final class NotesApiResourceSwagger { @ApiModel(value = "GetResourceTypeResourceIdNotesNoteIdResponse") public final static class GetResourceTypeResourceIdNotesNoteIdResponse { - private GetResourceTypeResourceIdNotesNoteIdResponse() { - } + + private GetResourceTypeResourceIdNotesNoteIdResponse() {} @ApiModelProperty(example = "76") public Integer id; @@ -95,8 +95,8 @@ final class NotesApiResourceSwagger { @ApiModel(value = "PostResourceTypeResourceIdNotesRequest") public final static class PostResourceTypeResourceIdNotesRequest { - private PostResourceTypeResourceIdNotesRequest() { - } + + private PostResourceTypeResourceIdNotesRequest() {} @ApiModelProperty(example = "a note about the client") public String note; @@ -104,8 +104,8 @@ final class NotesApiResourceSwagger { @ApiModel(value = "PostResourceTypeResourceIdNotesResponse") public final static class PostResourceTypeResourceIdNotesResponse { - private PostResourceTypeResourceIdNotesResponse() { - } + + private PostResourceTypeResourceIdNotesResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -117,8 +117,8 @@ final class NotesApiResourceSwagger { @ApiModel(value = "PutResourceTypeResourceIdNotesNoteIdRequest") public final static class PutResourceTypeResourceIdNotesNoteIdRequest { - private PutResourceTypeResourceIdNotesNoteIdRequest() { - } + + private PutResourceTypeResourceIdNotesNoteIdRequest() {} @ApiModelProperty(example = "a note about the client") public String note; @@ -126,12 +126,12 @@ final class NotesApiResourceSwagger { @ApiModel(value = "PutResourceTypeResourceIdNotesNoteIdResponse") public final static class PutResourceTypeResourceIdNotesNoteIdResponse { - private PutResourceTypeResourceIdNotesNoteIdResponse() { - } + + private PutResourceTypeResourceIdNotesNoteIdResponse() {} final class PutNotesChanges { - private PutNotesChanges() { - } + + private PutNotesChanges() {} @ApiModelProperty(example = "a note about the client") public String note; @@ -148,8 +148,8 @@ final class NotesApiResourceSwagger { @ApiModel(value = "DeleteResourceTypeResourceIdNotesNoteIdResponse") public final static class DeleteResourceTypeResourceIdNotesNoteIdResponse { - private DeleteResourceTypeResourceIdNotesNoteIdResponse() { - } + + private DeleteResourceTypeResourceIdNotesNoteIdResponse() {} @ApiModelProperty(example = "76") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/command/NoteCommand.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/command/NoteCommand.java index 5b5ca666b..6f2419d11 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/command/NoteCommand.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/command/NoteCommand.java @@ -30,4 +30,4 @@ public class NoteCommand { this.note = note; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/data/NoteData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/data/NoteData.java index 99e8d5e9b..1dc2f1ba3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/data/NoteData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/data/NoteData.java @@ -78,4 +78,4 @@ public class NoteData { this.updatedById = lastModifiedById; this.updatedByUsername = updatedByUsername; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/Note.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/Note.java index 64852859c..f52a7d972 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/Note.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/Note.java @@ -74,7 +74,6 @@ public class Note extends AbstractAuditableCustom { @JoinColumn(name = "share_account_id", nullable = true) private ShareAccount shareAccount; - public static Note clientNoteFromJson(final Client client, final JsonCommand command) { final String note = command.stringValueOfParameterNamed("note"); return new Note(client, note); @@ -184,4 +183,4 @@ public class Note extends AbstractAuditableCustom { public String getNote() { return note; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/NoteRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/NoteRepository.java index 2480ec42b..f9e33b2bb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/NoteRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/NoteRepository.java @@ -41,4 +41,4 @@ public interface NoteRepository extends JpaRepository, JpaSpecificat List findBySavingsAccountId(Long savingAccountId); // Note findBySavingsAccountIdAndId(Long savingAccountId, Long id); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/NoteType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/NoteType.java index 3610a7a70..e80ba8fd1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/NoteType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/domain/NoteType.java @@ -27,9 +27,8 @@ public enum NoteType { LOAN(200, "noteType.loan", "loans"), // LOAN_TRANSACTION(300, "noteType.loan.transaction", "loanTransactions"), // SAVING_ACCOUNT(500, "noteType.saving", "savings"), // - GROUP(600, "noteType.group", "groups"), - SHARE_ACCOUNT(700, "noteType.shares", "accounts/share"), - SAVINGS_TRANSACTION(800, "noteType.savings.transaction", "savingsTransactions"); + GROUP(600, "noteType.group", "groups"), SHARE_ACCOUNT(700, "noteType.shares", "accounts/share"), SAVINGS_TRANSACTION(800, + "noteType.savings.transaction", "savingsTransactions"); private final Integer value; private final String code; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/exception/NoteNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/exception/NoteNotFoundException.java index 5c95644f8..c6e1f83c3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/exception/NoteNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/exception/NoteNotFoundException.java @@ -30,8 +30,8 @@ public class NoteNotFoundException extends AbstractPlatformResourceNotFoundExcep } public NoteNotFoundException(final Long id, final Long resourceId, final String resource) { - super("error.msg." + resource + ".note.id.invalid", "Note with identifier " + id + " does not exist for " + resource - + " with identifier " + resourceId, id, resourceId); + super("error.msg." + resource + ".note.id.invalid", + "Note with identifier " + id + " does not exist for " + resource + " with identifier " + resourceId, id, resourceId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/exception/NoteResourceNotSupportedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/exception/NoteResourceNotSupportedException.java index 9192d57fa..2fb986f99 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/exception/NoteResourceNotSupportedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/exception/NoteResourceNotSupportedException.java @@ -28,4 +28,4 @@ public class NoteResourceNotSupportedException extends AbstractPlatformResourceN public NoteResourceNotSupportedException(final String resource) { super("error.msg.note.resource.not.supported", "Note does not support resource " + resource); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/handler/DeleteNoteCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/handler/DeleteNoteCommandHandler.java index fd1833390..b6483c928 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/handler/DeleteNoteCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/handler/DeleteNoteCommandHandler.java @@ -41,4 +41,4 @@ public class DeleteNoteCommandHandler implements NewCommandSourceHandler { public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.deleteNote(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/serialization/NoteCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/serialization/NoteCommandFromApiJsonDeserializer.java index 4afe62e34..b4516324b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/serialization/NoteCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/serialization/NoteCommandFromApiJsonDeserializer.java @@ -85,8 +85,10 @@ public final class NoteCommandFromApiJsonDeserializer extends AbstractFromApiJso final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notBlank().notExceedingLengthOf(1000); - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteReadPlatformService.java index 5e31ba7fc..e422037f6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteReadPlatformService.java @@ -26,4 +26,4 @@ public interface NoteReadPlatformService { NoteData retrieveNote(final Long noteId, Long resourceId, Integer noteTypeId); Collection retrieveNotesByResource(final Long resourceId, final Integer noteTypeId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteReadPlatformServiceImpl.java index 1d622b18e..0fd2b010d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteReadPlatformServiceImpl.java @@ -88,8 +88,7 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { final NoteType noteType = NoteType.fromInt(noteTypeId); try { final NoteMapper rm = new NoteMapper(); - List paramList = new ArrayList<>( - Arrays.asList(noteId, resourceId)); + List paramList = new ArrayList<>(Arrays.asList(noteId, resourceId)); String conditionSql = getResourceCondition(noteType, paramList); if (StringUtils.isNotBlank(conditionSql)) { conditionSql = " and " + conditionSql; @@ -107,8 +106,7 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { public Collection retrieveNotesByResource(final Long resourceId, final Integer noteTypeId) { final NoteType noteType = NoteType.fromInt(noteTypeId); final NoteMapper rm = new NoteMapper(); - List paramList = new ArrayList<>( - Arrays.asList(resourceId)); + List paramList = new ArrayList<>(Arrays.asList(resourceId)); final String conditionSql = getResourceCondition(noteType, paramList); final String sql = rm.schema() + " where " + conditionSql + " order by n.created_date DESC"; @@ -137,8 +135,8 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { conditionSql = " n.saving_account_id = ? and ( n.note_type_enum = ? or n.note_type_enum = ? ) "; break; case SAVINGS_TRANSACTION: - conditionSql = " n.savings_account_transaction_id = ? " ; - break ; + conditionSql = " n.savings_account_transaction_id = ? "; + break; case GROUP: conditionSql = " n.group_id = ? "; break; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteWritePlatformServiceJpaRepositoryImpl.java index c4225b236..0002b0734 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/note/service/NoteWritePlatformServiceJpaRepositoryImpl.java @@ -132,8 +132,8 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf final Long resourceId = command.subentityId(); - final LoanTransaction loanTransaction = this.loanTransactionRepository - .findById(resourceId).orElseThrow(() -> new LoanTransactionNotFoundException(resourceId)); + final LoanTransaction loanTransaction = this.loanTransactionRepository.findById(resourceId) + .orElseThrow(() -> new LoanTransactionNotFoundException(resourceId)); final Loan loan = loanTransaction.getLoan(); @@ -176,7 +176,7 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf this.fromApiJsonDeserializer.validateNote(command.json()); - final String resourceUrl = getResourceUrlFromCommand(command); //command.getSupportedEntityType(); + final String resourceUrl = getResourceUrlFromCommand(command); // command.getSupportedEntityType(); final NoteType type = NoteType.fromApiUrl(resourceUrl); switch (type) { case CLIENT: { @@ -215,7 +215,7 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf resourceUrl = NoteType.LOAN.getApiUrl(); } } else if (command.getSavingsId() != null) { - //TODO: SAVING_TRANSACTION type need to be add. + // TODO: SAVING_TRANSACTION type need to be add. resourceUrl = NoteType.SAVING_ACCOUNT.getApiUrl(); } else { resourceUrl = ""; @@ -258,8 +258,7 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf final NoteType type = NoteType.GROUP; - final Group group = this.groupRepository.findById(resourceId) - .orElseThrow(() -> new GroupNotFoundException(resourceId)); + final Group group = this.groupRepository.findById(resourceId).orElseThrow(() -> new GroupNotFoundException(resourceId)); final Note noteForUpdate = this.noteRepository.findByGroupIdAndId(resourceId, noteId); @@ -366,7 +365,7 @@ public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatf this.fromApiJsonDeserializer.validateNote(command.json()); - final String resourceUrl = getResourceUrlFromCommand(command); //command.getSupportedEntityType(); + final String resourceUrl = getResourceUrlFromCommand(command); // command.getSupportedEntityType(); final NoteType type = NoteType.fromApiUrl(resourceUrl); switch (type) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/PaymentDetailConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/PaymentDetailConstants.java old mode 100755 new mode 100644 index 41a4e32f3..9605e38b4 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/PaymentDetailConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/PaymentDetailConstants.java @@ -33,4 +33,4 @@ public class PaymentDetailConstants { // template related part of response public static final String officeOptionsParamName = "paymentTypeOptions"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/data/PaymentDetailData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/data/PaymentDetailData.java old mode 100755 new mode 100644 index 408c7752f..c7dabef8e --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/data/PaymentDetailData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/data/PaymentDetailData.java @@ -55,24 +55,17 @@ public class PaymentDetailData implements Serializable { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof PaymentDetailData)) { - return false; - } + if (this == o) { return true; } + if (!(o instanceof PaymentDetailData)) { return false; } PaymentDetailData that = (PaymentDetailData) o; - return Objects.equals(id, that.id) && - Objects.equals(paymentType, that.paymentType) && - Objects.equals(accountNumber, that.accountNumber) && - Objects.equals(checkNumber, that.checkNumber) && - Objects.equals(routingCode, that.routingCode) && - Objects.equals(receiptNumber, that.receiptNumber) && - Objects.equals(bankNumber, that.bankNumber); + return Objects.equals(id, that.id) && Objects.equals(paymentType, that.paymentType) + && Objects.equals(accountNumber, that.accountNumber) && Objects.equals(checkNumber, that.checkNumber) + && Objects.equals(routingCode, that.routingCode) && Objects.equals(receiptNumber, that.receiptNumber) + && Objects.equals(bankNumber, that.bankNumber); } @Override public int hashCode() { return Objects.hash(id, paymentType, accountNumber, checkNumber, routingCode, receiptNumber, bankNumber); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/domain/PaymentDetail.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/domain/PaymentDetail.java old mode 100755 new mode 100644 index c5564439d..0eaadb30d --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/domain/PaymentDetail.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/domain/PaymentDetail.java @@ -120,4 +120,4 @@ public final class PaymentDetail extends AbstractPersistableCustom { public String getRoutingCode() { return routingCode; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/domain/PaymentDetailRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/domain/PaymentDetailRepository.java old mode 100755 new mode 100644 index a40f6b920..c34c9fe3a --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/domain/PaymentDetailRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/domain/PaymentDetailRepository.java @@ -24,4 +24,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface PaymentDetailRepository extends JpaRepository, JpaSpecificationExecutor { // no added behaviour -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/service/PaymentDetailWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/service/PaymentDetailWritePlatformService.java old mode 100755 new mode 100644 index 1a92941c7..6a0111ec7 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/service/PaymentDetailWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/service/PaymentDetailWritePlatformService.java @@ -29,4 +29,4 @@ public interface PaymentDetailWritePlatformService { PaymentDetail createPaymentDetail(final JsonCommand command, Map changes); PaymentDetail persistPaymentDetail(PaymentDetail paymentDetail); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/service/PaymentDetailWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/service/PaymentDetailWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index e8f788f27..e66571a33 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/service/PaymentDetailWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymentdetail/service/PaymentDetailWritePlatformServiceJpaRepositoryImpl.java @@ -67,4 +67,4 @@ public class PaymentDetailWritePlatformServiceJpaRepositoryImpl implements Payme if (paymentDetail != null) { return persistPaymentDetail(paymentDetail); } return paymentDetail; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResource.java index 3de69e2ee..c39f17eb6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResource.java @@ -55,10 +55,8 @@ import org.springframework.stereotype.Component; @Path("/paymenttypes") @Component -@Api(tags = {"Payment Type"}) -@SwaggerDefinition(tags = { - @Tag(name = "Payment Type", description = "This defines the payment type") -}) +@Api(tags = { "Payment Type" }) +@SwaggerDefinition(tags = { @Tag(name = "Payment Type", description = "This defines the payment type") }) public class PaymentTypeApiResource { private final PlatformSecurityContext securityContext; @@ -89,7 +87,8 @@ public class PaymentTypeApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Retrieve all Payment Types", httpMethod = "GET", notes = "Retrieve list of payment types") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = PaymentTypeApiResourceSwagger.GetPaymentTypesResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = PaymentTypeApiResourceSwagger.GetPaymentTypesResponse.class) }) public String getAllPaymentTypes(@Context final UriInfo uriInfo) { this.securityContext.authenticatedUser().validateHasReadPermission(PaymentTypeApiResourceConstants.resourceNameForPermissions); final Collection paymentTypes = this.readPlatformService.retrieveAllPaymentTypes(); @@ -102,8 +101,10 @@ public class PaymentTypeApiResource { @Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Retrieve a Payment Type", httpMethod = "GET", notes = "Retrieves a payment type") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = PaymentTypeApiResourceSwagger.GetPaymentTypesPaymentTypeIdResponse.class)}) - public String retrieveOnePaymentType(@PathParam("paymentTypeId") @ApiParam(value = "paymentTypeId") final Long paymentTypeId, @Context final UriInfo uriInfo) { + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = PaymentTypeApiResourceSwagger.GetPaymentTypesPaymentTypeIdResponse.class) }) + public String retrieveOnePaymentType(@PathParam("paymentTypeId") @ApiParam(value = "paymentTypeId") final Long paymentTypeId, + @Context final UriInfo uriInfo) { this.securityContext.authenticatedUser().validateHasReadPermission(PaymentTypeApiResourceConstants.resourceNameForPermissions); this.paymentTypeRepositoryWrapper.findOneWithNotFoundDetection(paymentTypeId); final PaymentTypeData paymentTypes = this.readPlatformService.retrieveOne(paymentTypeId); @@ -114,9 +115,11 @@ public class PaymentTypeApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Payment Type", httpMethod = "POST", notes = "Creates a new Payment type\n\n" + "Mandatory Fields: name\n\n" + "Optional Fields: Description, isCashPayment,Position") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = PaymentTypeApiResourceSwagger.PostPaymentTypesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = PaymentTypeApiResourceSwagger.PostPaymentTypesResponse.class)}) + @ApiOperation(value = "Create a Payment Type", httpMethod = "POST", notes = "Creates a new Payment type\n\n" + + "Mandatory Fields: name\n\n" + "Optional Fields: Description, isCashPayment,Position") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = PaymentTypeApiResourceSwagger.PostPaymentTypesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = PaymentTypeApiResourceSwagger.PostPaymentTypesResponse.class) }) public String createPaymentType(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createPaymentType().withJson(apiRequestBodyAsJson).build(); @@ -131,9 +134,12 @@ public class PaymentTypeApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Payment Type", httpMethod = "PUT", notes = "Updates a Payment Type") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = PaymentTypeApiResourceSwagger.PutPaymentTypesPaymentTypeIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = PaymentTypeApiResourceSwagger.PutPaymentTypesPaymentTypeIdResponse.class)}) - public String updatePaymentType(@PathParam("paymentTypeId") @ApiParam(value = "paymentTypeId") final Long paymentTypeId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = PaymentTypeApiResourceSwagger.PutPaymentTypesPaymentTypeIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = PaymentTypeApiResourceSwagger.PutPaymentTypesPaymentTypeIdResponse.class) }) + public String updatePaymentType(@PathParam("paymentTypeId") @ApiParam(value = "paymentTypeId") final Long paymentTypeId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updatePaymentType(paymentTypeId).withJson(apiRequestBodyAsJson) .build(); @@ -148,7 +154,8 @@ public class PaymentTypeApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Payment Type", httpMethod = "DELETE", notes = "Deletes payment type") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = PaymentTypeApiResourceSwagger.DeletePaymentTypesPaymentTypeIdResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = PaymentTypeApiResourceSwagger.DeletePaymentTypesPaymentTypeIdResponse.class) }) public String deleteCode(@PathParam("paymentTypeId") @ApiParam(value = "paymentTypeId") final Long paymentTypeId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deletePaymentType(paymentTypeId).build(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResourceConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResourceConstants.java index 25a5261c2..e34f2ca21 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResourceConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResourceConstants.java @@ -34,6 +34,5 @@ public class PaymentTypeApiResourceConstants { public static final String ISCASHPAYMENT = "isCashPayment"; public static final String POSITION = "position"; - protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(ID, NAME, DESCRIPTION, - ISCASHPAYMENT)); + protected static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(ID, NAME, DESCRIPTION, ISCASHPAYMENT)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResourceSwagger.java index 690e1b6b9..c1e10e79e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/api/PaymentTypeApiResourceSwagger.java @@ -25,13 +25,13 @@ import io.swagger.annotations.ApiModelProperty; * Created by Chirag Gupta on 01/01/18. */ final class PaymentTypeApiResourceSwagger { - private PaymentTypeApiResourceSwagger() { - } + + private PaymentTypeApiResourceSwagger() {} @ApiModel(value = "GetPaymentTypesResponse") public final static class GetPaymentTypesResponse { - private GetPaymentTypesResponse() { - } + + private GetPaymentTypesResponse() {} @ApiModelProperty(example = "24") public Integer id; @@ -47,8 +47,8 @@ final class PaymentTypeApiResourceSwagger { @ApiModel(value = "GetPaymentTypesPaymentTypeIdResponse") public final static class GetPaymentTypesPaymentTypeIdResponse { - private GetPaymentTypesPaymentTypeIdResponse() { - } + + private GetPaymentTypesPaymentTypeIdResponse() {} @ApiModelProperty(example = "13") public Integer id; @@ -64,8 +64,8 @@ final class PaymentTypeApiResourceSwagger { @ApiModel(value = "PostPaymentTypesRequest") public final static class PostPaymentTypesRequest { - private PostPaymentTypesRequest() { - } + + private PostPaymentTypesRequest() {} @ApiModelProperty(example = "cash") public String name; @@ -79,8 +79,8 @@ final class PaymentTypeApiResourceSwagger { @ApiModel(value = "PostPaymentTypesResponse") public final static class PostPaymentTypesResponse { - private PostPaymentTypesResponse() { - } + + private PostPaymentTypesResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -88,8 +88,8 @@ final class PaymentTypeApiResourceSwagger { @ApiModel(value = "PutPaymentTypesPaymentTypeIdRequest") public final static class PutPaymentTypesPaymentTypeIdRequest { - private PutPaymentTypesPaymentTypeIdRequest() { - } + + private PutPaymentTypesPaymentTypeIdRequest() {} @ApiModelProperty(example = "mPay") public String name; @@ -103,8 +103,8 @@ final class PaymentTypeApiResourceSwagger { @ApiModel(value = "PutPaymentTypesPaymentTypeIdResponse") public final static class PutPaymentTypesPaymentTypeIdResponse { - private PutPaymentTypesPaymentTypeIdResponse() { - } + + private PutPaymentTypesPaymentTypeIdResponse() {} @ApiModelProperty(example = "13") public Integer resourceId; @@ -112,8 +112,8 @@ final class PaymentTypeApiResourceSwagger { @ApiModel(value = "DeletePaymentTypesPaymentTypeIdResponse") public final static class DeletePaymentTypesPaymentTypeIdResponse { - private DeletePaymentTypesPaymentTypeIdResponse() { - } + + private DeletePaymentTypesPaymentTypeIdResponse() {} @ApiModelProperty(example = "13") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/data/PaymentTypeData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/data/PaymentTypeData.java index 2eaebdbf9..943329d0f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/data/PaymentTypeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/data/PaymentTypeData.java @@ -64,21 +64,14 @@ public class PaymentTypeData implements Serializable { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } + if (this == o) { return true; } - if (!(o instanceof PaymentTypeData)) { - return false; - } + if (!(o instanceof PaymentTypeData)) { return false; } PaymentTypeData that = (PaymentTypeData) o; - return Objects.equals(id, that.id) && - Objects.equals(name, that.name) && - Objects.equals(description, that.description) && - Objects.equals(isCashPayment, that.isCashPayment) && - Objects.equals(position, that.position); + return Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(description, that.description) + && Objects.equals(isCashPayment, that.isCashPayment) && Objects.equals(position, that.position); } @Override diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/data/PaymentTypeDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/data/PaymentTypeDataValidator.java index 172ee3ea4..7253bec79 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/data/PaymentTypeDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/data/PaymentTypeDataValidator.java @@ -74,13 +74,15 @@ public class PaymentTypeDataValidator { if (this.fromApiJsonHelper.parameterExists(PaymentTypeApiResourceConstants.DESCRIPTION, element)) { final String description = this.fromApiJsonHelper.extractStringNamed(PaymentTypeApiResourceConstants.DESCRIPTION, element); - baseDataValidator.reset().parameter(PaymentTypeApiResourceConstants.DESCRIPTION).value(description).ignoreIfNull().notExceedingLengthOf(500); + baseDataValidator.reset().parameter(PaymentTypeApiResourceConstants.DESCRIPTION).value(description).ignoreIfNull() + .notExceedingLengthOf(500); } if (this.fromApiJsonHelper.parameterExists(PaymentTypeApiResourceConstants.ISCASHPAYMENT, element)) { - final Boolean isCashPayment = this.fromApiJsonHelper - .extractBooleanNamed(PaymentTypeApiResourceConstants.ISCASHPAYMENT, element); - baseDataValidator.reset().parameter(PaymentTypeApiResourceConstants.ISCASHPAYMENT).value(isCashPayment).validateForBooleanValue(); + final Boolean isCashPayment = this.fromApiJsonHelper.extractBooleanNamed(PaymentTypeApiResourceConstants.ISCASHPAYMENT, + element); + baseDataValidator.reset().parameter(PaymentTypeApiResourceConstants.ISCASHPAYMENT).value(isCashPayment) + .validateForBooleanValue(); } if (this.fromApiJsonHelper.parameterExists(PaymentTypeApiResourceConstants.POSITION, element)) { @@ -103,8 +105,7 @@ public class PaymentTypeDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - UPDATE_PAYMENT_TYPE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, UPDATE_PAYMENT_TYPE_REQUEST_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); @@ -120,13 +121,15 @@ public class PaymentTypeDataValidator { if (this.fromApiJsonHelper.parameterExists(PaymentTypeApiResourceConstants.DESCRIPTION, element)) { final String description = this.fromApiJsonHelper.extractStringNamed(PaymentTypeApiResourceConstants.DESCRIPTION, element); - baseDataValidator.reset().parameter(PaymentTypeApiResourceConstants.DESCRIPTION).value(description).ignoreIfNull().notExceedingLengthOf(500); + baseDataValidator.reset().parameter(PaymentTypeApiResourceConstants.DESCRIPTION).value(description).ignoreIfNull() + .notExceedingLengthOf(500); } if (this.fromApiJsonHelper.parameterExists(PaymentTypeApiResourceConstants.ISCASHPAYMENT, element)) { - final Boolean isCashPayment = this.fromApiJsonHelper - .extractBooleanNamed(PaymentTypeApiResourceConstants.ISCASHPAYMENT, element); - baseDataValidator.reset().parameter(PaymentTypeApiResourceConstants.ISCASHPAYMENT).value(isCashPayment).validateForBooleanValue(); + final Boolean isCashPayment = this.fromApiJsonHelper.extractBooleanNamed(PaymentTypeApiResourceConstants.ISCASHPAYMENT, + element); + baseDataValidator.reset().parameter(PaymentTypeApiResourceConstants.ISCASHPAYMENT).value(isCashPayment) + .validateForBooleanValue(); } if (this.fromApiJsonHelper.parameterExists(PaymentTypeApiResourceConstants.POSITION, element)) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/exception/PaymentTypeNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/exception/PaymentTypeNotFoundException.java index e9d2c5bff..56da3cf85 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/exception/PaymentTypeNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/exception/PaymentTypeNotFoundException.java @@ -20,13 +20,9 @@ package org.apache.fineract.portfolio.paymenttype.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - public class PaymentTypeNotFoundException extends AbstractPlatformResourceNotFoundException { public PaymentTypeNotFoundException(final Long id) { super("error.msg.payment.type.invalid", "PaymentType with " + id + " does not exist", id); } } - - - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/handler/UpdatePaymentTypeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/handler/UpdatePaymentTypeCommandHandler.java index 9b691ab41..1240dd8bc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/handler/UpdatePaymentTypeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/handler/UpdatePaymentTypeCommandHandler.java @@ -41,6 +41,6 @@ public class UpdatePaymentTypeCommandHandler implements NewCommandSourceHandler @Override @Transactional public CommandProcessingResult processCommand(JsonCommand command) { - return this.paymentTypeWriteService.updatePaymentType(command.entityId(),command); + return this.paymentTypeWriteService.updatePaymentType(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/service/PaymentTypeReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/service/PaymentTypeReadPlatformService.java index 7e8c374a6..b3aead6d3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/service/PaymentTypeReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/service/PaymentTypeReadPlatformService.java @@ -24,6 +24,7 @@ import org.apache.fineract.portfolio.paymenttype.data.PaymentTypeData; public interface PaymentTypeReadPlatformService { Collection retrieveAllPaymentTypes(); + PaymentTypeData retrieveOne(Long paymentTypeId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/service/PaymentTypeWriteServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/service/PaymentTypeWriteServiceImpl.java index 97b3d3441..a95e95df0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/service/PaymentTypeWriteServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/paymenttype/service/PaymentTypeWriteServiceImpl.java @@ -93,8 +93,10 @@ public class PaymentTypeWriteServiceImpl implements PaymentTypeWriteService { if (realCause.getMessage().contains("acc_product_mapping")) { throw new PlatformDataIntegrityException("error.msg.payment.type.association.exist", "cannot.delete.payment.type.with.association"); - } else if (realCause.getMessage().contains("payment_type_id")) { throw new PlatformDataIntegrityException( - "error.msg.payment.type.association.exist", "cannot.delete.payment.type.with.association"); } + } else if (realCause.getMessage().contains("payment_type_id")) { + throw new PlatformDataIntegrityException("error.msg.payment.type.association.exist", + "cannot.delete.payment.type.with.association"); + } throw new PlatformDataIntegrityException("error.msg.paymenttypes.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/api/ProductsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/api/ProductsApiResource.java index 44f57088d..59bf373cc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/api/ProductsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/api/ProductsApiResource.java @@ -89,8 +89,8 @@ public class ProductsApiResource { ProductData data = service.retrieveTemplate(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, data, service.getResponseDataParams()); - }catch(BeansException e) { - throw new ResourceNotFoundException() ; + } catch (BeansException e) { + throw new ResourceNotFoundException(); } } @@ -98,10 +98,12 @@ public class ProductsApiResource { @Path("{productId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Share Product", httpMethod = "GET", notes = "Retrieves a Share Product\n\n" + "Example Requests:\n" + "\n" + "products/share/1\n" + "\n" + "\n" + "products/share/1?template=true") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProductsApiResourceSwagger.GetProductsTypeProductIdResponse.class)}) - public String retrieveProduct(@PathParam("productId") @ApiParam(value = "productId") final Long productId, @PathParam("type") @ApiParam(value = "type") final String productType, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Share Product", httpMethod = "GET", notes = "Retrieves a Share Product\n\n" + "Example Requests:\n" + + "\n" + "products/share/1\n" + "\n" + "\n" + "products/share/1?template=true") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ProductsApiResourceSwagger.GetProductsTypeProductIdResponse.class) }) + public String retrieveProduct(@PathParam("productId") @ApiParam(value = "productId") final Long productId, + @PathParam("type") @ApiParam(value = "type") final String productType, @Context final UriInfo uriInfo) { try { String serviceName = productType + ProductsApiConstants.READPLATFORM_NAME; ProductReadPlatformService service = (ProductReadPlatformService) this.applicationContext.getBean(serviceName); @@ -116,17 +118,19 @@ public class ProductsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Share Products", httpMethod = "GET", notes = "Lists Share Products\n\n" + "Mandatory Fields: limit, offset\n\n" + "Example Requests:\n" + "\n" + "shareproducts") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProductsApiResourceSwagger.GetProductsTypeResponse.class)}) - public String retrieveAllProducts(@PathParam("type") @ApiParam(value = "type") final String productType, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "List Share Products", httpMethod = "GET", notes = "Lists Share Products\n\n" + + "Mandatory Fields: limit, offset\n\n" + "Example Requests:\n" + "\n" + "shareproducts") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ProductsApiResourceSwagger.GetProductsTypeResponse.class) }) + public String retrieveAllProducts(@PathParam("type") @ApiParam(value = "type") final String productType, + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, @Context final UriInfo uriInfo) { try { String serviceName = productType + ProductsApiConstants.READPLATFORM_NAME; ProductReadPlatformService service = (ProductReadPlatformService) this.applicationContext.getBean(serviceName); Page data = service.retrieveAllProducts(offset, limit); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, data, service.getResponseDataParams()); - }catch(BeansException e) { + } catch (BeansException e) { throw new ResourceNotFoundException(); } } @@ -134,10 +138,15 @@ public class ProductsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Share Product", httpMethod = "POST", notes = "Creates a Share Product\n\n" + "Mandatory Fields: name, shortName, description, currencyCode, digitsAfterDecimal,inMultiplesOf, locale, totalShares, unitPrice, nominalShares,allowDividendCalculationForInactiveClients,accountingRule\n\n" + "Mandatory Fields for Cash based accounting (accountingRule = 2): shareReferenceId, shareSuspenseId, shareEquityId, incomeFromFeeAccountId\n\n" + "Optional Fields: sharesIssued, minimumShares, maximumShares, minimumActivePeriodForDividends, minimumactiveperiodFrequencyType, lockinPeriodFrequency, lockinPeriodFrequencyType, marketPricePeriods, chargesSelected") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ProductsApiResourceSwagger.PostProductsTypeRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProductsApiResourceSwagger.PostProductsTypeResponse.class)}) - public String createProduct(@PathParam("type") @ApiParam(value = "type") final String productType, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Create a Share Product", httpMethod = "POST", notes = "Creates a Share Product\n\n" + + "Mandatory Fields: name, shortName, description, currencyCode, digitsAfterDecimal,inMultiplesOf, locale, totalShares, unitPrice, nominalShares,allowDividendCalculationForInactiveClients,accountingRule\n\n" + + "Mandatory Fields for Cash based accounting (accountingRule = 2): shareReferenceId, shareSuspenseId, shareEquityId, incomeFromFeeAccountId\n\n" + + "Optional Fields: sharesIssued, minimumShares, maximumShares, minimumActivePeriodForDividends, minimumactiveperiodFrequencyType, lockinPeriodFrequency, lockinPeriodFrequencyType, marketPricePeriods, chargesSelected") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ProductsApiResourceSwagger.PostProductsTypeRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ProductsApiResourceSwagger.PostProductsTypeResponse.class) }) + public String createProduct(@PathParam("type") @ApiParam(value = "type") final String productType, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { CommandWrapper commandWrapper = null; this.platformSecurityContext.authenticatedUser(); commandWrapper = new CommandWrapperBuilder().createProduct(productType).withJson(apiRequestBodyAsJson).build(); @@ -149,8 +158,10 @@ public class ProductsApiResource { @Path("{productId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String handleCommands(@PathParam("type") @ApiParam(value = "type") final String productType, @PathParam("productId") @ApiParam(value = "productId") final Long productId, - @QueryParam("command") @ApiParam(value = "command") final String commandParam, @SuppressWarnings("unused") @Context final UriInfo uriInfo, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + public String handleCommands(@PathParam("type") @ApiParam(value = "type") final String productType, + @PathParam("productId") @ApiParam(value = "productId") final Long productId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @SuppressWarnings("unused") @Context final UriInfo uriInfo, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { CommandWrapper commandWrapper = new CommandWrapperBuilder().createProductCommand(productType, commandParam, productId) .withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandWrapper); @@ -162,9 +173,12 @@ public class ProductsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Share Product", httpMethod = "PUT", notes = "Updates a Share Product") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ProductsApiResourceSwagger.PutProductsTypeProductIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProductsApiResourceSwagger.PutProductsTypeProductIdResponse.class)}) - public String updateProduct(@PathParam("type") @ApiParam(value = "type")final String productType, @PathParam("productId") @ApiParam(value = "productId")final Long productId, + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = ProductsApiResourceSwagger.PutProductsTypeProductIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = ProductsApiResourceSwagger.PutProductsTypeProductIdResponse.class) }) + public String updateProduct(@PathParam("type") @ApiParam(value = "type") final String productType, + @PathParam("productId") @ApiParam(value = "productId") final Long productId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { this.platformSecurityContext.authenticatedUser(); final CommandWrapper commandRequest = new CommandWrapperBuilder().updateProduct(productType, productId) diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/api/ProductsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/api/ProductsApiResourceSwagger.java index cb05f196c..6bb5b73d1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/api/ProductsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/api/ProductsApiResourceSwagger.java @@ -26,17 +26,17 @@ import java.util.Set; * Created by Chirag Gupta on 01/01/18. */ final class ProductsApiResourceSwagger { - private ProductsApiResourceSwagger() { - } + + private ProductsApiResourceSwagger() {} @ApiModel(value = "GetProductsTypeProductIdResponse") public final static class GetProductsTypeProductIdResponse { - private GetProductsTypeProductIdResponse() { - } + + private GetProductsTypeProductIdResponse() {} final class GetProductsCurrency { - private GetProductsCurrency() { - } + + private GetProductsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -55,8 +55,8 @@ final class ProductsApiResourceSwagger { } final class GetProductsMarketPrice { - private GetProductsMarketPrice() { - } + + private GetProductsMarketPrice() {} @ApiModelProperty(example = "4") public Integer id; @@ -67,12 +67,12 @@ final class ProductsApiResourceSwagger { } final class GetProductsCharges { - private GetProductsCharges() { - } + + private GetProductsCharges() {} final class GetChargesCurrency { - private GetChargesCurrency() { - } + + private GetChargesCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -89,8 +89,8 @@ final class ProductsApiResourceSwagger { } final class GetChargeTimeType { - private GetChargeTimeType() { - } + + private GetChargeTimeType() {} @ApiModelProperty(example = "13") public Integer id; @@ -101,8 +101,8 @@ final class ProductsApiResourceSwagger { } final class GetChargeAppliesTo { - private GetChargeAppliesTo() { - } + + private GetChargeAppliesTo() {} @ApiModelProperty(example = "4") public Integer id; @@ -113,8 +113,8 @@ final class ProductsApiResourceSwagger { } final class GetChargeCalculationType { - private GetChargeCalculationType() { - } + + private GetChargeCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -125,8 +125,8 @@ final class ProductsApiResourceSwagger { } final class GetChargePaymentMode { - private GetChargePaymentMode() { - } + + private GetChargePaymentMode() {} @ApiModelProperty(example = "0") public Integer id; @@ -154,8 +154,8 @@ final class ProductsApiResourceSwagger { } final class GetLockPeriodTypeEnum { - private GetLockPeriodTypeEnum() { - } + + private GetLockPeriodTypeEnum() {} @ApiModelProperty(example = "0") public Integer id; @@ -164,8 +164,8 @@ final class ProductsApiResourceSwagger { } final class GetProductsAccountingRule { - private GetProductsAccountingRule() { - } + + private GetProductsAccountingRule() {} @ApiModelProperty(example = "2") public Integer id; @@ -176,12 +176,12 @@ final class ProductsApiResourceSwagger { } final class GetProductsAccountingMappings { - private GetProductsAccountingMappings() { - } + + private GetProductsAccountingMappings() {} final class GetShareReferenceId { - private GetShareReferenceId() { - } + + private GetShareReferenceId() {} @ApiModelProperty(example = "1") public Integer id; @@ -192,8 +192,8 @@ final class ProductsApiResourceSwagger { } final class GetIncomeFromFeeAccountId { - private GetIncomeFromFeeAccountId() { - } + + private GetIncomeFromFeeAccountId() {} @ApiModelProperty(example = "14") public Integer id; @@ -204,8 +204,8 @@ final class ProductsApiResourceSwagger { } final class GetShareEquityId { - private GetShareEquityId() { - } + + private GetShareEquityId() {} @ApiModelProperty(example = "66") public Integer id; @@ -216,8 +216,8 @@ final class ProductsApiResourceSwagger { } final class GetShareSuspenseId { - private GetShareSuspenseId() { - } + + private GetShareSuspenseId() {} @ApiModelProperty(example = "8") public Integer id; @@ -234,8 +234,8 @@ final class ProductsApiResourceSwagger { } final class GetProductsMinimumActivePeriodFrequencyTypeOptions { - private GetProductsMinimumActivePeriodFrequencyTypeOptions() { - } + + private GetProductsMinimumActivePeriodFrequencyTypeOptions() {} @ApiModelProperty(example = "0") public Integer id; @@ -246,16 +246,16 @@ final class ProductsApiResourceSwagger { } final class GetProductsAccountingMappingOptions { - private GetProductsAccountingMappingOptions() { - } + + private GetProductsAccountingMappingOptions() {} final class GetProductsLiabilityAccountOptions { - private GetProductsLiabilityAccountOptions() { - } + + private GetProductsLiabilityAccountOptions() {} final class GetProductsLiabilityType { - private GetProductsLiabilityType() { - } + + private GetProductsLiabilityType() {} @ApiModelProperty(example = "2") public Integer id; @@ -266,8 +266,8 @@ final class ProductsApiResourceSwagger { } final class GetProductsLiabilityUsage { - private GetProductsLiabilityUsage() { - } + + private GetProductsLiabilityUsage() {} @ApiModelProperty(example = "1") public Integer id; @@ -278,8 +278,8 @@ final class ProductsApiResourceSwagger { } final class GetProductsTagId { - private GetProductsTagId() { - } + + private GetProductsTagId() {} @ApiModelProperty(example = "0") public Integer id; @@ -307,12 +307,12 @@ final class ProductsApiResourceSwagger { } final class GetProductsAssetAccountOptions { - private GetProductsAssetAccountOptions() { - } + + private GetProductsAssetAccountOptions() {} final class GetAssetType { - private GetAssetType() { - } + + private GetAssetType() {} @ApiModelProperty(example = "1") public Integer id; @@ -342,12 +342,12 @@ final class ProductsApiResourceSwagger { } final class GetProductsIncomeAccountOptions { - private GetProductsIncomeAccountOptions() { - } + + private GetProductsIncomeAccountOptions() {} final class GetIncomeType { - private GetIncomeType() { - } + + private GetIncomeType() {} @ApiModelProperty(example = "1") public Integer id; @@ -377,12 +377,12 @@ final class ProductsApiResourceSwagger { } final class GetProductsEquityAccountOptions { - private GetProductsEquityAccountOptions() { - } + + private GetProductsEquityAccountOptions() {} final class GetEquityType { - private GetEquityType() { - } + + private GetEquityType() {} @ApiModelProperty(example = "3") public Integer id; @@ -459,12 +459,12 @@ final class ProductsApiResourceSwagger { @ApiModel(value = "GetProductsTypeResponse") public static final class GetProductsTypeResponse { - private GetProductsTypeResponse() { - } + + private GetProductsTypeResponse() {} final class GetProductsPageItems { - private GetProductsPageItems() { - } + + private GetProductsPageItems() {} @ApiModelProperty(example = "1") public Integer id; @@ -483,12 +483,12 @@ final class ProductsApiResourceSwagger { @ApiModel(value = "PostProductsTypeRequest") public final static class PostProductsTypeRequest { - private PostProductsTypeRequest() { - } + + private PostProductsTypeRequest() {} final class PostProductsMarketPricePeriods { - private PostProductsMarketPricePeriods() { - } + + private PostProductsMarketPricePeriods() {} @ApiModelProperty(example = "en") public String locale; @@ -501,8 +501,8 @@ final class ProductsApiResourceSwagger { } final class PostProductsChargesSelected { - private PostProductsChargesSelected() { - } + + private PostProductsChargesSelected() {} @ApiModelProperty(example = "20") public Integer id; @@ -552,8 +552,8 @@ final class ProductsApiResourceSwagger { @ApiModel(value = "PostProductsTypeResponse") public final static class PostProductsTypeResponse { - private PostProductsTypeResponse() { - } + + private PostProductsTypeResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -561,8 +561,8 @@ final class ProductsApiResourceSwagger { @ApiModel(value = "PutProductsTypeProductIdRequest") public final static class PutProductsTypeProductIdRequest { - private PutProductsTypeProductIdRequest() { - } + + private PutProductsTypeProductIdRequest() {} @ApiModelProperty(example = "Share Product Description.") public String description; @@ -574,12 +574,12 @@ final class ProductsApiResourceSwagger { @ApiModel(value = "PutProductsTypeProductIdResponse") public final static class PutProductsTypeProductIdResponse { - private PutProductsTypeProductIdResponse() { - } + + private PutProductsTypeProductIdResponse() {} final class PutProductsChanges { - private PutProductsChanges() { - } + + private PutProductsChanges() {} @ApiModelProperty(example = "Share Product Description.") public String description; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/constants/ProductsApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/constants/ProductsApiConstants.java index 2e808bba6..75616df97 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/constants/ProductsApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/constants/ProductsApiConstants.java @@ -18,10 +18,9 @@ */ package org.apache.fineract.portfolio.products.constants; - public interface ProductsApiConstants { - public final String READPLATFORM_NAME = "ReadPlatformService" ; - public final String PRODUCT_COMMANDSERVICE = "PRODUCT_COMMANDSERVICE" ; + public final String READPLATFORM_NAME = "ReadPlatformService"; + public final String PRODUCT_COMMANDSERVICE = "PRODUCT_COMMANDSERVICE"; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/data/ProductData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/data/ProductData.java index 733c7d121..d31475581 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/data/ProductData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/data/ProductData.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.portfolio.products.data; - public interface ProductData { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/exception/ProductNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/exception/ProductNotFoundException.java index 62955fc92..233be65bc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/exception/ProductNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/exception/ProductNotFoundException.java @@ -26,6 +26,6 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class ProductNotFoundException extends AbstractPlatformResourceNotFoundException { public ProductNotFoundException(final Long id, String type) { - super("error.msg.product.id.invalid", type + " product with identifier " + id + " does not exist" , id); + super("error.msg.product.id.invalid", type + " product with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/exception/ResourceNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/exception/ResourceNotFoundException.java index 98135f7be..4dfce9d00 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/exception/ResourceNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/exception/ResourceNotFoundException.java @@ -20,14 +20,13 @@ package org.apache.fineract.portfolio.products.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - -public class ResourceNotFoundException extends AbstractPlatformResourceNotFoundException{ +public class ResourceNotFoundException extends AbstractPlatformResourceNotFoundException { public ResourceNotFoundException(String globalisationMessageCode, String defaultUserMessage, Object[] defaultUserMessageArgs) { super(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs); } public ResourceNotFoundException() { - super("","","") ; + super("", "", ""); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/service/ProductCommandsService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/service/ProductCommandsService.java index 4a17a8214..59504d735 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/service/ProductCommandsService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/service/ProductCommandsService.java @@ -18,9 +18,7 @@ */ package org.apache.fineract.portfolio.products.service; - - public interface ProductCommandsService { - public Object handleCommand(final Long productId, final String command, final String jsonBody) ; + public Object handleCommand(final Long productId, final String command, final String jsonBody); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/service/ProductReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/service/ProductReadPlatformService.java index e95a020dd..674ee5d53 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/service/ProductReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/products/service/ProductReadPlatformService.java @@ -33,5 +33,5 @@ public interface ProductReadPlatformService { public Set getResponseDataParams(); - public Collection retrieveAllForLookup() ; + public Collection retrieveAllForLookup(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/api/RateApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/api/RateApiConstants.java index 20d64d651..d3b1f640b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/api/RateApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/api/RateApiConstants.java @@ -20,10 +20,10 @@ package org.apache.fineract.portfolio.rate.api; public class RateApiConstants { - public static final String approveUserIdParamName = "approveUserId"; - public static final String rate = "rate"; - public static final String rateName = "name"; - public static final String ratePercentage = "percentage"; - public static final String rateProductApply = "productApply"; + public static final String approveUserIdParamName = "approveUserId"; + public static final String rate = "rate"; + public static final String rateName = "name"; + public static final String ratePercentage = "percentage"; + public static final String rateProductApply = "productApply"; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/api/RateApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/api/RateApiResource.java index 014891dc2..bdd6eb40f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/api/RateApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/api/RateApiResource.java @@ -56,86 +56,76 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class RateApiResource { - private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList("id", "name", "percentage", "productApply", "active")); - private final String resourceNameForPermissions = "RATE"; - private final PlatformSecurityContext context; - private final RateReadService readPlatformService; - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final ApiRequestParameterHelper apiRequestParameterHelper; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "percentage", "productApply", "active")); + private final String resourceNameForPermissions = "RATE"; + private final PlatformSecurityContext context; + private final RateReadService readPlatformService; + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final ApiRequestParameterHelper apiRequestParameterHelper; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - @Autowired - public RateApiResource(final PlatformSecurityContext context, - final RateReadService rateReadService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, - final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { - this.context = context; - this.readPlatformService = rateReadService; - this.toApiJsonSerializer = toApiJsonSerializer; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - } + @Autowired + public RateApiResource(final PlatformSecurityContext context, final RateReadService rateReadService, + final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + this.context = context; + this.readPlatformService = rateReadService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + } - @GET - @Path("{rateId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public String retrieveRate(@PathParam("rateId") Long rateId, @Context final UriInfo uriInfo) { + @GET + @Path("{rateId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveRate(@PathParam("rateId") Long rateId, @Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final RateData rate = this.readPlatformService.retrieveOne(rateId); + final RateData rate = this.readPlatformService.retrieveOne(rateId); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, rate, this.RESPONSE_DATA_PARAMETERS); - } + return this.toApiJsonSerializer.serialize(settings, rate, this.RESPONSE_DATA_PARAMETERS); + } - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public String createRate(final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().createRate() - .withJson(apiRequestBodyAsJson).build(); + @POST + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String createRate(final String apiRequestBodyAsJson) { + final CommandWrapper commandRequest = new CommandWrapperBuilder().createRate().withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); + return this.toApiJsonSerializer.serialize(result); - } + } - @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public String getAllRates(@Context final UriInfo uriInfo) { + @GET + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String getAllRates(@Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - Collection rates = this.readPlatformService.retrieveAllRates(); + Collection rates = this.readPlatformService.retrieveAllRates(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, rates, this.RESPONSE_DATA_PARAMETERS); - } + return this.toApiJsonSerializer.serialize(settings, rates, this.RESPONSE_DATA_PARAMETERS); + } - @PUT - @Path("{rateId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public String updateRate(@PathParam("rateId") Long rateId, final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateRate(rateId) - .withJson(apiRequestBodyAsJson).build(); + @PUT + @Path("{rateId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String updateRate(@PathParam("rateId") Long rateId, final String apiRequestBodyAsJson) { + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateRate(rateId).withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); - - return this.toApiJsonSerializer.serialize(result); - } + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + return this.toApiJsonSerializer.serialize(result); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/data/RateData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/data/RateData.java index d6fdeb4f8..589a0df20 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/data/RateData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/data/RateData.java @@ -28,27 +28,27 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; */ public class RateData implements Serializable { - private Long id; + private Long id; - private String name; + private String name; - private BigDecimal percentage; + private BigDecimal percentage; - private EnumOptionData productApply; + private EnumOptionData productApply; - private boolean active; + private boolean active; - public static RateData instance(final Long id, final String name, final BigDecimal percentage, - final EnumOptionData productApply, final boolean active) { - return new RateData(id, name, percentage, productApply, active); - } + public static RateData instance(final Long id, final String name, final BigDecimal percentage, final EnumOptionData productApply, + final boolean active) { + return new RateData(id, name, percentage, productApply, active); + } - private RateData(final Long id, final String name, final BigDecimal percentage, - final EnumOptionData productApply, final boolean active) { - this.id = id; - this.name = name; - this.percentage = percentage; - this.productApply = productApply; - this.active = active; - } + private RateData(final Long id, final String name, final BigDecimal percentage, final EnumOptionData productApply, + final boolean active) { + this.id = id; + this.name = name; + this.percentage = percentage; + this.productApply = productApply; + this.active = active; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/Rate.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/Rate.java index 1a20d0fb8..3dbc28c78 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/Rate.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/Rate.java @@ -39,170 +39,157 @@ import org.apache.fineract.useradministration.domain.AppUser; */ @Entity -@Table(name = "m_rate", uniqueConstraints = { - @UniqueConstraint(columnNames = {"name"}, name = "name")}) +@Table(name = "m_rate", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "name") }) public class Rate extends AbstractAuditableCustom { - @Column(name = "name", length = 250, unique = true) - private String name; + @Column(name = "name", length = 250, unique = true) + private String name; - @Column(name = "percentage", scale = 10, precision = 2, nullable = false) - private BigDecimal percentage; + @Column(name = "percentage", scale = 10, precision = 2, nullable = false) + private BigDecimal percentage; - @Column(name = "product_apply", length = 100) - private Integer productApply; + @Column(name = "product_apply", length = 100) + private Integer productApply; - @Column(name = "active", nullable = false) - private boolean active; + @Column(name = "active", nullable = false) + private boolean active; - @ManyToOne - @JoinColumn(name = "approve_user", nullable = true) - private AppUser approveUser; + @ManyToOne + @JoinColumn(name = "approve_user", nullable = true) + private AppUser approveUser; + public Rate() {} - public Rate() { - } - - - public Rate(String name, BigDecimal percentage, RateAppliesTo productApply, boolean active, - AppUser approveUser) { - this.name = name; - this.percentage = percentage; - this.productApply = productApply.getValue(); - this.active = active; - this.approveUser = approveUser; - } - - public Rate(String name, BigDecimal percentage, RateAppliesTo productApply, boolean active) { - this.name = name; - this.percentage = percentage; - this.productApply = productApply.getValue(); - this.active = active; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public BigDecimal getPercentage() { - return percentage; - } - - public void setPercentage(BigDecimal percentage) { - this.percentage = percentage; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - - public AppUser getApproveUser() { - return approveUser; - } - - public void setApproveUser(AppUser approveUser) { - this.approveUser = approveUser; - } - - public Integer getProductApply() { - return productApply; - } - - public void setProductApply(Integer productApply) { - this.productApply = productApply; - } - - @Override - public String toString() { - return "Rate{" + - "name='" + name + '\'' + - ", percentage=" + percentage + - ", productApply='" + productApply + '\'' + - ", active=" + active + - ", approveUser=" + approveUser + - '}'; - } - - public static Rate from(String name, BigDecimal percentage, RateAppliesTo productApply, - Boolean active) { - return new Rate(name, percentage, productApply, active); - } - - public static Rate fromJson(final JsonCommand command, AppUser user) { - - final String name = command.stringValueOfParameterNamed("name"); - - final BigDecimal percentage = command.bigDecimalValueOfParameterNamed("percentage"); - - final RateAppliesTo productApply = RateAppliesTo - .fromInt(command.integerValueOfParameterNamed("productApply")); - - final boolean active = command.booleanPrimitiveValueOfParameterNamed("active"); - - return new Rate(name, percentage, productApply, active, user); - } - - public Map update(final JsonCommand command) { - - final Map actualChanges = new LinkedHashMap<>(7); - - final String nameParamName = "name"; - if (command.isChangeInStringParameterNamed(nameParamName, this.name)) { - final String newValue = command.stringValueOfParameterNamed(nameParamName); - actualChanges.put(nameParamName, newValue); - this.name = StringUtils.defaultIfEmpty(newValue, null); + public Rate(String name, BigDecimal percentage, RateAppliesTo productApply, boolean active, AppUser approveUser) { + this.name = name; + this.percentage = percentage; + this.productApply = productApply.getValue(); + this.active = active; + this.approveUser = approveUser; } - final String percentageParamName = "percentage"; - if (command.isChangeInBigDecimalParameterNamed(percentageParamName, this.percentage)) { - final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(percentageParamName); - actualChanges.put(percentageParamName, newValue); - this.percentage = newValue; + public Rate(String name, BigDecimal percentage, RateAppliesTo productApply, boolean active) { + this.name = name; + this.percentage = percentage; + this.productApply = productApply.getValue(); + this.active = active; } - final String productApplyParamName = "productApply"; - if (command.isChangeInIntegerParameterNamed(productApplyParamName, this.productApply)) { - final String errorMessage = "Update of Rate applies to is not supported"; - throw new ChargeParameterUpdateNotSupportedException("rate.applies.to", errorMessage); + public String getName() { + return name; } - final String activeParamName = "active"; - if (command.isChangeInBooleanParameterNamed(activeParamName, this.active)) { - final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(activeParamName); - actualChanges.put(activeParamName, newValue); - this.active = newValue; + public void setName(String name) { + this.name = name; } - final String approveUserParamName = "approveUserId"; - if (command.isChangeInLongParameterNamed(approveUserParamName, getApproveUserId())) { - final Long newValue = command.longValueOfParameterNamed(approveUserParamName); - actualChanges.put(approveUserParamName, newValue); + public BigDecimal getPercentage() { + return percentage; } - return actualChanges; - } - - private Long getApproveUserId() { - Long approveUserId = null; - if (this.approveUser != null) { - approveUserId = this.approveUser.getId(); + public void setPercentage(BigDecimal percentage) { + this.percentage = percentage; } - return approveUserId; - } - public void assembleFrom(String name, BigDecimal percentage, Integer productApply, - boolean active) { - this.name = name; - this.percentage = percentage; - this.productApply = productApply; - this.active = active; - } + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public AppUser getApproveUser() { + return approveUser; + } + + public void setApproveUser(AppUser approveUser) { + this.approveUser = approveUser; + } + + public Integer getProductApply() { + return productApply; + } + + public void setProductApply(Integer productApply) { + this.productApply = productApply; + } + + @Override + public String toString() { + return "Rate{" + "name='" + name + '\'' + ", percentage=" + percentage + ", productApply='" + productApply + '\'' + ", active=" + + active + ", approveUser=" + approveUser + '}'; + } + + public static Rate from(String name, BigDecimal percentage, RateAppliesTo productApply, Boolean active) { + return new Rate(name, percentage, productApply, active); + } + + public static Rate fromJson(final JsonCommand command, AppUser user) { + + final String name = command.stringValueOfParameterNamed("name"); + + final BigDecimal percentage = command.bigDecimalValueOfParameterNamed("percentage"); + + final RateAppliesTo productApply = RateAppliesTo.fromInt(command.integerValueOfParameterNamed("productApply")); + + final boolean active = command.booleanPrimitiveValueOfParameterNamed("active"); + + return new Rate(name, percentage, productApply, active, user); + } + + public Map update(final JsonCommand command) { + + final Map actualChanges = new LinkedHashMap<>(7); + + final String nameParamName = "name"; + if (command.isChangeInStringParameterNamed(nameParamName, this.name)) { + final String newValue = command.stringValueOfParameterNamed(nameParamName); + actualChanges.put(nameParamName, newValue); + this.name = StringUtils.defaultIfEmpty(newValue, null); + } + + final String percentageParamName = "percentage"; + if (command.isChangeInBigDecimalParameterNamed(percentageParamName, this.percentage)) { + final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(percentageParamName); + actualChanges.put(percentageParamName, newValue); + this.percentage = newValue; + } + + final String productApplyParamName = "productApply"; + if (command.isChangeInIntegerParameterNamed(productApplyParamName, this.productApply)) { + final String errorMessage = "Update of Rate applies to is not supported"; + throw new ChargeParameterUpdateNotSupportedException("rate.applies.to", errorMessage); + } + + final String activeParamName = "active"; + if (command.isChangeInBooleanParameterNamed(activeParamName, this.active)) { + final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(activeParamName); + actualChanges.put(activeParamName, newValue); + this.active = newValue; + } + + final String approveUserParamName = "approveUserId"; + if (command.isChangeInLongParameterNamed(approveUserParamName, getApproveUserId())) { + final Long newValue = command.longValueOfParameterNamed(approveUserParamName); + actualChanges.put(approveUserParamName, newValue); + } + + return actualChanges; + } + + private Long getApproveUserId() { + Long approveUserId = null; + if (this.approveUser != null) { + approveUserId = this.approveUser.getId(); + } + return approveUserId; + } + + public void assembleFrom(String name, BigDecimal percentage, Integer productApply, boolean active) { + this.name = name; + this.percentage = percentage; + this.productApply = productApply; + this.active = active; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateAppliesTo.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateAppliesTo.java index 7115fe939..50d0477a8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateAppliesTo.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateAppliesTo.java @@ -21,47 +21,46 @@ package org.apache.fineract.portfolio.rate.domain; public enum RateAppliesTo { - INVALID(0, "rateAppliesTo.invalid"), - LOAN(1, "rateAppliesTo.loan"); + INVALID(0, "rateAppliesTo.invalid"), LOAN(1, "rateAppliesTo.loan"); - private final Integer value; - private final String code; + private final Integer value; + private final String code; - private RateAppliesTo(final Integer value, final String code) { - this.value = value; - this.code = code; - } - - public Integer getValue() { - return this.value; - } - - public String getCode() { - return this.code; - } - - public static RateAppliesTo fromInt(final Integer rateAppliesTo) { - RateAppliesTo rateAppliesToType = RateAppliesTo.INVALID; - - if (rateAppliesTo != null) { - switch (rateAppliesTo) { - case 1: - rateAppliesToType = LOAN; - break; - default: - rateAppliesToType = INVALID; - break; - } + private RateAppliesTo(final Integer value, final String code) { + this.value = value; + this.code = code; } - return rateAppliesToType; - } + public Integer getValue() { + return this.value; + } - public boolean isLoanRate() { - return this.value.equals(RateAppliesTo.LOAN.getValue()); - } + public String getCode() { + return this.code; + } - public static Object[] validValues() { - return new Object[]{RateAppliesTo.LOAN.getValue()}; - } + public static RateAppliesTo fromInt(final Integer rateAppliesTo) { + RateAppliesTo rateAppliesToType = RateAppliesTo.INVALID; + + if (rateAppliesTo != null) { + switch (rateAppliesTo) { + case 1: + rateAppliesToType = LOAN; + break; + default: + rateAppliesToType = INVALID; + break; + } + } + + return rateAppliesToType; + } + + public boolean isLoanRate() { + return this.value.equals(RateAppliesTo.LOAN.getValue()); + } + + public static Object[] validValues() { + return new Object[] { RateAppliesTo.LOAN.getValue() }; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateRepository.java index f9210fa44..243b3289b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateRepository.java @@ -23,13 +23,13 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** - * Bowpi GT Rate repository to save on m_rate table (custom change for Credi Chapin) Created by Jose - * on 19/07/2017. + * Bowpi GT Rate repository to save on m_rate table (custom change for Credi + * Chapin) Created by Jose on 19/07/2017. */ public interface RateRepository extends JpaRepository, JpaSpecificationExecutor { - Rate findByName(String name); + Rate findByName(String name); - List findAllByActiveAndProductApply(boolean active, String productApply); + List findAllByActiveAndProductApply(boolean active, String productApply); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateRepositoryWrapper.java index 679c2d798..21a0091e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/domain/RateRepositoryWrapper.java @@ -28,38 +28,35 @@ import org.springframework.stereotype.Service; @Service public class RateRepositoryWrapper { - private final RateRepository repository; + private final RateRepository repository; - @Autowired - public RateRepositoryWrapper(final RateRepository repository) { - this.repository = repository; - } + @Autowired + public RateRepositoryWrapper(final RateRepository repository) { + this.repository = repository; + } - public Rate findOneWithNotFoundDetection(final Long rateId) { - final Rate rate = this.repository.findById(rateId).orElseThrow(() -> new RateNotFoundException(rateId)); - return rate; - } + public Rate findOneWithNotFoundDetection(final Long rateId) { + final Rate rate = this.repository.findById(rateId).orElseThrow(() -> new RateNotFoundException(rateId)); + return rate; + } - public List findMultipleWithNotFoundDetection(final List rateIds) { - List rates = new ArrayList<>(); - if (rateIds != null && !rateIds.isEmpty()) { - final List foundRates = this.repository.findAllById(rateIds); - for (Long rateId : rateIds) { - Boolean found = false; - for (Rate foundRate : foundRates) { - if (Objects.equals(foundRate.getId(), - rateId)) { - found = true; - break; - } + public List findMultipleWithNotFoundDetection(final List rateIds) { + List rates = new ArrayList<>(); + if (rateIds != null && !rateIds.isEmpty()) { + final List foundRates = this.repository.findAllById(rateIds); + for (Long rateId : rateIds) { + Boolean found = false; + for (Rate foundRate : foundRates) { + if (Objects.equals(foundRate.getId(), rateId)) { + found = true; + break; + } + } + if (!found) { throw new RateNotFoundException(rateId); } + } + rates.addAll(foundRates); } - if (!found) { - throw new RateNotFoundException(rateId); - } - } - rates.addAll(foundRates); + return rates; } - return rates; - } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/exception/RateAlreadyExistException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/exception/RateAlreadyExistException.java index f0a844e88..6f9e473af 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/exception/RateAlreadyExistException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/exception/RateAlreadyExistException.java @@ -19,10 +19,9 @@ package org.apache.fineract.portfolio.rate.exception; /** - * Bowpi GT - * Created by Jose on 24/07/2017. + * Bowpi GT Created by Jose on 24/07/2017. */ -public class RateAlreadyExistException extends Exception{ +public class RateAlreadyExistException extends Exception { public RateAlreadyExistException(String s) { super(s); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/exception/RateNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/exception/RateNotFoundException.java index 48cf904fb..9912bfa1c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/exception/RateNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/exception/RateNotFoundException.java @@ -23,13 +23,12 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class RateNotFoundException extends AbstractPlatformResourceNotFoundException { + public RateNotFoundException(final Long id) { + super("error.msg.rate.id.invalid", "Rate with identifier " + id + " does not exist", id); + } - public RateNotFoundException(final Long id) { - super("error.msg.rate.id.invalid", "Rate with identifier " + id + " does not exist", id); - } - - public RateNotFoundException(final String name) { - super("error.msg.rate.id.invalid", "Rate with name " + name + " does not exist", name); - } + public RateNotFoundException(final String name) { + super("error.msg.rate.id.invalid", "Rate with name " + name + " does not exist", name); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/handler/CreateRateCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/handler/CreateRateCommandHandler.java index 879454047..489955ee1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/handler/CreateRateCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/handler/CreateRateCommandHandler.java @@ -27,22 +27,21 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** - * Bowpi GT - * Created by Jose on 19/07/2017. + * Bowpi GT Created by Jose on 19/07/2017. */ @Service @CommandType(entity = "RATE", action = "CREATE") public class CreateRateCommandHandler implements NewCommandSourceHandler { - private final RateWriteService writePlatformService; + private final RateWriteService writePlatformService; - @Autowired - public CreateRateCommandHandler(final RateWriteService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public CreateRateCommandHandler(final RateWriteService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.createRate(command); - } + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.writePlatformService.createRate(command); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/handler/UpdateRateCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/handler/UpdateRateCommandHandler.java index cc22e53dc..f1ed8e1ab 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/handler/UpdateRateCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/handler/UpdateRateCommandHandler.java @@ -28,24 +28,23 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** - * Bowpi GT - * Created by Jose on 19/07/2017. + * Bowpi GT Created by Jose on 19/07/2017. */ @Service @CommandType(entity = "RATE", action = "UPDATE") public class UpdateRateCommandHandler implements NewCommandSourceHandler { - private final RateWriteService writePlatformService; + private final RateWriteService writePlatformService; - @Autowired - public UpdateRateCommandHandler(final RateWriteService writePlatformService) { - this.writePlatformService = writePlatformService; - } + @Autowired + public UpdateRateCommandHandler(final RateWriteService writePlatformService) { + this.writePlatformService = writePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { - return this.writePlatformService.updateRate(command.entityId(), command); - } + return this.writePlatformService.updateRate(command.entityId(), command); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/serialization/RateDefinitionCommandFromApiJsonDeserializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/serialization/RateDefinitionCommandFromApiJsonDeserializer.java index cb5d1968b..f9a0b40a6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/serialization/RateDefinitionCommandFromApiJsonDeserializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/serialization/RateDefinitionCommandFromApiJsonDeserializer.java @@ -41,89 +41,75 @@ import org.springframework.stereotype.Component; @Component public class RateDefinitionCommandFromApiJsonDeserializer { - /** - * The parameters supported for this command. - */ - private final Set supportedParameters = new HashSet<>( - Arrays.asList("id", "name", "percentage", "productApply", "active", "approveUser", "locale")); + /** + * The parameters supported for this command. + */ + private final Set supportedParameters = new HashSet<>( + Arrays.asList("id", "name", "percentage", "productApply", "active", "approveUser", "locale")); - private final FromJsonHelper fromApiJsonHelper; + private final FromJsonHelper fromApiJsonHelper; - @Autowired - public RateDefinitionCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } - - public void validateForCreate(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); + @Autowired + public RateDefinitionCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; } - final Type typeOfMap = new TypeToken>() { - }.getType(); + public void validateForCreate(final String json) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); + final Type typeOfMap = new TypeToken>() {}.getType(); - final List dataValidationErrors = new ArrayList<>(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource(RateApiConstants.rateName); + final List dataValidationErrors = new ArrayList<>(); - final JsonElement element = this.fromApiJsonHelper.parse(json); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(RateApiConstants.rateName); - final String name = this.fromApiJsonHelper.extractStringNamed(RateApiConstants.rateName, element); - baseDataValidator.reset().parameter(RateApiConstants.rateName).value(name).notBlank().notExceedingLengthOf(250); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final BigDecimal percentage = this.fromApiJsonHelper - .extractBigDecimalWithLocaleNamed(RateApiConstants.ratePercentage, element); - baseDataValidator.reset().parameter(RateApiConstants.ratePercentage).value(percentage).notBlank(); + final String name = this.fromApiJsonHelper.extractStringNamed(RateApiConstants.rateName, element); + baseDataValidator.reset().parameter(RateApiConstants.rateName).value(name).notBlank().notExceedingLengthOf(250); - final String productApply = this.fromApiJsonHelper.extractStringNamed(RateApiConstants.rateProductApply, element); - baseDataValidator.reset().parameter(RateApiConstants.rateProductApply).value(productApply).notBlank() - .notExceedingLengthOf(100); + final BigDecimal percentage = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(RateApiConstants.ratePercentage, element); + baseDataValidator.reset().parameter(RateApiConstants.ratePercentage).value(percentage).notBlank(); - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } + final String productApply = this.fromApiJsonHelper.extractStringNamed(RateApiConstants.rateProductApply, element); + baseDataValidator.reset().parameter(RateApiConstants.rateProductApply).value(productApply).notBlank().notExceedingLengthOf(100); - public void validateForUpdate(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); + throwExceptionIfValidationWarningsExist(dataValidationErrors); } - final Type typeOfMap = new TypeToken>() { - }.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); + public void validateForUpdate(final String json) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource(RateApiConstants.rate); + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); - final JsonElement element = this.fromApiJsonHelper.parse(json); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(RateApiConstants.rate); - if (this.fromApiJsonHelper.parameterExists(RateApiConstants.rateName, element)) { - final String name = this.fromApiJsonHelper.extractStringNamed(RateApiConstants.rateName, element); - baseDataValidator.reset().parameter(RateApiConstants.rateName).value(name).notBlank().notExceedingLengthOf(250); + final JsonElement element = this.fromApiJsonHelper.parse(json); + + if (this.fromApiJsonHelper.parameterExists(RateApiConstants.rateName, element)) { + final String name = this.fromApiJsonHelper.extractStringNamed(RateApiConstants.rateName, element); + baseDataValidator.reset().parameter(RateApiConstants.rateName).value(name).notBlank().notExceedingLengthOf(250); + } + + if (this.fromApiJsonHelper.parameterExists(RateApiConstants.ratePercentage, element)) { + final BigDecimal percentage = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(RateApiConstants.ratePercentage, element); + baseDataValidator.reset().parameter(RateApiConstants.ratePercentage).value(percentage).notBlank(); + } + + if (this.fromApiJsonHelper.parameterExists(RateApiConstants.rateProductApply, element)) { + final String productApply = this.fromApiJsonHelper.extractStringNamed(RateApiConstants.rateProductApply, element); + baseDataValidator.reset().parameter(RateApiConstants.rateProductApply).value(productApply).notBlank(); + } + + throwExceptionIfValidationWarningsExist(dataValidationErrors); } - if (this.fromApiJsonHelper.parameterExists(RateApiConstants.ratePercentage, element)) { - final BigDecimal percentage = this.fromApiJsonHelper - .extractBigDecimalWithLocaleNamed(RateApiConstants.ratePercentage, element); - baseDataValidator.reset().parameter(RateApiConstants.ratePercentage).value(percentage).notBlank(); + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - if (this.fromApiJsonHelper.parameterExists(RateApiConstants.rateProductApply, element)) { - final String productApply = this.fromApiJsonHelper.extractStringNamed(RateApiConstants.rateProductApply, element); - baseDataValidator.reset().parameter(RateApiConstants.rateProductApply).value(productApply).notBlank(); - } - - throwExceptionIfValidationWarningsExist(dataValidationErrors); - } - - private void throwExceptionIfValidationWarningsExist( - final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } - } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateAssembler.java index 247a37c37..4404e99b4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateAssembler.java @@ -34,47 +34,44 @@ import org.springframework.stereotype.Service; @Service public class RateAssembler { - private final FromJsonHelper fromApiJsonHelper; - private final RateRepositoryWrapper rateRepository; + private final FromJsonHelper fromApiJsonHelper; + private final RateRepositoryWrapper rateRepository; - @Autowired - public RateAssembler(final FromJsonHelper fromApiJsonHelper, - final RateRepositoryWrapper rateRepository) { - this.fromApiJsonHelper = fromApiJsonHelper; - this.rateRepository = rateRepository; - } - - public List fromParsedJson(final JsonElement element) { - - final List rateItems = new ArrayList<>(); - - if (element.isJsonObject()) { - final JsonObject topLevelJsonElement = element.getAsJsonObject(); - final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); - - if (topLevelJsonElement.has(LoanProductConstants.RATES_PARAM_NAME) && topLevelJsonElement - .get(LoanProductConstants.RATES_PARAM_NAME) - .isJsonArray()) { - final JsonArray array = topLevelJsonElement.get(LoanProductConstants.RATES_PARAM_NAME) - .getAsJsonArray(); - List idList = new ArrayList<>(); - - for (int i = 0; i < array.size(); i++) { - - final JsonObject rateElement = array.get(i).getAsJsonObject(); - - final Long id = this.fromApiJsonHelper.extractLongNamed("id", rateElement); - - if (id != null) { - final Long rateId = this.fromApiJsonHelper.extractLongNamed("id", rateElement); - idList.add(rateId); - } - } - rateItems.addAll(rateRepository.findMultipleWithNotFoundDetection(idList)); - } + @Autowired + public RateAssembler(final FromJsonHelper fromApiJsonHelper, final RateRepositoryWrapper rateRepository) { + this.fromApiJsonHelper = fromApiJsonHelper; + this.rateRepository = rateRepository; } - return rateItems; - } + public List fromParsedJson(final JsonElement element) { + + final List rateItems = new ArrayList<>(); + + if (element.isJsonObject()) { + final JsonObject topLevelJsonElement = element.getAsJsonObject(); + final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); + + if (topLevelJsonElement.has(LoanProductConstants.RATES_PARAM_NAME) + && topLevelJsonElement.get(LoanProductConstants.RATES_PARAM_NAME).isJsonArray()) { + final JsonArray array = topLevelJsonElement.get(LoanProductConstants.RATES_PARAM_NAME).getAsJsonArray(); + List idList = new ArrayList<>(); + + for (int i = 0; i < array.size(); i++) { + + final JsonObject rateElement = array.get(i).getAsJsonObject(); + + final Long id = this.fromApiJsonHelper.extractLongNamed("id", rateElement); + + if (id != null) { + final Long rateId = this.fromApiJsonHelper.extractLongNamed("id", rateElement); + idList.add(rateId); + } + } + rateItems.addAll(rateRepository.findMultipleWithNotFoundDetection(idList)); + } + } + + return rateItems; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateEnumerations.java index d2cdc226e..6513c1655 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateEnumerations.java @@ -24,25 +24,21 @@ import org.apache.fineract.portfolio.rate.domain.RateAppliesTo; public class RateEnumerations { - public static EnumOptionData rateAppliesTo(final int id) { - return rateAppliesTo(RateAppliesTo.fromInt(id)); - } - - public static EnumOptionData rateAppliesTo(final RateAppliesTo type) { - EnumOptionData optionData = null; - switch (type) { - case LOAN: - optionData = new EnumOptionData(RateAppliesTo.LOAN.getValue().longValue(), - RateAppliesTo.LOAN.getCode(), "Loan"); - break; - default: - optionData = new EnumOptionData(RateAppliesTo.INVALID.getValue().longValue(), - RateAppliesTo.INVALID.getCode(), - "Invalid"); - break; + public static EnumOptionData rateAppliesTo(final int id) { + return rateAppliesTo(RateAppliesTo.fromInt(id)); } - return optionData; - } + public static EnumOptionData rateAppliesTo(final RateAppliesTo type) { + EnumOptionData optionData = null; + switch (type) { + case LOAN: + optionData = new EnumOptionData(RateAppliesTo.LOAN.getValue().longValue(), RateAppliesTo.LOAN.getCode(), "Loan"); + break; + default: + optionData = new EnumOptionData(RateAppliesTo.INVALID.getValue().longValue(), RateAppliesTo.INVALID.getCode(), "Invalid"); + break; + } + return optionData; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateReadService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateReadService.java index 81b15d31d..4455e4d19 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateReadService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateReadService.java @@ -23,21 +23,20 @@ import java.util.List; import org.apache.fineract.portfolio.rate.data.RateData; /** - * Bowpi GT - * Created by Jose on 19/07/2017. + * Bowpi GT Created by Jose on 19/07/2017. */ public interface RateReadService { - Collection retrieveAllRates(); + Collection retrieveAllRates(); - Collection retrieveLoanApplicableRates(); + Collection retrieveLoanApplicableRates(); - RateData retrieveOne(Long rateId); + RateData retrieveOne(Long rateId); - RateData retrieveByName(String name); + RateData retrieveByName(String name); - List retrieveProductLoanRates(Long loanId); + List retrieveProductLoanRates(Long loanId); - List retrieveLoanRates(Long loanId); + List retrieveLoanRates(Long loanId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateReadServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateReadServiceImpl.java index 35a0e5bef..38c8c39a9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateReadServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateReadServiceImpl.java @@ -43,111 +43,108 @@ import org.springframework.stereotype.Service; @Service public class RateReadServiceImpl implements RateReadService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; - @Autowired - public RateReadServiceImpl(PlatformSecurityContext context, final RoutingDataSource dataSource) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Override - public Collection retrieveAllRates() { - this.context.authenticatedUser(); - final RateMapper rm = new RateMapper(); - final String sql = "select " + rm.rateSchema(); - return this.jdbcTemplate.query(sql, rm, new Object[]{}); - } - - @Override - public RateData retrieveOne(Long rateId) { - try { - this.context.authenticatedUser(); - final RateMapper rm = new RateMapper(); - final String sql = "select " + rm.rateSchema() + " where r.id = ?"; - final RateData selectedRate = this.jdbcTemplate.queryForObject(sql, rm, new Object[]{rateId}); - return selectedRate; - - } catch (final EmptyResultDataAccessException e) { - throw new RateNotFoundException(rateId); - } - } - - @Override - public RateData retrieveByName(String name) { - try { - this.context.authenticatedUser(); - final RateMapper rm = new RateMapper(); - final String sql = "select " + rm.rateSchema() + " where r.name = ?"; - final RateData selectedRate = this.jdbcTemplate.queryForObject(sql, rm, new Object[]{name}); - return selectedRate; - - } catch (final EmptyResultDataAccessException e) { - throw new RateNotFoundException(name); - } - } - - @Override - public Collection retrieveLoanApplicableRates() { - this.context.authenticatedUser(); - final RateMapper rm = new RateMapper(); - final String sql = "select " + rm.rateSchema() + " where r.active = ? and product_apply=?"; - return this.jdbcTemplate.query(sql, rm, new Object[]{true, RateAppliesTo.LOAN.getValue()}); - } - - @Override - public List retrieveLoanRates(Long loanId) { - final RateMapper rm = new RateMapper(); - final String sql = "select " + rm.loanRateSchema() + " where lr.loan_id = ?"; - return this.jdbcTemplate.query(sql, rm, new Object[]{loanId}); - } - - @Override - public List retrieveProductLoanRates(Long loanId) { - final RateMapper rm = new RateMapper(); - final String sql = "select " + rm.productLoanRateSchema() + " where lr.product_loan_id = ?"; - return this.jdbcTemplate.query(sql, rm, new Object[]{loanId}); - } - - private static final class RateMapper implements RowMapper { - - - public String rateSchema() { - return " r.id as id, r.name as name, r.percentage as percentage, " + - "r.product_apply as productApply, r.active as active from m_rate r "; - } - - public String loanRateSchema() { - return rateSchema() + " join m_loan_rate lr on lr.rate_id = r.id"; - } - - public String productLoanRateSchema() { - return rateSchema() + " join m_product_loan_rate lr on lr.rate_id = r.id"; - } - - public RateMapper() { + @Autowired + public RateReadServiceImpl(PlatformSecurityContext context, final RoutingDataSource dataSource) { + this.context = context; + this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override - public RateData mapRow(ResultSet resultSet, int i) throws SQLException { - final Long id = resultSet.getLong("id"); - final String name = resultSet.getString("name"); - final BigDecimal percentage = resultSet.getBigDecimal("percentage"); - final Integer productApply = resultSet.getInt("productApply"); - final EnumOptionData productAppliesTo = RateEnumerations.rateAppliesTo(productApply); - final boolean active = resultSet.getBoolean("active"); - return RateData.instance(id, name, percentage, productAppliesTo, active); + public Collection retrieveAllRates() { + this.context.authenticatedUser(); + final RateMapper rm = new RateMapper(); + final String sql = "select " + rm.rateSchema(); + return this.jdbcTemplate.query(sql, rm, new Object[] {}); } - public RateData mapRow(Rate rateResponse, int i) { - final Long id = rateResponse.getId(); - final String name = rateResponse.getName(); - final BigDecimal percentage = rateResponse.getPercentage(); - final EnumOptionData productApply = RateEnumerations - .rateAppliesTo(rateResponse.getProductApply()); - final boolean active = rateResponse.isActive(); - return RateData.instance(id, name, percentage, productApply, active); + @Override + public RateData retrieveOne(Long rateId) { + try { + this.context.authenticatedUser(); + final RateMapper rm = new RateMapper(); + final String sql = "select " + rm.rateSchema() + " where r.id = ?"; + final RateData selectedRate = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { rateId }); + return selectedRate; + + } catch (final EmptyResultDataAccessException e) { + throw new RateNotFoundException(rateId); + } + } + + @Override + public RateData retrieveByName(String name) { + try { + this.context.authenticatedUser(); + final RateMapper rm = new RateMapper(); + final String sql = "select " + rm.rateSchema() + " where r.name = ?"; + final RateData selectedRate = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { name }); + return selectedRate; + + } catch (final EmptyResultDataAccessException e) { + throw new RateNotFoundException(name); + } + } + + @Override + public Collection retrieveLoanApplicableRates() { + this.context.authenticatedUser(); + final RateMapper rm = new RateMapper(); + final String sql = "select " + rm.rateSchema() + " where r.active = ? and product_apply=?"; + return this.jdbcTemplate.query(sql, rm, new Object[] { true, RateAppliesTo.LOAN.getValue() }); + } + + @Override + public List retrieveLoanRates(Long loanId) { + final RateMapper rm = new RateMapper(); + final String sql = "select " + rm.loanRateSchema() + " where lr.loan_id = ?"; + return this.jdbcTemplate.query(sql, rm, new Object[] { loanId }); + } + + @Override + public List retrieveProductLoanRates(Long loanId) { + final RateMapper rm = new RateMapper(); + final String sql = "select " + rm.productLoanRateSchema() + " where lr.product_loan_id = ?"; + return this.jdbcTemplate.query(sql, rm, new Object[] { loanId }); + } + + private static final class RateMapper implements RowMapper { + + public String rateSchema() { + return " r.id as id, r.name as name, r.percentage as percentage, " + + "r.product_apply as productApply, r.active as active from m_rate r "; + } + + public String loanRateSchema() { + return rateSchema() + " join m_loan_rate lr on lr.rate_id = r.id"; + } + + public String productLoanRateSchema() { + return rateSchema() + " join m_product_loan_rate lr on lr.rate_id = r.id"; + } + + public RateMapper() {} + + @Override + public RateData mapRow(ResultSet resultSet, int i) throws SQLException { + final Long id = resultSet.getLong("id"); + final String name = resultSet.getString("name"); + final BigDecimal percentage = resultSet.getBigDecimal("percentage"); + final Integer productApply = resultSet.getInt("productApply"); + final EnumOptionData productAppliesTo = RateEnumerations.rateAppliesTo(productApply); + final boolean active = resultSet.getBoolean("active"); + return RateData.instance(id, name, percentage, productAppliesTo, active); + } + + public RateData mapRow(Rate rateResponse, int i) { + final Long id = rateResponse.getId(); + final String name = rateResponse.getName(); + final BigDecimal percentage = rateResponse.getPercentage(); + final EnumOptionData productApply = RateEnumerations.rateAppliesTo(rateResponse.getProductApply()); + final boolean active = rateResponse.isActive(); + return RateData.instance(id, name, percentage, productApply, active); + } } - } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateWriteService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateWriteService.java index 0cd7dfea5..deef18de5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateWriteService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateWriteService.java @@ -22,8 +22,7 @@ import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; /** - * Bowpi GT - * Created by Jose on 19/07/2017. + * Bowpi GT Created by Jose on 19/07/2017. */ public interface RateWriteService { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateWriteServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateWriteServiceImpl.java index dfa370715..aac4699ab 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateWriteServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/rate/service/RateWriteServiceImpl.java @@ -57,8 +57,7 @@ public class RateWriteServiceImpl implements RateWriteService { @Autowired public RateWriteServiceImpl(RateRepository rateRepository, AppUserRepository appUserRepository, - final RateDefinitionCommandFromApiJsonDeserializer fromApiJsonDeserializer, - PlatformSecurityContext context) { + final RateDefinitionCommandFromApiJsonDeserializer fromApiJsonDeserializer, PlatformSecurityContext context) { this.rateRepository = rateRepository; this.appUserRepository = appUserRepository; this.context = context; @@ -80,8 +79,7 @@ public class RateWriteServiceImpl implements RateWriteService { this.rateRepository.save(rate); - return new CommandProcessingResultBuilder().withCommandId(command.commandId()) - .withEntityId(rate.getId()).build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(rate.getId()).build(); } catch (final DataIntegrityViolationException dve) { handleRateDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); @@ -109,7 +107,8 @@ public class RateWriteServiceImpl implements RateWriteService { final Long newApproveUserId = (Long) changes.get(approveUserIdParamName); AppUser newApproveUser = null; if (newApproveUserId != null) { - newApproveUser = this.appUserRepository.findById(newApproveUserId).orElseThrow(() -> new UserNotFoundException(newApproveUserId)); + newApproveUser = this.appUserRepository.findById(newApproveUserId) + .orElseThrow(() -> new UserNotFoundException(newApproveUserId)); } rateToUpdate.setApproveUser(newApproveUser); } @@ -137,13 +136,11 @@ public class RateWriteServiceImpl implements RateWriteService { * Guaranteed to throw an exception no matter what the data integrity issue * is. */ - private void handleRateDataIntegrityIssues(final JsonCommand command, final Throwable realCause, - final Exception dve) { + private void handleRateDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { if (realCause.getMessage().contains("rate_name_org")) { final String name = command.stringValueOfParameterNamed("name"); throw new PlatformDataIntegrityException("error.msg.fund.duplicate.externalId", - "A rate with name '" + name - + "' already exists", "name", name); + "A rate with name '" + name + "' already exists", "name", name); } LOG.error("Error due to Exception", dve); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountOnClosureType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountOnClosureType.java index fc7a2dc51..2632ed7ec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountOnClosureType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountOnClosureType.java @@ -32,8 +32,8 @@ public enum DepositAccountOnClosureType { INVALID(0, "depositAccountClosureType.invalid"), // WITHDRAW_DEPOSIT(100, "depositAccountClosureType.withdrawDeposit"), // TRANSFER_TO_SAVINGS(200, "depositAccountClosureType.transferToSavings"), // - REINVEST_PRINCIPAL_AND_INTEREST(300, "depositAccountClosureType.reinvestPrincipalAndInterest"), - REINVEST_PRINCIPAL_ONLY(400, "depositAccountClosureType.reinvestPrincipalOnly"); // + REINVEST_PRINCIPAL_AND_INTEREST(300, "depositAccountClosureType.reinvestPrincipalAndInterest"), REINVEST_PRINCIPAL_ONLY(400, + "depositAccountClosureType.reinvestPrincipalOnly"); // private final Integer value; private final String code; @@ -82,8 +82,8 @@ public enum DepositAccountOnClosureType { } public boolean isReinvest() { - return this.value.equals(DepositAccountOnClosureType.REINVEST_PRINCIPAL_AND_INTEREST.getValue()) || - this.value.equals(DepositAccountOnClosureType.REINVEST_PRINCIPAL_ONLY.getValue()); + return this.value.equals(DepositAccountOnClosureType.REINVEST_PRINCIPAL_AND_INTEREST.getValue()) + || this.value.equals(DepositAccountOnClosureType.REINVEST_PRINCIPAL_ONLY.getValue()); } public boolean isReinvestPrincipal() { @@ -108,4 +108,4 @@ public enum DepositAccountOnClosureType { return values.toArray(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountOnHoldTransactionType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountOnHoldTransactionType.java old mode 100755 new mode 100644 index cbaea21eb..9263ca56e --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountOnHoldTransactionType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountOnHoldTransactionType.java @@ -71,4 +71,4 @@ public enum DepositAccountOnHoldTransactionType { return this.value.equals(DepositAccountOnHoldTransactionType.RELEASE.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountType.java index b54bf68af..147f687f1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositAccountType.java @@ -118,4 +118,4 @@ public enum DepositAccountType { public boolean isInvalid() { return this.value.equals(DepositAccountType.INVALID.value); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositsApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositsApiConstants.java index 44266f14d..d5af5f850 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositsApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/DepositsApiConstants.java @@ -206,24 +206,22 @@ public class DepositsApiConstants { */ private static final Set DEPOSIT_PRODUCT_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(localeParamName, monthDayFormatParamName, nameParamName, shortNameParamName, descriptionParamName, currencyCodeParamName, - digitsAfterDecimalParamName, inMultiplesOfParamName, nominalAnnualInterestRateParamName, - interestCompoundingPeriodTypeParamName, interestPostingPeriodTypeParamName, interestCalculationTypeParamName, - interestCalculationDaysInYearTypeParamName, lockinPeriodFrequencyParamName, lockinPeriodFrequencyTypeParamName, - accountingRuleParamName, chargesParamName, SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), - SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), + digitsAfterDecimalParamName, inMultiplesOfParamName, nominalAnnualInterestRateParamName, interestCompoundingPeriodTypeParamName, + interestPostingPeriodTypeParamName, interestCalculationTypeParamName, interestCalculationDaysInYearTypeParamName, + lockinPeriodFrequencyParamName, lockinPeriodFrequencyTypeParamName, accountingRuleParamName, chargesParamName, + SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), - SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), - SavingProductAccountingParams.FEE_INCOME_ACCOUNT_MAPPING.getValue(), + SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), SavingProductAccountingParams.FEE_INCOME_ACCOUNT_MAPPING.getValue(), SavingProductAccountingParams.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(), chartsParamName, SavingsApiConstants.withHoldTaxParamName, SavingsApiConstants.taxGroupIdParamName)); - private static final Set PRECLOSURE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(preClosurePenalApplicableParamName, - preClosurePenalInterestParamName, preClosurePenalInterestOnTypeIdParamName)); + private static final Set PRECLOSURE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(preClosurePenalApplicableParamName, preClosurePenalInterestParamName, preClosurePenalInterestOnTypeIdParamName)); - private static final Set PRECLOSURE_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(preClosurePenalApplicableParamName, - preClosurePenalInterestParamName, preClosurePenalInterestOnType)); + private static final Set PRECLOSURE_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(preClosurePenalApplicableParamName, preClosurePenalInterestParamName, preClosurePenalInterestOnType)); private static final Set DEPOSIT_TERM_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(minDepositTermParamName, maxDepositTermParamName, minDepositTermTypeIdParamName, maxDepositTermTypeIdParamName, inMultiplesOfDepositTermParamName, @@ -233,15 +231,15 @@ public class DepositsApiConstants { maxDepositTermParamName, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTermParamName, inMultiplesOfDepositTermType, depositAmountParamName, depositMinAmountParamName, depositMaxAmountParamName)); - private static final Set RECURRING_DETAILS_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - mandatoryRecommendedDepositAmountParamName, isMandatoryDepositParamName, allowWithdrawalParamName, - adjustAdvanceTowardsFuturePaymentsParamName, recurringFrequencyTypeParamName, recurringFrequencyParamName, - isCalendarInheritedParamName)); + private static final Set RECURRING_DETAILS_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(mandatoryRecommendedDepositAmountParamName, isMandatoryDepositParamName, allowWithdrawalParamName, + adjustAdvanceTowardsFuturePaymentsParamName, recurringFrequencyTypeParamName, recurringFrequencyParamName, + isCalendarInheritedParamName)); - private static final Set RECURRING_DETAILS_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - mandatoryRecommendedDepositAmountParamName, isMandatoryDepositParamName, allowWithdrawalParamName, - adjustAdvanceTowardsFuturePaymentsParamName, recurringFrequencyTypeParamName, recurringFrequencyParamName, - isCalendarInheritedParamName)); + private static final Set RECURRING_DETAILS_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(mandatoryRecommendedDepositAmountParamName, isMandatoryDepositParamName, allowWithdrawalParamName, + adjustAdvanceTowardsFuturePaymentsParamName, recurringFrequencyTypeParamName, recurringFrequencyParamName, + isCalendarInheritedParamName)); private static final Set DEPOSIT_PRECLOSURE_CALCULATION_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(preMatureCloseOnDateParamName)); @@ -293,15 +291,13 @@ public class DepositsApiConstants { */ private static final Set DEPOSIT_ACCOUNT_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(localeParamName, dateFormatParamName, monthDayFormatParamName, accountNoParamName, - externalIdParamName, clientIdParamName, groupIdParamName, productIdParamName, - fieldOfficerIdParamName, submittedOnDateParamName, nominalAnnualInterestRateParamName, - interestCompoundingPeriodTypeParamName, interestPostingPeriodTypeParamName, - interestCalculationTypeParamName, interestCalculationDaysInYearTypeParamName, - lockinPeriodFrequencyParamName, lockinPeriodFrequencyTypeParamName, chargesParamName, - chartsParamName, depositAmountParamName, depositPeriodParamName, depositPeriodFrequencyIdParamName, - savingsAccounts, expectedFirstDepositOnDateParamName, SavingsApiConstants.withHoldTaxParamName, - maturityInstructionIdParamName, transferToSavingsIdParamName)); + Arrays.asList(localeParamName, dateFormatParamName, monthDayFormatParamName, accountNoParamName, externalIdParamName, + clientIdParamName, groupIdParamName, productIdParamName, fieldOfficerIdParamName, submittedOnDateParamName, + nominalAnnualInterestRateParamName, interestCompoundingPeriodTypeParamName, interestPostingPeriodTypeParamName, + interestCalculationTypeParamName, interestCalculationDaysInYearTypeParamName, lockinPeriodFrequencyParamName, + lockinPeriodFrequencyTypeParamName, chargesParamName, chartsParamName, depositAmountParamName, depositPeriodParamName, + depositPeriodFrequencyIdParamName, savingsAccounts, expectedFirstDepositOnDateParamName, + SavingsApiConstants.withHoldTaxParamName, maturityInstructionIdParamName, transferToSavingsIdParamName)); public static final Set FIXED_DEPOSIT_ACCOUNT_REQUEST_DATA_PARAMETERS = fixedDepositAccountRequestData(); public static final Set FIXED_DEPOSIT_ACCOUNT_RESPONSE_DATA_PARAMETERS = fixedDepositAccountResponseData(); @@ -348,26 +344,22 @@ public class DepositsApiConstants { } private static final Set RECURRING_DEPOSIT_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(idParamName, "accountId", accountNoParamName, "currency", "amount", dateParamName, - paymentDetailDataParamName, runningBalanceParamName, reversedParamName)); + Arrays.asList(idParamName, "accountId", accountNoParamName, "currency", "amount", dateParamName, paymentDetailDataParamName, + runningBalanceParamName, reversedParamName)); - private static final Set SAVINGS_ACCOUNT_ACTIVATION_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList - (localeParamName, - dateFormatParamName, activatedOnDateParamName)); + private static final Set SAVINGS_ACCOUNT_ACTIVATION_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(localeParamName, dateFormatParamName, activatedOnDateParamName)); - private static final Set SAVINGS_ACCOUNT_CHARGES_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList - (chargeIdParamName, - savingsAccountChargeIdParamName, chargeNameParamName, penaltyParamName, chargeTimeTypeParamName, dueAsOfDateParamName, - chargeCalculationTypeParamName, percentageParamName, amountPercentageAppliedToParamName, currencyParamName, - amountWaivedParamName, amountWrittenOffParamName, amountOutstandingParamName, amountOrPercentageParamName, amountParamName, - amountPaidParamName, chargeOptionsParamName)); + private static final Set SAVINGS_ACCOUNT_CHARGES_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(chargeIdParamName, savingsAccountChargeIdParamName, chargeNameParamName, penaltyParamName, + chargeTimeTypeParamName, dueAsOfDateParamName, chargeCalculationTypeParamName, percentageParamName, + amountPercentageAppliedToParamName, currencyParamName, amountWaivedParamName, amountWrittenOffParamName, + amountOutstandingParamName, amountOrPercentageParamName, amountParamName, amountPaidParamName, chargeOptionsParamName)); - private static final Set SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList - (chargeIdParamName, - amountParamName, dueAsOfDateParamName, dateFormatParamName, localeParamName, feeOnMonthDayParamName, monthDayFormatParamName, - feeIntervalParamName)); + private static final Set SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(chargeIdParamName, amountParamName, dueAsOfDateParamName, dateFormatParamName, localeParamName, + feeOnMonthDayParamName, monthDayFormatParamName, feeIntervalParamName)); - private static final Set SAVINGS_ACCOUNT_CHARGES_PAY_CHARGE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays - .asList( - amountParamName, dueAsOfDateParamName, dateFormatParamName, localeParamName)); -} \ No newline at end of file + private static final Set SAVINGS_ACCOUNT_CHARGES_PAY_CHARGE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(amountParamName, dueAsOfDateParamName, dateFormatParamName, localeParamName)); +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/PreClosurePenalInterestOnType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/PreClosurePenalInterestOnType.java index 150fee289..ef6ad1f01 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/PreClosurePenalInterestOnType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/PreClosurePenalInterestOnType.java @@ -25,6 +25,7 @@ import java.util.List; * An enumeration of supported calendar periods used in savings. */ public enum PreClosurePenalInterestOnType { + INVALID(0, "preClosurePenalInterestOnType.invalid"), WHOLE_TERM(1, "preClosurePenalInterestOnType.wholeTerm"), // TILL_PREMATURE_WITHDRAWAL(2, "preClosurePenalInterestOnType.tillPrematureWithdrawal"); // diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/RecurringDepositType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/RecurringDepositType.java index a3eff1ee4..c8fc720cd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/RecurringDepositType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/RecurringDepositType.java @@ -25,6 +25,7 @@ import java.util.List; * An enumeration of supported calendar periods used in savings. */ public enum RecurringDepositType { + INVALID(0, "recurringDepositType.invalid"), VOLUNTARY(1, "recurringDepositType.voluntary"), // MANDATORY(2, "recurringDepositType.mandatory"); // diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsAccountTransactionType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsAccountTransactionType.java index 18038330a..0cfbcf350 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsAccountTransactionType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsAccountTransactionType.java @@ -40,10 +40,8 @@ public enum SavingsAccountTransactionType { WITHDRAW_TRANSFER(14, "savingsAccountTransactionType.withdrawTransfer"), // REJECT_TRANSFER(15, "savingsAccountTransactionType.rejectTransfer"), WRITTEN_OFF(16, "savingsAccountTransactionType.writtenoff"), // OVERDRAFT_INTEREST(17, "savingsAccountTransactionType.overdraftInterest"), // - WITHHOLD_TAX(18, "savingsAccountTransactionType.withholdTax"), - ESCHEAT(19, "savingsAccountTransactionType.escheat"), - AMOUNT_HOLD(20, "savingsAccountTransactionType.onHold"), - AMOUNT_RELEASE(21, "savingsAccountTransactionType.release"); + WITHHOLD_TAX(18, "savingsAccountTransactionType.withholdTax"), ESCHEAT(19, "savingsAccountTransactionType.escheat"), AMOUNT_HOLD(20, + "savingsAccountTransactionType.onHold"), AMOUNT_RELEASE(21, "savingsAccountTransactionType.release"); private final Integer value; private final String code; @@ -206,10 +204,11 @@ public enum SavingsAccountTransactionType { } public boolean isDebit() { - return isWithdrawal() || isWithdrawalFee() || isAnnualFee() || isPayCharge() || isIncomeFromInterest() || isWithHoldTax() || isEscheat(); + return isWithdrawal() || isWithdrawalFee() || isAnnualFee() || isPayCharge() || isIncomeFromInterest() || isWithHoldTax() + || isEscheat(); } public boolean isCredit() { return isDeposit() || isInterestPosting() || isDividendPayout(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsApiConstants.java index 36afd94a7..68f3127d5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsApiConstants.java @@ -57,7 +57,7 @@ public class SavingsApiConstants { public static final String COMMAND_INACTIVATE_CHARGE = "inactivate"; public static final String COMMAND_HOLD_AMOUNT = "holdAmount"; public static final String COMMAND_RELEASE_AMOUNT = "releaseAmount"; - public static final String COMMAND_UNBLOCK_ACCOUNT= "unblock"; + public static final String COMMAND_UNBLOCK_ACCOUNT = "unblock"; public static final String COMMAND_BLOCK_ACCOUNT = "block"; public static final String COMMAND_BLOCK_CREDIT = "blockCredit"; public static final String COMMAND_BLOCK_DEBIT = "blockDebit"; @@ -72,19 +72,19 @@ public class SavingsApiConstants { // savings product and account parameters public static final String idParamName = "id"; - public static final String isGSIM="isGSIM"; - public static final String isParentAccount="isParentAccount"; + public static final String isGSIM = "isGSIM"; + public static final String isParentAccount = "isParentAccount"; public static final String accountNoParamName = "accountNo"; public static final String externalIdParamName = "externalId"; public static final String statusParamName = "status"; public static final String subStatusParamName = "subStatus"; public static final String clientIdParamName = "clientId"; public static final String isRetailAccountParamName = "isRetailAccount"; - public static final String autogenerateTransactionIdParamName="autogenerateTransactionId"; - public static final String transactionUpperLimitParamName="transactionUpperLimit"; - public static final String transactionLowerLimitParamName="transactionLowerLimit"; - public static final String retailEntriesParamName="retailEntries"; - public static final String childAccountIdParamName="childAccountId"; + public static final String autogenerateTransactionIdParamName = "autogenerateTransactionId"; + public static final String transactionUpperLimitParamName = "transactionUpperLimit"; + public static final String transactionLowerLimitParamName = "transactionLowerLimit"; + public static final String retailEntriesParamName = "retailEntries"; + public static final String childAccountIdParamName = "childAccountId"; public static final String groupIdParamName = "groupId"; public static final String productIdParamName = "productId"; @@ -190,4 +190,4 @@ public class SavingsApiConstants { public static final String gsimApplicationId = "applicationId"; public static final String gsimLastApplication = "lastApplication"; public static final String ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE = "not.in.active.state"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsCompoundingInterestPeriodType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsCompoundingInterestPeriodType.java index 01e5ce5cf..966c3d4ff 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsCompoundingInterestPeriodType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsCompoundingInterestPeriodType.java @@ -104,4 +104,4 @@ public enum SavingsCompoundingInterestPeriodType { } return repaymentFrequencyType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsInterestCalculationDaysInYearType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsInterestCalculationDaysInYearType.java index 439814967..0696e0951 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsInterestCalculationDaysInYearType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsInterestCalculationDaysInYearType.java @@ -77,4 +77,4 @@ public enum SavingsInterestCalculationDaysInYearType { } return repaymentFrequencyType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsInterestCalculationType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsInterestCalculationType.java index 0b9f24388..0e35dbb25 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsInterestCalculationType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsInterestCalculationType.java @@ -91,4 +91,4 @@ public enum SavingsInterestCalculationType { } return repaymentFrequencyType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsPeriodFrequencyType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsPeriodFrequencyType.java index 70190b80e..89fd08e9f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsPeriodFrequencyType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsPeriodFrequencyType.java @@ -25,6 +25,7 @@ import java.util.List; * An enumeration of supported calendar periods used in savings. */ public enum SavingsPeriodFrequencyType { + DAYS(0, "savingsPeriodFrequencyType.days"), // WEEKS(1, "savingsPeriodFrequencyType.weeks"), // MONTHS(2, "savingsPeriodFrequencyType.months"), // diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsPostingInterestPeriodType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsPostingInterestPeriodType.java index 3dd09a74e..59e35ed7a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsPostingInterestPeriodType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsPostingInterestPeriodType.java @@ -79,4 +79,4 @@ public enum SavingsPostingInterestPeriodType { } return repaymentFrequencyType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsWithdrawalFeesType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsWithdrawalFeesType.java index ab97aad2d..b386e77ef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsWithdrawalFeesType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/SavingsWithdrawalFeesType.java @@ -67,4 +67,4 @@ public enum SavingsWithdrawalFeesType { } return withdrawalFeeType; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/DepositAccountOnHoldFundTransactionsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/DepositAccountOnHoldFundTransactionsApiResource.java old mode 100755 new mode 100644 index 3d8bc8236..46c41b75c --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/DepositAccountOnHoldFundTransactionsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/DepositAccountOnHoldFundTransactionsApiResource.java @@ -64,21 +64,20 @@ public class DepositAccountOnHoldFundTransactionsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveAll(@PathParam("savingsId") final Long savingsId, - @QueryParam("guarantorFundingId") final Long guarantorFundingId, @Context final UriInfo uriInfo, - @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, + public String retrieveAll(@PathParam("savingsId") final Long savingsId, @QueryParam("guarantorFundingId") final Long guarantorFundingId, + @Context final UriInfo uriInfo, @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, @QueryParam("orderBy") final String orderBy, @QueryParam("sortOrder") final String sortOrder) { this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); final SearchParameters searchParameters = SearchParameters.forPagination(offset, limit, orderBy, sortOrder); - final Page transfers = this.depositAccountOnHoldTransactionReadPlatformService.retriveAll( - savingsId, guarantorFundingId, searchParameters); + final Page transfers = this.depositAccountOnHoldTransactionReadPlatformService + .retriveAll(savingsId, guarantorFundingId, searchParameters); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, transfers, SavingsApiSetConstants.SAVINGS_ACCOUNT_ON_HOLD_RESPONSE_DATA_PARAMETERS); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountTransactionsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountTransactionsApiResource.java index dbc1e1095..20624e0c4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountTransactionsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountTransactionsApiResource.java @@ -65,10 +65,9 @@ public class FixedDepositAccountTransactionsApiResource { private final PaymentTypeReadPlatformService paymentTypeReadPlatformService; private static final Set FIXED_DEPOSIT_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( Arrays.asList(DepositsApiConstants.idParamName, DepositsApiConstants.accountIdParamName, - DepositsApiConstants.accountNoParamName, DepositsApiConstants.currencyParamName, - DepositsApiConstants.amountParamName, DepositsApiConstants.dateParamName, - DepositsApiConstants.paymentDetailDataParamName, DepositsApiConstants.runningBalanceParamName, - DepositsApiConstants.reversedParamName)); + DepositsApiConstants.accountNoParamName, DepositsApiConstants.currencyParamName, DepositsApiConstants.amountParamName, + DepositsApiConstants.dateParamName, DepositsApiConstants.paymentDetailDataParamName, + DepositsApiConstants.runningBalanceParamName, DepositsApiConstants.reversedParamName)); @Autowired public FixedDepositAccountTransactionsApiResource(final PlatformSecurityContext context, @@ -94,13 +93,13 @@ public class FixedDepositAccountTransactionsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveTemplate(@PathParam("fixedDepositAccountId") final Long fixedDepositAccountId, - // @QueryParam("command") final String commandParam, + // @QueryParam("command") final String commandParam, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.FIXED_DEPOSIT_ACCOUNT_RESOURCE_NAME); - SavingsAccountTransactionData savingsAccount = this.savingsAccountReadPlatformService.retrieveDepositTransactionTemplate( - fixedDepositAccountId, DepositAccountType.FIXED_DEPOSIT); + SavingsAccountTransactionData savingsAccount = this.savingsAccountReadPlatformService + .retrieveDepositTransactionTemplate(fixedDepositAccountId, DepositAccountType.FIXED_DEPOSIT); final Collection paymentTypeOptions = this.paymentTypeReadPlatformService.retrieveAllPaymentTypes(); savingsAccount = SavingsAccountTransactionData.templateOnTop(savingsAccount, paymentTypeOptions); @@ -118,16 +117,15 @@ public class FixedDepositAccountTransactionsApiResource { @PathParam("transactionId") final Long transactionId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.FIXED_DEPOSIT_ACCOUNT_RESOURCE_NAME); - SavingsAccountTransactionData transactionData = this.savingsAccountReadPlatformService.retrieveSavingsTransaction( - fixedDepositAccountId, transactionId, DepositAccountType.FIXED_DEPOSIT); + SavingsAccountTransactionData transactionData = this.savingsAccountReadPlatformService + .retrieveSavingsTransaction(fixedDepositAccountId, transactionId, DepositAccountType.FIXED_DEPOSIT); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (settings.isTemplate()) { final Collection paymentTypeOptions = this.paymentTypeReadPlatformService.retrieveAllPaymentTypes(); transactionData = SavingsAccountTransactionData.templateOnTop(transactionData, paymentTypeOptions); } - return this.toApiJsonSerializer.serialize(settings, transactionData, - FIXED_DEPOSIT_TRANSACTION_RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, transactionData, FIXED_DEPOSIT_TRANSACTION_RESPONSE_DATA_PARAMETERS); } @POST @@ -187,4 +185,4 @@ public class FixedDepositAccountTransactionsApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountsApiResource.java index fa67b7936..e5f34b25b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountsApiResource.java @@ -85,14 +85,12 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; - @Path("/fixeddepositaccounts") @Component @Scope("singleton") -@Api(tags = {"Fixed Deposit Account"}) +@Api(tags = { "Fixed Deposit Account" }) @SwaggerDefinition(tags = { - @Tag(name = "Fixed Deposit Account", description = "Fixed Deposit accounts are instances of a praticular fixed deposit product created. An application process around the creation of accounts is also supported.") -}) + @Tag(name = "Fixed Deposit Account", description = "Fixed Deposit accounts are instances of a praticular fixed deposit product created. An application process around the creation of accounts is also supported.") }) public class FixedDepositAccountsApiResource { private final DepositAccountReadPlatformService depositAccountReadPlatformService; @@ -107,7 +105,6 @@ public class FixedDepositAccountsApiResource { private final BulkImportWorkbookService bulkImportWorkbookService; private final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService; - @Autowired public FixedDepositAccountsApiResource(final DepositAccountReadPlatformService depositAccountReadPlatformService, final PlatformSecurityContext context, final DefaultToApiJsonSerializer toApiJsonSerializer, @@ -127,20 +124,24 @@ public class FixedDepositAccountsApiResource { this.fromJsonHelper = fromJsonHelper; this.accountPreMatureCalculationPlatformService = accountPreMatureCalculationPlatformService; this.accountAssociationsReadPlatformService = accountAssociationsReadPlatformService; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Fixed Deposit Account Template", httpMethod = "GET", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for fixed deposit applications. The template data returned consists of any or all of:\n\n" + "\n\n" + "Field Defaults\n\n" + "Allowed Value Lists" + "Example Requests:\n\n" + "\n\n" + "fixeddepositaccounts/template?clientId=1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.GetFixedDepositAccountsTemplateResponse.class)}) - public String template(@QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, @QueryParam("groupId") @ApiParam(value = "groupId") final Long groupId, - @QueryParam("productId")@ApiParam(value = "productId") final Long productId, - @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve Fixed Deposit Account Template", httpMethod = "GET", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for fixed deposit applications. The template data returned consists of any or all of:\n\n" + + "\n\n" + "Field Defaults\n\n" + "Allowed Value Lists" + "Example Requests:\n\n" + "\n\n" + + "fixeddepositaccounts/template?clientId=1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.GetFixedDepositAccountsTemplateResponse.class) }) + public String template(@QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @QueryParam("groupId") @ApiParam(value = "groupId") final Long groupId, + @QueryParam("productId") @ApiParam(value = "productId") final Long productId, + @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.FIXED_DEPOSIT_ACCOUNT_RESOURCE_NAME); @@ -154,19 +155,23 @@ public class FixedDepositAccountsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Fixed deposit applications/accounts", httpMethod = "GET", notes = "Lists Fixed Deposit Accounts\n\n" + "Example Requests:\n\n" + "\n\n" + "fixeddepositaccounts\n\n" + "\n\n" + "fixeddepositaccounts?fields=name") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.GetFixedDepositAccountsResponse.class, responseContainer = "List")}) + @ApiOperation(value = "List Fixed deposit applications/accounts", httpMethod = "GET", notes = "Lists Fixed Deposit Accounts\n\n" + + "Example Requests:\n\n" + "\n\n" + "fixeddepositaccounts\n\n" + "\n\n" + "fixeddepositaccounts?fields=name") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.GetFixedDepositAccountsResponse.class, responseContainer = "List") }) public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("paged") @ApiParam(value = "paged") final Boolean paged, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.FIXED_DEPOSIT_ACCOUNT_RESOURCE_NAME); final PaginationParameters paginationParameters = PaginationParameters.instance(paged, offset, limit, orderBy, sortOrder); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (paginationParameters.isPaged()) { - final Page account = this.depositAccountReadPlatformService.retrieveAllPaged( - DepositAccountType.FIXED_DEPOSIT, paginationParameters); + final Page account = this.depositAccountReadPlatformService + .retrieveAllPaged(DepositAccountType.FIXED_DEPOSIT, paginationParameters); return this.toApiJsonSerializer.serialize(settings, account, DepositsApiConstants.FIXED_DEPOSIT_ACCOUNT_RESPONSE_DATA_PARAMETERS); } @@ -180,9 +185,13 @@ public class FixedDepositAccountsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Submit new fixed deposit application", httpMethod = "POST", notes = "Submits a new fixed deposit application"+"Mandatory Fields: clientId or groupId, productId, submittedOnDate, depositAmount, depositPeriod, depositPeriodFrequencyId\n\n" + "Optional Fields: accountNo, externalId, fieldOfficerId,linkAccountId(if provided initial deposit amount will be collected from this account),transferInterestToSavings(By enabling this flag all interest postings will be transferred to linked saving account )") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FixedDepositAccountsApiResourceSwagger.PostFixedDepositAccountsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.PostFixedDepositAccountsResponse.class)}) + @ApiOperation(value = "Submit new fixed deposit application", httpMethod = "POST", notes = "Submits a new fixed deposit application" + + "Mandatory Fields: clientId or groupId, productId, submittedOnDate, depositAmount, depositPeriod, depositPeriodFrequencyId\n\n" + + "Optional Fields: accountNo, externalId, fieldOfficerId,linkAccountId(if provided initial deposit amount will be collected from this account),transferInterestToSavings(By enabling this flag all interest postings will be transferred to linked saving account )") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FixedDepositAccountsApiResourceSwagger.PostFixedDepositAccountsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.PostFixedDepositAccountsResponse.class) }) public String submitApplication(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createFixedDepositAccount().withJson(apiRequestBodyAsJson) @@ -197,19 +206,23 @@ public class FixedDepositAccountsApiResource { @Path("{accountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a fixed deposit application/account", httpMethod = "GET", notes = "Retrieves a fixed deposit application/account\n\n" + "Example Requests :\n\n" + "\n\n" + "fixeddepositaccounts/1" + "\n\n" + "fixeddepositaccounts/1?associations=all" ) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.GetFixedDepositAccountsAccountIdResponse.class)}) + @ApiOperation(value = "Retrieve a fixed deposit application/account", httpMethod = "GET", notes = "Retrieves a fixed deposit application/account\n\n" + + "Example Requests :\n\n" + "\n\n" + "fixeddepositaccounts/1" + "\n\n" + "fixeddepositaccounts/1?associations=all") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.GetFixedDepositAccountsAccountIdResponse.class) }) public String retrieveOne(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, - @DefaultValue("all") @QueryParam("chargeStatus")@ApiParam(value = "chargeStatus") final String chargeStatus, @Context final UriInfo uriInfo) { + @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.FIXED_DEPOSIT_ACCOUNT_RESOURCE_NAME); - if (!(is(chargeStatus, "all") || is(chargeStatus, "active") || is(chargeStatus, "inactive"))) { throw new UnrecognizedQueryParamException( - "status", chargeStatus, new Object[] { "all", "active", "inactive" }); } + if (!(is(chargeStatus, "all") || is(chargeStatus, "active") || is(chargeStatus, "inactive"))) { + throw new UnrecognizedQueryParamException("status", chargeStatus, new Object[] { "all", "active", "inactive" }); + } - final FixedDepositAccountData account = (FixedDepositAccountData) this.depositAccountReadPlatformService.retrieveOneWithChartSlabs( - DepositAccountType.FIXED_DEPOSIT, accountId); + final FixedDepositAccountData account = (FixedDepositAccountData) this.depositAccountReadPlatformService + .retrieveOneWithChartSlabs(DepositAccountType.FIXED_DEPOSIT, accountId); final Set mandatoryResponseParameters = new HashSet<>(); final FixedDepositAccountData accountTemplate = populateTemplateAndAssociations(accountId, account, staffInSelectedOfficeOnly, @@ -221,11 +234,12 @@ public class FixedDepositAccountsApiResource { DepositsApiConstants.FIXED_DEPOSIT_ACCOUNT_RESPONSE_DATA_PARAMETERS); } - private BigDecimal getActivationCharge(Long accountId){ + private BigDecimal getActivationCharge(Long accountId) { BigDecimal activationCharge = BigDecimal.ZERO; - Collection savingCharges = this.savingsAccountChargeReadPlatformService.retrieveSavingsAccountCharges(accountId, "active"); + Collection savingCharges = this.savingsAccountChargeReadPlatformService + .retrieveSavingsAccountCharges(accountId, "active"); for (SavingsAccountChargeData savingsAccountChargeData : savingCharges) { - if(savingsAccountChargeData.isSavingsActivation()){ + if (savingsAccountChargeData.isSavingsActivation()) { activationCharge = activationCharge.add(savingsAccountChargeData.getAmountOutstanding()); } } @@ -245,8 +259,8 @@ public class FixedDepositAccountsApiResource { if (!associationParameters.isEmpty()) { if (associationParameters.contains("all")) { - associationParameters.addAll(Arrays.asList(SavingsApiConstants.transactions, SavingsApiConstants.charges, - SavingsApiConstants.linkedAccount)); + associationParameters.addAll( + Arrays.asList(SavingsApiConstants.transactions, SavingsApiConstants.charges, SavingsApiConstants.linkedAccount)); } if (associationParameters.contains(SavingsApiConstants.transactions)) { @@ -273,8 +287,9 @@ public class FixedDepositAccountsApiResource { } } - if(savingsAccount.getTransferToSavingsId() !=null){ - transferToSavingsAccount = this.accountAssociationsReadPlatformService.retriveSavingsAccount(savingsAccount.getTransferToSavingsId()); + if (savingsAccount.getTransferToSavingsId() != null) { + transferToSavingsAccount = this.accountAssociationsReadPlatformService + .retriveSavingsAccount(savingsAccount.getTransferToSavingsId()); } FixedDepositAccountData templateData = null; @@ -286,7 +301,8 @@ public class FixedDepositAccountsApiResource { staffInSelectedOfficeOnly); } - return FixedDepositAccountData.associationsAndTemplate(savingsAccount, templateData, transactions, charges, linkedAccount, transferToSavingsAccount); + return FixedDepositAccountData.associationsAndTemplate(savingsAccount, templateData, transactions, charges, linkedAccount, + transferToSavingsAccount); } @PUT @@ -294,9 +310,12 @@ public class FixedDepositAccountsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Modify a fixed deposit application", httpMethod = "PUT", notes = "Fixed deposit application can only be modified when in 'Submitted and pending approval' state. Once the application is approved, the details cannot be changed using this method. Specific api endpoints will be created to allow change of interest detail such as rate, compounding period, posting period etc") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FixedDepositAccountsApiResourceSwagger.PutFixedDepositAccountsAccountIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.PutFixedDepositAccountsAccountIdResponse.class)}) - public String update(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FixedDepositAccountsApiResourceSwagger.PutFixedDepositAccountsAccountIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.PutFixedDepositAccountsAccountIdResponse.class) }) + public String update(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateFixedDepositAccount(accountId) .withJson(apiRequestBodyAsJson).build(); @@ -310,11 +329,32 @@ public class FixedDepositAccountsApiResource { @Path("{accountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Approve fixed deposit application | Undo approval fixed deposit application | Reject fixed deposit application | Withdraw fixed deposit application | Activate a fixed deposit account | Close a fixed deposit account | Premature Close a fixed deposit account | Calculate Premature amount on Fixed deposit account | Calculate Interest on Fixed Deposit Account | Post Interest on Fixed Deposit Account", httpMethod = "POST", notes = "Approve fixed deposit application:\n\n" + "Approves fixed deposit application so long as its in 'Submitted and pending approval' state.\n\n" + "Undo approval fixed deposit application:\n\n" + "Will move 'approved' fixed deposit application back to 'Submitted and pending approval' state.\n\n" + "Reject fixed deposit application:\n\n" + "Rejects fixed deposit application so long as its in 'Submitted and pending approval' state.\n\n" + "Withdraw fixed deposit application:\n\n" + "Used when an applicant withdraws from the fixed deposit application. It must be in 'Submitted and pending approval' state.\n\n" + "Close a fixed deposit account:\n\n" + "Results in a Matured fixed deposit account being converted into a 'closed' fixed deposit account.\n\n" + "Premature Close a fixed deposit account:\n\n" + "Results in an Active fixed deposit account being converted into a 'Premature Closed' fixed deposit account with options to withdraw prematured amount. (premature amount is calculated using interest rate chart applicable along with penal interest if any.)\n\n" + "Calculate Premature amount on Fixed deposit account:\n\n" + "Calculate premature amount on fixed deposit account till premature close date. Premature amount is calculated based on interest chart and penal interest applicable.\n\n" + "Calculate Interest on Fixed Deposit Account:\n\n" + "Calculates interest earned on a fixed deposit account based on todays date. It does not attempt to post or credit the interest on the account. That is responsibility of the Post Interest API that will likely be called by overnight process.\n\n" + "Post Interest on Fixed Deposit Account:\n\n" + "Calculates and Posts interest earned on a fixed deposit account based on today's date and whether an interest posting or crediting event is due.\n\n" + "Showing request/response for Calculate Interest on Fixed Deposit Account") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FixedDepositAccountsApiResourceSwagger.PostFixedDepositAccountsAccountIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.PostFixedDepositAccountsAccountIdResponse.class)}) - public String handleCommands(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, - @Context final UriInfo uriInfo, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Approve fixed deposit application | Undo approval fixed deposit application | Reject fixed deposit application | Withdraw fixed deposit application | Activate a fixed deposit account | Close a fixed deposit account | Premature Close a fixed deposit account | Calculate Premature amount on Fixed deposit account | Calculate Interest on Fixed Deposit Account | Post Interest on Fixed Deposit Account", httpMethod = "POST", notes = "Approve fixed deposit application:\n\n" + + "Approves fixed deposit application so long as its in 'Submitted and pending approval' state.\n\n" + + "Undo approval fixed deposit application:\n\n" + + "Will move 'approved' fixed deposit application back to 'Submitted and pending approval' state.\n\n" + + "Reject fixed deposit application:\n\n" + + "Rejects fixed deposit application so long as its in 'Submitted and pending approval' state.\n\n" + + "Withdraw fixed deposit application:\n\n" + + "Used when an applicant withdraws from the fixed deposit application. It must be in 'Submitted and pending approval' state.\n\n" + + "Close a fixed deposit account:\n\n" + + "Results in a Matured fixed deposit account being converted into a 'closed' fixed deposit account.\n\n" + + "Premature Close a fixed deposit account:\n\n" + + "Results in an Active fixed deposit account being converted into a 'Premature Closed' fixed deposit account with options to withdraw prematured amount. (premature amount is calculated using interest rate chart applicable along with penal interest if any.)\n\n" + + "Calculate Premature amount on Fixed deposit account:\n\n" + + "Calculate premature amount on fixed deposit account till premature close date. Premature amount is calculated based on interest chart and penal interest applicable.\n\n" + + "Calculate Interest on Fixed Deposit Account:\n\n" + + "Calculates interest earned on a fixed deposit account based on todays date. It does not attempt to post or credit the interest on the account. That is responsibility of the Post Interest API that will likely be called by overnight process.\n\n" + + "Post Interest on Fixed Deposit Account:\n\n" + + "Calculates and Posts interest earned on a fixed deposit account based on today's date and whether an interest posting or crediting event is due.\n\n" + + "Showing request/response for Calculate Interest on Fixed Deposit Account") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FixedDepositAccountsApiResourceSwagger.PostFixedDepositAccountsAccountIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.PostFixedDepositAccountsAccountIdResponse.class) }) + public String handleCommands(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { String jsonApiRequest = apiRequestBodyAsJson; if (StringUtils.isBlank(jsonApiRequest)) { @@ -361,9 +401,11 @@ public class FixedDepositAccountsApiResource { DepositsApiConstants.FIXED_DEPOSIT_ACCOUNT_RESPONSE_DATA_PARAMETERS); } - if (result == null) { throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { "reject", - "withdrawnByApplicant", "approve", "undoapproval", "activate", "calculateInterest", "postInterest", "close", - "prematureClose", "calculatePrematureAmount" }); } + if (result == null) { + throw new UnrecognizedQueryParamException("command", commandParam, + new Object[] { "reject", "withdrawnByApplicant", "approve", "undoapproval", "activate", "calculateInterest", + "postInterest", "close", "prematureClose", "calculatePrematureAmount" }); + } return this.toApiJsonSerializer.serialize(result); } @@ -377,7 +419,8 @@ public class FixedDepositAccountsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a fixed deposit application", httpMethod = "DELETE", notes = "At present we support hard delete of fixed deposit application so long as its in 'Submitted and pending approval' state. One the application is moves past this state, it is not possible to do a 'hard' delete of the application or the account. An API endpoint will be added to close/de-activate the fixed deposit account.") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.DeleteFixedDepositAccountsAccountIdResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositAccountsApiResourceSwagger.DeleteFixedDepositAccountsAccountIdResponse.class) }) public String delete(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteFixedDepositAccount(accountId).build(); @@ -391,8 +434,8 @@ public class FixedDepositAccountsApiResource { @Path("{accountId}/template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String accountClosureTemplate(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, - @Context final UriInfo uriInfo) { + public String accountClosureTemplate(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.FIXED_DEPOSIT_ACCOUNT_RESOURCE_NAME); DepositAccountData account = null; @@ -407,37 +450,40 @@ public class FixedDepositAccountsApiResource { @GET @Path("downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getFixedDepositTemplate(@QueryParam("officeId")final Long officeId, - @QueryParam("staffId")final Long staffId,@QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate - (GlobalEntityType.FIXED_DEPOSIT_ACCOUNTS.toString(),officeId,staffId,dateFormat); + public Response getFixedDepositTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("staffId") final Long staffId, + @QueryParam("dateFormat") final String dateFormat) { + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.FIXED_DEPOSIT_ACCOUNTS.toString(), officeId, staffId, + dateFormat); } + @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postFixedDepositTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail,@FormDataParam("locale") final String locale, - @FormDataParam("dateFormat") final String dateFormat){ + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { Long importDocumentId = bulkImportWorkbookService.importWorkbook(GlobalEntityType.FIXED_DEPOSIT_ACCOUNTS.toString(), - uploadedInputStream,fileDetail,locale,dateFormat); + uploadedInputStream, fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } @GET @Path("transaction/downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getFixedDepositTransactionTemplate(@QueryParam("officeId")final Long officeId,@QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.FIXED_DEPOSIT_TRANSACTIONS.toString(), officeId,null,dateFormat); + public Response getFixedDepositTransactionTemplate(@QueryParam("officeId") final Long officeId, + @QueryParam("dateFormat") final String dateFormat) { + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.FIXED_DEPOSIT_TRANSACTIONS.toString(), officeId, null, + dateFormat); } @POST @Path("transaction/uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postFixedDepositTransactionTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail,@FormDataParam("locale") final String locale, - @FormDataParam("dateFormat") final String dateFormat){ + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.FIXED_DEPOSIT_TRANSACTIONS.toString(), - uploadedInputStream,fileDetail,locale,dateFormat); + uploadedInputStream, fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountsApiResourceSwagger.java index 2e0ecfb6e..44fc7df0a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositAccountsApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/15/17. */ final class FixedDepositAccountsApiResourceSwagger { - private FixedDepositAccountsApiResourceSwagger() { - } + + private FixedDepositAccountsApiResourceSwagger() {} @ApiModel(value = "GetFixedDepositAccountsTemplateResponse") public final static class GetFixedDepositAccountsTemplateResponse { - private GetFixedDepositAccountsTemplateResponse() { - } + + private GetFixedDepositAccountsTemplateResponse() {} final class GetFixedDepositAccountsProductOptions { - private GetFixedDepositAccountsProductOptions() { - } + + private GetFixedDepositAccountsProductOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -54,12 +54,12 @@ final class FixedDepositAccountsApiResourceSwagger { @ApiModel(value = "GetFixedDepositAccountsResponse") public final static class GetFixedDepositAccountsResponse { - private GetFixedDepositAccountsResponse() { - } + + private GetFixedDepositAccountsResponse() {} final class GetFixedDepositAccountsStatus { - private GetFixedDepositAccountsStatus() { - } + + private GetFixedDepositAccountsStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -88,8 +88,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsTimeline { - private GetFixedDepositAccountsTimeline() { - } + + private GetFixedDepositAccountsTimeline() {} @ApiModelProperty(example = "[2014, 3, 1]") public LocalDate submittedOnDate; @@ -102,8 +102,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsCurrency { - private GetFixedDepositAccountsCurrency() { - } + + private GetFixedDepositAccountsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -122,8 +122,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsInterestCompoundingPeriodType { - private GetFixedDepositAccountsInterestCompoundingPeriodType() { - } + + private GetFixedDepositAccountsInterestCompoundingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -134,8 +134,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsInterestPostingPeriodType { - private GetFixedDepositAccountsInterestPostingPeriodType() { - } + + private GetFixedDepositAccountsInterestPostingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -146,8 +146,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsInterestCalculationType { - private GetFixedDepositAccountsInterestCalculationType() { - } + + private GetFixedDepositAccountsInterestCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -158,8 +158,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsInterestCalculationDaysInYearType { - private GetFixedDepositAccountsInterestCalculationDaysInYearType() { - } + + private GetFixedDepositAccountsInterestCalculationDaysInYearType() {} @ApiModelProperty(example = "365") public Integer id; @@ -170,8 +170,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsSummary { - private GetFixedDepositAccountsSummary() { - } + + private GetFixedDepositAccountsSummary() {} public GetFixedDepositAccountsCurrency currency; @ApiModelProperty(example = "0") @@ -179,8 +179,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsMinDepositTermType { - private GetFixedDepositAccountsMinDepositTermType() { - } + + private GetFixedDepositAccountsMinDepositTermType() {} @ApiModelProperty(example = "2") public Integer id; @@ -191,8 +191,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsMaxDepositTermType { - private GetFixedDepositAccountsMaxDepositTermType() { - } + + private GetFixedDepositAccountsMaxDepositTermType() {} @ApiModelProperty(example = "3") public Integer id; @@ -203,8 +203,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsDepositPeriodFrequency { - private GetFixedDepositAccountsDepositPeriodFrequency() { - } + + private GetFixedDepositAccountsDepositPeriodFrequency() {} @ApiModelProperty(example = "2") public Integer id; @@ -259,8 +259,8 @@ final class FixedDepositAccountsApiResourceSwagger { @ApiModel(value = "PostFixedDepositAccountsRequest") public final static class PostFixedDepositAccountsRequest { - private PostFixedDepositAccountsRequest() { - } + + private PostFixedDepositAccountsRequest() {} @ApiModelProperty(example = "1") public Integer clientId; @@ -282,8 +282,8 @@ final class FixedDepositAccountsApiResourceSwagger { @ApiModel(value = "PostFixedDepositAccountsResponse") public final static class PostFixedDepositAccountsResponse { - private PostFixedDepositAccountsResponse() { - } + + private PostFixedDepositAccountsResponse() {} @ApiModelProperty(example = "2") public Integer officeId; @@ -297,20 +297,20 @@ final class FixedDepositAccountsApiResourceSwagger { @ApiModel(value = "GetFixedDepositAccountsAccountIdResponse") public final static class GetFixedDepositAccountsAccountIdResponse { - private GetFixedDepositAccountsAccountIdResponse() { - } + + private GetFixedDepositAccountsAccountIdResponse() {} final class GetFixedDepositAccountsAccountChart { - private GetFixedDepositAccountsAccountChart() { - } + + private GetFixedDepositAccountsAccountChart() {} final class GetFixedDepositAccountsChartSlabs { - private GetFixedDepositAccountsChartSlabs() { - } + + private GetFixedDepositAccountsChartSlabs() {} final class GetFixedDepositAccountsPeriodType { - private GetFixedDepositAccountsPeriodType() { - } + + private GetFixedDepositAccountsPeriodType() {} @ApiModelProperty(example = "0") public Integer id; @@ -321,8 +321,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsAccountChartCurrency { - private GetFixedDepositAccountsAccountChartCurrency() { - } + + private GetFixedDepositAccountsAccountChartCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -351,8 +351,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsPeriodTypes { - private GetFixedDepositAccountsPeriodTypes() { - } + + private GetFixedDepositAccountsPeriodTypes() {} @ApiModelProperty(example = "0") public Integer id; @@ -375,8 +375,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsAccountIdCurrency { - private GetFixedDepositAccountsAccountIdCurrency() { - } + + private GetFixedDepositAccountsAccountIdCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -395,8 +395,8 @@ final class FixedDepositAccountsApiResourceSwagger { } final class GetFixedDepositAccountsAccountIdSummary { - private GetFixedDepositAccountsAccountIdSummary() { - } + + private GetFixedDepositAccountsAccountIdSummary() {} public GetFixedDepositAccountsAccountIdCurrency currency; @ApiModelProperty(example = "0") @@ -451,8 +451,8 @@ final class FixedDepositAccountsApiResourceSwagger { @ApiModel(value = "PutFixedDepositAccountsAccountIdRequest") public final static class PutFixedDepositAccountsAccountIdRequest { - private PutFixedDepositAccountsAccountIdRequest() { - } + + private PutFixedDepositAccountsAccountIdRequest() {} @ApiModelProperty(example = "en") public String locale; @@ -462,12 +462,12 @@ final class FixedDepositAccountsApiResourceSwagger { @ApiModel(value = "PutFixedDepositAccountsAccountIdResponse") public final static class PutFixedDepositAccountsAccountIdResponse { - private PutFixedDepositAccountsAccountIdResponse() { - } + + private PutFixedDepositAccountsAccountIdResponse() {} final class PutFixedDepositAccountsChanges { - private PutFixedDepositAccountsChanges() { - } + + private PutFixedDepositAccountsChanges() {} @ApiModelProperty(example = "6000") public Float depositAmount; @@ -488,14 +488,14 @@ final class FixedDepositAccountsApiResourceSwagger { @ApiModel(value = "PostFixedDepositAccountsAccountIdRequest") public final static class PostFixedDepositAccountsAccountIdRequest { - private PostFixedDepositAccountsAccountIdRequest() { - } + + private PostFixedDepositAccountsAccountIdRequest() {} } @ApiModel(value = "PostFixedDepositAccountsAccountIdResponse") public final static class PostFixedDepositAccountsAccountIdResponse { - private PostFixedDepositAccountsAccountIdResponse() { - } + + private PostFixedDepositAccountsAccountIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -509,8 +509,8 @@ final class FixedDepositAccountsApiResourceSwagger { @ApiModel(value = "DeleteFixedDepositAccountsAccountIdResponse") public final static class DeleteFixedDepositAccountsAccountIdResponse { - private DeleteFixedDepositAccountsAccountIdResponse() { - } + + private DeleteFixedDepositAccountsAccountIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositProductsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositProductsApiResource.java index 771d6a33e..03c7d656b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositProductsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositProductsApiResource.java @@ -88,10 +88,11 @@ import org.springframework.util.CollectionUtils; @Path("/fixeddepositproducts") @Component @Scope("singleton") -@Api(tags = {"Fixed Deposit Product"}) +@Api(tags = { "Fixed Deposit Product" }) @SwaggerDefinition(tags = { - @Tag(name = "Fixed Deposit Product", description = "This is one of the advanced term deposit product offered by MFI's. The Fixed Deposit Products (aka FD) product offerings are modeled using this API.\n" + "\n" + "The FD products are deposit accounts which are held for a fixed term – like 1 year, 2 years etc.\n" + "\n" + "When creating fixed deposit accounts, the details from the fixed deposit product are used to auto fill details of the fixed deposit account application process.") -}) + @Tag(name = "Fixed Deposit Product", description = "This is one of the advanced term deposit product offered by MFI's. The Fixed Deposit Products (aka FD) product offerings are modeled using this API.\n" + + "\n" + "The FD products are deposit accounts which are held for a fixed term – like 1 year, 2 years etc.\n" + "\n" + + "When creating fixed deposit accounts, the details from the fixed deposit product are used to auto fill details of the fixed deposit account application process.") }) public class FixedDepositProductsApiResource { private final DepositProductReadPlatformService depositProductReadPlatformService; @@ -146,9 +147,15 @@ public class FixedDepositProductsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Fixed Deposit Product", httpMethod = "POST", notes = "Creates a Fixed Deposit Product\n\n" + "Mandatory Fields: name, shortName, description, currencyCode, digitsAfterDecimal,inMultiplesOf, interestCompoundingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minDepositTerm, minDepositTermTypeId, accountingRule\n\n" + "Optional Fields: lockinPeriodFrequency, lockinPeriodFrequencyType, maxDepositTerm, maxDepositTermTypeId, inMultiplesOfDepositTerm, inMultiplesOfDepositTermTypeId, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnTypeId, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, charges, charts, , withHoldTax, taxGroupId\n\n" + "\n" + "Mandatory Fields for Cash based accounting (accountingRule = 2): savingsReferenceAccountId, savingsControlAccountId, interestOnSavingsAccountId, incomeFromFeeAccountId, transfersInSuspenseAccountId, incomeFromPenaltyAccountId") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FixedDepositProductsApiResourceSwagger.PostFixedDepositProductsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositProductsApiResourceSwagger.PostFixedDepositProductsResponse.class)}) + @ApiOperation(value = "Create a Fixed Deposit Product", httpMethod = "POST", notes = "Creates a Fixed Deposit Product\n\n" + + "Mandatory Fields: name, shortName, description, currencyCode, digitsAfterDecimal,inMultiplesOf, interestCompoundingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minDepositTerm, minDepositTermTypeId, accountingRule\n\n" + + "Optional Fields: lockinPeriodFrequency, lockinPeriodFrequencyType, maxDepositTerm, maxDepositTermTypeId, inMultiplesOfDepositTerm, inMultiplesOfDepositTermTypeId, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnTypeId, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, charges, charts, , withHoldTax, taxGroupId\n\n" + + "\n" + + "Mandatory Fields for Cash based accounting (accountingRule = 2): savingsReferenceAccountId, savingsControlAccountId, interestOnSavingsAccountId, incomeFromFeeAccountId, transfersInSuspenseAccountId, incomeFromPenaltyAccountId") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FixedDepositProductsApiResourceSwagger.PostFixedDepositProductsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositProductsApiResourceSwagger.PostFixedDepositProductsResponse.class) }) public String create(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createFixedDepositProduct().withJson(apiRequestBodyAsJson) @@ -164,9 +171,12 @@ public class FixedDepositProductsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Fixed Deposit Product", httpMethod = "PUT", notes = "Updates a Fixed Deposit Product") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FixedDepositProductsApiResourceSwagger.PutFixedDepositProductsProductIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositProductsApiResourceSwagger.PutFixedDepositProductsProductIdResponse.class)}) - public String update(@PathParam("productId") @ApiParam(value = "productId") final Long productId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = FixedDepositProductsApiResourceSwagger.PutFixedDepositProductsProductIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositProductsApiResourceSwagger.PutFixedDepositProductsProductIdResponse.class) }) + public String update(@PathParam("productId") @ApiParam(value = "productId") final Long productId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateFixedDepositProduct(productId) .withJson(apiRequestBodyAsJson).build(); @@ -180,8 +190,10 @@ public class FixedDepositProductsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Fixed Deposit Products", httpMethod = "GET", notes = "Lists Fixed Deposit Products\n\n" + "Example Requests:\n" + "\n" +"fixeddepositproducts\n" + "\n" + "\n" + "fixeddepositproducts?fields=name") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositProductsApiResourceSwagger.GetFixedDepositProductsResponse.class, responseContainer = "List")}) + @ApiOperation(value = "List Fixed Deposit Products", httpMethod = "GET", notes = "Lists Fixed Deposit Products\n\n" + + "Example Requests:\n" + "\n" + "fixeddepositproducts\n" + "\n" + "\n" + "fixeddepositproducts?fields=name") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositProductsApiResourceSwagger.GetFixedDepositProductsResponse.class, responseContainer = "List") }) public String retrieveAll(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.FIXED_DEPOSIT_PRODUCT_RESOURCE_NAME); @@ -198,14 +210,17 @@ public class FixedDepositProductsApiResource { @Path("{productId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Fixed Deposit Product", httpMethod = "GET", notes = "Retrieves a Fixed Deposit Product\n\n" + "Example Requests:\n" + "\n" + "fixeddepositproducts/1\n" + "\n" + "\n" + "fixeddepositproducts/1?template=true\n" + "\n" + "\n" + "fixeddepositproducts/1?fields=name,description") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositProductsApiResourceSwagger.GetFixedDepositProductsProductIdResponse.class)}) + @ApiOperation(value = "Retrieve a Fixed Deposit Product", httpMethod = "GET", notes = "Retrieves a Fixed Deposit Product\n\n" + + "Example Requests:\n" + "\n" + "fixeddepositproducts/1\n" + "\n" + "\n" + "fixeddepositproducts/1?template=true\n" + "\n" + + "\n" + "fixeddepositproducts/1?fields=name,description") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositProductsApiResourceSwagger.GetFixedDepositProductsProductIdResponse.class) }) public String retrieveOne(@PathParam("productId") @ApiParam(value = "productId") final Long productId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.FIXED_DEPOSIT_PRODUCT_RESOURCE_NAME); - FixedDepositProductData fixedDepositProductData = (FixedDepositProductData) this.depositProductReadPlatformService.retrieveOne( - DepositAccountType.FIXED_DEPOSIT, productId); + FixedDepositProductData fixedDepositProductData = (FixedDepositProductData) this.depositProductReadPlatformService + .retrieveOne(DepositAccountType.FIXED_DEPOSIT, productId); final Collection charges = this.chargeReadPlatformService.retrieveSavingsProductCharges(productId); fixedDepositProductData = FixedDepositProductData.withCharges(fixedDepositProductData, charges); @@ -341,7 +356,8 @@ public class FixedDepositProductsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Fixed Deposit Product", httpMethod = "DELETE", notes = "Deletes a Fixed Deposit Product") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FixedDepositProductsApiResourceSwagger.DeleteFixedDepositProductsProductIdResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = FixedDepositProductsApiResourceSwagger.DeleteFixedDepositProductsProductIdResponse.class) }) public String delete(@PathParam("productId") @ApiParam(value = "productId") final Long productId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteFixedDepositProduct(productId).build(); @@ -351,4 +367,4 @@ public class FixedDepositProductsApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositProductsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositProductsApiResourceSwagger.java index 0ee7329cd..ffaf5af9f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositProductsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/FixedDepositProductsApiResourceSwagger.java @@ -27,21 +27,21 @@ import java.util.Set; * Created by Chirag Gupta on 12/23/17. */ final class FixedDepositProductsApiResourceSwagger { - private FixedDepositProductsApiResourceSwagger() { - } + + private FixedDepositProductsApiResourceSwagger() {} @ApiModel(value = "PostFixedDepositProductsRequest") public final static class PostFixedDepositProductsRequest { - private PostFixedDepositProductsRequest() { - } + + private PostFixedDepositProductsRequest() {} final class PostFixedDepositProductsCharts { - private PostFixedDepositProductsCharts() { - } + + private PostFixedDepositProductsCharts() {} final class PostFixedDepositProductsChartSlabs { - private PostFixedDepositProductsChartSlabs() { - } + + private PostFixedDepositProductsChartSlabs() {} @ApiModelProperty(example = "from 0 to 90 days") public String description; @@ -107,8 +107,8 @@ final class FixedDepositProductsApiResourceSwagger { @ApiModel(value = "PostFixedDepositProductsResponse") public final static class PostFixedDepositProductsResponse { - private PostFixedDepositProductsResponse() { - } + + private PostFixedDepositProductsResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -116,8 +116,8 @@ final class FixedDepositProductsApiResourceSwagger { @ApiModel(value = "PutFixedDepositProductsProductIdRequest") public final static class PutFixedDepositProductsProductIdRequest { - private PutFixedDepositProductsProductIdRequest() { - } + + private PutFixedDepositProductsProductIdRequest() {} @ApiModelProperty(example = "Fixed deposit product new offerings") public String description; @@ -131,12 +131,12 @@ final class FixedDepositProductsApiResourceSwagger { @ApiModel(value = "PutFixedDepositProductsProductIdResponse") public final static class PutFixedDepositProductsProductIdResponse { - private PutFixedDepositProductsProductIdResponse() { - } + + private PutFixedDepositProductsProductIdResponse() {} final class PutFixedDepositProductsChanges { - private PutFixedDepositProductsChanges() { - } + + private PutFixedDepositProductsChanges() {} @ApiModelProperty(example = "Fixed deposit product new offerings") public String description; @@ -151,12 +151,12 @@ final class FixedDepositProductsApiResourceSwagger { @ApiModel(value = "GetFixedDepositProductsResponse") public final static class GetFixedDepositProductsResponse { - private GetFixedDepositProductsResponse() { - } + + private GetFixedDepositProductsResponse() {} final class GetFixedDepositProductsCurrency { - private GetFixedDepositProductsCurrency() { - } + + private GetFixedDepositProductsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -175,8 +175,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsMinDepositTermType { - private GetFixedDepositProductsMinDepositTermType() { - } + + private GetFixedDepositProductsMinDepositTermType() {} @ApiModelProperty(example = "2") public Integer id; @@ -187,8 +187,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsMaxDepositTermType { - private GetFixedDepositProductsMaxDepositTermType() { - } + + private GetFixedDepositProductsMaxDepositTermType() {} @ApiModelProperty(example = "3") public Integer id; @@ -199,8 +199,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsInterestCompoundingPeriodType { - private GetFixedDepositProductsInterestCompoundingPeriodType() { - } + + private GetFixedDepositProductsInterestCompoundingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -211,8 +211,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsInterestPostingPeriodType { - private GetFixedDepositProductsInterestPostingPeriodType() { - } + + private GetFixedDepositProductsInterestPostingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -223,8 +223,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsInterestCalculationType { - private GetFixedDepositProductsInterestCalculationType() { - } + + private GetFixedDepositProductsInterestCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -235,8 +235,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsInterestCalculationDaysInYearType { - private GetFixedDepositProductsInterestCalculationDaysInYearType() { - } + + private GetFixedDepositProductsInterestCalculationDaysInYearType() {} @ApiModelProperty(example = "365") public Integer id; @@ -247,8 +247,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsAccountingRule { - private GetFixedDepositProductsAccountingRule() { - } + + private GetFixedDepositProductsAccountingRule() {} @ApiModelProperty(example = "1") public Integer id; @@ -286,12 +286,12 @@ final class FixedDepositProductsApiResourceSwagger { @ApiModel(value = "GetFixedDepositProductsProductIdResponse") public final static class GetFixedDepositProductsProductIdResponse { - private GetFixedDepositProductsProductIdResponse() { - } + + private GetFixedDepositProductsProductIdResponse() {} final class GetFixedDepositProductsProductIdCurrency { - private GetFixedDepositProductsProductIdCurrency() { - } + + private GetFixedDepositProductsProductIdCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -308,8 +308,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdInterestCompoundingPeriodType { - private GetFixedDepositProductsProductIdInterestCompoundingPeriodType() { - } + + private GetFixedDepositProductsProductIdInterestCompoundingPeriodType() {} @ApiModelProperty(example = "1") public Integer id; @@ -320,12 +320,12 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdAccountingMappings { - private GetFixedDepositProductsProductIdAccountingMappings() { - } + + private GetFixedDepositProductsProductIdAccountingMappings() {} final class GetFixedDepositProductsProductIdSavingsReferenceAccount { - private GetFixedDepositProductsProductIdSavingsReferenceAccount() { - } + + private GetFixedDepositProductsProductIdSavingsReferenceAccount() {} @ApiModelProperty(example = "12") public Integer id; @@ -336,8 +336,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdIncomeFromFeeAccount { - private GetFixedDepositProductsProductIdIncomeFromFeeAccount() { - } + + private GetFixedDepositProductsProductIdIncomeFromFeeAccount() {} @ApiModelProperty(example = "16") public Integer id; @@ -348,8 +348,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdIncomeFromPenaltyAccount { - private GetFixedDepositProductsProductIdIncomeFromPenaltyAccount() { - } + + private GetFixedDepositProductsProductIdIncomeFromPenaltyAccount() {} @ApiModelProperty(example = "17") public Integer id; @@ -360,8 +360,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdInterestOnSavingsAccount { - private GetFixedDepositProductsProductIdInterestOnSavingsAccount() { - } + + private GetFixedDepositProductsProductIdInterestOnSavingsAccount() {} @ApiModelProperty(example = "15") public Integer id; @@ -372,8 +372,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdSavingsControlAccount { - private GetFixedDepositProductsProductIdSavingsControlAccount() { - } + + private GetFixedDepositProductsProductIdSavingsControlAccount() {} @ApiModelProperty(example = "13") public Integer id; @@ -384,8 +384,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdTransfersInSuspenseAccount { - private GetFixedDepositProductsProductIdTransfersInSuspenseAccount() { - } + + private GetFixedDepositProductsProductIdTransfersInSuspenseAccount() {} @ApiModelProperty(example = "14") public Integer id; @@ -404,12 +404,12 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdFeeToIncomeAccountMappings { - private GetFixedDepositProductsProductIdFeeToIncomeAccountMappings() { - } + + private GetFixedDepositProductsProductIdFeeToIncomeAccountMappings() {} final class GetFixedDepositProductsProductIdFeeToIncomeAccountMappingsCharge { - private GetFixedDepositProductsProductIdFeeToIncomeAccountMappingsCharge() { - } + + private GetFixedDepositProductsProductIdFeeToIncomeAccountMappingsCharge() {} @ApiModelProperty(example = "11") public Integer id; @@ -422,8 +422,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdFeeToIncomeAccountMappingsIncomeAccount { - private GetFixedDepositProductsProductIdFeeToIncomeAccountMappingsIncomeAccount() { - } + + private GetFixedDepositProductsProductIdFeeToIncomeAccountMappingsIncomeAccount() {} @ApiModelProperty(example = "16") public Integer id; @@ -438,12 +438,12 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdPenaltyToIncomeAccountMappings { - private GetFixedDepositProductsProductIdPenaltyToIncomeAccountMappings() { - } + + private GetFixedDepositProductsProductIdPenaltyToIncomeAccountMappings() {} final class GetFixedDepositProductsProductIdPenaltyToIncomeAccountMappingsCharge { - private GetFixedDepositProductsProductIdPenaltyToIncomeAccountMappingsCharge() { - } + + private GetFixedDepositProductsProductIdPenaltyToIncomeAccountMappingsCharge() {} @ApiModelProperty(example = "12") public Integer id; @@ -460,8 +460,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdPreClosurePenalInterestOnType { - private GetFixedDepositProductsProductIdPreClosurePenalInterestOnType() { - } + + private GetFixedDepositProductsProductIdPreClosurePenalInterestOnType() {} @ApiModelProperty(example = "1") public Integer id; @@ -472,8 +472,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdMinDepositTermType { - private GetFixedDepositProductsProductIdMinDepositTermType() { - } + + private GetFixedDepositProductsProductIdMinDepositTermType() {} @ApiModelProperty(example = "1") public Integer id; @@ -484,8 +484,8 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdMaxDepositTermType { - private GetFixedDepositProductsProductIdMaxDepositTermType() { - } + + private GetFixedDepositProductsProductIdMaxDepositTermType() {} @ApiModelProperty(example = "3") public Integer id; @@ -496,16 +496,16 @@ final class FixedDepositProductsApiResourceSwagger { } final class GetFixedDepositProductsProductIdActiveChart { - private GetFixedDepositProductsProductIdActiveChart() { - } + + private GetFixedDepositProductsProductIdActiveChart() {} final class GetFixedDepositProductsProductIdChartSlabs { - private GetFixedDepositProductsProductIdChartSlabs() { - } + + private GetFixedDepositProductsProductIdChartSlabs() {} final class GetFixedDepositProductsProductIdPeriodType { - private GetFixedDepositProductsProductIdPeriodType() { - } + + private GetFixedDepositProductsProductIdPeriodType() {} @ApiModelProperty(example = "1") public Integer id; @@ -573,8 +573,8 @@ final class FixedDepositProductsApiResourceSwagger { @ApiModel(value = "DeleteFixedDepositProductsProductIdResponse") public final static class DeleteFixedDepositProductsProductIdResponse { - private DeleteFixedDepositProductsProductIdResponse() { - } + + private DeleteFixedDepositProductsProductIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountTransactionsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountTransactionsApiResource.java index 5cb8e540c..115c267a5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountTransactionsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountTransactionsApiResource.java @@ -65,10 +65,9 @@ import org.springframework.stereotype.Component; @Path("/recurringdepositaccounts/{recurringDepositAccountId}/transactions") @Component @Scope("singleton") -@Api(tags = {"Recurring Deposit Account Transactions"}) +@Api(tags = { "Recurring Deposit Account Transactions" }) @SwaggerDefinition(tags = { - @Tag(name = "Recurring Deposit Account Transactions", description = "Transactions possible on a recurring deposit account.") -}) + @Tag(name = "Recurring Deposit Account Transactions", description = "Transactions possible on a recurring deposit account.") }) public class RecurringDepositAccountTransactionsApiResource { private final PlatformSecurityContext context; @@ -80,10 +79,9 @@ public class RecurringDepositAccountTransactionsApiResource { private final PaymentTypeReadPlatformService paymentTypeReadPlatformService; private static final Set FIXED_DEPOSIT_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( Arrays.asList(DepositsApiConstants.idParamName, DepositsApiConstants.accountIdParamName, - DepositsApiConstants.accountNoParamName, DepositsApiConstants.currencyParamName, - DepositsApiConstants.amountParamName, DepositsApiConstants.dateParamName, - DepositsApiConstants.paymentDetailDataParamName, DepositsApiConstants.runningBalanceParamName, - DepositsApiConstants.reversedParamName)); + DepositsApiConstants.accountNoParamName, DepositsApiConstants.currencyParamName, DepositsApiConstants.amountParamName, + DepositsApiConstants.dateParamName, DepositsApiConstants.paymentDetailDataParamName, + DepositsApiConstants.runningBalanceParamName, DepositsApiConstants.reversedParamName)); @Autowired public RecurringDepositAccountTransactionsApiResource(final PlatformSecurityContext context, @@ -110,9 +108,14 @@ public class RecurringDepositAccountTransactionsApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Recurring Deposit Account Transaction Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Requests:\n" + "\n" + "recurringdepositaccounts/1/transactions/template?command=deposit\n" + "\n" + "recurringdepositaccounts/1/transactions/template?command=withdrawal") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountTransactionsApiResourceSwagger.GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTemplateResponse.class)}) - public String retrieveTemplate(@PathParam("recurringDepositAccountId") @ApiParam(value = "recurringDepositAccountId") final Long recurringDepositAccountId, + @ApiOperation(value = "Retrieve Recurring Deposit Account Transaction Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Requests:\n" + "\n" + + "recurringdepositaccounts/1/transactions/template?command=deposit\n" + "\n" + + "recurringdepositaccounts/1/transactions/template?command=withdrawal") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountTransactionsApiResourceSwagger.GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTemplateResponse.class) }) + public String retrieveTemplate( + @PathParam("recurringDepositAccountId") @ApiParam(value = "recurringDepositAccountId") final Long recurringDepositAccountId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESOURCE_NAME); @@ -120,8 +123,9 @@ public class RecurringDepositAccountTransactionsApiResource { /*** * Check @Param commandParam value for deposit or withdrawal */ - if (!(is(commandParam, "deposit") || is(commandParam, "withdrawal"))) { throw new UnrecognizedQueryParamException("command", - commandParam, new Object[] { "deposit", "withdrawal" }); } + if (!(is(commandParam, "deposit") || is(commandParam, "withdrawal"))) { + throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { "deposit", "withdrawal" }); + } /*** * By default get the deposit template for deposits and withdrawal @@ -150,32 +154,40 @@ public class RecurringDepositAccountTransactionsApiResource { @Path("{transactionId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Recurring Deposit Account Transaction", httpMethod = "GET", notes = "Retrieves Recurring Deposit Account Transaction\n\n" + "Example Requests:\n" + "\n" + "recurringdepositaccounts/1/transactions/1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountTransactionsApiResourceSwagger.GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse.class)}) - public String retrieveOne(@PathParam("recurringDepositAccountId") @ApiParam(value = "recurringDepositAccountId") final Long recurringDepositAccountId, + @ApiOperation(value = "Retrieve Recurring Deposit Account Transaction", httpMethod = "GET", notes = "Retrieves Recurring Deposit Account Transaction\n\n" + + "Example Requests:\n" + "\n" + "recurringdepositaccounts/1/transactions/1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountTransactionsApiResourceSwagger.GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse.class) }) + public String retrieveOne( + @PathParam("recurringDepositAccountId") @ApiParam(value = "recurringDepositAccountId") final Long recurringDepositAccountId, @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESOURCE_NAME); - SavingsAccountTransactionData transactionData = this.savingsAccountReadPlatformService.retrieveSavingsTransaction( - recurringDepositAccountId, transactionId, DepositAccountType.RECURRING_DEPOSIT); + SavingsAccountTransactionData transactionData = this.savingsAccountReadPlatformService + .retrieveSavingsTransaction(recurringDepositAccountId, transactionId, DepositAccountType.RECURRING_DEPOSIT); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (settings.isTemplate()) { final Collection paymentTypeOptions = this.paymentTypeReadPlatformService.retrieveAllPaymentTypes(); transactionData = SavingsAccountTransactionData.templateOnTop(transactionData, paymentTypeOptions); } - return this.toApiJsonSerializer.serialize(settings, transactionData, - FIXED_DEPOSIT_TRANSACTION_RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, transactionData, FIXED_DEPOSIT_TRANSACTION_RESPONSE_DATA_PARAMETERS); } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Deposit Transaction | Withdrawal Transaction", httpMethod = "POST", notes = "Deposit Transaction:\n\n" + "Used for a deposit transaction\n\n" + "Withdrawal Transaction:\n\n" + "Used for a Withdrawal Transaction\n\n" + "Showing request/response for Deposit Transaction") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositAccountTransactionsApiResourceSwagger.PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountTransactionsApiResourceSwagger.PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsResponse.class)}) - public String transaction(@PathParam("recurringDepositAccountId") @ApiParam(value = "recurringDepositAccountId") final Long recurringDepositAccountId, - @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Deposit Transaction | Withdrawal Transaction", httpMethod = "POST", notes = "Deposit Transaction:\n\n" + + "Used for a deposit transaction\n\n" + "Withdrawal Transaction:\n\n" + "Used for a Withdrawal Transaction\n\n" + + "Showing request/response for Deposit Transaction") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositAccountTransactionsApiResourceSwagger.PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountTransactionsApiResourceSwagger.PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsResponse.class) }) + public String transaction( + @PathParam("recurringDepositAccountId") @ApiParam(value = "recurringDepositAccountId") final Long recurringDepositAccountId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); @@ -201,11 +213,17 @@ public class RecurringDepositAccountTransactionsApiResource { @Path("{transactionId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Adjust Transaction | Undo transaction", httpMethod = "POST", notes = "Adjust Transaction:\n\n" + "This command modifies the given transaction.\n\n" + "Undo transaction:\n\n" + "This command reverses the given transaction.\n\n" + "Showing request/response for 'Adjust Transaction'") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositAccountTransactionsApiResourceSwagger.PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountTransactionsApiResourceSwagger.PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse.class)}) - public String handleTransactionCommands(@PathParam("recurringDepositAccountId") @ApiParam(value = "recurringDepositAccountId") final Long recurringDepositAccountId, - @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiOperation(value = "Adjust Transaction | Undo transaction", httpMethod = "POST", notes = "Adjust Transaction:\n\n" + + "This command modifies the given transaction.\n\n" + "Undo transaction:\n\n" + + "This command reverses the given transaction.\n\n" + "Showing request/response for 'Adjust Transaction'") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositAccountTransactionsApiResourceSwagger.PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountTransactionsApiResourceSwagger.PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse.class) }) + public String handleTransactionCommands( + @PathParam("recurringDepositAccountId") @ApiParam(value = "recurringDepositAccountId") final Long recurringDepositAccountId, + @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { String jsonApiRequest = apiRequestBodyAsJson; @@ -232,4 +250,4 @@ public class RecurringDepositAccountTransactionsApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountTransactionsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountTransactionsApiResourceSwagger.java index 79b93247d..cbac0937a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountTransactionsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountTransactionsApiResourceSwagger.java @@ -28,17 +28,17 @@ import java.util.List; * Created by Chirag Gupta on 12/31/17. */ final class RecurringDepositAccountTransactionsApiResourceSwagger { - private RecurringDepositAccountTransactionsApiResourceSwagger() { - } + + private RecurringDepositAccountTransactionsApiResourceSwagger() {} @ApiModel(value = "GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTemplateResponse") public final static class GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTemplateResponse { - private GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTemplateResponse() { - } + + private GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTemplateResponse() {} final class GetRecurringTransactionType { - private GetRecurringTransactionType() { - } + + private GetRecurringTransactionType() {} @ApiModelProperty(example = "1") public Integer id; @@ -71,8 +71,8 @@ final class RecurringDepositAccountTransactionsApiResourceSwagger { } final class GetRecurringCurrency { - private GetRecurringCurrency() { - } + + private GetRecurringCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -110,12 +110,12 @@ final class RecurringDepositAccountTransactionsApiResourceSwagger { @ApiModel(value = "GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse") public final static class GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse { - private GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse() { - } + + private GetRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse() {} final class GetRecurringTransactionsCurrency { - private GetRecurringTransactionsCurrency() { - } + + private GetRecurringTransactionsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -134,8 +134,8 @@ final class RecurringDepositAccountTransactionsApiResourceSwagger { } final class GetRecurringTransactionsTransactionType { - private GetRecurringTransactionsTransactionType() { - } + + private GetRecurringTransactionsTransactionType() {} @ApiModelProperty(example = "2") public Integer id; @@ -154,12 +154,12 @@ final class RecurringDepositAccountTransactionsApiResourceSwagger { } final class GetRecurringPaymentDetailData { - private GetRecurringPaymentDetailData() { - } + + private GetRecurringPaymentDetailData() {} final class GetRecurringPaymentType { - private GetRecurringPaymentType() { - } + + private GetRecurringPaymentType() {} @ApiModelProperty(example = "11") public Integer id; @@ -203,8 +203,8 @@ final class RecurringDepositAccountTransactionsApiResourceSwagger { @ApiModel(value = "PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsRequest") public final static class PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsRequest { - private PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsRequest() { - } + + private PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsRequest() {} @ApiModelProperty(example = "en") public String locale; @@ -230,12 +230,12 @@ final class RecurringDepositAccountTransactionsApiResourceSwagger { @ApiModel(value = "PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsResponse") public final static class PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsResponse { - private PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsResponse() { - } + + private PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsResponse() {} final class PostRecurringChanges { - private PostRecurringChanges() { - } + + private PostRecurringChanges() {} @ApiModelProperty(example = "acc123") public String accountNumber; @@ -262,8 +262,8 @@ final class RecurringDepositAccountTransactionsApiResourceSwagger { @ApiModel(value = "PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse") public final static class PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse { - private PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse() { - } + + private PostRecurringDepositAccountsRecurringDepositAccountIdTransactionsTransactionIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountsApiResource.java index 88d448748..6d0f06c06 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountsApiResource.java @@ -82,14 +82,12 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; - @Path("/recurringdepositaccounts") @Component @Scope("singleton") -@Api(tags = {"Recurring Deposit Account"}) +@Api(tags = { "Recurring Deposit Account" }) @SwaggerDefinition(tags = { - @Tag(name = "Recurring Deposit Account", description = "Recurring Deposit accounts are instances of a praticular recurring deposit product created. An application process around the creation of accounts is also supported.") -}) + @Tag(name = "Recurring Deposit Account", description = "Recurring Deposit accounts are instances of a praticular recurring deposit product created. An application process around the creation of accounts is also supported.") }) public class RecurringDepositAccountsApiResource { private final DepositAccountReadPlatformService depositAccountReadPlatformService; @@ -103,7 +101,6 @@ public class RecurringDepositAccountsApiResource { private final BulkImportWorkbookService bulkImportWorkbookService; private final BulkImportWorkbookPopulatorService bulkImportWorkbookPopulatorService; - @Autowired public RecurringDepositAccountsApiResource(final DepositAccountReadPlatformService depositAccountReadPlatformService, final PlatformSecurityContext context, final DefaultToApiJsonSerializer toApiJsonSerializer, @@ -121,20 +118,24 @@ public class RecurringDepositAccountsApiResource { this.savingsAccountChargeReadPlatformService = savingsAccountChargeReadPlatformService; this.fromJsonHelper = fromJsonHelper; this.accountPreMatureCalculationPlatformService = accountPreMatureCalculationPlatformService; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve recurring Deposit Account Template", httpMethod = "GET", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for recurring deposit applications. The template data returned consists of any or all of:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Requests:\n" + "\n" + "recurringdepositaccounts/template?clientId=1\n" + "\n" + "\n" + "recurringdepositaccounts/template?clientId=1&productId=1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.GetRecurringDepositAccountsTemplateResponse.class)}) - public String template(@QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, @QueryParam("groupId") @ApiParam(value = "groupId") final Long groupId, - @QueryParam("productId") @ApiParam(value = "productId") final Long productId, - @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve recurring Deposit Account Template", httpMethod = "GET", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for recurring deposit applications. The template data returned consists of any or all of:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Requests:\n" + "\n" + + "recurringdepositaccounts/template?clientId=1\n" + "\n" + "\n" + "recurringdepositaccounts/template?clientId=1&productId=1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.GetRecurringDepositAccountsTemplateResponse.class) }) + public String template(@QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @QueryParam("groupId") @ApiParam(value = "groupId") final Long groupId, + @QueryParam("productId") @ApiParam(value = "productId") final Long productId, + @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESOURCE_NAME); @@ -149,25 +150,29 @@ public class RecurringDepositAccountsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Recurring deposit applications/accounts", httpMethod = "GET", notes = "Lists Recurring deposit applications/accounts\n\n" + "Example Requests:\n" + "\n" + "recurringdepositaccounts\n" + "\n" + "\n" + "recurringdepositaccounts?fields=name") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.GetRecurringDepositAccountsResponse.class, responseContainer = "List")}) + @ApiOperation(value = "List Recurring deposit applications/accounts", httpMethod = "GET", notes = "Lists Recurring deposit applications/accounts\n\n" + + "Example Requests:\n" + "\n" + "recurringdepositaccounts\n" + "\n" + "\n" + "recurringdepositaccounts?fields=name") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.GetRecurringDepositAccountsResponse.class, responseContainer = "List") }) public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("paged") @ApiParam(value = "paged") final Boolean paged, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESOURCE_NAME); final PaginationParameters paginationParameters = PaginationParameters.instance(paged, offset, limit, orderBy, sortOrder); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (paginationParameters.isPaged()) { - final Page account = this.depositAccountReadPlatformService.retrieveAllPaged( - DepositAccountType.RECURRING_DEPOSIT, paginationParameters); + final Page account = this.depositAccountReadPlatformService + .retrieveAllPaged(DepositAccountType.RECURRING_DEPOSIT, paginationParameters); return this.toApiJsonSerializer.serialize(settings, account, DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESPONSE_DATA_PARAMETERS); } - final Collection account = this.depositAccountReadPlatformService.retrieveAll( - DepositAccountType.RECURRING_DEPOSIT, paginationParameters); + final Collection account = this.depositAccountReadPlatformService + .retrieveAll(DepositAccountType.RECURRING_DEPOSIT, paginationParameters); return this.toApiJsonSerializer.serialize(settings, account, DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESPONSE_DATA_PARAMETERS); @@ -176,9 +181,14 @@ public class RecurringDepositAccountsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Submit new recurring deposit application", httpMethod = "POST", notes = "Submits new recurring deposit application\n\n" + "Mandatory Fields: clientId or groupId, productId, submittedOnDate, depositAmount, depositPeriod, depositPeriodFrequencyId\n\n" + "Optional Fields: accountNo, externalId, fieldOfficerId,linkAccountId(if provided initial deposit amount will be collected from this account),transferInterestToSavings(By enabling this flag all interest postings will be transferred to linked saving account )\n\n" + "Inherited from Product (if not provided): interestCompoundingPeriodType, interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency, lockinPeriodFrequencyType, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnTypeId, charts, withHoldTax") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositAccountsApiResourceSwagger.PostRecurringDepositAccountsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.PostRecurringDepositAccountsResponse.class)}) + @ApiOperation(value = "Submit new recurring deposit application", httpMethod = "POST", notes = "Submits new recurring deposit application\n\n" + + "Mandatory Fields: clientId or groupId, productId, submittedOnDate, depositAmount, depositPeriod, depositPeriodFrequencyId\n\n" + + "Optional Fields: accountNo, externalId, fieldOfficerId,linkAccountId(if provided initial deposit amount will be collected from this account),transferInterestToSavings(By enabling this flag all interest postings will be transferred to linked saving account )\n\n" + + "Inherited from Product (if not provided): interestCompoundingPeriodType, interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency, lockinPeriodFrequencyType, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnTypeId, charts, withHoldTax") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositAccountsApiResourceSwagger.PostRecurringDepositAccountsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.PostRecurringDepositAccountsResponse.class) }) public String submitApplication(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createRecurringDepositAccount().withJson(apiRequestBodyAsJson) @@ -193,16 +203,20 @@ public class RecurringDepositAccountsApiResource { @Path("{accountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a recurring deposit application/account", httpMethod = "GET", notes = "Retrieves a recurring deposit application/account\n\n" + "Example Requests :\n" + "\n" + "recurringdepositaccounts/1\n" + "\n" + "\n" + "recurringdepositaccounts/1?associations=all") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.GetRecurringDepositAccountsAccountIdResponse.class)}) + @ApiOperation(value = "Retrieve a recurring deposit application/account", httpMethod = "GET", notes = "Retrieves a recurring deposit application/account\n\n" + + "Example Requests :\n" + "\n" + "recurringdepositaccounts/1\n" + "\n" + "\n" + "recurringdepositaccounts/1?associations=all") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.GetRecurringDepositAccountsAccountIdResponse.class) }) public String retrieveOne(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, - @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, @Context final UriInfo uriInfo) { + @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESOURCE_NAME); - if (!(is(chargeStatus, "all") || is(chargeStatus, "active") || is(chargeStatus, "inactive"))) { throw new UnrecognizedQueryParamException( - "status", chargeStatus, new Object[] { "all", "active", "inactive" }); } + if (!(is(chargeStatus, "all") || is(chargeStatus, "active") || is(chargeStatus, "inactive"))) { + throw new UnrecognizedQueryParamException("status", chargeStatus, new Object[] { "all", "active", "inactive" }); + } final RecurringDepositAccountData account = (RecurringDepositAccountData) this.depositAccountReadPlatformService .retrieveOneWithChartSlabs(DepositAccountType.RECURRING_DEPOSIT, accountId); @@ -267,9 +281,12 @@ public class RecurringDepositAccountsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Modify a recurring deposit application", httpMethod = "PUT", notes = "Recurring deposit application can only be modified when in 'Submitted and pending approval' state. Once the application is approved, the details cannot be changed using this method. Specific api endpoints will be created to allow change of interest detail such as rate, compounding period, posting period etc") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositAccountsApiResourceSwagger.PutRecurringDepositAccountsAccountIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.PutRecurringDepositAccountsAccountIdResponse.class)}) - public String update(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositAccountsApiResourceSwagger.PutRecurringDepositAccountsAccountIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.PutRecurringDepositAccountsAccountIdResponse.class) }) + public String update(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateRecurringDepositAccount(accountId) .withJson(apiRequestBodyAsJson).build(); @@ -283,11 +300,37 @@ public class RecurringDepositAccountsApiResource { @Path("{accountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Approve recurring deposit application | Undo approval recurring deposit application | Reject recurring deposit application | Withdraw recurring deposit application | Activate a recurring deposit account | Update the recommended deposit amount for a recurring deposit account | Close a recurring deposit account | Premature Close a recurring deposit account | Calculate Premature amount on Recurring deposit account | Calculate Interest on recurring Deposit Account | Post Interest on recurring Deposit Account", httpMethod = "POST", notes = "Approve recurring deposit application:\n\n" + "Approves recurring deposit application so long as its in 'Submitted and pending approval' state.\n\n" + "Undo approval recurring deposit application:\n\n" + "Will move 'approved' recurring deposit application back to 'Submitted and pending approval' state.\n\n" + "Reject recurring deposit application\n\n" + "Rejects recurring deposit application so long as its in 'Submitted and pending approval' state.\n\n" + "Withdraw recurring deposit application:\n\n" + "Used when an applicant withdraws from the recurring deposit application. It must be in 'Submitted and pending approval' state.\n\n" + "Activate a recurring deposit account:\n\n" + "Results in an approved recurring deposit application being converted into an 'active' recurring deposit account.\n\n" + "Update the recommended deposit amount for a recurring deposit account:\n\n" + "Updates the recommended deposit amount for a RD account as on the effective date.\n\n" + "Close a recurring deposit account\n\n" + "Results in a Matured recurring deposit account being converted into a 'closed' recurring deposit account.\n" + "\n" + "On account close allowed actions are." + "Premature Close a recurring deposit account:\n\n" + "Results in an Active recurring deposit account being converted into a 'Premature Closed' recurring deposit account with options to withdraw prematured amount. (premature amount is calculated using interest rate chart applicable along with penal interest if any.)\n" + "\n" + "On account premature closure allowed actions are.\n\n" + "Calculate Premature amount on Recurring deposit account:\n\n" + "Calculate premature amount on recurring deposit till premature close date. Premature amount is calculated based on interest chart and penal interest applicable if any.\n\n" + "Calculate Interest on recurring Deposit Account:\n\n" + "Calculates interest earned on a recurring deposit account based on todays date. It does not attempt to post or credit the interest on the account. That is responsibility of the Post Interest API that will likely be called by overnight process.\n\n" + "Post Interest on recurring Deposit Account:\n\n" + "Calculates and Posts interest earned on a recurring deposit account based on todays date and whether an interest posting or crediting event is due.\n\n" + "Showing request/response for 'Post Interest on recurring Deposit Account'") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositAccountsApiResourceSwagger.PostRecurringDepositAccountsAccountIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.PostRecurringDepositAccountsAccountIdResponse.class)}) - public String handleCommands(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, - @Context final UriInfo uriInfo, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Approve recurring deposit application | Undo approval recurring deposit application | Reject recurring deposit application | Withdraw recurring deposit application | Activate a recurring deposit account | Update the recommended deposit amount for a recurring deposit account | Close a recurring deposit account | Premature Close a recurring deposit account | Calculate Premature amount on Recurring deposit account | Calculate Interest on recurring Deposit Account | Post Interest on recurring Deposit Account", httpMethod = "POST", notes = "Approve recurring deposit application:\n\n" + + "Approves recurring deposit application so long as its in 'Submitted and pending approval' state.\n\n" + + "Undo approval recurring deposit application:\n\n" + + "Will move 'approved' recurring deposit application back to 'Submitted and pending approval' state.\n\n" + + "Reject recurring deposit application\n\n" + + "Rejects recurring deposit application so long as its in 'Submitted and pending approval' state.\n\n" + + "Withdraw recurring deposit application:\n\n" + + "Used when an applicant withdraws from the recurring deposit application. It must be in 'Submitted and pending approval' state.\n\n" + + "Activate a recurring deposit account:\n\n" + + "Results in an approved recurring deposit application being converted into an 'active' recurring deposit account.\n\n" + + "Update the recommended deposit amount for a recurring deposit account:\n\n" + + "Updates the recommended deposit amount for a RD account as on the effective date.\n\n" + + "Close a recurring deposit account\n\n" + + "Results in a Matured recurring deposit account being converted into a 'closed' recurring deposit account.\n" + "\n" + + "On account close allowed actions are." + "Premature Close a recurring deposit account:\n\n" + + "Results in an Active recurring deposit account being converted into a 'Premature Closed' recurring deposit account with options to withdraw prematured amount. (premature amount is calculated using interest rate chart applicable along with penal interest if any.)\n" + + "\n" + "On account premature closure allowed actions are.\n\n" + + "Calculate Premature amount on Recurring deposit account:\n\n" + + "Calculate premature amount on recurring deposit till premature close date. Premature amount is calculated based on interest chart and penal interest applicable if any.\n\n" + + "Calculate Interest on recurring Deposit Account:\n\n" + + "Calculates interest earned on a recurring deposit account based on todays date. It does not attempt to post or credit the interest on the account. That is responsibility of the Post Interest API that will likely be called by overnight process.\n\n" + + "Post Interest on recurring Deposit Account:\n\n" + + "Calculates and Posts interest earned on a recurring deposit account based on todays date and whether an interest posting or crediting event is due.\n\n" + + "Showing request/response for 'Post Interest on recurring Deposit Account'") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositAccountsApiResourceSwagger.PostRecurringDepositAccountsAccountIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.PostRecurringDepositAccountsAccountIdResponse.class) }) + public String handleCommands(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { String jsonApiRequest = apiRequestBodyAsJson; if (StringUtils.isBlank(jsonApiRequest)) { @@ -338,9 +381,11 @@ public class RecurringDepositAccountsApiResource { DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESPONSE_DATA_PARAMETERS); } - if (result == null) { throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { "reject", - "withdrawnByApplicant", "approve", "undoapproval", "activate", "calculateInterest", "postInterest", "close", - "prematureClose", "calculatePrematureAmount" }); } + if (result == null) { + throw new UnrecognizedQueryParamException("command", commandParam, + new Object[] { "reject", "withdrawnByApplicant", "approve", "undoapproval", "activate", "calculateInterest", + "postInterest", "close", "prematureClose", "calculatePrematureAmount" }); + } return this.toApiJsonSerializer.serialize(result); } @@ -354,7 +399,8 @@ public class RecurringDepositAccountsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a recurring deposit application", httpMethod = "DELETE", notes = "At present we support hard delete of recurring deposit application so long as its in 'Submitted and pending approval' state. One the application is moves past this state, it is not possible to do a 'hard' delete of the application or the account. An API endpoint will be added to close/de-activate the recurring deposit account.") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.DeleteRecurringDepositAccountsResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositAccountsApiResourceSwagger.DeleteRecurringDepositAccountsResponse.class) }) public String delete(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteRecurringDepositAccount(accountId).build(); @@ -368,14 +414,14 @@ public class RecurringDepositAccountsApiResource { @Path("{accountId}/template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String accountClosureTemplate(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, - @Context final UriInfo uriInfo) { + public String accountClosureTemplate(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESOURCE_NAME); DepositAccountData account = null; if (is(commandParam, "close")) { - account = this.depositAccountReadPlatformService - .retrieveOneWithClosureTemplate(DepositAccountType.RECURRING_DEPOSIT, accountId); + account = this.depositAccountReadPlatformService.retrieveOneWithClosureTemplate(DepositAccountType.RECURRING_DEPOSIT, + accountId); } @@ -383,32 +429,34 @@ public class RecurringDepositAccountsApiResource { return this.toApiJsonSerializer.serialize(settings, account, DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESPONSE_DATA_PARAMETERS); } + @GET @Path("downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getRecurringDepositTemplate(@QueryParam("officeId")final Long officeId, - @QueryParam("staffId")final Long staffId,@QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS.toString(),officeId,staffId,dateFormat); + public Response getRecurringDepositTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("staffId") final Long staffId, + @QueryParam("dateFormat") final String dateFormat) { + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS.toString(), officeId, staffId, + dateFormat); } @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postRecurringDepositTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, @FormDataParam("dateFormat") final String dateFormat){ + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS.toString(), - uploadedInputStream,fileDetail,locale,dateFormat); + uploadedInputStream, fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } @GET @Path("transactions/downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getRecurringDepositTransactionTemplate(@QueryParam("officeId")final Long officeId, + public Response getRecurringDepositTransactionTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS.toString(),officeId, - null,dateFormat); + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS.toString(), officeId, + null, dateFormat); } @POST @@ -416,9 +464,9 @@ public class RecurringDepositAccountsApiResource { @Consumes(MediaType.MULTIPART_FORM_DATA) public String postRecurringDepositTransactionsTemplate(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, - @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId = this. bulkImportWorkbookService.importWorkbook(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS.toString(), - uploadedInputStream,fileDetail,locale,dateFormat); + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook( + GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS.toString(), uploadedInputStream, fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountsApiResourceSwagger.java index 411ec5366..b9e2e6511 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositAccountsApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/26/17. */ final class RecurringDepositAccountsApiResourceSwagger { - private RecurringDepositAccountsApiResourceSwagger() { - } + + private RecurringDepositAccountsApiResourceSwagger() {} @ApiModel(value = "GetRecurringDepositAccountsTemplateResponse") public final static class GetRecurringDepositAccountsTemplateResponse { - private GetRecurringDepositAccountsTemplateResponse() { - } + + private GetRecurringDepositAccountsTemplateResponse() {} final class GetRecurringProductOptions { - private GetRecurringProductOptions() { - } + + private GetRecurringProductOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -54,12 +54,12 @@ final class RecurringDepositAccountsApiResourceSwagger { @ApiModel(value = "GetRecurringDepositAccountsResponse") public final static class GetRecurringDepositAccountsResponse { - private GetRecurringDepositAccountsResponse() { - } + + private GetRecurringDepositAccountsResponse() {} final class GetRecurringDepositAccountsStatus { - private GetRecurringDepositAccountsStatus() { - } + + private GetRecurringDepositAccountsStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -88,8 +88,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsTimeline { - private GetRecurringDepositAccountsTimeline() { - } + + private GetRecurringDepositAccountsTimeline() {} @ApiModelProperty(example = "[2014, 3, 1]") public LocalDate submittedOnDate; @@ -102,8 +102,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsCurrency { - private GetRecurringDepositAccountsCurrency() { - } + + private GetRecurringDepositAccountsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -122,8 +122,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsInterestCompoundingPeriodType { - private GetRecurringDepositAccountsInterestCompoundingPeriodType() { - } + + private GetRecurringDepositAccountsInterestCompoundingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -134,8 +134,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsInterestPostingPeriodType { - private GetRecurringDepositAccountsInterestPostingPeriodType() { - } + + private GetRecurringDepositAccountsInterestPostingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -146,8 +146,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsInterestCalculationType { - private GetRecurringDepositAccountsInterestCalculationType() { - } + + private GetRecurringDepositAccountsInterestCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -158,8 +158,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsInterestCalculationDaysInYearType { - private GetRecurringDepositAccountsInterestCalculationDaysInYearType() { - } + + private GetRecurringDepositAccountsInterestCalculationDaysInYearType() {} @ApiModelProperty(example = "365") public Integer id; @@ -170,8 +170,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsSummary { - private GetRecurringDepositAccountsSummary() { - } + + private GetRecurringDepositAccountsSummary() {} public GetRecurringDepositAccountsCurrency currency; @ApiModelProperty(example = "0") @@ -179,8 +179,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsMinDepositTermType { - private GetRecurringDepositAccountsMinDepositTermType() { - } + + private GetRecurringDepositAccountsMinDepositTermType() {} @ApiModelProperty(example = "2") public Integer id; @@ -191,8 +191,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsMaxDepositTermType { - private GetRecurringDepositAccountsMaxDepositTermType() { - } + + private GetRecurringDepositAccountsMaxDepositTermType() {} @ApiModelProperty(example = "3") public Integer id; @@ -203,8 +203,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsDepositPeriodFrequency { - private GetRecurringDepositAccountsDepositPeriodFrequency() { - } + + private GetRecurringDepositAccountsDepositPeriodFrequency() {} @ApiModelProperty(example = "2") public Integer id; @@ -215,8 +215,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsRecurringDepositFrequencyType { - private GetRecurringDepositAccountsRecurringDepositFrequencyType() { - } + + private GetRecurringDepositAccountsRecurringDepositFrequencyType() {} @ApiModelProperty(example = "2") public Integer id; @@ -274,8 +274,8 @@ final class RecurringDepositAccountsApiResourceSwagger { @ApiModel(value = "PostRecurringDepositAccountsRequest") public final static class PostRecurringDepositAccountsRequest { - private PostRecurringDepositAccountsRequest() { - } + + private PostRecurringDepositAccountsRequest() {} @ApiModelProperty(example = "1") public Integer clientId; @@ -305,8 +305,8 @@ final class RecurringDepositAccountsApiResourceSwagger { @ApiModel(value = "PostRecurringDepositAccountsResponse") public final static class PostRecurringDepositAccountsResponse { - private PostRecurringDepositAccountsResponse() { - } + + private PostRecurringDepositAccountsResponse() {} @ApiModelProperty(example = "2") public Integer officeId; @@ -320,20 +320,20 @@ final class RecurringDepositAccountsApiResourceSwagger { @ApiModel(value = "GetRecurringDepositAccountsAccountIdResponse") public final static class GetRecurringDepositAccountsAccountIdResponse { - private GetRecurringDepositAccountsAccountIdResponse() { - } + + private GetRecurringDepositAccountsAccountIdResponse() {} final class GetRecurringDepositAccountsAccountChart { - private GetRecurringDepositAccountsAccountChart() { - } + + private GetRecurringDepositAccountsAccountChart() {} final class GetRecurringDepositAccountsChartSlabs { - private GetRecurringDepositAccountsChartSlabs() { - } + + private GetRecurringDepositAccountsChartSlabs() {} final class GetRecurringDepositAccountsPeriodType { - private GetRecurringDepositAccountsPeriodType() { - } + + private GetRecurringDepositAccountsPeriodType() {} @ApiModelProperty(example = "0") public Integer id; @@ -344,8 +344,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsAccountChartCurrency { - private GetRecurringDepositAccountsAccountChartCurrency() { - } + + private GetRecurringDepositAccountsAccountChartCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -374,8 +374,8 @@ final class RecurringDepositAccountsApiResourceSwagger { } final class GetRecurringDepositAccountsPeriodTypes { - private GetRecurringDepositAccountsPeriodTypes() { - } + + private GetRecurringDepositAccountsPeriodTypes() {} @ApiModelProperty(example = "0") public Integer id; @@ -444,8 +444,8 @@ final class RecurringDepositAccountsApiResourceSwagger { @ApiModel(value = "PutRecurringDepositAccountsAccountIdRequest") public final static class PutRecurringDepositAccountsAccountIdRequest { - private PutRecurringDepositAccountsAccountIdRequest() { - } + + private PutRecurringDepositAccountsAccountIdRequest() {} @ApiModelProperty(example = "en") public String locale; @@ -455,12 +455,12 @@ final class RecurringDepositAccountsApiResourceSwagger { @ApiModel(value = "PutRecurringDepositAccountsAccountIdResponse") public final static class PutRecurringDepositAccountsAccountIdResponse { - private PutRecurringDepositAccountsAccountIdResponse() { - } + + private PutRecurringDepositAccountsAccountIdResponse() {} final class PutRecurringDepositAccountsChanges { - private PutRecurringDepositAccountsChanges() { - } + + private PutRecurringDepositAccountsChanges() {} @ApiModelProperty(example = "6000") public Integer depositAmount; @@ -481,14 +481,14 @@ final class RecurringDepositAccountsApiResourceSwagger { @ApiModel(value = "PostRecurringDepositAccountsAccountIdRequest") public final static class PostRecurringDepositAccountsAccountIdRequest { - private PostRecurringDepositAccountsAccountIdRequest() { - } + + private PostRecurringDepositAccountsAccountIdRequest() {} } @ApiModel(value = "PostRecurringDepositAccountsAccountIdResponse") public final static class PostRecurringDepositAccountsAccountIdResponse { - private PostRecurringDepositAccountsAccountIdResponse() { - } + + private PostRecurringDepositAccountsAccountIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -502,8 +502,8 @@ final class RecurringDepositAccountsApiResourceSwagger { @ApiModel(value = "DeleteRecurringDepositAccountsResponse") public final static class DeleteRecurringDepositAccountsResponse { - private DeleteRecurringDepositAccountsResponse() { - } + + private DeleteRecurringDepositAccountsResponse() {} @ApiModelProperty(example = "1") public Integer officeId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositProductsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositProductsApiResource.java index 2a78f1207..2c14c877a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositProductsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositProductsApiResource.java @@ -88,10 +88,13 @@ import org.springframework.util.CollectionUtils; @Path("/recurringdepositproducts") @Component @Scope("singleton") -@Api(tags = {"Recurring Deposit Product"}) +@Api(tags = { "Recurring Deposit Product" }) @SwaggerDefinition(tags = { - @Tag(name = "Recurring Deposit Product", description = "Recurring Deposits are a special kind of Term Deposits offered by MFI's. The Recurring Deposit Products (aka RD) product offerings are modeled using this API.\n" + "\n" + "Recurring Deposits help people with regular incomes to deposit a fixed amount every month (specified recurring frequency) into their Recurring Deposit account.\n" + "\n" + "When creating recurring deposit accounts, the details from the recurring deposit product are used to auto fill details of the recurring deposit account application process.") -}) + @Tag(name = "Recurring Deposit Product", description = "Recurring Deposits are a special kind of Term Deposits offered by MFI's. The Recurring Deposit Products (aka RD) product offerings are modeled using this API.\n" + + "\n" + + "Recurring Deposits help people with regular incomes to deposit a fixed amount every month (specified recurring frequency) into their Recurring Deposit account.\n" + + "\n" + + "When creating recurring deposit accounts, the details from the recurring deposit product are used to auto fill details of the recurring deposit account application process.") }) public class RecurringDepositProductsApiResource { private final DepositProductReadPlatformService depositProductReadPlatformService; @@ -146,9 +149,14 @@ public class RecurringDepositProductsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Recurring Deposit Product", httpMethod = "POST", notes = "Creates a Recurring Deposit Product\n\n" + "Mandatory Fields: name, shortName, description, currencyCode, digitsAfterDecimal,inMultiplesOf, interestCompoundingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minDepositTerm, minDepositTermTypeId, recurringDepositFrequency, recurringDepositFrequencyTypeId, accountingRule, depositAmount\n\n" + "Mandatory Fields for Cash based accounting (accountingRule = 2): savingsReferenceAccountId, savingsControlAccountId, interestOnSavingsAccountId, incomeFromFeeAccountId, transfersInSuspenseAccountId, incomeFromPenaltyAccountId\n\n" + "Optional Fields: lockinPeriodFrequency, lockinPeriodFrequencyType, maxDepositTerm, maxDepositTermTypeId, inMultiplesOfDepositTerm, inMultiplesOfDepositTermTypeId, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnTypeId, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, charges, charts, minDepositAmount, maxDepositAmount, withHoldTax, taxGroupId") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositProductsApiResourceSwagger.PostRecurringDepositProductsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositProductsApiResourceSwagger.PostRecurringDepositProductsResponse.class)}) + @ApiOperation(value = "Create a Recurring Deposit Product", httpMethod = "POST", notes = "Creates a Recurring Deposit Product\n\n" + + "Mandatory Fields: name, shortName, description, currencyCode, digitsAfterDecimal,inMultiplesOf, interestCompoundingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minDepositTerm, minDepositTermTypeId, recurringDepositFrequency, recurringDepositFrequencyTypeId, accountingRule, depositAmount\n\n" + + "Mandatory Fields for Cash based accounting (accountingRule = 2): savingsReferenceAccountId, savingsControlAccountId, interestOnSavingsAccountId, incomeFromFeeAccountId, transfersInSuspenseAccountId, incomeFromPenaltyAccountId\n\n" + + "Optional Fields: lockinPeriodFrequency, lockinPeriodFrequencyType, maxDepositTerm, maxDepositTermTypeId, inMultiplesOfDepositTerm, inMultiplesOfDepositTermTypeId, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnTypeId, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, charges, charts, minDepositAmount, maxDepositAmount, withHoldTax, taxGroupId") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositProductsApiResourceSwagger.PostRecurringDepositProductsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositProductsApiResourceSwagger.PostRecurringDepositProductsResponse.class) }) public String create(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createRecurringDepositProduct().withJson(apiRequestBodyAsJson) @@ -164,9 +172,12 @@ public class RecurringDepositProductsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Recurring Deposit Product", httpMethod = "PUT", notes = "Updates a Recurring Deposit Product") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositProductsApiResourceSwagger.PutRecurringDepositProductsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositProductsApiResourceSwagger.PutRecurringDepositProductsResponse.class)}) - public String update(@PathParam("productId") @ApiParam(value = "productId") final Long productId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = RecurringDepositProductsApiResourceSwagger.PutRecurringDepositProductsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositProductsApiResourceSwagger.PutRecurringDepositProductsResponse.class) }) + public String update(@PathParam("productId") @ApiParam(value = "productId") final Long productId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateRecurringDepositProduct(productId) .withJson(apiRequestBodyAsJson).build(); @@ -180,8 +191,10 @@ public class RecurringDepositProductsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Recuring Deposit Products", httpMethod = "GET", notes = "Lists Recuring Deposit Products\n\n" + "Example Requests:\n" + "\n" + "recurringdepositproducts\n" + "\n" + "\n" + "recurringdepositproducts?fields=name") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = RecurringDepositProductsApiResourceSwagger.GetRecurringDepositProductsResponse.class)}) + @ApiOperation(value = "List Recuring Deposit Products", httpMethod = "GET", notes = "Lists Recuring Deposit Products\n\n" + + "Example Requests:\n" + "\n" + "recurringdepositproducts\n" + "\n" + "\n" + "recurringdepositproducts?fields=name") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = RecurringDepositProductsApiResourceSwagger.GetRecurringDepositProductsResponse.class) }) public String retrieveAll(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.RECURRING_DEPOSIT_PRODUCT_RESOURCE_NAME); @@ -199,8 +212,11 @@ public class RecurringDepositProductsApiResource { @Path("{productId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Recurring Deposit Product", httpMethod = "GET", notes = "Retrieves a Recurring Deposit Product\n\n" + "Example Requests:\n" + "\n" + "recurringdepositproducts/1\n" + "\n" + "\n" + "recurringdepositproducts/1?template=true\n" + "\n" + "\n" + "recurringdepositproducts/1?fields=name,description") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositProductsApiResourceSwagger.GetRecurringDepositProductsProductIdResponse.class)}) + @ApiOperation(value = "Retrieve a Recurring Deposit Product", httpMethod = "GET", notes = "Retrieves a Recurring Deposit Product\n\n" + + "Example Requests:\n" + "\n" + "recurringdepositproducts/1\n" + "\n" + "\n" + "recurringdepositproducts/1?template=true\n" + + "\n" + "\n" + "recurringdepositproducts/1?fields=name,description") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositProductsApiResourceSwagger.GetRecurringDepositProductsProductIdResponse.class) }) public String retrieveOne(@PathParam("productId") @ApiParam(value = "productId") final Long productId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.RECURRING_DEPOSIT_PRODUCT_RESOURCE_NAME); @@ -225,8 +241,8 @@ public class RecurringDepositProductsApiResource { .fetchFeeToIncomeAccountMappingsForSavingsProduct(productId); Collection penaltyToGLAccountMappings = this.accountMappingReadPlatformService .fetchPenaltyToIncomeAccountMappingsForSavingsProduct(productId); - recurringDepositProductData = RecurringDepositProductData.withAccountingDetails(recurringDepositProductData, - accountingMappings, paymentChannelToFundSourceMappings, feeToGLAccountMappings, penaltyToGLAccountMappings); + recurringDepositProductData = RecurringDepositProductData.withAccountingDetails(recurringDepositProductData, accountingMappings, + paymentChannelToFundSourceMappings, feeToGLAccountMappings, penaltyToGLAccountMappings); } if (settings.isTemplate()) { @@ -338,7 +354,8 @@ public class RecurringDepositProductsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Recurring Deposit Product", httpMethod = "DELETE", notes = "Deletes a Recurring Deposit Product") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = RecurringDepositProductsApiResourceSwagger.DeleteRecurringDepositProductsProductIdResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = RecurringDepositProductsApiResourceSwagger.DeleteRecurringDepositProductsProductIdResponse.class) }) public String delete(@PathParam("productId") @ApiParam(value = "productId") final Long productId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteRecurringDepositProduct(productId).build(); @@ -348,4 +365,4 @@ public class RecurringDepositProductsApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositProductsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositProductsApiResourceSwagger.java index b5fabefaf..2c498ea59 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositProductsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/RecurringDepositProductsApiResourceSwagger.java @@ -27,21 +27,21 @@ import java.util.Set; * Created by Chirag Gupta on 12/27/17. */ final class RecurringDepositProductsApiResourceSwagger { - private RecurringDepositProductsApiResourceSwagger() { - } + + private RecurringDepositProductsApiResourceSwagger() {} @ApiModel(value = "PostRecurringDepositProductsRequest") public final static class PostRecurringDepositProductsRequest { - private PostRecurringDepositProductsRequest() { - } + + private PostRecurringDepositProductsRequest() {} final class PostRecurringDepositProductsCharts { - private PostRecurringDepositProductsCharts() { - } + + private PostRecurringDepositProductsCharts() {} final class PostRecurringDepositProductsChartSlabs { - private PostRecurringDepositProductsChartSlabs() { - } + + private PostRecurringDepositProductsChartSlabs() {} @ApiModelProperty(example = "from 0 to 90 days") public String description; @@ -117,8 +117,8 @@ final class RecurringDepositProductsApiResourceSwagger { @ApiModel(value = "PostRecurringDepositProductsResponse") public final static class PostRecurringDepositProductsResponse { - private PostRecurringDepositProductsResponse() { - } + + private PostRecurringDepositProductsResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -126,8 +126,8 @@ final class RecurringDepositProductsApiResourceSwagger { @ApiModel(value = "PutRecurringDepositProductsRequest") public final static class PutRecurringDepositProductsRequest { - private PutRecurringDepositProductsRequest() { - } + + private PutRecurringDepositProductsRequest() {} @ApiModelProperty(example = "Recurring deposit product new offerings") public String description; @@ -141,12 +141,12 @@ final class RecurringDepositProductsApiResourceSwagger { @ApiModel(value = "PutRecurringDepositProductsResponse") public final static class PutRecurringDepositProductsResponse { - private PutRecurringDepositProductsResponse() { - } + + private PutRecurringDepositProductsResponse() {} final class PutRecurringDepositProductsChanges { - private PutRecurringDepositProductsChanges() { - } + + private PutRecurringDepositProductsChanges() {} @ApiModelProperty(example = "Recurring deposit product new offerings") public String description; @@ -161,12 +161,12 @@ final class RecurringDepositProductsApiResourceSwagger { @ApiModel(value = "GetRecurringDepositProductsResponse") public final static class GetRecurringDepositProductsResponse { - private GetRecurringDepositProductsResponse() { - } + + private GetRecurringDepositProductsResponse() {} final class GetRecurringDepositProductsCurrency { - private GetRecurringDepositProductsCurrency() { - } + + private GetRecurringDepositProductsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -185,8 +185,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsMinDepositTermType { - private GetRecurringDepositProductsMinDepositTermType() { - } + + private GetRecurringDepositProductsMinDepositTermType() {} @ApiModelProperty(example = "2") public Integer id; @@ -197,8 +197,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsMaxDepositTermType { - private GetRecurringDepositProductsMaxDepositTermType() { - } + + private GetRecurringDepositProductsMaxDepositTermType() {} @ApiModelProperty(example = "3") public Integer id; @@ -209,8 +209,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsInterestCompoundingPeriodType { - private GetRecurringDepositProductsInterestCompoundingPeriodType() { - } + + private GetRecurringDepositProductsInterestCompoundingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -221,8 +221,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsInterestPostingPeriodType { - private GetRecurringDepositProductsInterestPostingPeriodType() { - } + + private GetRecurringDepositProductsInterestPostingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -233,8 +233,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsInterestCalculationType { - private GetRecurringDepositProductsInterestCalculationType() { - } + + private GetRecurringDepositProductsInterestCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -245,8 +245,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsInterestCalculationDaysInYearType { - private GetRecurringDepositProductsInterestCalculationDaysInYearType() { - } + + private GetRecurringDepositProductsInterestCalculationDaysInYearType() {} @ApiModelProperty(example = "365") public Integer id; @@ -257,8 +257,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsAccountingRule { - private GetRecurringDepositProductsAccountingRule() { - } + + private GetRecurringDepositProductsAccountingRule() {} @ApiModelProperty(example = "1") public Integer id; @@ -269,8 +269,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsRecurringDepositFrequencyType { - private GetRecurringDepositProductsRecurringDepositFrequencyType() { - } + + private GetRecurringDepositProductsRecurringDepositFrequencyType() {} @ApiModelProperty(example = "1") public Integer id; @@ -311,12 +311,12 @@ final class RecurringDepositProductsApiResourceSwagger { @ApiModel(value = "GetRecurringDepositProductsProductIdResponse") public final static class GetRecurringDepositProductsProductIdResponse { - private GetRecurringDepositProductsProductIdResponse() { - } + + private GetRecurringDepositProductsProductIdResponse() {} final class GetRecurringDepositProductsProductIdCurrency { - private GetRecurringDepositProductsProductIdCurrency() { - } + + private GetRecurringDepositProductsProductIdCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -333,8 +333,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdInterestCompoundingPeriodType { - private GetRecurringDepositProductsProductIdInterestCompoundingPeriodType() { - } + + private GetRecurringDepositProductsProductIdInterestCompoundingPeriodType() {} @ApiModelProperty(example = "1") public Integer id; @@ -345,12 +345,12 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdAccountingMappings { - private GetRecurringDepositProductsProductIdAccountingMappings() { - } + + private GetRecurringDepositProductsProductIdAccountingMappings() {} final class GetRecurringDepositProductsProductIdSavingsReferenceAccount { - private GetRecurringDepositProductsProductIdSavingsReferenceAccount() { - } + + private GetRecurringDepositProductsProductIdSavingsReferenceAccount() {} @ApiModelProperty(example = "12") public Integer id; @@ -361,8 +361,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdIncomeFromFeeAccount { - private GetRecurringDepositProductsProductIdIncomeFromFeeAccount() { - } + + private GetRecurringDepositProductsProductIdIncomeFromFeeAccount() {} @ApiModelProperty(example = "16") public Integer id; @@ -373,8 +373,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdIncomeFromPenaltyAccount { - private GetRecurringDepositProductsProductIdIncomeFromPenaltyAccount() { - } + + private GetRecurringDepositProductsProductIdIncomeFromPenaltyAccount() {} @ApiModelProperty(example = "17") public Integer id; @@ -385,8 +385,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdInterestOnSavingsAccount { - private GetRecurringDepositProductsProductIdInterestOnSavingsAccount() { - } + + private GetRecurringDepositProductsProductIdInterestOnSavingsAccount() {} @ApiModelProperty(example = "15") public Integer id; @@ -397,8 +397,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdSavingsControlAccount { - private GetRecurringDepositProductsProductIdSavingsControlAccount() { - } + + private GetRecurringDepositProductsProductIdSavingsControlAccount() {} @ApiModelProperty(example = "13") public Integer id; @@ -409,8 +409,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdTransfersInSuspenseAccount { - private GetRecurringDepositProductsProductIdTransfersInSuspenseAccount() { - } + + private GetRecurringDepositProductsProductIdTransfersInSuspenseAccount() {} @ApiModelProperty(example = "14") public Integer id; @@ -429,12 +429,12 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdFeeToIncomeAccountMappings { - private GetRecurringDepositProductsProductIdFeeToIncomeAccountMappings() { - } + + private GetRecurringDepositProductsProductIdFeeToIncomeAccountMappings() {} final class GetRecurringDepositProductsProductIdFeeToIncomeAccountMappingsCharge { - private GetRecurringDepositProductsProductIdFeeToIncomeAccountMappingsCharge() { - } + + private GetRecurringDepositProductsProductIdFeeToIncomeAccountMappingsCharge() {} @ApiModelProperty(example = "11") public Integer id; @@ -447,8 +447,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdFeeToIncomeAccountMappingsIncomeAccount { - private GetRecurringDepositProductsProductIdFeeToIncomeAccountMappingsIncomeAccount() { - } + + private GetRecurringDepositProductsProductIdFeeToIncomeAccountMappingsIncomeAccount() {} @ApiModelProperty(example = "16") public Integer id; @@ -463,12 +463,12 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdPenaltyToIncomeAccountMappings { - private GetRecurringDepositProductsProductIdPenaltyToIncomeAccountMappings() { - } + + private GetRecurringDepositProductsProductIdPenaltyToIncomeAccountMappings() {} final class GetRecurringDepositProductsProductIdPenaltyToIncomeAccountMappingsCharge { - private GetRecurringDepositProductsProductIdPenaltyToIncomeAccountMappingsCharge() { - } + + private GetRecurringDepositProductsProductIdPenaltyToIncomeAccountMappingsCharge() {} @ApiModelProperty(example = "12") public Integer id; @@ -485,8 +485,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdPreClosurePenalInterestOnType { - private GetRecurringDepositProductsProductIdPreClosurePenalInterestOnType() { - } + + private GetRecurringDepositProductsProductIdPreClosurePenalInterestOnType() {} @ApiModelProperty(example = "1") public Integer id; @@ -497,8 +497,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdMinDepositTermType { - private GetRecurringDepositProductsProductIdMinDepositTermType() { - } + + private GetRecurringDepositProductsProductIdMinDepositTermType() {} @ApiModelProperty(example = "1") public Integer id; @@ -509,8 +509,8 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdMaxDepositTermType { - private GetRecurringDepositProductsProductIdMaxDepositTermType() { - } + + private GetRecurringDepositProductsProductIdMaxDepositTermType() {} @ApiModelProperty(example = "3") public Integer id; @@ -521,16 +521,16 @@ final class RecurringDepositProductsApiResourceSwagger { } final class GetRecurringDepositProductsProductIdActiveChart { - private GetRecurringDepositProductsProductIdActiveChart() { - } + + private GetRecurringDepositProductsProductIdActiveChart() {} final class GetRecurringDepositProductsProductIdChartSlabs { - private GetRecurringDepositProductsProductIdChartSlabs() { - } + + private GetRecurringDepositProductsProductIdChartSlabs() {} final class GetRecurringDepositProductsProductIdPeriodType { - private GetRecurringDepositProductsProductIdPeriodType() { - } + + private GetRecurringDepositProductsProductIdPeriodType() {} @ApiModelProperty(example = "1") public Integer id; @@ -601,11 +601,10 @@ final class RecurringDepositProductsApiResourceSwagger { @ApiModel(value = "DeleteRecurringDepositProductsProductIdResponse") public final static class DeleteRecurringDepositProductsProductIdResponse { - private DeleteRecurringDepositProductsProductIdResponse() { - } + + private DeleteRecurringDepositProductsProductIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; } } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountChargesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountChargesApiResource.java index 1eb06a0cc..77bb155a2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountChargesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountChargesApiResource.java @@ -17,6 +17,7 @@ * under the License. */ package org.apache.fineract.portfolio.savings.api; + import static org.apache.fineract.portfolio.savings.SavingsApiConstants.COMMAND_INACTIVATE_CHARGE; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.COMMAND_PAY_CHARGE; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.COMMAND_WAIVE_CHARGE; @@ -66,10 +67,11 @@ import org.springframework.stereotype.Component; @Path("/savingsaccounts/{savingsAccountId}/charges") @Component @Scope("singleton") -@Api(tags = {"Savings Charges"}) +@Api(tags = { "Savings Charges" }) @SwaggerDefinition(tags = { - @Tag(name = "Savings Charges", description = "Its typical for MFIs to add maintenance and operating charges. They can be either Fees or Penalties.\n" + "\n" + "Savings Charges are instances of Charges and represent either fees and penalties for savings products. Refer Charges for documentation of the various properties of a charge, Only additional properties ( specific to the context of a Charge being associated with a Savings account) are described here") -}) + @Tag(name = "Savings Charges", description = "Its typical for MFIs to add maintenance and operating charges. They can be either Fees or Penalties.\n" + + "\n" + + "Savings Charges are instances of Charges and represent either fees and penalties for savings products. Refer Charges for documentation of the various properties of a charge, Only additional properties ( specific to the context of a Charge being associated with a Savings account) are described here") }) public class SavingsAccountChargesApiResource { private final PlatformSecurityContext context; @@ -101,15 +103,22 @@ public class SavingsAccountChargesApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Savings Charges", httpMethod = "GET", notes = "Lists Savings Charges\n\n" + "Example Requests:\n" + "\n" + "savingsaccounts/1/charges\n" + "\n" + "savingsaccounts/1/charges?chargeStatus=all\n" + "\n" + "savingsaccounts/1/charges?chargeStatus=inactive\n" + "\n" + "savingsaccounts/1/charges?chargeStatus=active\n" + "\n" + "savingsaccounts/1/charges?fields=name,amountOrPercentage") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SavingsAccountChargesApiResourceSwagger.GetSavingsAccountsSavingsAccountIdChargesResponse.class)}) - public String retrieveAllSavingsAccountCharges(@PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Long savingsAccountId, - @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, @Context final UriInfo uriInfo) { + @ApiOperation(value = "List Savings Charges", httpMethod = "GET", notes = "Lists Savings Charges\n\n" + "Example Requests:\n" + "\n" + + "savingsaccounts/1/charges\n" + "\n" + "savingsaccounts/1/charges?chargeStatus=all\n" + "\n" + + "savingsaccounts/1/charges?chargeStatus=inactive\n" + "\n" + "savingsaccounts/1/charges?chargeStatus=active\n" + "\n" + + "savingsaccounts/1/charges?fields=name,amountOrPercentage") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SavingsAccountChargesApiResourceSwagger.GetSavingsAccountsSavingsAccountIdChargesResponse.class) }) + public String retrieveAllSavingsAccountCharges( + @PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Long savingsAccountId, + @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); - if (!(is(chargeStatus, "all") || is(chargeStatus, "active") || is(chargeStatus, "inactive"))) { throw new UnrecognizedQueryParamException( - "status", chargeStatus, new Object[] { "all", "active", "inactive" }); } + if (!(is(chargeStatus, "all") || is(chargeStatus, "active") || is(chargeStatus, "inactive"))) { + throw new UnrecognizedQueryParamException("status", chargeStatus, new Object[] { "all", "active", "inactive" }); + } final Collection savingsAccountCharges = this.savingsAccountChargeReadPlatformService .retrieveSavingsAccountCharges(savingsAccountId, chargeStatus); @@ -123,13 +132,17 @@ public class SavingsAccountChargesApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Savings Charges Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "savingsaccounts/1/charges/template") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.GetSavingsAccountsSavingsAccountIdChargesTemplateResponse.class)}) - public String retrieveTemplate(@PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId")final Long savingsAccountId, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve Savings Charges Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "savingsaccounts/1/charges/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.GetSavingsAccountsSavingsAccountIdChargesTemplateResponse.class) }) + public String retrieveTemplate(@PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Long savingsAccountId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); - final Collection chargeOptions = this.chargeReadPlatformService.retrieveSavingsAccountApplicableCharges(savingsAccountId); + final Collection chargeOptions = this.chargeReadPlatformService + .retrieveSavingsAccountApplicableCharges(savingsAccountId); final SavingsAccountChargeData savingsAccountChargeTemplate = SavingsAccountChargeData.template(chargeOptions); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -141,10 +154,15 @@ public class SavingsAccountChargesApiResource { @Path("{savingsAccountChargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Savings account Charge", httpMethod = "GET", notes = "Retrieves a Savings account Charge\n\n" + "Example Requests:\n" + "\n" + "/savingsaccounts/1/charges/5\n" + "\n" + "\n" + "/savingsaccounts/1/charges/5?fields=name,amountOrPercentage") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.GetSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse.class)}) - public String retrieveSavingsAccountCharge(@PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId")final Long savingsAccountId, - @PathParam("savingsAccountChargeId") @ApiParam(value = "savingsAccountChargeId") final Long savingsAccountChargeId, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Savings account Charge", httpMethod = "GET", notes = "Retrieves a Savings account Charge\n\n" + + "Example Requests:\n" + "\n" + "/savingsaccounts/1/charges/5\n" + "\n" + "\n" + + "/savingsaccounts/1/charges/5?fields=name,amountOrPercentage") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.GetSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse.class) }) + public String retrieveSavingsAccountCharge( + @PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Long savingsAccountId, + @PathParam("savingsAccountChargeId") @ApiParam(value = "savingsAccountChargeId") final Long savingsAccountChargeId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); @@ -159,10 +177,15 @@ public class SavingsAccountChargesApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Savings account Charge", httpMethod = "POST", notes = "Creates a Savings account Charge\n\n" + "Mandatory Fields for Savings account Charges: chargeId, amount\n\n" + "chargeId, amount, dueDate, dateFormat, locale\n\n" + "chargeId, amount, feeOnMonthDay, monthDayFormat, locale") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountChargesApiResourceSwagger.PostSavingsAccountsSavingsAccountIdChargesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.PostSavingsAccountsSavingsAccountIdChargesResponse.class)}) - public String addSavingsAccountCharge(@PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId")final Long savingsAccountId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Create a Savings account Charge", httpMethod = "POST", notes = "Creates a Savings account Charge\n\n" + + "Mandatory Fields for Savings account Charges: chargeId, amount\n\n" + "chargeId, amount, dueDate, dateFormat, locale\n\n" + + "chargeId, amount, feeOnMonthDay, monthDayFormat, locale") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountChargesApiResourceSwagger.PostSavingsAccountsSavingsAccountIdChargesRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.PostSavingsAccountsSavingsAccountIdChargesResponse.class) }) + public String addSavingsAccountCharge(@PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Long savingsAccountId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createSavingsAccountCharge(savingsAccountId) .withJson(apiRequestBodyAsJson).build(); @@ -177,10 +200,14 @@ public class SavingsAccountChargesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Savings account Charge", httpMethod = "PUT", notes = "Currently Savings account Charges may be updated only if the Savings account is not yet approved.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountChargesApiResourceSwagger.PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse.class)}) - public String updateSavingsAccountCharge(@PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId")final Long savingsAccountId, - @PathParam("savingsAccountChargeId") @ApiParam(value = "savingsAccountChargeId") final Long savingsAccountChargeId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountChargesApiResourceSwagger.PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse.class) }) + public String updateSavingsAccountCharge( + @PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Long savingsAccountId, + @PathParam("savingsAccountChargeId") @ApiParam(value = "savingsAccountChargeId") final Long savingsAccountChargeId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder() .updateSavingsAccountCharge(savingsAccountId, savingsAccountChargeId).withJson(apiRequestBodyAsJson).build(); @@ -194,11 +221,20 @@ public class SavingsAccountChargesApiResource { @Path("{savingsAccountChargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Pay a Savings account Charge | Waive off a Savings account Charge | Inactivate a Savings account Charge", httpMethod = "POST", notes = "Pay a Savings account Charge:\n\n" + "An active charge will be paid when savings account is active and having sufficient balance.\n\n" + "Waive off a Savings account Charge:\n\n" + "Outstanding charge amount will be waived off.\n\n" + "Inactivate a Savings account Charge:\n\n" + "A charge will be allowed to inactivate when savings account is active and not having any dues as of today. If charge is overpaid, corresponding charge payment transactions will be reversed.\n\n" + "Showing request/response for 'Pay a Savings account Charge'") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountChargesApiResourceSwagger.PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200,message = "OK", response = SavingsAccountChargesApiResourceSwagger.PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse.class)}) - public String payOrWaiveSavingsAccountCharge(@PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Long savingsAccountId, - @PathParam("savingsAccountChargeId") @ApiParam(value = "savingsAccountChargeId")final Long savingsAccountChargeId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiOperation(value = "Pay a Savings account Charge | Waive off a Savings account Charge | Inactivate a Savings account Charge", httpMethod = "POST", notes = "Pay a Savings account Charge:\n\n" + + "An active charge will be paid when savings account is active and having sufficient balance.\n\n" + + "Waive off a Savings account Charge:\n\n" + "Outstanding charge amount will be waived off.\n\n" + + "Inactivate a Savings account Charge:\n\n" + + "A charge will be allowed to inactivate when savings account is active and not having any dues as of today. If charge is overpaid, corresponding charge payment transactions will be reversed.\n\n" + + "Showing request/response for 'Pay a Savings account Charge'") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountChargesApiResourceSwagger.PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse.class) }) + public String payOrWaiveSavingsAccountCharge( + @PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Long savingsAccountId, + @PathParam("savingsAccountChargeId") @ApiParam(value = "savingsAccountChargeId") final Long savingsAccountChargeId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { String json = ""; @@ -236,15 +272,17 @@ public class SavingsAccountChargesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Savings account Charge", httpMethod = "DELETE", notes = "Note: Currently, A Savings account Charge may only be removed from Savings that are not yet approved.") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.DeleteSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse.class)}) - public String deleteSavingsAccountCharge(@PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Long savingsAccountId, + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountChargesApiResourceSwagger.DeleteSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse.class) }) + public String deleteSavingsAccountCharge( + @PathParam("savingsAccountId") @ApiParam(value = "savingsAccountId") final Long savingsAccountId, @PathParam("savingsAccountChargeId") @ApiParam(value = "savingsAccountChargeId") final Long savingsAccountChargeId) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteSavingsAccountCharge(savingsAccountId, - savingsAccountChargeId).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder() + .deleteSavingsAccountCharge(savingsAccountId, savingsAccountChargeId).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountChargesApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountChargesApiResourceSwagger.java index 11270e403..48c335ca0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountChargesApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountChargesApiResourceSwagger.java @@ -26,15 +26,16 @@ import java.util.Set; * Created by Chirag Gupta on 12/30/17. */ final class SavingsAccountChargesApiResourceSwagger { - private SavingsAccountChargesApiResourceSwagger() { - } + + private SavingsAccountChargesApiResourceSwagger() {} @ApiModel(value = "GetSavingsAccountsSavingsAccountIdChargesResponse") public final static class GetSavingsAccountsSavingsAccountIdChargesResponse { - private GetSavingsAccountsSavingsAccountIdChargesResponse() { - } + + private GetSavingsAccountsSavingsAccountIdChargesResponse() {} final class GetChargesCurrencyResponse { + @ApiModelProperty(example = "USD") public String code; @ApiModelProperty(example = "US Dollar") @@ -50,8 +51,8 @@ final class SavingsAccountChargesApiResourceSwagger { } final class GetChargesChargeCalculationType { - private GetChargesChargeCalculationType() { - } + + private GetChargesChargeCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -62,8 +63,8 @@ final class SavingsAccountChargesApiResourceSwagger { } final class GetChargesChargeTimeType { - private GetChargesChargeTimeType() { - } + + private GetChargesChargeTimeType() {} @ApiModelProperty(example = "1") public Integer id; @@ -106,16 +107,16 @@ final class SavingsAccountChargesApiResourceSwagger { @ApiModel(value = "GetSavingsAccountsSavingsAccountIdChargesTemplateResponse") public final static class GetSavingsAccountsSavingsAccountIdChargesTemplateResponse { - private GetSavingsAccountsSavingsAccountIdChargesTemplateResponse() { - } + + private GetSavingsAccountsSavingsAccountIdChargesTemplateResponse() {} final class GetSavingsChargesOptions { - private GetSavingsChargesOptions() { - } + + private GetSavingsChargesOptions() {} final class GetSavingsChargesChargeTimeType { - private GetSavingsChargesChargeTimeType() { - } + + private GetSavingsChargesChargeTimeType() {} @ApiModelProperty(example = "2") public Integer id; @@ -126,8 +127,8 @@ final class SavingsAccountChargesApiResourceSwagger { } final class GetChargesAppliesTo { - private GetChargesAppliesTo() { - } + + private GetChargesAppliesTo() {} @ApiModelProperty(example = "1") public Integer id; @@ -166,8 +167,8 @@ final class SavingsAccountChargesApiResourceSwagger { @ApiModel(value = "GetSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse") public final static class GetSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse { - private GetSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse() { - } + + private GetSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse() {} @ApiModelProperty(example = "1") public Integer id; @@ -200,8 +201,8 @@ final class SavingsAccountChargesApiResourceSwagger { @ApiModel(value = "PostSavingsAccountsSavingsAccountIdChargesRequest") public final static class PostSavingsAccountsSavingsAccountIdChargesRequest { - private PostSavingsAccountsSavingsAccountIdChargesRequest() { - } + + private PostSavingsAccountsSavingsAccountIdChargesRequest() {} @ApiModelProperty(example = "2") public Integer chargeId; @@ -217,8 +218,8 @@ final class SavingsAccountChargesApiResourceSwagger { @ApiModel(value = "PostSavingsAccountsSavingsAccountIdChargesResponse") public final static class PostSavingsAccountsSavingsAccountIdChargesResponse { - private PostSavingsAccountsSavingsAccountIdChargesResponse() { - } + + private PostSavingsAccountsSavingsAccountIdChargesResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -232,8 +233,8 @@ final class SavingsAccountChargesApiResourceSwagger { @ApiModel(value = "PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest") public final static class PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest { - private PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest() { - } + + private PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest() {} @ApiModelProperty(example = "dd MMMM yyyy") public String dateFormat; @@ -247,12 +248,12 @@ final class SavingsAccountChargesApiResourceSwagger { @ApiModel(value = "PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse") public final static class PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse { - private PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse() { - } + + private PutSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse() {} final class PutSavingsChanges { - private PutSavingsChanges() { - } + + private PutSavingsChanges() {} @ApiModelProperty(example = "27 March 2013") public String dueDate; @@ -277,8 +278,8 @@ final class SavingsAccountChargesApiResourceSwagger { @ApiModel(value = "PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest") public final static class PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest { - private PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest() { - } + + private PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdRequest() {} @ApiModelProperty(example = "dd MMMM yyyy") public String dateFormat; @@ -292,8 +293,8 @@ final class SavingsAccountChargesApiResourceSwagger { @ApiModel(value = "PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse") public final static class PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse { - private PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse() { - } + + private PostSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -307,8 +308,8 @@ final class SavingsAccountChargesApiResourceSwagger { @ApiModel(value = "DeleteSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse") public final static class DeleteSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse { - private DeleteSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse() { - } + + private DeleteSavingsAccountsSavingsAccountIdChargesSavingsAccountChargeIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountTransactionsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountTransactionsApiResource.java index 5d3a70c00..133abea77 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountTransactionsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountTransactionsApiResource.java @@ -88,7 +88,7 @@ public class SavingsAccountTransactionsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveTemplate(@PathParam("savingsId") final Long savingsId, - // @QueryParam("command") final String commandParam, + // @QueryParam("command") final String commandParam, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); @@ -137,11 +137,9 @@ public class SavingsAccountTransactionsApiResource { if (is(commandParam, "deposit")) { final CommandWrapper commandRequest = builder.savingsAccountDeposit(savingsId).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } - else if(is(commandParam, "gsimDeposit")) - { - final CommandWrapper commandRequest = builder.gsimSavingsAccountDeposit(savingsId).build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + } else if (is(commandParam, "gsimDeposit")) { + final CommandWrapper commandRequest = builder.gsimSavingsAccountDeposit(savingsId).build(); + result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); } else if (is(commandParam, "withdrawal")) { final CommandWrapper commandRequest = builder.savingsAccountWithdrawal(savingsId).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); @@ -155,7 +153,8 @@ public class SavingsAccountTransactionsApiResource { if (result == null) { // - throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { "deposit", "withdrawal", SavingsApiConstants.COMMAND_HOLD_AMOUNT }); + throw new UnrecognizedQueryParamException("command", commandParam, + new Object[] { "deposit", "withdrawal", SavingsApiConstants.COMMAND_HOLD_AMOUNT }); } return this.toApiJsonSerializer.serialize(result); @@ -189,7 +188,7 @@ public class SavingsAccountTransactionsApiResource { } else if (is(commandParam, SavingsApiConstants.COMMAND_ADJUST_TRANSACTION)) { final CommandWrapper commandRequest = builder.adjustSavingsAccountTransaction(savingsId, transactionId).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam,SavingsApiConstants.COMMAND_RELEASE_AMOUNT)) { + } else if (is(commandParam, SavingsApiConstants.COMMAND_RELEASE_AMOUNT)) { final CommandWrapper commandRequest = builder.releaseAmount(savingsId, transactionId).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); } @@ -197,9 +196,9 @@ public class SavingsAccountTransactionsApiResource { if (result == null) { // throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { SavingsApiConstants.COMMAND_UNDO_TRANSACTION, - SavingsApiConstants.COMMAND_ADJUST_TRANSACTION, SavingsApiConstants.COMMAND_RELEASE_AMOUNT}); + SavingsApiConstants.COMMAND_ADJUST_TRANSACTION, SavingsApiConstants.COMMAND_RELEASE_AMOUNT }); } return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountsApiResource.java index daf25a368..49390fa7d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountsApiResource.java @@ -79,10 +79,9 @@ import org.springframework.util.CollectionUtils; @Path("/savingsaccounts") @Component @Scope("singleton") -@Api(tags = {"Savings Account"}) +@Api(tags = { "Savings Account" }) @SwaggerDefinition(tags = { - @Tag(name = "Savings Account", description = "Savings accounts are instances of a particular savings product created for an individual or group. An application process around the creation of accounts is also supported.") -}) + @Tag(name = "Savings Account", description = "Savings accounts are instances of a particular savings product created for an individual or group. An application process around the creation of accounts is also supported.") }) public class SavingsAccountsApiResource { private final SavingsAccountReadPlatformService savingsAccountReadPlatformService; @@ -108,20 +107,24 @@ public class SavingsAccountsApiResource { this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; this.apiRequestParameterHelper = apiRequestParameterHelper; this.savingsAccountChargeReadPlatformService = savingsAccountChargeReadPlatformService; - this.bulkImportWorkbookService=bulkImportWorkbookService; - this.bulkImportWorkbookPopulatorService=bulkImportWorkbookPopulatorService; + this.bulkImportWorkbookService = bulkImportWorkbookService; + this.bulkImportWorkbookPopulatorService = bulkImportWorkbookPopulatorService; } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Savings Account Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Requests:\n" + "\n" + "savingsaccounts/template?clientId=1\n" + "\n" + "\n" + "savingsaccounts/template?clientId=1&productId=1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.GetSavingsAccountsTemplateResponse.class)}) - public String template(@QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, @QueryParam("groupId") @ApiParam(value = "groupId") final Long groupId, - @QueryParam("productId") @ApiParam(value = "productId") final Long productId, - @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve Savings Account Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Requests:\n" + "\n" + "savingsaccounts/template?clientId=1\n" + + "\n" + "\n" + "savingsaccounts/template?clientId=1&productId=1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.GetSavingsAccountsTemplateResponse.class) }) + public String template(@QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @QueryParam("groupId") @ApiParam(value = "groupId") final Long groupId, + @QueryParam("productId") @ApiParam(value = "productId") final Long productId, + @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); @@ -136,13 +139,18 @@ public class SavingsAccountsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List savings applications/accounts", httpMethod = "GET", notes = "Lists savings applications/accounts\n\n" + "Example Requests:\n" + "\n" + "savingsaccounts\n" + "\n" + "\n" + "savingsaccounts?fields=name") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.GetSavingsAccountsResponse.class)}) - public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, + @ApiOperation(value = "List savings applications/accounts", httpMethod = "GET", notes = "Lists savings applications/accounts\n\n" + + "Example Requests:\n" + "\n" + "savingsaccounts\n" + "\n" + "\n" + "savingsaccounts?fields=name") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.GetSavingsAccountsResponse.class) }) + public String retrieveAll(@Context final UriInfo uriInfo, + @QueryParam("sqlSearch") @ApiParam(value = "sqlSearch") final String sqlSearch, @QueryParam("externalId") @ApiParam(value = "externalId") final String externalId, // @QueryParam("underHierarchy") final String hierarchy, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, - @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { + @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, + @QueryParam("orderBy") @ApiParam(value = "orderBy") final String orderBy, + @QueryParam("sortOrder") @ApiParam(value = "sortOrder") final String sortOrder) { this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); @@ -151,16 +159,21 @@ public class SavingsAccountsApiResource { final Page products = this.savingsAccountReadPlatformService.retrieveAll(searchParameters); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, products, - SavingsApiSetConstants.SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, products, SavingsApiSetConstants.SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS); } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Submit new savings application", httpMethod = "POST", notes = "Submits new savings application\n\n" + "Mandatory Fields: clientId or groupId, productId, submittedOnDate\n\n" + "Optional Fields: accountNo, externalId, fieldOfficerId\n\n" + "Inherited from Product (if not provided): nominalAnnualInterestRate, interestCompoundingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, allowOverdraft, overdraftLimit, withHoldTax\n\n" + "Additional Mandatory Field if Entity-Datatable Check is enabled for the entity of type Savings: datatables") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountsApiResourceSwagger.PostSavingsAccountsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.PostSavingsAccountsResponse.class)}) + @ApiOperation(value = "Submit new savings application", httpMethod = "POST", notes = "Submits new savings application\n\n" + + "Mandatory Fields: clientId or groupId, productId, submittedOnDate\n\n" + + "Optional Fields: accountNo, externalId, fieldOfficerId\n\n" + + "Inherited from Product (if not provided): nominalAnnualInterestRate, interestCompoundingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, allowOverdraft, overdraftLimit, withHoldTax\n\n" + + "Additional Mandatory Field if Entity-Datatable Check is enabled for the entity of type Savings: datatables") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountsApiResourceSwagger.PostSavingsAccountsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.PostSavingsAccountsResponse.class) }) public String submitApplication(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createSavingsAccount().withJson(apiRequestBodyAsJson).build(); @@ -187,16 +200,20 @@ public class SavingsAccountsApiResource { @Path("{accountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a savings application/account", httpMethod = "GET", notes = "Retrieves a savings application/account\n\n" + "Example Requests :\n" + "\n" + "savingsaccounts/1\n" + "\n" + "\n" + "savingsaccounts/1?associations=all") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.GetSavingsAccountsAccountIdResponse.class)}) + @ApiOperation(value = "Retrieve a savings application/account", httpMethod = "GET", notes = "Retrieves a savings application/account\n\n" + + "Example Requests :\n" + "\n" + "savingsaccounts/1\n" + "\n" + "\n" + "savingsaccounts/1?associations=all") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.GetSavingsAccountsAccountIdResponse.class) }) public String retrieveOne(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") @ApiParam(value = "staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, - @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, @Context final UriInfo uriInfo) { + @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); - if (!(is(chargeStatus, "all") || is(chargeStatus, "active") || is(chargeStatus, "inactive"))) { throw new UnrecognizedQueryParamException( - "status", chargeStatus, new Object[] { "all", "active", "inactive" }); } + if (!(is(chargeStatus, "all") || is(chargeStatus, "active") || is(chargeStatus, "inactive"))) { + throw new UnrecognizedQueryParamException("status", chargeStatus, new Object[] { "all", "active", "inactive" }); + } final SavingsAccountData savingsAccount = this.savingsAccountReadPlatformService.retrieveOne(accountId); @@ -257,10 +274,17 @@ public class SavingsAccountsApiResource { @Path("{accountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Modify a savings application | Modify savings account withhold tax applicability", httpMethod = "PUT", notes = "Modify a savings application:\n\n" + "Savings application can only be modified when in 'Submitted and pending approval' state. Once the application is approved, the details cannot be changed using this method. Specific api endpoints will be created to allow change of interest detail such as rate, compounding period, posting period etc\n\n" + "Modify savings account withhold tax applicability:\n\n"+ "Savings application's withhold tax can be modified when in 'Active' state. Once the application is activated, can modify the account withhold tax to post tax or vice-versa" +"Showing request/response for 'Modify a savings application'") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountsApiResourceSwagger.PutSavingsAccountsAccountIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.PutSavingsAccountsAccountIdResponse.class)}) - public String update(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @ApiParam(hidden = true) final String apiRequestBodyAsJson, + @ApiOperation(value = "Modify a savings application | Modify savings account withhold tax applicability", httpMethod = "PUT", notes = "Modify a savings application:\n\n" + + "Savings application can only be modified when in 'Submitted and pending approval' state. Once the application is approved, the details cannot be changed using this method. Specific api endpoints will be created to allow change of interest detail such as rate, compounding period, posting period etc\n\n" + + "Modify savings account withhold tax applicability:\n\n" + + "Savings application's withhold tax can be modified when in 'Active' state. Once the application is activated, can modify the account withhold tax to post tax or vice-versa" + + "Showing request/response for 'Modify a savings application'") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountsApiResourceSwagger.PutSavingsAccountsAccountIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.PutSavingsAccountsAccountIdResponse.class) }) + public String update(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson, @QueryParam("command") @ApiParam(value = "command") final String commandParam) { if (is(commandParam, "updateWithHoldTax")) { @@ -282,17 +306,22 @@ public class SavingsAccountsApiResource { @Path("/gsim/{parentAccountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - /* public String updateGsim(@PathParam("parentAccountId") final Long parentAccountId, final String apiRequestBodyAsJson, - @QueryParam("command") final String commandParam) {*/ - public String updateGsim(@PathParam("parentAccountId") final Long parentAccountId, final String apiRequestBodyAsJson) - { + /* + * public String updateGsim(@PathParam("parentAccountId") final Long + * parentAccountId, final String apiRequestBodyAsJson, + * + * @QueryParam("command") final String commandParam) { + */ + public String updateGsim(@PathParam("parentAccountId") final Long parentAccountId, final String apiRequestBodyAsJson) { - /* if (is(commandParam, "updateWithHoldTax")) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson).updateWithHoldTax(accountId) - .build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - }*/ + /* + * if (is(commandParam, "updateWithHoldTax")) { final CommandWrapper + * commandRequest = new + * CommandWrapperBuilder().withJson(apiRequestBodyAsJson). + * updateWithHoldTax(accountId) .build(); final CommandProcessingResult + * result = this.commandsSourceWritePlatformService.logCommandSource( + * commandRequest); return this.toApiJsonSerializer.serialize(result); } + */ final CommandWrapper commandRequest = new CommandWrapperBuilder().updateGSIMAccount(parentAccountId).withJson(apiRequestBodyAsJson) .build(); @@ -301,12 +330,13 @@ public class SavingsAccountsApiResource { return this.toApiJsonSerializer.serialize(result); } + @POST @Path("/gsimcommands/{parentAccountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String handleGSIMCommands(@PathParam("parentAccountId") final Long parentAccountId, @QueryParam("command") final String commandParam, - final String apiRequestBodyAsJson) { + public String handleGSIMCommands(@PathParam("parentAccountId") final Long parentAccountId, + @QueryParam("command") final String commandParam, final String apiRequestBodyAsJson) { String jsonApiRequest = apiRequestBodyAsJson; if (StringUtils.isBlank(jsonApiRequest)) { @@ -345,11 +375,12 @@ public class SavingsAccountsApiResource { result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); } if (result == null) { - throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { "reject", "withdrawnByApplicant", "approve", - "undoapproval", "activate", "calculateInterest", "postInterest", "close", "assignSavingsOfficer", - "unassignSavingsOfficer", SavingsApiConstants.COMMAND_BLOCK_DEBIT, SavingsApiConstants.COMMAND_UNBLOCK_DEBIT, - SavingsApiConstants.COMMAND_BLOCK_CREDIT, SavingsApiConstants.COMMAND_UNBLOCK_CREDIT, - SavingsApiConstants.COMMAND_BLOCK_ACCOUNT, SavingsApiConstants.COMMAND_UNBLOCK_ACCOUNT }); + throw new UnrecognizedQueryParamException("command", commandParam, + new Object[] { "reject", "withdrawnByApplicant", "approve", "undoapproval", "activate", "calculateInterest", + "postInterest", "close", "assignSavingsOfficer", "unassignSavingsOfficer", + SavingsApiConstants.COMMAND_BLOCK_DEBIT, SavingsApiConstants.COMMAND_UNBLOCK_DEBIT, + SavingsApiConstants.COMMAND_BLOCK_CREDIT, SavingsApiConstants.COMMAND_UNBLOCK_CREDIT, + SavingsApiConstants.COMMAND_BLOCK_ACCOUNT, SavingsApiConstants.COMMAND_UNBLOCK_ACCOUNT }); } return this.toApiJsonSerializer.serialize(result); @@ -359,11 +390,45 @@ public class SavingsAccountsApiResource { @Path("{accountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Approve savings application | Undo approval savings application | Assign Savings Officer | Unassign Savings Officer | Reject savings application | Withdraw savings application | Activate a savings account | Close a savings account | Calculate Interest on Savings Account | Post Interest on Savings Account | Block Savings Account | Unblock Savings Account | Block Savings Account Credit transactions | Unblock Savings Account Credit transactions | Block Savings Account Debit transactions | Unblock Savings Account debit transactions", httpMethod = "POST", notes = "Approve savings application:\n\n" + "Approves savings application so long as its in 'Submitted and pending approval' state.\n\n" + "Undo approval savings application:\n\n" + "Will move 'approved' savings application back to 'Submitted and pending approval' state.\n\n" + "Assign Savings Officer:\n\n" + "Allows you to assign Savings Officer for existing Savings Account.\n\n" + "Unassign Savings Officer:\n\n" + "Allows you to unassign the Savings Officer.\n\n" + "Reject savings application:\n\n" + "Rejects savings application so long as its in 'Submitted and pending approval' state.\n\n" + "Withdraw savings application:\n\n" + "Used when an applicant withdraws from the savings application. It must be in 'Submitted and pending approval' state.\n\n" + "Activate a savings account:\n\n" + "Results in an approved savings application being converted into an 'active' savings account.\n\n" + "Close a savings account:\n\n" + "Results in an Activated savings application being converted into an 'closed' savings account.\n" + "\n" + "closedOnDate is closure date of savings account\n" + "\n" + "withdrawBalance is a boolean value, true value of this field performs a withdrawal transaction with account's running balance.\n\n" + "Mandatory Fields: dateFormat,locale,closedOnDate\n\n" + "Optional Fields: note, withdrawBalance, paymentTypeId, accountNumber, checkNumber, routingCode, receiptNumber, bankNumber\n\n" + "Calculate Interest on Savings Account:\n\n" + "Calculates interest earned on a savings account based on todays date. It does not attempt to post or credit the interest on the account. That is responsibility of the Post Interest API that will likely be called by overnight process.\n\n" + "Post Interest on Savings Account:\n\n" + "Calculates and Posts interest earned on a savings account based on today's date and whether an interest posting or crediting event is due.\n\n" + "Block Savings Account:\n\n" + "Blocks Savings account from all types of credit and debit transactions\n\n" + "Unblock Savings Account:\n\n" + "Unblock a blocked account. On unblocking account, user can perform debit and credit transactions\n\n" + "Block Savings Account Credit transactions:\n\n" + "Savings account will be blocked from all types of credit transactions.\n\n" + "Unblock Savings Account Credit transactions:\n\n" + "It unblocks the Saving account's credit operations. Now all types of credits can be transacted to Savings account\n\n" + "Block Savings Account Debit transactions:\n\n" + "All types of debit operations from Savings account wil be blocked\n\n" + "Unblock Savings Account debit transactions:\n\n" + "It unblocks the Saving account's debit operations. Now all types of debits can be transacted from Savings account\n\n" + "Showing request/response for 'Unassign Savings Officer'") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountsApiResourceSwagger.PostSavingsAccountsAccountIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.PostSavingsAccountsAccountIdResponse.class)}) - public String handleCommands(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Approve savings application | Undo approval savings application | Assign Savings Officer | Unassign Savings Officer | Reject savings application | Withdraw savings application | Activate a savings account | Close a savings account | Calculate Interest on Savings Account | Post Interest on Savings Account | Block Savings Account | Unblock Savings Account | Block Savings Account Credit transactions | Unblock Savings Account Credit transactions | Block Savings Account Debit transactions | Unblock Savings Account debit transactions", httpMethod = "POST", notes = "Approve savings application:\n\n" + + "Approves savings application so long as its in 'Submitted and pending approval' state.\n\n" + + "Undo approval savings application:\n\n" + + "Will move 'approved' savings application back to 'Submitted and pending approval' state.\n\n" + "Assign Savings Officer:\n\n" + + "Allows you to assign Savings Officer for existing Savings Account.\n\n" + "Unassign Savings Officer:\n\n" + + "Allows you to unassign the Savings Officer.\n\n" + "Reject savings application:\n\n" + + "Rejects savings application so long as its in 'Submitted and pending approval' state.\n\n" + + "Withdraw savings application:\n\n" + + "Used when an applicant withdraws from the savings application. It must be in 'Submitted and pending approval' state.\n\n" + + "Activate a savings account:\n\n" + + "Results in an approved savings application being converted into an 'active' savings account.\n\n" + + "Close a savings account:\n\n" + + "Results in an Activated savings application being converted into an 'closed' savings account.\n" + "\n" + + "closedOnDate is closure date of savings account\n" + "\n" + + "withdrawBalance is a boolean value, true value of this field performs a withdrawal transaction with account's running balance.\n\n" + + "Mandatory Fields: dateFormat,locale,closedOnDate\n\n" + + "Optional Fields: note, withdrawBalance, paymentTypeId, accountNumber, checkNumber, routingCode, receiptNumber, bankNumber\n\n" + + "Calculate Interest on Savings Account:\n\n" + + "Calculates interest earned on a savings account based on todays date. It does not attempt to post or credit the interest on the account. That is responsibility of the Post Interest API that will likely be called by overnight process.\n\n" + + "Post Interest on Savings Account:\n\n" + + "Calculates and Posts interest earned on a savings account based on today's date and whether an interest posting or crediting event is due.\n\n" + + "Block Savings Account:\n\n" + "Blocks Savings account from all types of credit and debit transactions\n\n" + + "Unblock Savings Account:\n\n" + + "Unblock a blocked account. On unblocking account, user can perform debit and credit transactions\n\n" + + "Block Savings Account Credit transactions:\n\n" + + "Savings account will be blocked from all types of credit transactions.\n\n" + + "Unblock Savings Account Credit transactions:\n\n" + + "It unblocks the Saving account's credit operations. Now all types of credits can be transacted to Savings account\n\n" + + "Block Savings Account Debit transactions:\n\n" + "All types of debit operations from Savings account wil be blocked\n\n" + + "Unblock Savings Account debit transactions:\n\n" + + "It unblocks the Saving account's debit operations. Now all types of debits can be transacted from Savings account\n\n" + + "Showing request/response for 'Unassign Savings Officer'") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsAccountsApiResourceSwagger.PostSavingsAccountsAccountIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.PostSavingsAccountsAccountIdResponse.class) }) + public String handleCommands(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { String jsonApiRequest = apiRequestBodyAsJson; if (StringUtils.isBlank(jsonApiRequest)) { @@ -430,11 +495,12 @@ public class SavingsAccountsApiResource { if (result == null) { // - throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { "reject", "withdrawnByApplicant", "approve", - "undoapproval", "activate", "calculateInterest", "postInterest", "close", "assignSavingsOfficer", - "unassignSavingsOfficer", SavingsApiConstants.COMMAND_BLOCK_DEBIT, SavingsApiConstants.COMMAND_UNBLOCK_DEBIT, - SavingsApiConstants.COMMAND_BLOCK_CREDIT, SavingsApiConstants.COMMAND_UNBLOCK_CREDIT, - SavingsApiConstants.COMMAND_BLOCK_ACCOUNT, SavingsApiConstants.COMMAND_UNBLOCK_ACCOUNT }); + throw new UnrecognizedQueryParamException("command", commandParam, + new Object[] { "reject", "withdrawnByApplicant", "approve", "undoapproval", "activate", "calculateInterest", + "postInterest", "close", "assignSavingsOfficer", "unassignSavingsOfficer", + SavingsApiConstants.COMMAND_BLOCK_DEBIT, SavingsApiConstants.COMMAND_UNBLOCK_DEBIT, + SavingsApiConstants.COMMAND_BLOCK_CREDIT, SavingsApiConstants.COMMAND_UNBLOCK_CREDIT, + SavingsApiConstants.COMMAND_BLOCK_ACCOUNT, SavingsApiConstants.COMMAND_UNBLOCK_ACCOUNT }); } return this.toApiJsonSerializer.serialize(result); @@ -449,7 +515,8 @@ public class SavingsAccountsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a savings application", httpMethod = "DELETE", notes = "At present we support hard delete of savings application so long as its in 'Submitted and pending approval' state. One the application is moves past this state, it is not possible to do a 'hard' delete of the application or the account. An API endpoint will be added to close/de-activate the savings account.") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.DeleteSavingsAccountsAccountIdResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsAccountsApiResourceSwagger.DeleteSavingsAccountsAccountIdResponse.class) }) public String delete(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteSavingsAccount(accountId).build(); @@ -462,38 +529,38 @@ public class SavingsAccountsApiResource { @GET @Path("downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getSavingsTemplate(@QueryParam("officeId")final Long officeId, - @QueryParam("staffId")final Long staffId,@QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.SAVINGS_ACCOUNT.toString(),officeId, staffId,dateFormat); + public Response getSavingsTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("staffId") final Long staffId, + @QueryParam("dateFormat") final String dateFormat) { + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.SAVINGS_ACCOUNT.toString(), officeId, staffId, dateFormat); } @POST @Path("uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postSavingsTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, - @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId = this. bulkImportWorkbookService.importWorkbook(GlobalEntityType.SAVINGS_ACCOUNT.toString(), uploadedInputStream, - fileDetail, locale, dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.SAVINGS_ACCOUNT.toString(), + uploadedInputStream, fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } @GET @Path("transactions/downloadtemplate") @Produces("application/vnd.ms-excel") - public Response getSavingsTransactionTemplate(@QueryParam("officeId")final Long officeId,@QueryParam("dateFormat") final String dateFormat) { - return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.SAVINGS_TRANSACTIONS.toString(),officeId, null,dateFormat); + public Response getSavingsTransactionTemplate(@QueryParam("officeId") final Long officeId, + @QueryParam("dateFormat") final String dateFormat) { + return bulkImportWorkbookPopulatorService.getTemplate(GlobalEntityType.SAVINGS_TRANSACTIONS.toString(), officeId, null, dateFormat); } @POST @Path("transactions/uploadtemplate") @Consumes(MediaType.MULTIPART_FORM_DATA) public String postSavingsTransactionTemplate(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @FormDataParam("locale") final String locale, @FormDataParam("dateFormat") final String dateFormat){ - final Long importDocumentId = this. bulkImportWorkbookService.importWorkbook(GlobalEntityType.SAVINGS_TRANSACTIONS.toString(), uploadedInputStream, - fileDetail,locale,dateFormat); + @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("locale") final String locale, + @FormDataParam("dateFormat") final String dateFormat) { + final Long importDocumentId = this.bulkImportWorkbookService.importWorkbook(GlobalEntityType.SAVINGS_TRANSACTIONS.toString(), + uploadedInputStream, fileDetail, locale, dateFormat); return this.toApiJsonSerializer.serialize(importDocumentId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountsApiResourceSwagger.java index 62e913949..3ee435f6f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsAccountsApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/29/17. */ final class SavingsAccountsApiResourceSwagger { - private SavingsAccountsApiResourceSwagger() { - } + + private SavingsAccountsApiResourceSwagger() {} @ApiModel(value = "GetSavingsAccountsTemplateResponse") public final static class GetSavingsAccountsTemplateResponse { - private GetSavingsAccountsTemplateResponse() { - } + + private GetSavingsAccountsTemplateResponse() {} final class GetSavingsProductOptions { - private GetSavingsProductOptions() { - } + + private GetSavingsProductOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -54,16 +54,16 @@ final class SavingsAccountsApiResourceSwagger { @ApiModel(value = "GetSavingsAccountsResponse") public final static class GetSavingsAccountsResponse { - private GetSavingsAccountsResponse() { - } + + private GetSavingsAccountsResponse() {} final class GetSavingsPageItems { - private GetSavingsPageItems() { - } + + private GetSavingsPageItems() {} final class GetSavingsStatus { - private GetSavingsStatus() { - } + + private GetSavingsStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -87,16 +87,16 @@ final class SavingsAccountsApiResourceSwagger { } final class GetSavingsTimeline { - private GetSavingsTimeline() { - } + + private GetSavingsTimeline() {} @ApiModelProperty(example = "[2013, 3, 1]") public LocalDate submittedOnDate; } final class GetSavingsCurrency { - private GetSavingsCurrency() { - } + + private GetSavingsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -113,8 +113,8 @@ final class SavingsAccountsApiResourceSwagger { } final class GetSavingsInterestCompoundingPeriodType { - private GetSavingsInterestCompoundingPeriodType() { - } + + private GetSavingsInterestCompoundingPeriodType() {} @ApiModelProperty(example = "1") public Integer id; @@ -125,8 +125,8 @@ final class SavingsAccountsApiResourceSwagger { } final class GetSavingsInterestPostingPeriodType { - private GetSavingsInterestPostingPeriodType() { - } + + private GetSavingsInterestPostingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -137,8 +137,8 @@ final class SavingsAccountsApiResourceSwagger { } final class GetSavingsInterestCalculationType { - private GetSavingsInterestCalculationType() { - } + + private GetSavingsInterestCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -149,8 +149,8 @@ final class SavingsAccountsApiResourceSwagger { } final class GetSavingsInterestCalculationDaysInYearType { - private GetSavingsInterestCalculationDaysInYearType() { - } + + private GetSavingsInterestCalculationDaysInYearType() {} @ApiModelProperty(example = "365") public Integer id; @@ -161,8 +161,8 @@ final class SavingsAccountsApiResourceSwagger { } final class GetSavingsSummary { - private GetSavingsSummary() { - } + + private GetSavingsSummary() {} public GetSavingsCurrency currency; @ApiModelProperty(example = "0") @@ -202,8 +202,8 @@ final class SavingsAccountsApiResourceSwagger { @ApiModel(value = "PostSavingsAccountsRequest") public final static class PostSavingsAccountsRequest { - private PostSavingsAccountsRequest() { - } + + private PostSavingsAccountsRequest() {} @ApiModelProperty(example = "1") public Integer clientId; @@ -219,8 +219,8 @@ final class SavingsAccountsApiResourceSwagger { @ApiModel(value = "PostSavingsAccountsResponse") public final static class PostSavingsAccountsResponse { - private PostSavingsAccountsResponse() { - } + + private PostSavingsAccountsResponse() {} @ApiModelProperty(example = "2") public Integer officeId; @@ -234,12 +234,12 @@ final class SavingsAccountsApiResourceSwagger { @ApiModel(value = "GetSavingsAccountsAccountIdResponse") public final static class GetSavingsAccountsAccountIdResponse { - private GetSavingsAccountsAccountIdResponse() { - } + + private GetSavingsAccountsAccountIdResponse() {} final class GetSavingsAccountsSummary { - private GetSavingsAccountsSummary() { - } + + private GetSavingsAccountsSummary() {} public GetSavingsAccountsResponse.GetSavingsPageItems.GetSavingsCurrency currency; @ApiModelProperty(example = "0") @@ -276,8 +276,8 @@ final class SavingsAccountsApiResourceSwagger { @ApiModel(value = "PutSavingsAccountsAccountIdRequest") public final static class PutSavingsAccountsAccountIdRequest { - private PutSavingsAccountsAccountIdRequest() { - } + + private PutSavingsAccountsAccountIdRequest() {} @ApiModelProperty(example = "en") public String locale; @@ -287,12 +287,12 @@ final class SavingsAccountsApiResourceSwagger { @ApiModel(value = "PutSavingsAccountsAccountIdResponse") public final static class PutSavingsAccountsAccountIdResponse { - private PutSavingsAccountsAccountIdResponse() { - } + + private PutSavingsAccountsAccountIdResponse() {} final class PutSavingsAccountsChanges { - private PutSavingsAccountsChanges() { - } + + private PutSavingsAccountsChanges() {} @ApiModelProperty(example = "5.9999999999") public Double nominalAnnualInterestRate; @@ -313,8 +313,8 @@ final class SavingsAccountsApiResourceSwagger { @ApiModel(value = "PostSavingsAccountsAccountIdRequest") public final static class PostSavingsAccountsAccountIdRequest { - private PostSavingsAccountsAccountIdRequest() { - } + + private PostSavingsAccountsAccountIdRequest() {} @ApiModelProperty(example = "dd MMMM yyyy") public String dateFormat; @@ -326,12 +326,12 @@ final class SavingsAccountsApiResourceSwagger { @ApiModel(value = "PostSavingsAccountsAccountIdResponse") public final static class PostSavingsAccountsAccountIdResponse { - private PostSavingsAccountsAccountIdResponse() { - } + + private PostSavingsAccountsAccountIdResponse() {} final class PostSavingsAccountsAccountIdChanges { - private PostSavingsAccountsAccountIdChanges() { - } + + private PostSavingsAccountsAccountIdChanges() {} } @ApiModelProperty(example = "2") @@ -345,8 +345,8 @@ final class SavingsAccountsApiResourceSwagger { @ApiModel(value = "DeleteSavingsAccountsAccountIdResponse") public final static class DeleteSavingsAccountsAccountIdResponse { - private DeleteSavingsAccountsAccountIdResponse() { - } + + private DeleteSavingsAccountsAccountIdResponse() {} @ApiModelProperty(example = "1") public Integer officeId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsApiSetConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsApiSetConstants.java index 00d0439ce..78fb5ef47 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsApiSetConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsApiSetConstants.java @@ -32,19 +32,17 @@ public class SavingsApiSetConstants extends SavingsApiConstants { * {@link SavingsProductData}. Where possible, we try to get response * parameters to match those of request parameters. */ - protected static final Set SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - idParamName, nameParamName, shortNameParamName, descriptionParamName, "currency", - digitsAfterDecimalParamName, inMultiplesOfParamName, nominalAnnualInterestRateParamName, - interestCompoundingPeriodTypeParamName, interestPostingPeriodTypeParamName, - interestCalculationTypeParamName, interestCalculationDaysInYearTypeParamName, - minRequiredOpeningBalanceParamName, lockinPeriodFrequencyParamName, lockinPeriodFrequencyTypeParamName, - withdrawalFeeAmountParamName, withdrawalFeeTypeParamName, withdrawalFeeForTransfersParamName, - feeAmountParamName, feeOnMonthDayParamName, "currencyOptions", "interestCompoundingPeriodTypeOptions", - "interestPostingPeriodTypeOptions", "interestCalculationTypeOptions", - "interestCalculationDaysInYearTypeOptions", "lockinPeriodFrequencyTypeOptions", "withdrawalFeeTypeOptions", - nominalAnnualInterestRateOverdraftParamName, minOverdraftForInterestCalculationParamName, - withHoldTaxParamName, taxGroupIdParamName, isDormancyTrackingActiveParamName, daysToInactiveParamName, - daysToDormancyParamName, daysToInactiveParamName)); + protected static final Set SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(idParamName, nameParamName, shortNameParamName, descriptionParamName, "currency", digitsAfterDecimalParamName, + inMultiplesOfParamName, nominalAnnualInterestRateParamName, interestCompoundingPeriodTypeParamName, + interestPostingPeriodTypeParamName, interestCalculationTypeParamName, interestCalculationDaysInYearTypeParamName, + minRequiredOpeningBalanceParamName, lockinPeriodFrequencyParamName, lockinPeriodFrequencyTypeParamName, + withdrawalFeeAmountParamName, withdrawalFeeTypeParamName, withdrawalFeeForTransfersParamName, feeAmountParamName, + feeOnMonthDayParamName, "currencyOptions", "interestCompoundingPeriodTypeOptions", "interestPostingPeriodTypeOptions", + "interestCalculationTypeOptions", "interestCalculationDaysInYearTypeOptions", "lockinPeriodFrequencyTypeOptions", + "withdrawalFeeTypeOptions", nominalAnnualInterestRateOverdraftParamName, minOverdraftForInterestCalculationParamName, + withHoldTaxParamName, taxGroupIdParamName, isDormancyTrackingActiveParamName, daysToInactiveParamName, + daysToDormancyParamName, daysToInactiveParamName)); /** * These parameters will match the class level parameters of @@ -53,31 +51,27 @@ public class SavingsApiSetConstants extends SavingsApiConstants { */ protected static final Set SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, - accountNoParamName, externalIdParamName, statusParamName, activatedOnDateParamName, staffIdParamName, - clientIdParamName, "clientName", groupIdParamName, "groupName", "savingsProductId", "savingsProductName", - "currency", nominalAnnualInterestRateParamName, interestCompoundingPeriodTypeParamName, - interestCalculationTypeParamName, interestCalculationDaysInYearTypeParamName, - minRequiredOpeningBalanceParamName, lockinPeriodFrequencyParamName, lockinPeriodFrequencyTypeParamName, - withdrawalFeeAmountParamName, withdrawalFeeTypeParamName, withdrawalFeeForTransfersParamName, - feeAmountParamName, feeOnMonthDayParamName, "summary", "transactions", "productOptions", - "interestCompoundingPeriodTypeOptions", "interestPostingPeriodTypeOptions", - "interestCalculationTypeOptions", "interestCalculationDaysInYearTypeOptions", - "lockinPeriodFrequencyTypeOptions", "withdrawalFeeTypeOptions", "withdrawalFee", "annualFee", - onHoldFundsParamName, nominalAnnualInterestRateOverdraftParamName, - minOverdraftForInterestCalculationParamName, datatables, savingsAmountOnHold)); + accountNoParamName, externalIdParamName, statusParamName, activatedOnDateParamName, staffIdParamName, clientIdParamName, + "clientName", groupIdParamName, "groupName", "savingsProductId", "savingsProductName", "currency", + nominalAnnualInterestRateParamName, interestCompoundingPeriodTypeParamName, interestCalculationTypeParamName, + interestCalculationDaysInYearTypeParamName, minRequiredOpeningBalanceParamName, lockinPeriodFrequencyParamName, + lockinPeriodFrequencyTypeParamName, withdrawalFeeAmountParamName, withdrawalFeeTypeParamName, + withdrawalFeeForTransfersParamName, feeAmountParamName, feeOnMonthDayParamName, "summary", "transactions", "productOptions", + "interestCompoundingPeriodTypeOptions", "interestPostingPeriodTypeOptions", "interestCalculationTypeOptions", + "interestCalculationDaysInYearTypeOptions", "lockinPeriodFrequencyTypeOptions", "withdrawalFeeTypeOptions", "withdrawalFee", + "annualFee", onHoldFundsParamName, nominalAnnualInterestRateOverdraftParamName, minOverdraftForInterestCalculationParamName, + datatables, savingsAmountOnHold)); protected static final Set SAVINGS_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(idParamName, "accountId", accountNoParamName, "currency", "amount", dateParamName, - paymentDetailDataParamName, runningBalanceParamName, reversedParamName, noteParamName)); + Arrays.asList(idParamName, "accountId", accountNoParamName, "currency", "amount", dateParamName, paymentDetailDataParamName, + runningBalanceParamName, reversedParamName, noteParamName)); protected static final Set SAVINGS_ACCOUNT_CHARGES_RESPONSE_DATA_PARAMETERS = new HashSet<>( Arrays.asList(chargeIdParamName, savingsAccountChargeIdParamName, chargeNameParamName, penaltyParamName, chargeTimeTypeParamName, dueAsOfDateParamName, chargeCalculationTypeParamName, percentageParamName, - amountPercentageAppliedToParamName, currencyParamName, amountWaivedParamName, - amountWrittenOffParamName, amountOutstandingParamName, amountOrPercentageParamName, amountParamName, - amountPaidParamName, chargeOptionsParamName)); + amountPercentageAppliedToParamName, currencyParamName, amountWaivedParamName, amountWrittenOffParamName, + amountOutstandingParamName, amountOrPercentageParamName, amountParamName, amountPaidParamName, chargeOptionsParamName)); - protected static final Set SAVINGS_ACCOUNT_ON_HOLD_RESPONSE_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(idParamName, amountParamName, onHoldTransactionTypeParamName, onHoldTransactionDateParamName, - onHoldReversedParamName)); + protected static final Set SAVINGS_ACCOUNT_ON_HOLD_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(idParamName, + amountParamName, onHoldTransactionTypeParamName, onHoldTransactionDateParamName, onHoldReversedParamName)); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsProductsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsProductsApiResource.java index d088239de..d9dbc389f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsProductsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsProductsApiResource.java @@ -83,10 +83,10 @@ import org.springframework.util.CollectionUtils; @Path("/savingsproducts") @Component @Scope("singleton") -@Api(tags = {"Savings Product"}) -@SwaggerDefinition(tags = { - @Tag(name = "Savings Product", description = "An MFIs savings product offerings are modeled using this API." + "\n" + "When creating savings accounts, the details from the savings product are used to auto fill details of the savings account application process.") -}) +@Api(tags = { "Savings Product" }) +@SwaggerDefinition(tags = { @Tag(name = "Savings Product", description = "An MFIs savings product offerings are modeled using this API." + + "\n" + + "When creating savings accounts, the details from the savings product are used to auto fill details of the savings account application process.") }) public class SavingsProductsApiResource { private final SavingsProductReadPlatformService savingProductReadPlatformService; @@ -130,9 +130,14 @@ public class SavingsProductsApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a Savings Product", httpMethod = "POST", notes = "Creates a Savings Product\n\n" + "Mandatory Fields: name, shortName, description, currencyCode, digitsAfterDecimal,inMultiplesOf, nominalAnnualInterestRate, interestCompoundingPeriodType, interestCalculationType, interestCalculationDaysInYearType,accountingRule\n\n" + "Mandatory Fields for Cash based accounting (accountingRule = 2): savingsReferenceAccountId, savingsControlAccountId, interestOnSavingsAccountId, incomeFromFeeAccountId, transfersInSuspenseAccountId, incomeFromPenaltyAccountId\n\n" + "Optional Fields: minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, paymentChannelToFundSourceMappings, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, charges, allowOverdraft, overdraftLimit, minBalanceForInterestCalculation,withHoldTax,taxGroupId") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsProductsApiResourceSwagger.PostSavingsProductsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsProductsApiResourceSwagger.PostSavingsProductsResponse.class)}) + @ApiOperation(value = "Create a Savings Product", httpMethod = "POST", notes = "Creates a Savings Product\n\n" + + "Mandatory Fields: name, shortName, description, currencyCode, digitsAfterDecimal,inMultiplesOf, nominalAnnualInterestRate, interestCompoundingPeriodType, interestCalculationType, interestCalculationDaysInYearType,accountingRule\n\n" + + "Mandatory Fields for Cash based accounting (accountingRule = 2): savingsReferenceAccountId, savingsControlAccountId, interestOnSavingsAccountId, incomeFromFeeAccountId, transfersInSuspenseAccountId, incomeFromPenaltyAccountId\n\n" + + "Optional Fields: minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, paymentChannelToFundSourceMappings, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, charges, allowOverdraft, overdraftLimit, minBalanceForInterestCalculation,withHoldTax,taxGroupId") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsProductsApiResourceSwagger.PostSavingsProductsRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsProductsApiResourceSwagger.PostSavingsProductsResponse.class) }) public String create(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createSavingProduct().withJson(apiRequestBodyAsJson).build(); @@ -147,9 +152,12 @@ public class SavingsProductsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Savings Product", httpMethod = "PUT", notes = "Updates a Savings Product") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsProductsApiResourceSwagger.PutSavingsProductsProductIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsProductsApiResourceSwagger.PutSavingsProductsProductIdResponse.class)}) - public String update(@PathParam("productId") @ApiParam(value = "productId") final Long productId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SavingsProductsApiResourceSwagger.PutSavingsProductsProductIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsProductsApiResourceSwagger.PutSavingsProductsProductIdResponse.class) }) + public String update(@PathParam("productId") @ApiParam(value = "productId") final Long productId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateSavingProduct(productId).withJson(apiRequestBodyAsJson) .build(); @@ -163,8 +171,10 @@ public class SavingsProductsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Savings Products", httpMethod = "GET", notes = "Lists Savings Products\n\n" + "Example Requests:\n" + "\n" + "savingsproducts\n" + "\n" + "savingsproducts?fields=name") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SavingsProductsApiResourceSwagger.GetSavingsProductsResponse.class)}) + @ApiOperation(value = "List Savings Products", httpMethod = "GET", notes = "Lists Savings Products\n\n" + "Example Requests:\n" + "\n" + + "savingsproducts\n" + "\n" + "savingsproducts?fields=name") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SavingsProductsApiResourceSwagger.GetSavingsProductsResponse.class) }) public String retrieveAll(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); @@ -172,16 +182,18 @@ public class SavingsProductsApiResource { final Collection products = this.savingProductReadPlatformService.retrieveAll(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, products, - SavingsApiSetConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, products, SavingsApiSetConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); } @GET @Path("{productId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Savings Product", httpMethod = "GET", notes = "Retrieves a Savings Product\n\n" + "Example Requests:\n" + "\n" + "savingsproducts/1\n" + "\n" + "savingsproducts/1?template=true\n" + "\n" + "savingsproducts/1?fields=name,description") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsProductsApiResourceSwagger.GetSavingsProductsProductIdResponse.class)}) + @ApiOperation(value = "Retrieve a Savings Product", httpMethod = "GET", notes = "Retrieves a Savings Product\n\n" + + "Example Requests:\n" + "\n" + "savingsproducts/1\n" + "\n" + "savingsproducts/1?template=true\n" + "\n" + + "savingsproducts/1?fields=name,description") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsProductsApiResourceSwagger.GetSavingsProductsProductIdResponse.class) }) public String retrieveOne(@PathParam("productId") @ApiParam(value = "productId") final Long productId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); @@ -219,8 +231,10 @@ public class SavingsProductsApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Savings Product Template", httpMethod = "GET", notes = "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "savingsproducts/template") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsProductsApiResourceSwagger.GetSavingsProductsTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Savings Product Template", httpMethod = "GET", notes = "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n" + "Example Request:\n" + "\n" + "savingsproducts/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsProductsApiResourceSwagger.GetSavingsProductsTemplateResponse.class) }) public String retrieveTemplate(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); @@ -228,8 +242,7 @@ public class SavingsProductsApiResource { final SavingsProductData savingProduct = handleTemplateRelatedData(null); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, savingProduct, - SavingsApiSetConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, savingProduct, SavingsApiSetConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); } private SavingsProductData handleTemplateRelatedData(final SavingsProductData savingsProduct) { @@ -308,7 +321,8 @@ public class SavingsProductsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Delete a Savings Product", httpMethod = "DELETE", notes = "Deletes a Savings Product") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SavingsProductsApiResourceSwagger.DeleteSavingsProductsProductIdResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SavingsProductsApiResourceSwagger.DeleteSavingsProductsProductIdResponse.class) }) public String delete(@PathParam("productId") @ApiParam(value = "productId") final Long productId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteSavingProduct(productId).build(); @@ -318,4 +332,4 @@ public class SavingsProductsApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsProductsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsProductsApiResourceSwagger.java index 960075318..76bc2e563 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsProductsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/api/SavingsProductsApiResourceSwagger.java @@ -28,17 +28,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/31/17. */ final class SavingsProductsApiResourceSwagger { - private SavingsProductsApiResourceSwagger() { - } + + private SavingsProductsApiResourceSwagger() {} @ApiModel(value = "PostSavingsProductsRequest") public final static class PostSavingsProductsRequest { - private PostSavingsProductsRequest() { - } + + private PostSavingsProductsRequest() {} final class PostSavingsCharges { - private PostSavingsCharges() { - } + + private PostSavingsCharges() {} @ApiModelProperty(example = "1") public Integer id; @@ -75,8 +75,8 @@ final class SavingsProductsApiResourceSwagger { @ApiModel(value = "PostSavingsProductsResponse") public final static class PostSavingsProductsResponse { - private PostSavingsProductsResponse() { - } + + private PostSavingsProductsResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -84,8 +84,8 @@ final class SavingsProductsApiResourceSwagger { @ApiModel(value = "PutSavingsProductsProductIdRequest") public final static class PutSavingsProductsProductIdRequest { - private PutSavingsProductsProductIdRequest() { - } + + private PutSavingsProductsProductIdRequest() {} @ApiModelProperty(example = "Passbook Savings Lite.") public String description; @@ -97,12 +97,12 @@ final class SavingsProductsApiResourceSwagger { @ApiModel(value = "PutSavingsProductsProductIdResponse") public final static class PutSavingsProductsProductIdResponse { - private PutSavingsProductsProductIdResponse() { - } + + private PutSavingsProductsProductIdResponse() {} final class PutSavingsChanges { - private PutSavingsChanges() { - } + + private PutSavingsChanges() {} @ApiModelProperty(example = "Passbook Savings Lite.") public String description; @@ -119,12 +119,12 @@ final class SavingsProductsApiResourceSwagger { @ApiModel(value = "GetSavingsProductsResponse") public final static class GetSavingsProductsResponse { - private GetSavingsProductsResponse() { - } + + private GetSavingsProductsResponse() {} final class GetSavingsCurrency { - private GetSavingsCurrency() { - } + + private GetSavingsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -141,8 +141,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsInterestCompoundingPeriodType { - private GetSavingsProductsInterestCompoundingPeriodType() { - } + + private GetSavingsProductsInterestCompoundingPeriodType() {} @ApiModelProperty(example = "1") public Integer id; @@ -153,8 +153,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsInterestPostingPeriodType { - private GetSavingsProductsInterestPostingPeriodType() { - } + + private GetSavingsProductsInterestPostingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -165,8 +165,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsInterestCalculationType { - private GetSavingsProductsInterestCalculationType() { - } + + private GetSavingsProductsInterestCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -177,8 +177,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsInterestCalculationDaysInYearType { - private GetSavingsProductsInterestCalculationDaysInYearType() { - } + + private GetSavingsProductsInterestCalculationDaysInYearType() {} @ApiModelProperty(example = "365") public Integer id; @@ -189,8 +189,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsAccountingRule { - private GetSavingsProductsAccountingRule() { - } + + private GetSavingsProductsAccountingRule() {} @ApiModelProperty(example = "2") public Integer id; @@ -222,16 +222,16 @@ final class SavingsProductsApiResourceSwagger { @ApiModel(value = "GetSavingsProductsProductIdResponse") public final static class GetSavingsProductsProductIdResponse { - private GetSavingsProductsProductIdResponse() { - } + + private GetSavingsProductsProductIdResponse() {} final class GetSavingsProductsAccountingMappings { - private GetSavingsProductsAccountingMappings() { - } + + private GetSavingsProductsAccountingMappings() {} final class GetSavingsProductsSavingsReferenceAccount { - private GetSavingsProductsSavingsReferenceAccount() { - } + + private GetSavingsProductsSavingsReferenceAccount() {} @ApiModelProperty(example = "12") public Integer id; @@ -242,8 +242,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsIncomeFromFeeAccount { - private GetSavingsProductsIncomeFromFeeAccount() { - } + + private GetSavingsProductsIncomeFromFeeAccount() {} @ApiModelProperty(example = "16") public Integer id; @@ -254,8 +254,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsIncomeFromPenaltyAccount { - private GetSavingsProductsIncomeFromPenaltyAccount() { - } + + private GetSavingsProductsIncomeFromPenaltyAccount() {} @ApiModelProperty(example = "17") public Integer id; @@ -266,8 +266,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsInterestOnSavingsAccount { - private GetSavingsProductsInterestOnSavingsAccount() { - } + + private GetSavingsProductsInterestOnSavingsAccount() {} @ApiModelProperty(example = "15") public Integer id; @@ -278,8 +278,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsSavingsControlAccount { - private GetSavingsProductsSavingsControlAccount() { - } + + private GetSavingsProductsSavingsControlAccount() {} @ApiModelProperty(example = "13") public Integer id; @@ -290,8 +290,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsTransfersInSuspenseAccount { - private GetSavingsProductsTransfersInSuspenseAccount() { - } + + private GetSavingsProductsTransfersInSuspenseAccount() {} @ApiModelProperty(example = "14") public Integer id; @@ -310,12 +310,12 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsPaymentChannelToFundSourceMappings { - private GetSavingsProductsPaymentChannelToFundSourceMappings() { - } + + private GetSavingsProductsPaymentChannelToFundSourceMappings() {} final class GetSavingsProductsPaymentType { - private GetSavingsProductsPaymentType() { - } + + private GetSavingsProductsPaymentType() {} @ApiModelProperty(example = "10") public Integer id; @@ -324,8 +324,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsFundSourceAccount { - private GetSavingsProductsFundSourceAccount() { - } + + private GetSavingsProductsFundSourceAccount() {} @ApiModelProperty(example = "12") public Integer id; @@ -340,12 +340,12 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsFeeToIncomeAccountMappings { - private GetSavingsProductsFeeToIncomeAccountMappings() { - } + + private GetSavingsProductsFeeToIncomeAccountMappings() {} final class GetSavingsProductsFeeToIncomeAccountMappingsCharge { - private GetSavingsProductsFeeToIncomeAccountMappingsCharge() { - } + + private GetSavingsProductsFeeToIncomeAccountMappingsCharge() {} @ApiModelProperty(example = "11") public Integer id; @@ -358,8 +358,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsFeeToIncomeAccountMappingsIncomeAccount { - private GetSavingsProductsFeeToIncomeAccountMappingsIncomeAccount() { - } + + private GetSavingsProductsFeeToIncomeAccountMappingsIncomeAccount() {} @ApiModelProperty(example = "16") public Integer id; @@ -374,12 +374,12 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsPenaltyToIncomeAccountMappings { - private GetSavingsProductsPenaltyToIncomeAccountMappings() { - } + + private GetSavingsProductsPenaltyToIncomeAccountMappings() {} final class GetSavingsProductsPenaltyToIncomeAccountMappingsCharge { - private GetSavingsProductsPenaltyToIncomeAccountMappingsCharge() { - } + + private GetSavingsProductsPenaltyToIncomeAccountMappingsCharge() {} @ApiModelProperty(example = "12") public Integer id; @@ -423,12 +423,12 @@ final class SavingsProductsApiResourceSwagger { @ApiModel(value = "GetSavingsProductsTemplateResponse") public final static class GetSavingsProductsTemplateResponse { - private GetSavingsProductsTemplateResponse() { - } + + private GetSavingsProductsTemplateResponse() {} final class GetSavingsProductsTemplateAccountingRule { - private GetSavingsProductsTemplateAccountingRule() { - } + + private GetSavingsProductsTemplateAccountingRule() {} @ApiModelProperty(example = "1") public Integer id; @@ -439,8 +439,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsLockinPeriodFrequencyTypeOptions { - private GetSavingsProductsLockinPeriodFrequencyTypeOptions() { - } + + private GetSavingsProductsLockinPeriodFrequencyTypeOptions() {} @ApiModelProperty(example = "0") public Integer id; @@ -451,8 +451,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsWithdrawalFeeTypeOptions { - private GetSavingsProductsWithdrawalFeeTypeOptions() { - } + + private GetSavingsProductsWithdrawalFeeTypeOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -463,8 +463,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsPaymentTypeOptions { - private GetSavingsProductsPaymentTypeOptions() { - } + + private GetSavingsProductsPaymentTypeOptions() {} @ApiModelProperty(example = "14") public Integer id; @@ -475,16 +475,16 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsAccountingMappingOptions { - private GetSavingsProductsAccountingMappingOptions() { - } + + private GetSavingsProductsAccountingMappingOptions() {} final class GetSavingsProductsLiabilityAccountOptions { - private GetSavingsProductsLiabilityAccountOptions() { - } + + private GetSavingsProductsLiabilityAccountOptions() {} final class GetSavingsProductsLiabilityType { - private GetSavingsProductsLiabilityType() { - } + + private GetSavingsProductsLiabilityType() {} @ApiModelProperty(example = "2") public Integer id; @@ -495,8 +495,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsLiabilityUsage { - private GetSavingsProductsLiabilityUsage() { - } + + private GetSavingsProductsLiabilityUsage() {} @ApiModelProperty(example = "1") public Integer id; @@ -507,8 +507,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsLiabilityTagId { - private GetSavingsProductsLiabilityTagId() { - } + + private GetSavingsProductsLiabilityTagId() {} @ApiModelProperty(example = "0") public Integer id; @@ -532,12 +532,12 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsAssetAccountOptions { - private GetSavingsProductsAssetAccountOptions() { - } + + private GetSavingsProductsAssetAccountOptions() {} final class GetSavingsAssetLiabilityType { - private GetSavingsAssetLiabilityType() { - } + + private GetSavingsAssetLiabilityType() {} @ApiModelProperty(example = "1") public Integer id; @@ -548,8 +548,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsAssetTagId { - private GetSavingsAssetTagId() { - } + + private GetSavingsAssetTagId() {} } @ApiModelProperty(example = "2") @@ -568,12 +568,12 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsExpenseAccountOptions { - private GetSavingsProductsExpenseAccountOptions() { - } + + private GetSavingsProductsExpenseAccountOptions() {} final class GetSavingsProductsExpenseType { - private GetSavingsProductsExpenseType() { - } + + private GetSavingsProductsExpenseType() {} @ApiModelProperty(example = "5") public Integer id; @@ -599,12 +599,12 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsIncomeAccountOptions { - private GetSavingsProductsIncomeAccountOptions() { - } + + private GetSavingsProductsIncomeAccountOptions() {} final class GetSavingsProductsIncomeType { - private GetSavingsProductsIncomeType() { - } + + private GetSavingsProductsIncomeType() {} @ApiModelProperty(example = "4") public Integer id; @@ -637,12 +637,12 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsChargeOptions { - private GetSavingsProductsChargeOptions() { - } + + private GetSavingsProductsChargeOptions() {} final class GetSavingsChargeTimeType { - private GetSavingsChargeTimeType() { - } + + private GetSavingsChargeTimeType() {} @ApiModelProperty(example = "chargeTimeType.specifiedDueDate") public String code; @@ -653,8 +653,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsProductsChargeAppliesTo { - private GetSavingsProductsChargeAppliesTo() { - } + + private GetSavingsProductsChargeAppliesTo() {} @ApiModelProperty(example = "chargeAppliesTo.savings") public String code; @@ -665,8 +665,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsChargeCalculationType { - private GetSavingsChargeCalculationType() { - } + + private GetSavingsChargeCalculationType() {} @ApiModelProperty(example = "chargeCalculationType.flat") public String code; @@ -677,8 +677,8 @@ final class SavingsProductsApiResourceSwagger { } final class GetSavingsChargePaymentMode { - private GetSavingsChargePaymentMode() { - } + + private GetSavingsChargePaymentMode() {} @ApiModelProperty(example = "chargepaymentmode.regular") public String code; @@ -726,8 +726,8 @@ final class SavingsProductsApiResourceSwagger { @ApiModel(value = "DeleteSavingsProductsProductIdResponse") public final static class DeleteSavingsProductsProductIdResponse { - private DeleteSavingsProductsProductIdResponse() { - } + + private DeleteSavingsProductsProductIdResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/ClosingOfSavingsAccounts.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/ClosingOfSavingsAccounts.java index 68dba70f7..40e7cbff7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/ClosingOfSavingsAccounts.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/ClosingOfSavingsAccounts.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.portfolio.savings.data; - import org.joda.time.LocalDate; public class ClosingOfSavingsAccounts { @@ -41,21 +40,19 @@ public class ClosingOfSavingsAccounts { private final String note; - public static ClosingOfSavingsAccounts importInstance(Long accountId, LocalDate closedOnDate, - Long onAccountClosureId,Long toSavingsAccountId, String accountType,Integer rowIndex, - String locale,String dateFormat){ - return new ClosingOfSavingsAccounts(accountId, closedOnDate,onAccountClosureId,toSavingsAccountId, accountType, - rowIndex,locale,dateFormat); + public static ClosingOfSavingsAccounts importInstance(Long accountId, LocalDate closedOnDate, Long onAccountClosureId, + Long toSavingsAccountId, String accountType, Integer rowIndex, String locale, String dateFormat) { + return new ClosingOfSavingsAccounts(accountId, closedOnDate, onAccountClosureId, toSavingsAccountId, accountType, rowIndex, locale, + dateFormat); } - private ClosingOfSavingsAccounts(Long accountId, LocalDate closedOnDate, - Long onAccountClosureId,Long toSavingsAccountId, String accountType,Integer rowIndex, - String locale,String dateFormat ) { + private ClosingOfSavingsAccounts(Long accountId, LocalDate closedOnDate, Long onAccountClosureId, Long toSavingsAccountId, + String accountType, Integer rowIndex, String locale, String dateFormat) { this.accountId = accountId; this.closedOnDate = closedOnDate; this.onAccountClosureId = onAccountClosureId; this.toSavingsAccountId = toSavingsAccountId; - this.accountType=accountType; + this.accountType = accountType; this.rowIndex = rowIndex; this.dateFormat = dateFormat; this.locale = locale; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountData.java index 30b82be19..f912b3787 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountData.java @@ -86,13 +86,13 @@ public class DepositAccountData { protected final DepositAccountInterestRateChartData chartTemplate; - //import fields + // import fields private Long productId; - public DepositAccountData(Long clientId,Long productId,Long fieldOfficerId, - EnumOptionData interestCompoundingPeriodType, EnumOptionData interestPostingPeriodType, - EnumOptionData interestCalculationType,EnumOptionData interestCalculationDaysInYearType,Integer lockinPeriodFrequency, - EnumOptionData lockinPeriodFrequencyType,String externalId,Collection charges) { + public DepositAccountData(Long clientId, Long productId, Long fieldOfficerId, EnumOptionData interestCompoundingPeriodType, + EnumOptionData interestPostingPeriodType, EnumOptionData interestCalculationType, + EnumOptionData interestCalculationDaysInYearType, Integer lockinPeriodFrequency, EnumOptionData lockinPeriodFrequencyType, + String externalId, Collection charges) { this.id = null; this.accountNo = null; this.externalId = externalId; @@ -136,7 +136,7 @@ public class DepositAccountData { this.withdrawalFee = null; this.annualFee = null; this.chartTemplate = null; - this.productId=productId; + this.productId = productId; } public static DepositAccountData instance(final Long id, final String accountNo, final String externalId, final Long groupId, @@ -145,10 +145,9 @@ public class DepositAccountData { final SavingsAccountApplicationTimelineData timeline, final CurrencyData currency, final BigDecimal interestRate, final EnumOptionData interestCompoundingPeriodType, final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, - final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, - final EnumOptionData lockinPeriodFrequencyType, final boolean withdrawalFeeForTransfers, - final SavingsAccountSummaryData summary, final EnumOptionData depositType, final BigDecimal minBalanceForInterestCalculation, - final boolean withHoldTax, final TaxGroupData taxGroup) { + final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, + final boolean withdrawalFeeForTransfers, final SavingsAccountSummaryData summary, final EnumOptionData depositType, + final BigDecimal minBalanceForInterestCalculation, final boolean withHoldTax, final TaxGroupData taxGroup) { final Collection productOptions = null; final Collection fieldOfficerOptions = null; @@ -169,10 +168,9 @@ public class DepositAccountData { fieldOfficerId, fieldOfficerName, status, timeline, currency, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions, productOptions, - fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, - interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, - withdrawalFeeTypeOptions, charges, chargeOptions, accountChart, chartTemplate, depositType, - minBalanceForInterestCalculation, withHoldTax, taxGroup); + fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, + interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, + chargeOptions, accountChart, chartTemplate, depositType, minBalanceForInterestCalculation, withHoldTax, taxGroup); } public static DepositAccountData lookup(final Long id, final String accountNo, final EnumOptionData depositType) { @@ -221,20 +219,18 @@ public class DepositAccountData { fieldOfficerId, fieldOfficerName, status, timeline, currency, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions, productOptions, - fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, - interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, - withdrawalFeeTypeOptions, charges, chargeOptions, accountChart, chartTemplate, depositType, - minBalanceForInterestCalculation, withHoldTax, taxGroup); + fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, + interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, + chargeOptions, accountChart, chartTemplate, depositType, minBalanceForInterestCalculation, withHoldTax, taxGroup); } - protected DepositAccountData(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 Long fieldOfficerId, final String fieldOfficerName, final SavingsAccountStatusEnumData status, - final SavingsAccountApplicationTimelineData timeline, final CurrencyData currency, final BigDecimal nominalAnnualInterestRate, - final EnumOptionData interestPeriodType, final EnumOptionData interestPostingPeriodType, - final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, - final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, - final EnumOptionData lockinPeriodFrequencyType, final boolean withdrawalFeeForTransfers, + protected DepositAccountData(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 Long fieldOfficerId, + final String fieldOfficerName, final SavingsAccountStatusEnumData status, final SavingsAccountApplicationTimelineData timeline, + final CurrencyData currency, final BigDecimal nominalAnnualInterestRate, final EnumOptionData interestPeriodType, + final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, + final EnumOptionData interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, + final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, final boolean withdrawalFeeForTransfers, final SavingsAccountSummaryData summary, final Collection transactions, final Collection productOptions, final Collection fieldOfficerOptions, final Collection interestCompoundingPeriodTypeOptions, @@ -298,18 +294,14 @@ public class DepositAccountData { private SavingsAccountChargeData getWithdrawalFee() { for (SavingsAccountChargeData charge : this.charges()) { - if (charge.isWithdrawalFee()) { - return charge; - } + if (charge.isWithdrawalFee()) { return charge; } } return null; } private SavingsAccountChargeData getAnnualFee() { for (SavingsAccountChargeData charge : this.charges()) { - if (charge.isAnnualFee()) { - return charge; - } + if (charge.isAnnualFee()) { return charge; } } return null; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountDataValidator.java index cc0a1bf20..c3d02e60a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountDataValidator.java @@ -237,15 +237,15 @@ public class DepositAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { - final Integer interestCompoundingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCompoundingPeriodTypeParamName, element); + final Integer interestCompoundingPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(interestPostingPeriodTypeParamName, element)) { - final Integer interestPostingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestPostingPeriodTypeParamName, element); + final Integer interestPostingPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestPostingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestPostingPeriodTypeParamName).value(interestPostingPeriodType).notNull() .isOneOfTheseValues(SavingsPostingInterestPeriodType.integerValues()); } @@ -258,15 +258,15 @@ public class DepositAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { - final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCalculationDaysInYearTypeParamName, element); + final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(SavingsInterestCalculationDaysInYearType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { - final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minRequiredOpeningBalanceParamName, element); + final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, + element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).zeroOrPositiveAmount(); } @@ -280,16 +280,16 @@ public class DepositAccountDataValidator { if (lockinPeriodFrequency != null) { isLockinPeriodFrequencyTypeValidated = true; - final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - lockinPeriodFrequencyTypeParamName, element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).notNull() .inMinMaxRange(0, 3); } } if (!isLockinPeriodFrequencyTypeValidated && this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { - final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - lockinPeriodFrequencyTypeParamName, element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); if (lockinPeriodFrequencyType != null && !isLockinPeriodFrequencyValidated) { @@ -313,15 +313,14 @@ public class DepositAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(maturityInstructionIdParamName, element)) { - final Integer depositRolloverId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - maturityInstructionIdParamName, element); + final Integer depositRolloverId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(maturityInstructionIdParamName, element); baseDataValidator.reset().parameter(maturityInstructionIdParamName).value(depositRolloverId).notNull() .isOneOfTheseValues(DepositAccountOnClosureType.integerValues()); - if(depositRolloverId.equals(DepositAccountOnClosureType.TRANSFER_TO_SAVINGS.getValue())){ - final Long transferToSavingsId = this.fromApiJsonHelper.extractLongNamed( - transferToSavingsIdParamName, element); - baseDataValidator.reset().parameter(transferToSavingsIdParamName).value(transferToSavingsId).notNull().longGreaterThanZero(); + if (depositRolloverId.equals(DepositAccountOnClosureType.TRANSFER_TO_SAVINGS.getValue())) { + final Long transferToSavingsId = this.fromApiJsonHelper.extractLongNamed(transferToSavingsIdParamName, element); + baseDataValidator.reset().parameter(transferToSavingsIdParamName).value(transferToSavingsId).notNull() + .longGreaterThanZero(); } } } @@ -394,15 +393,15 @@ public class DepositAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { - final Integer interestCompoundingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCompoundingPeriodTypeParamName, element); + final Integer interestCompoundingPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(interestPostingPeriodTypeParamName, element)) { - final Integer interestPostingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestPostingPeriodTypeParamName, element); + final Integer interestPostingPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestPostingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestPostingPeriodTypeParamName).value(interestPostingPeriodType).notNull() .isOneOfTheseValues(SavingsPostingInterestPeriodType.integerValues()); } @@ -415,15 +414,15 @@ public class DepositAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { - final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCalculationDaysInYearTypeParamName, element); + final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(SavingsInterestCalculationDaysInYearType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { - final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minRequiredOpeningBalanceParamName, element); + final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, + element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } @@ -436,8 +435,8 @@ public class DepositAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { - final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - lockinPeriodFrequencyTypeParamName, element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } @@ -456,15 +455,14 @@ public class DepositAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(maturityInstructionIdParamName, element)) { - final Integer depositRolloverId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - maturityInstructionIdParamName, element); + final Integer depositRolloverId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(maturityInstructionIdParamName, element); baseDataValidator.reset().parameter(maturityInstructionIdParamName).value(depositRolloverId).notNull() .isOneOfTheseValues(DepositAccountOnClosureType.integerValues()); - if(depositRolloverId.equals(DepositAccountOnClosureType.TRANSFER_TO_SAVINGS.getValue())){ - final Long transferToSavingsId = this.fromApiJsonHelper.extractLongNamed( - transferToSavingsIdParamName, element); - baseDataValidator.reset().parameter(transferToSavingsIdParamName).value(transferToSavingsId).notNull().longGreaterThanZero(); + if (depositRolloverId.equals(DepositAccountOnClosureType.TRANSFER_TO_SAVINGS.getValue())) { + final Long transferToSavingsId = this.fromApiJsonHelper.extractLongNamed(transferToSavingsIdParamName, element); + baseDataValidator.reset().parameter(transferToSavingsIdParamName).value(transferToSavingsId).notNull() + .longGreaterThanZero(); } } @@ -482,8 +480,8 @@ public class DepositAccountDataValidator { .cantBeBlankWhenParameterProvidedIs(preClosurePenalApplicableParamName, preClosurePenalApplicable) .zeroOrPositiveAmount(); - final Integer preClosurePenalInterestType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - preClosurePenalInterestOnTypeIdParamName, element); + final Integer preClosurePenalInterestType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(preClosurePenalInterestOnTypeIdParamName, element); baseDataValidator.reset().parameter(preClosurePenalInterestOnTypeIdParamName).value(preClosurePenalInterestType) .cantBeBlankWhenParameterProvidedIs(preClosurePenalApplicableParamName, preClosurePenalApplicable) .isOneOfTheseValues(PreClosurePenalInterestOnType.integerValues()); @@ -525,8 +523,8 @@ public class DepositAccountDataValidator { final Integer inMultiplesOfDepositTerm = fromApiJsonHelper.extractIntegerSansLocaleNamed(inMultiplesOfDepositTermParamName, element); baseDataValidator.reset().parameter(inMultiplesOfDepositTermParamName).value(inMultiplesOfDepositTerm).integerGreaterThanZero(); - final Integer inMultiplesOfDepositTermType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - inMultiplesOfDepositTermTypeIdParamName, element); + final Integer inMultiplesOfDepositTermType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(inMultiplesOfDepositTermTypeIdParamName, element); baseDataValidator.reset().parameter(inMultiplesOfDepositTermTypeIdParamName).value(inMultiplesOfDepositTermType) .cantBeBlankWhenParameterProvidedIs(inMultiplesOfDepositTermParamName, inMultiplesOfDepositTerm) .isOneOfTheseValues(SavingsPeriodFrequencyType.integerValues()); @@ -569,8 +567,8 @@ public class DepositAccountDataValidator { } if (fromApiJsonHelper.parameterExists(depositPeriodFrequencyIdParamName, element)) { - final Integer depositPeriodFrequencyId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - depositPeriodFrequencyIdParamName, element); + final Integer depositPeriodFrequencyId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(depositPeriodFrequencyIdParamName, + element); baseDataValidator.reset().parameter(depositPeriodFrequencyIdParamName).value(depositPeriodFrequencyId) .isOneOfTheseValues(SavingsPeriodFrequencyType.integerValues()); } @@ -578,8 +576,8 @@ public class DepositAccountDataValidator { private void validateRecurringDetailForSubmit(final JsonElement element, final DataValidatorBuilder baseDataValidator) { - final BigDecimal mandatoryRecommendedDepositAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - mandatoryRecommendedDepositAmountParamName, element); + final BigDecimal mandatoryRecommendedDepositAmount = fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(mandatoryRecommendedDepositAmountParamName, element); baseDataValidator.reset().parameter(mandatoryRecommendedDepositAmountParamName).value(mandatoryRecommendedDepositAmount).notNull() .positiveAmount(); @@ -595,8 +593,8 @@ public class DepositAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(adjustAdvanceTowardsFuturePaymentsParamName, element)) { - final Boolean adjustAdvanceTowardsFuturePayments = this.fromApiJsonHelper.extractBooleanNamed( - adjustAdvanceTowardsFuturePaymentsParamName, element); + final Boolean adjustAdvanceTowardsFuturePayments = this.fromApiJsonHelper + .extractBooleanNamed(adjustAdvanceTowardsFuturePaymentsParamName, element); baseDataValidator.reset().parameter(adjustAdvanceTowardsFuturePaymentsParamName).value(adjustAdvanceTowardsFuturePayments) .ignoreIfNull().validateForBooleanValue(); } @@ -611,8 +609,8 @@ public class DepositAccountDataValidator { baseDataValidator.reset().parameter(isCalendarInheritedParamName).value(isCalendarInherited).notNull() .validateForBooleanValue(); if (!isCalendarInherited) { - final Integer frequencyType = this.fromApiJsonHelper - .extractIntegerSansLocaleNamed(recurringFrequencyTypeParamName, element); + final Integer frequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(recurringFrequencyTypeParamName, + element); baseDataValidator.reset().parameter(recurringFrequencyTypeParamName).value(frequencyType).notBlank() .isOneOfTheseValues(SavingsPeriodFrequencyType.integerValues()); @@ -646,8 +644,8 @@ public class DepositAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(adjustAdvanceTowardsFuturePaymentsParamName, element)) { - final Boolean adjustAdvanceTowardsFuturePayments = this.fromApiJsonHelper.extractBooleanNamed( - adjustAdvanceTowardsFuturePaymentsParamName, element); + final Boolean adjustAdvanceTowardsFuturePayments = this.fromApiJsonHelper + .extractBooleanNamed(adjustAdvanceTowardsFuturePaymentsParamName, element); baseDataValidator.reset().parameter(adjustAdvanceTowardsFuturePaymentsParamName).value(adjustAdvanceTowardsFuturePayments) .ignoreIfNull().validateForBooleanValue(); } @@ -691,19 +689,21 @@ public class DepositAccountDataValidator { dataValidationErrors.add(error); } else if (!savingsAccount.clientId().equals(linkedSavingsAccount.clientId())) { final ApiParameterError error = ApiParameterError.parameterError( - "validation.msg.deposit.linked.savings.account.not.belongs.to.same.client", "Linked Savings account with id:" - + linkedSavingsAccount.getId() + " is not belongs to the same client", "linkAccountId", - linkedSavingsAccount.getId()); + "validation.msg.deposit.linked.savings.account.not.belongs.to.same.client", + "Linked Savings account with id:" + linkedSavingsAccount.getId() + " is not belongs to the same client", + "linkAccountId", linkedSavingsAccount.getId()); dataValidationErrors.add(error); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void throwLinkedAccountRequiredError() { final List dataValidationErrors = new ArrayList<>(); - final ApiParameterError error = ApiParameterError.parameterError( - "validation.msg.fixeddepositaccount.linkAccountId.cannot.be.blank", "Linked Savings account required", "linkAccountId"); + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.fixeddepositaccount.linkAccountId.cannot.be.blank", + "Linked Savings account required", "linkAccountId"); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); @@ -747,7 +747,7 @@ public class DepositAccountDataValidator { } } - private void validateWithHoldTax(final JsonElement element, final DataValidatorBuilder baseDataValidator){ + private void validateWithHoldTax(final JsonElement element, final DataValidatorBuilder baseDataValidator) { if (this.fromApiJsonHelper.parameterExists(withHoldTaxParamName, element)) { final String withHoldTax = this.fromApiJsonHelper.extractStringNamed(withHoldTaxParamName, element); baseDataValidator.reset().parameter(withHoldTaxParamName).value(withHoldTax).ignoreIfNull().validateForBooleanValue(); @@ -758,4 +758,4 @@ public class DepositAccountDataValidator { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountInterestRateChartData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountInterestRateChartData.java index 4f1c8c022..09b2ebbbf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountInterestRateChartData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountInterestRateChartData.java @@ -64,8 +64,8 @@ public class DepositAccountInterestRateChartData { final Collection clientTypeOptions = null; final Collection clientClassificationOptions = null; return new DepositAccountInterestRateChartData(id, name, description, fromDate, endDate, isPrimaryGroupingByAmount, accountId, - accountNumber, chartSlabs, periodTypes, entityTypeOptions, attributeNameOptions, conditionTypeOptions, - incentiveTypeOptions, genderOptions, clientTypeOptions, clientClassificationOptions); + accountNumber, chartSlabs, periodTypes, entityTypeOptions, attributeNameOptions, conditionTypeOptions, incentiveTypeOptions, + genderOptions, clientTypeOptions, clientClassificationOptions); } public static DepositAccountInterestRateChartData from(InterestRateChartData productChartData) { @@ -125,8 +125,8 @@ public class DepositAccountInterestRateChartData { final boolean isPrimaryGroupingByAmount = false; final Collection chartSlabs = null; return new DepositAccountInterestRateChartData(id, name, description, fromDate, endDate, isPrimaryGroupingByAmount, accountId, - accountNumber, chartSlabs, periodTypes, entityTypeOptions, attributeNameOptions, conditionTypeOptions, - incentiveTypeOptions, genderOptions, clientTypeOptions, clientClassificationOptions); + accountNumber, chartSlabs, periodTypes, entityTypeOptions, attributeNameOptions, conditionTypeOptions, incentiveTypeOptions, + genderOptions, clientTypeOptions, clientClassificationOptions); } private DepositAccountInterestRateChartData(Long id, String name, String description, LocalDate fromDate, LocalDate endDate, @@ -174,4 +174,4 @@ public class DepositAccountInterestRateChartData { public LocalDate fromDate() { return this.fromDate; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountInterestRateChartSlabData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountInterestRateChartSlabData.java index b0c6325cc..f2fea6bf2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountInterestRateChartSlabData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountInterestRateChartSlabData.java @@ -64,9 +64,9 @@ public class DepositAccountInterestRateChartSlabData { @SuppressWarnings("unused") private final Collection clientClassificationOptions; - public static DepositAccountInterestRateChartSlabData instance(final Long id, final String description, - final EnumOptionData periodType, final Integer fromPeriod, final Integer toPeriod, final BigDecimal amountRangeFrom, - final BigDecimal amountRangeTo, final BigDecimal annualInterestRate, final CurrencyData currency) { + public static DepositAccountInterestRateChartSlabData instance(final Long id, final String description, final EnumOptionData periodType, + final Integer fromPeriod, final Integer toPeriod, final BigDecimal amountRangeFrom, final BigDecimal amountRangeTo, + final BigDecimal annualInterestRate, final CurrencyData currency) { final Collection periodTypes = null; final Collection entityTypeOptions = null; final Collection attributeNameOptions = null; @@ -143,4 +143,4 @@ public class DepositAccountInterestRateChartSlabData { this.incentives.add(incentive); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountOnHoldTransactionData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountOnHoldTransactionData.java old mode 100755 new mode 100644 index 25f623aae..052081452 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountOnHoldTransactionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountOnHoldTransactionData.java @@ -78,10 +78,9 @@ public class DepositAccountOnHoldTransactionData { this.loanClientName = null; } - public static DepositAccountOnHoldTransactionData instance(final Long id, final BigDecimal amount, - final EnumOptionData transactionType, final LocalDate transactionDate, final boolean reversed, final Long savingsId, - final String savingsAccountNo, final String savingsClientName, final Long loanId, final String loanAccountNo, - final String loanClientName) { + public static DepositAccountOnHoldTransactionData instance(final Long id, final BigDecimal amount, final EnumOptionData transactionType, + final LocalDate transactionDate, final boolean reversed, final Long savingsId, final String savingsAccountNo, + final String savingsClientName, final Long loanId, final String loanAccountNo, final String loanClientName) { return new DepositAccountOnHoldTransactionData(id, amount, transactionType, transactionDate, reversed, savingsId, savingsAccountNo, savingsClientName, loanId, loanAccountNo, loanClientName); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountTransactionDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountTransactionDataValidator.java index f3ca4f6b3..c50ff424c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountTransactionDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositAccountTransactionDataValidator.java @@ -61,26 +61,23 @@ public class DepositAccountTransactionDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set DEPOSIT_ACCOUNT_TRANSACTION_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - DepositsApiConstants.localeParamName, DepositsApiConstants.dateFormatParamName, transactionDateParamName, - transactionAmountParamName, paymentTypeIdParamName, transactionAccountNumberParamName, checkNumberParamName, - routingCodeParamName, receiptNumberParamName, bankNumberParamName)); + private static final Set DEPOSIT_ACCOUNT_TRANSACTION_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(DepositsApiConstants.localeParamName, DepositsApiConstants.dateFormatParamName, transactionDateParamName, + transactionAmountParamName, paymentTypeIdParamName, transactionAccountNumberParamName, checkNumberParamName, + routingCodeParamName, receiptNumberParamName, bankNumberParamName)); private static final Set DEPOSIT_ACCOUNT_RECOMMENDED_DEPOSIT_AMOUNT_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(DepositsApiConstants.localeParamName, DepositsApiConstants.dateFormatParamName, - DepositsApiConstants.mandatoryRecommendedDepositAmountParamName, - DepositsApiConstants.effectiveDateParamName)); + DepositsApiConstants.mandatoryRecommendedDepositAmountParamName, DepositsApiConstants.effectiveDateParamName)); - private static final Set DEPOSIT_ACCOUNT_CLOSE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - DepositsApiConstants.localeParamName, DepositsApiConstants.dateFormatParamName, closedOnDateParamName, - DepositsApiConstants.noteParamName, onAccountClosureIdParamName, paymentTypeIdParamName, - transactionAccountNumberParamName, checkNumberParamName, routingCodeParamName, receiptNumberParamName, - bankNumberParamName, DepositsApiConstants.transferDescriptionParamName, toSavingsAccountIdParamName)); + private static final Set DEPOSIT_ACCOUNT_CLOSE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(DepositsApiConstants.localeParamName, DepositsApiConstants.dateFormatParamName, closedOnDateParamName, + DepositsApiConstants.noteParamName, onAccountClosureIdParamName, paymentTypeIdParamName, + transactionAccountNumberParamName, checkNumberParamName, routingCodeParamName, receiptNumberParamName, + bankNumberParamName, DepositsApiConstants.transferDescriptionParamName, toSavingsAccountIdParamName)); private static final Set DEPOSIT_ACCOUNT_PRE_MATURE_CALCULATION_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(DepositsApiConstants.localeParamName, DepositsApiConstants.dateFormatParamName, - closedOnDateParamName)); - + Arrays.asList(DepositsApiConstants.localeParamName, DepositsApiConstants.dateFormatParamName, closedOnDateParamName)); @Autowired public DepositAccountTransactionDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -94,12 +91,11 @@ public class DepositAccountTransactionDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - DEPOSIT_ACCOUNT_TRANSACTION_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, DEPOSIT_ACCOUNT_TRANSACTION_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(depositAccountType - .resourceName()); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(depositAccountType.resourceName()); final JsonElement element = command.parsedJson(); @@ -141,8 +137,8 @@ public class DepositAccountTransactionDataValidator { final LocalDate effectiveDate = this.fromApiJsonHelper.extractLocalDateNamed(DepositsApiConstants.effectiveDateParamName, element); baseDataValidator.reset().parameter(DepositsApiConstants.effectiveDateParamName).value(effectiveDate).notNull(); - final BigDecimal mandatoryRecommendedDepositAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - DepositsApiConstants.mandatoryRecommendedDepositAmountParamName, element); + final BigDecimal mandatoryRecommendedDepositAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(DepositsApiConstants.mandatoryRecommendedDepositAmountParamName, element); baseDataValidator.reset().parameter(DepositsApiConstants.mandatoryRecommendedDepositAmountParamName) .value(mandatoryRecommendedDepositAmount).notNull().positiveAmount(); @@ -179,8 +175,8 @@ public class DepositAccountTransactionDataValidator { DEPOSIT_ACCOUNT_PRE_MATURE_CALCULATION_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(depositAccountType - .resourceName()); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(depositAccountType.resourceName()); final JsonElement element = this.fromApiJsonHelper.parse(json); @@ -196,12 +192,11 @@ public class DepositAccountTransactionDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - DEPOSIT_ACCOUNT_CLOSE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, DEPOSIT_ACCOUNT_CLOSE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(depositAccountType - .resourceName()); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(depositAccountType.resourceName()); final JsonElement element = command.parsedJson(); @@ -216,10 +211,7 @@ public class DepositAccountTransactionDataValidator { final DepositAccountOnClosureType accountOnClosureType = DepositAccountOnClosureType.fromInt(onAccountClosureId); if (accountOnClosureType.isTransferToSavings()) { final Long toSavingsAccountId = this.fromApiJsonHelper.extractLongNamed(toSavingsAccountIdParamName, element); - baseDataValidator - .reset() - .parameter(toSavingsAccountIdParamName) - .value(toSavingsAccountId) + baseDataValidator.reset().parameter(toSavingsAccountIdParamName).value(toSavingsAccountId) .cantBeBlankWhenParameterProvidedIs(onAccountClosureIdParamName, DepositAccountOnClosureType.fromInt(onAccountClosureId).getCode()); } else if (accountOnClosureType.isReinvest() && isPreMatureClose) { @@ -249,4 +241,4 @@ public class DepositAccountTransactionDataValidator { dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductData.java index f8b5a2630..0493c2d5a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductData.java @@ -158,7 +158,8 @@ public class DepositProductData { final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, final Collection paymentTypeOptions, final Collection accountingRuleOptions, final Map> accountingMappingOptions, final Collection chargeOptions, - final Collection penaltyOptions, final InterestRateChartData chartTemplate, Collection taxGroupOptions) { + final Collection penaltyOptions, final InterestRateChartData chartTemplate, + Collection taxGroupOptions) { return new DepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, existingProduct.description, existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType, @@ -175,8 +176,7 @@ public class DepositProductData { } public static DepositProductData withAccountingDetails(final DepositProductData existingProduct, - final Map accountingMappings, - final Collection paymentChannelToFundSourceMappings, + final Map accountingMappings, final Collection paymentChannelToFundSourceMappings, final Collection feeToIncomeAccountMappings, final Collection penaltyToIncomeAccountMappings) { @@ -199,12 +199,12 @@ public class DepositProductData { existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, existingProduct.accountingRule, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, existingProduct.interestRateCharts, existingProduct.chartTemplate, - existingProduct.minBalanceForInterestCalculation, existingProduct.withHoldTax, existingProduct.taxGroup, taxGroupOptions); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, existingProduct.charges, + chargeOptions, penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, + existingProduct.interestRateCharts, existingProduct.chartTemplate, existingProduct.minBalanceForInterestCalculation, + existingProduct.withHoldTax, existingProduct.taxGroup, taxGroupOptions); } public static DepositProductData instance(final Long id, final String name, final String shortName, final String description, @@ -318,8 +318,7 @@ public class DepositProductData { final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, final EnumOptionData accountingType, - final Map accountingMappings, - final Collection paymentChannelToFundSourceMappings, + final Map accountingMappings, final Collection paymentChannelToFundSourceMappings, final Collection currencyOptions, final Collection interestCompoundingPeriodTypeOptions, final Collection interestPostingPeriodTypeOptions, final Collection interestCalculationTypeOptions, @@ -455,4 +454,3 @@ public class DepositProductData { return interestCompoundingPeriodType; } } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java index c719433d9..519e6a538 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java @@ -226,13 +226,13 @@ public class DepositProductDataValidator { } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { - final BigDecimal nominalAnnualInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - nominalAnnualInterestRateParamName, element); + final BigDecimal nominalAnnualInterestRate = fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(nominalAnnualInterestRate).notNull() .zeroOrPositiveAmount(); } - final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCompoundingPeriodTypeParamName, element); + final Integer interestCompoundingPeriodType = fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); @@ -245,8 +245,8 @@ public class DepositProductDataValidator { baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .isOneOfTheseValues(SavingsInterestCalculationType.integerValues()); - final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCalculationDaysInYearTypeParamName, element); + final Integer interestCalculationDaysInYearType = fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType).notNull() .isOneOfTheseValues(SavingsInterestCalculationDaysInYearType.integerValues()); @@ -267,8 +267,8 @@ public class DepositProductDataValidator { baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).integerZeroOrGreater(); if (lockinPeriodFrequency != null) { - final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed( - lockinPeriodFrequencyTypeParamName, element); + final Integer lockinPeriodFrequencyType = fromApiJsonHelper + .extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).notNull() .inMinMaxRange(0, 3); } @@ -288,8 +288,8 @@ public class DepositProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { - final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minBalanceForInterestCalculationParamName, element); + final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } @@ -300,35 +300,35 @@ public class DepositProductDataValidator { if (isCashBasedAccounting(accountingRuleType)) { - final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_CONTROL.getValue()) - .value(savingsControlAccountId).notNull().integerGreaterThanZero(); + final Long savingsControlAccountId = fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) + .notNull().integerGreaterThanZero(); - final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue()) - .value(savingsReferenceAccountId).notNull().integerGreaterThanZero(); + final Long savingsReferenceAccountId = fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue()).value(savingsReferenceAccountId) + .notNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); + final Long transfersInSuspenseAccountId = fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero(); - final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); + final Long interestOnSavingsAccountId = fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).notNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) - .notNull().integerGreaterThanZero(); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId).notNull() + .integerGreaterThanZero(); - final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue()) - .value(incomeFromPenaltyId).notNull().integerGreaterThanZero(); + final Long incomeFromPenaltyId = fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) + .notNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); @@ -348,8 +348,8 @@ public class DepositProductDataValidator { .cantBeBlankWhenParameterProvidedIs(preClosurePenalApplicableParamName, preClosurePenalApplicable) .zeroOrPositiveAmount(); - final Integer preClosurePenalInterestType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - preClosurePenalInterestOnTypeIdParamName, element); + final Integer preClosurePenalInterestType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(preClosurePenalInterestOnTypeIdParamName, element); baseDataValidator.reset().parameter(preClosurePenalInterestOnTypeIdParamName).value(preClosurePenalInterestType) .cantBeBlankWhenParameterProvidedIs(preClosurePenalApplicableParamName, preClosurePenalApplicable) .isOneOfTheseValues(PreClosurePenalInterestOnType.integerValues()); @@ -381,8 +381,8 @@ public class DepositProductDataValidator { final Integer inMultiplesOfDepositTerm = fromApiJsonHelper.extractIntegerSansLocaleNamed(inMultiplesOfDepositTermParamName, element); baseDataValidator.reset().parameter(inMultiplesOfDepositTermParamName).value(inMultiplesOfDepositTerm).integerGreaterThanZero(); - final Integer inMultiplesOfDepositTermType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - inMultiplesOfDepositTermTypeIdParamName, element); + final Integer inMultiplesOfDepositTermType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(inMultiplesOfDepositTermTypeIdParamName, element); baseDataValidator.reset().parameter(inMultiplesOfDepositTermTypeIdParamName).value(inMultiplesOfDepositTermType) .cantBeBlankWhenParameterProvidedIs(inMultiplesOfDepositTermParamName, inMultiplesOfDepositTerm) .isOneOfTheseValues(SavingsPeriodFrequencyType.integerValues()); @@ -446,8 +446,8 @@ public class DepositProductDataValidator { } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { - final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCompoundingPeriodTypeParamName, element); + final Integer interestCompoundingPeriodType = fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } @@ -455,13 +455,13 @@ public class DepositProductDataValidator { if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); - baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() - .inMinMaxRange(1, 2); + baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull().inMinMaxRange(1, + 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { - final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCalculationDaysInYearTypeParamName, element); + final Integer interestCalculationDaysInYearType = fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } @@ -503,39 +503,38 @@ public class DepositProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { - final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minBalanceForInterestCalculationParamName, element); + final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } - final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), element); + final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), + element); baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); - final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue()) - .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); - - final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue()) - .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); - - final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue()) - .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); - - final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), - element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) + final Long savingsReferenceAccountId = fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue()).value(savingsReferenceAccountId) .ignoreIfNull().integerGreaterThanZero(); - final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); + final Long transfersInSuspenseAccountId = fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue()).value(transfersInSuspenseAccountId) + .ignoreIfNull().integerGreaterThanZero(); + + final Long interestOnSavingsAccountId = fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue()).value(interestOnSavingsAccountId) + .ignoreIfNull().integerGreaterThanZero(); + + final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId).ignoreIfNull() + .integerGreaterThanZero(); + + final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), + element); baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); @@ -557,8 +556,8 @@ public class DepositProductDataValidator { } if (fromApiJsonHelper.parameterExists(preClosurePenalInterestOnTypeIdParamName, element)) { - final Integer preClosurePenalInterestType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - preClosurePenalInterestOnTypeIdParamName, element); + final Integer preClosurePenalInterestType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(preClosurePenalInterestOnTypeIdParamName, element); baseDataValidator.reset().parameter(preClosurePenalInterestOnTypeIdParamName).value(preClosurePenalInterestType).notNull() .isOneOfTheseValues(PreClosurePenalInterestOnType.integerValues()); } @@ -595,8 +594,8 @@ public class DepositProductDataValidator { } if (fromApiJsonHelper.parameterExists(inMultiplesOfDepositTermTypeIdParamName, element)) { - final Integer inMultiplesOfDepositTermType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - inMultiplesOfDepositTermTypeIdParamName, element); + final Integer inMultiplesOfDepositTermType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(inMultiplesOfDepositTermTypeIdParamName, element); baseDataValidator.reset().parameter(inMultiplesOfDepositTermTypeIdParamName).value(inMultiplesOfDepositTermType) .isOneOfTheseValues(SavingsPeriodFrequencyType.integerValues()); } @@ -616,8 +615,8 @@ public class DepositProductDataValidator { private void validatePaymentChannelFundSourceMappings(final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator, final JsonElement element) { if (fromApiJsonHelper.parameterExists(SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element)) { - final JsonArray paymentChannelMappingArray = fromApiJsonHelper.extractJsonArrayNamed( - SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); + final JsonArray paymentChannelMappingArray = fromApiJsonHelper + .extractJsonArrayNamed(SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); if (paymentChannelMappingArray != null && paymentChannelMappingArray.size() > 0) { int i = 0; do { @@ -625,33 +624,29 @@ public class DepositProductDataValidator { final Long paymentTypeId = jsonObject.get(SavingProductAccountingParams.PAYMENT_TYPE.getValue()).getAsLong(); final Long paymentSpecificFundAccountId = jsonObject.get(SavingProductAccountingParams.FUND_SOURCE.getValue()) .getAsLong(); - baseDataValidator - .reset() - .parameter( - SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." - + SavingProductAccountingParams.PAYMENT_TYPE.toString()).value(paymentTypeId).notNull() - .integerGreaterThanZero(); - baseDataValidator - .reset() - .parameter( - SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." - + SavingProductAccountingParams.FUND_SOURCE.getValue()).value(paymentSpecificFundAccountId) - .notNull().integerGreaterThanZero(); + baseDataValidator.reset() + .parameter(SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." + + SavingProductAccountingParams.PAYMENT_TYPE.toString()) + .value(paymentTypeId).notNull().integerGreaterThanZero(); + baseDataValidator.reset() + .parameter(SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." + + SavingProductAccountingParams.FUND_SOURCE.getValue()) + .value(paymentSpecificFundAccountId).notNull().integerGreaterThanZero(); i++; } while (i < paymentChannelMappingArray.size()); } } } - private void validateChargeToIncomeAccountMappings(final FromJsonHelper fromApiJsonHelper, - final DataValidatorBuilder baseDataValidator, final JsonElement element) { + private void validateChargeToIncomeAccountMappings(final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator, + final JsonElement element) { // validate for both fee and penalty charges validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element, true); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element, true); } - private void validateChargeToIncomeAccountMappings(final FromJsonHelper fromApiJsonHelper, - final DataValidatorBuilder baseDataValidator, final JsonElement element, final boolean isPenalty) { + private void validateChargeToIncomeAccountMappings(final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator, + final JsonElement element, final boolean isPenalty) { String parameterName; if (isPenalty) { parameterName = SavingProductAccountingParams.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(); @@ -667,10 +662,9 @@ public class DepositProductDataValidator { final JsonObject jsonObject = chargeToIncomeAccountMappingArray.get(i).getAsJsonObject(); final Long chargeId = fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.CHARGE_ID.getValue(), jsonObject); - final Long incomeAccountId = fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_ACCOUNT_ID.getValue(), jsonObject); - baseDataValidator.reset() - .parameter(parameterName + "[" + i + "]." + SavingProductAccountingParams.CHARGE_ID.getValue()) + final Long incomeAccountId = fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_ACCOUNT_ID.getValue(), jsonObject); + baseDataValidator.reset().parameter(parameterName + "[" + i + "]." + SavingProductAccountingParams.CHARGE_ID.getValue()) .value(chargeId).notNull().integerGreaterThanZero(); baseDataValidator.reset() .parameter(parameterName + "[" + i + "]." + SavingProductAccountingParams.INCOME_ACCOUNT_ID.getValue()) @@ -687,8 +681,8 @@ public class DepositProductDataValidator { baseDataValidator.reset().parameter(isMandatoryDepositParamName).value(isMandatoryDeposit).ignoreIfNull().validateForBooleanValue(); final Boolean allowWithdrawal = this.fromApiJsonHelper.extractBooleanNamed(allowWithdrawalParamName, element); baseDataValidator.reset().parameter(allowWithdrawalParamName).value(allowWithdrawal).ignoreIfNull().validateForBooleanValue(); - final Boolean adjustAdvanceTowardsFuturePayments = this.fromApiJsonHelper.extractBooleanNamed( - adjustAdvanceTowardsFuturePaymentsParamName, element); + final Boolean adjustAdvanceTowardsFuturePayments = this.fromApiJsonHelper + .extractBooleanNamed(adjustAdvanceTowardsFuturePaymentsParamName, element); baseDataValidator.reset().parameter(adjustAdvanceTowardsFuturePaymentsParamName).value(adjustAdvanceTowardsFuturePayments) .ignoreIfNull().validateForBooleanValue(); } @@ -707,8 +701,8 @@ public class DepositProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(adjustAdvanceTowardsFuturePaymentsParamName, element)) { - final Boolean adjustAdvanceTowardsFuturePayments = this.fromApiJsonHelper.extractBooleanNamed( - adjustAdvanceTowardsFuturePaymentsParamName, element); + final Boolean adjustAdvanceTowardsFuturePayments = this.fromApiJsonHelper + .extractBooleanNamed(adjustAdvanceTowardsFuturePaymentsParamName, element); baseDataValidator.reset().parameter(adjustAdvanceTowardsFuturePaymentsParamName).value(adjustAdvanceTowardsFuturePayments) .ignoreIfNull().validateForBooleanValue(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/FixedDepositAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/FixedDepositAccountData.java index 026fe676f..76db8df2f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/FixedDepositAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/FixedDepositAccountData.java @@ -71,35 +71,32 @@ public class FixedDepositAccountData extends DepositAccountData { private Collection paymentTypeOptions; private final Collection maturityInstructionOptions; - //import fields + // import fields private transient Integer rowIndex; private String dateFormat; private String locale; private LocalDate submittedOnDate; private Long depositPeriodFrequencyId; - public static FixedDepositAccountData importInstance(Long clientId,Long productId,Long fieldOfficerId,LocalDate submittedOnDate, - EnumOptionData interestCompoundingPeriodTypeEnum,EnumOptionData interestPostingPeriodTypeEnum, - EnumOptionData interestCalculationTypeEnum,EnumOptionData interestCalculationDaysInYearTypeEnum, - Integer lockinPeriodFrequency,EnumOptionData lockinPeriodFrequencyTypeEnum,BigDecimal depositAmount, - Integer depositPeriod,Long depositPeriodFrequencyId,String externalId, - Collection charges,Integer rowIndex,String locale,String dateFormat){ + public static FixedDepositAccountData importInstance(Long clientId, Long productId, Long fieldOfficerId, LocalDate submittedOnDate, + EnumOptionData interestCompoundingPeriodTypeEnum, EnumOptionData interestPostingPeriodTypeEnum, + EnumOptionData interestCalculationTypeEnum, EnumOptionData interestCalculationDaysInYearTypeEnum, Integer lockinPeriodFrequency, + EnumOptionData lockinPeriodFrequencyTypeEnum, BigDecimal depositAmount, Integer depositPeriod, Long depositPeriodFrequencyId, + String externalId, Collection charges, Integer rowIndex, String locale, String dateFormat) { - return new FixedDepositAccountData(clientId, productId, fieldOfficerId, submittedOnDate, - interestCompoundingPeriodTypeEnum, interestPostingPeriodTypeEnum, interestCalculationTypeEnum, - interestCalculationDaysInYearTypeEnum, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, - depositAmount, depositPeriod, depositPeriodFrequencyId, externalId, charges,rowIndex,locale,dateFormat); + return new FixedDepositAccountData(clientId, productId, fieldOfficerId, submittedOnDate, interestCompoundingPeriodTypeEnum, + interestPostingPeriodTypeEnum, interestCalculationTypeEnum, interestCalculationDaysInYearTypeEnum, lockinPeriodFrequency, + lockinPeriodFrequencyTypeEnum, depositAmount, depositPeriod, depositPeriodFrequencyId, externalId, charges, rowIndex, + locale, dateFormat); } - private FixedDepositAccountData(Long clientId,Long productId,Long fieldofficerId,LocalDate submittedOnDate, - EnumOptionData interestCompoundingPeriodType,EnumOptionData interestPostingPeriodType, - EnumOptionData interestCalculationType,EnumOptionData interestCalculationDaysInYearType, - Integer lockinPeriodFrequency,EnumOptionData lockinPeriodFrequencyType,BigDecimal depositAmount, - Integer depositPeriod,Long depositPeriodFrequencyId,String externalId, - Collection charges,Integer rowIndex,String locale,String dateFormat) { - super(clientId, productId, fieldofficerId, interestCompoundingPeriodType, interestPostingPeriodType, - interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency, - lockinPeriodFrequencyType, externalId, charges); + private FixedDepositAccountData(Long clientId, Long productId, Long fieldofficerId, LocalDate submittedOnDate, + EnumOptionData interestCompoundingPeriodType, EnumOptionData interestPostingPeriodType, EnumOptionData interestCalculationType, + EnumOptionData interestCalculationDaysInYearType, Integer lockinPeriodFrequency, EnumOptionData lockinPeriodFrequencyType, + BigDecimal depositAmount, Integer depositPeriod, Long depositPeriodFrequencyId, String externalId, + Collection charges, Integer rowIndex, String locale, String dateFormat) { + super(clientId, productId, fieldofficerId, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, + interestCalculationDaysInYearType, lockinPeriodFrequency, lockinPeriodFrequencyType, externalId, charges); this.preClosurePenalApplicable = false; this.preClosurePenalInterest = null; this.preClosurePenalInterestOnType = null; @@ -125,8 +122,8 @@ public class FixedDepositAccountData extends DepositAccountData { this.onAccountClosureOptions = null; this.paymentTypeOptions = null; this.rowIndex = rowIndex; - this.dateFormat= dateFormat; - this.locale= locale; + this.dateFormat = dateFormat; + this.locale = locale; this.submittedOnDate = submittedOnDate; this.depositPeriodFrequencyId = depositPeriodFrequencyId; this.maturityInstructionOptions = null; @@ -195,13 +192,13 @@ public class FixedDepositAccountData extends DepositAccountData { account.inMultiplesOfDepositTermType, account.depositAmount, account.maturityAmount, account.maturityDate, account.depositPeriod, account.depositPeriodFrequency, account.periodFrequencyTypeOptions, account.depositType, account.onAccountClosure, account.onAccountClosureOptions, account.paymentTypeOptions, account.savingsAccounts, - account.linkedAccount, account.transferInterestToSavings, account.withHoldTax, account.taxGroup, account.maturityInstructionOptions, - account.transferToSavingsId, account.transferToSavingsAccount); + account.linkedAccount, account.transferInterestToSavings, account.withHoldTax, account.taxGroup, + account.maturityInstructionOptions, account.transferToSavingsId, account.transferToSavingsAccount); } public static FixedDepositAccountData associationsAndTemplate(final FixedDepositAccountData account, FixedDepositAccountData template, final Collection transactions, final Collection charges, - final PortfolioAccountData linkedAccount, PortfolioAccountData transferToSavingsAccount ) { + final PortfolioAccountData linkedAccount, PortfolioAccountData transferToSavingsAccount) { if (template == null) { template = account; @@ -249,8 +246,8 @@ public class FixedDepositAccountData extends DepositAccountData { interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, account.accountChart, account.chartTemplate, account.preClosurePenalApplicable, account.preClosurePenalInterest, - account.preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, account.minDepositTerm, - account.maxDepositTerm, account.minDepositTermType, account.maxDepositTermType, account.inMultiplesOfDepositTerm, + account.preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, account.minDepositTerm, account.maxDepositTerm, + account.minDepositTermType, account.maxDepositTermType, account.inMultiplesOfDepositTerm, account.inMultiplesOfDepositTermType, account.depositAmount, account.maturityAmount, account.maturityDate, account.depositPeriod, account.depositPeriodFrequency, periodFrequencyTypeOptions, account.depositType, account.onAccountClosure, account.onAccountClosureOptions, account.paymentTypeOptions, savingsAccounts, @@ -337,9 +334,10 @@ public class FixedDepositAccountData extends DepositAccountData { withdrawalFeeTypeOptions, charges, chargeOptions, accountChart, chartTemplate, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, - depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, periodFrequencyTypeOptions, - depositType, onAccountClosure, onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas, linkedAccount, - transferInterestToSavings, withHoldTax, taxGroup, maturityInstructionOptions, transferToSavingsId, transferToSavingsAccount); + depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, periodFrequencyTypeOptions, depositType, + onAccountClosure, onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas, linkedAccount, + transferInterestToSavings, withHoldTax, taxGroup, maturityInstructionOptions, transferToSavingsId, + transferToSavingsAccount); } public static FixedDepositAccountData preClosureDetails(final Long accountId, BigDecimal maturityAmount, @@ -421,9 +419,10 @@ public class FixedDepositAccountData extends DepositAccountData { withdrawalFeeTypeOptions, charges, chargeOptions, accountChart, chartTemplate, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, - depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, periodFrequencyTypeOptions, - depositType, onAccountClosure, onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas, linkedAccount, - transferInterestToSavings, withHoldTax, taxGroup, maturityInstructionOptions, transferToSavingsId, transferToSavingsAccount); + depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, periodFrequencyTypeOptions, depositType, + onAccountClosure, onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas, linkedAccount, + transferInterestToSavings, withHoldTax, taxGroup, maturityInstructionOptions, transferToSavingsId, + transferToSavingsAccount); } public static FixedDepositAccountData withClosureTemplateDetails(final FixedDepositAccountData account, @@ -452,37 +451,37 @@ public class FixedDepositAccountData extends DepositAccountData { } private FixedDepositAccountData(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 Long fieldofficerId, final String fieldofficerName, final SavingsAccountStatusEnumData status, - final SavingsAccountApplicationTimelineData timeline, final CurrencyData currency, final BigDecimal nominalAnnualInterestRate, - final EnumOptionData interestPeriodType, final EnumOptionData interestPostingPeriodType, - final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, - final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, - final EnumOptionData lockinPeriodFrequencyType, final boolean withdrawalFeeForTransfers, - final BigDecimal minBalanceForInterestCalculation, final SavingsAccountSummaryData summary, - final Collection transactions, final Collection productOptions, - final Collection fieldOfficerOptions, final Collection interestCompoundingPeriodTypeOptions, - final Collection interestPostingPeriodTypeOptions, - final Collection interestCalculationTypeOptions, - final Collection interestCalculationDaysInYearTypeOptions, - final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, - final Collection charges, final Collection chargeOptions, - final DepositAccountInterestRateChartData accountChart, final DepositAccountInterestRateChartData chartTemplate, - final boolean preClosurePenalApplicable, final BigDecimal preClosurePenalInterest, - final EnumOptionData preClosurePenalInterestOnType, final Collection preClosurePenalInterestOnTypeOptions, - final Integer minDepositTerm, final Integer maxDepositTerm, final EnumOptionData minDepositTermType, - final EnumOptionData maxDepositTermType, final Integer inMultiplesOfDepositTerm, - final EnumOptionData inMultiplesOfDepositTermType, final BigDecimal depositAmount, final BigDecimal maturityAmount, - final LocalDate maturityDate, final Integer depositPeriod, final EnumOptionData depositPeriodFrequency, - final Collection periodFrequencyTypeOptions, final EnumOptionData depositType, - final EnumOptionData onAccountClosure, final Collection onAccountClosureOptions, - final Collection paymentTypeOptions, final Collection savingsAccountDatas, - final PortfolioAccountData linkedAccount, final Boolean transferInterestToSavings, final boolean withHoldTax, - final TaxGroupData taxGroup, final Collection maturityInstructionOptions, final Long transferToSavingsId, - final PortfolioAccountData transferToSavingsAccount) { + final String groupName, final Long clientId, final String clientName, final Long productId, final String productName, + final Long fieldofficerId, final String fieldofficerName, final SavingsAccountStatusEnumData status, + final SavingsAccountApplicationTimelineData timeline, final CurrencyData currency, final BigDecimal nominalAnnualInterestRate, + final EnumOptionData interestPeriodType, final EnumOptionData interestPostingPeriodType, + final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, + final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, + final boolean withdrawalFeeForTransfers, final BigDecimal minBalanceForInterestCalculation, + final SavingsAccountSummaryData summary, final Collection transactions, + final Collection productOptions, final Collection fieldOfficerOptions, + final Collection interestCompoundingPeriodTypeOptions, + final Collection interestPostingPeriodTypeOptions, + final Collection interestCalculationTypeOptions, + final Collection interestCalculationDaysInYearTypeOptions, + final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, + final Collection charges, final Collection chargeOptions, + final DepositAccountInterestRateChartData accountChart, final DepositAccountInterestRateChartData chartTemplate, + final boolean preClosurePenalApplicable, final BigDecimal preClosurePenalInterest, + final EnumOptionData preClosurePenalInterestOnType, final Collection preClosurePenalInterestOnTypeOptions, + final Integer minDepositTerm, final Integer maxDepositTerm, final EnumOptionData minDepositTermType, + final EnumOptionData maxDepositTermType, final Integer inMultiplesOfDepositTerm, + final EnumOptionData inMultiplesOfDepositTermType, final BigDecimal depositAmount, final BigDecimal maturityAmount, + final LocalDate maturityDate, final Integer depositPeriod, final EnumOptionData depositPeriodFrequency, + final Collection periodFrequencyTypeOptions, final EnumOptionData depositType, + final EnumOptionData onAccountClosure, final Collection onAccountClosureOptions, + final Collection paymentTypeOptions, final Collection savingsAccountDatas, + final PortfolioAccountData linkedAccount, final Boolean transferInterestToSavings, final boolean withHoldTax, + final TaxGroupData taxGroup, final Collection maturityInstructionOptions, final Long transferToSavingsId, + final PortfolioAccountData transferToSavingsAccount) { - super(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldofficerId, - fieldofficerName, status, timeline, currency, nominalAnnualInterestRate, interestPeriodType, interestPostingPeriodType, + super(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldofficerId, fieldofficerName, + status, timeline, currency, nominalAnnualInterestRate, interestPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, @@ -535,12 +534,10 @@ public class FixedDepositAccountData extends DepositAccountData { return new HashCodeBuilder(17, 37).append(this.id).append(this.accountNo).toHashCode(); } - public BigDecimal getActivationCharge() { return this.activationCharge; } - public void setActivationCharge(BigDecimal activationCharge) { this.activationCharge = activationCharge; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/FixedDepositProductData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/FixedDepositProductData.java index ea936104d..6d34a84a8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/FixedDepositProductData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/FixedDepositProductData.java @@ -101,24 +101,23 @@ public class FixedDepositProductData extends DepositProductData { return new FixedDepositProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency, lockinPeriodFrequencyType, minBalanceForInterestCalculation, accountingRule, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, preClosurePenalApplicable, preClosurePenalInterest, - preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, - maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, minDepositAmount, depositAmount, - maxDepositAmount, periodFrequencyTypeOptions, withHoldTax, taxGroup, taxGroupOptions); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, + penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, + preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, + minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, + inMultiplesOfDepositTermType, minDepositAmount, depositAmount, maxDepositAmount, periodFrequencyTypeOptions, withHoldTax, + taxGroup, taxGroupOptions); } public static FixedDepositProductData withCharges(final FixedDepositProductData existingProduct, final Collection charges) { - return new FixedDepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, - existingProduct.description, existingProduct.currency, existingProduct.nominalAnnualInterestRate, - existingProduct.interestCompoundingPeriodType, existingProduct.interestPostingPeriodType, - existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, - existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, - existingProduct.minBalanceForInterestCalculation, existingProduct.accountingRule, existingProduct.accountingMappings, - existingProduct.paymentChannelToFundSourceMappings, existingProduct.currencyOptions, + return new FixedDepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, existingProduct.description, + existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType, + existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType, + existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency, + existingProduct.lockinPeriodFrequencyType, existingProduct.minBalanceForInterestCalculation, existingProduct.accountingRule, + existingProduct.accountingMappings, existingProduct.paymentChannelToFundSourceMappings, existingProduct.currencyOptions, existingProduct.interestCompoundingPeriodTypeOptions, existingProduct.interestPostingPeriodTypeOptions, existingProduct.interestCalculationTypeOptions, existingProduct.interestCalculationDaysInYearTypeOptions, existingProduct.lockinPeriodFrequencyTypeOptions, existingProduct.withdrawalFeeTypeOptions, @@ -154,16 +153,15 @@ public class FixedDepositProductData extends DepositProductData { final Collection preClosurePenalInterestOnTypeOptions, final Collection periodFrequencyTypeOptions, final Collection taxGroupOptions) { - return new FixedDepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, - existingProduct.description, existingProduct.currency, existingProduct.nominalAnnualInterestRate, - existingProduct.interestCompoundingPeriodType, existingProduct.interestPostingPeriodType, - existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, - existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, - existingProduct.minBalanceForInterestCalculation, existingProduct.accountingRule, existingProduct.accountingMappings, - existingProduct.paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, + return new FixedDepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, existingProduct.description, + existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType, + existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType, + existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency, + existingProduct.lockinPeriodFrequencyType, existingProduct.minBalanceForInterestCalculation, existingProduct.accountingRule, + existingProduct.accountingMappings, existingProduct.paymentChannelToFundSourceMappings, currencyOptions, + interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, + interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, + accountingRuleOptions, accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, existingProduct.feeToIncomeAccountMappings, existingProduct.penaltyToIncomeAccountMappings, existingProduct.interestRateCharts, chartTemplate, existingProduct.preClosurePenalApplicable, existingProduct.preClosurePenalInterest, existingProduct.preClosurePenalInterestOnType, @@ -175,8 +173,7 @@ public class FixedDepositProductData extends DepositProductData { } public static FixedDepositProductData withAccountingDetails(final FixedDepositProductData existingProduct, - final Map accountingMappings, - final Collection paymentChannelToFundSourceMappings, + final Map accountingMappings, final Collection paymentChannelToFundSourceMappings, final Collection feeToIncomeAccountMappings, final Collection penaltyToIncomeAccountMappings) { @@ -193,13 +190,12 @@ public class FixedDepositProductData extends DepositProductData { final Collection chargeOptions = null; final Collection penaltyOptions = null; - return new FixedDepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, - existingProduct.description, existingProduct.currency, existingProduct.nominalAnnualInterestRate, - existingProduct.interestCompoundingPeriodType, existingProduct.interestPostingPeriodType, - existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, - existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, - existingProduct.minBalanceForInterestCalculation, existingProduct.accountingRule, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, + return new FixedDepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, existingProduct.description, + existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType, + existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType, + existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency, + existingProduct.lockinPeriodFrequencyType, existingProduct.minBalanceForInterestCalculation, existingProduct.accountingRule, + accountingMappings, paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, @@ -249,14 +245,14 @@ public class FixedDepositProductData extends DepositProductData { depositProductData.interestCalculationType, depositProductData.interestCalculationDaysInYearType, depositProductData.lockinPeriodFrequency, depositProductData.lockinPeriodFrequencyType, depositProductData.minBalanceForInterestCalculation, depositProductData.accountingRule, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, preClosurePenalApplicable, preClosurePenalInterest, - preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, - maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, minDepositAmount, depositAmount, - maxDepositAmount, periodFrequencyTypeOptions, depositProductData.withHoldTax, depositProductData.taxGroup, taxGroupOptions); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, + penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, + preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, + minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, + inMultiplesOfDepositTermType, minDepositAmount, depositAmount, maxDepositAmount, periodFrequencyTypeOptions, + depositProductData.withHoldTax, depositProductData.taxGroup, taxGroupOptions); } public static FixedDepositProductData lookup(final Long id, final String name) { @@ -314,25 +310,24 @@ public class FixedDepositProductData extends DepositProductData { return new FixedDepositProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency, lockinPeriodFrequencyType, minBalanceForInterestCalculation, accountingType, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, preClosurePenalApplicable, preClosurePenalInterest, - preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, - maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, minDepositAmount, depositAmount, - maxDepositAmount, periodFrequencyTypeOptions, withHoldTax, taxGroup, taxGroupOptions); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, + penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, + preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, + minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, + inMultiplesOfDepositTermType, minDepositAmount, depositAmount, maxDepositAmount, periodFrequencyTypeOptions, withHoldTax, + taxGroup, taxGroupOptions); } public static FixedDepositProductData withInterestChart(final FixedDepositProductData existingProduct, final Collection interestRateCharts) { - return new FixedDepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, - existingProduct.description, existingProduct.currency, existingProduct.nominalAnnualInterestRate, - existingProduct.interestCompoundingPeriodType, existingProduct.interestPostingPeriodType, - existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, - existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, - existingProduct.minBalanceForInterestCalculation, existingProduct.accountingRule, existingProduct.accountingMappings, - existingProduct.paymentChannelToFundSourceMappings, existingProduct.currencyOptions, + return new FixedDepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, existingProduct.description, + existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType, + existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType, + existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency, + existingProduct.lockinPeriodFrequencyType, existingProduct.minBalanceForInterestCalculation, existingProduct.accountingRule, + existingProduct.accountingMappings, existingProduct.paymentChannelToFundSourceMappings, existingProduct.currencyOptions, existingProduct.interestCompoundingPeriodTypeOptions, existingProduct.interestPostingPeriodTypeOptions, existingProduct.interestCalculationTypeOptions, existingProduct.interestCalculationDaysInYearTypeOptions, existingProduct.lockinPeriodFrequencyTypeOptions, existingProduct.withdrawalFeeTypeOptions, @@ -451,4 +446,4 @@ public class FixedDepositProductData extends DepositProductData { return preClosurePenalApplicable; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/GSIMContainer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/GSIMContainer.java index 95ef74595..2d36c6e9a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/GSIMContainer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/GSIMContainer.java @@ -38,8 +38,7 @@ public class GSIMContainer { private final String savingsStatus; public GSIMContainer(final BigDecimal gsimId, final BigDecimal groupId, final String accountNumber, - final List childGSIMAccounts, final BigDecimal parentBalance, - final String savingsStatus) { + final List childGSIMAccounts, final BigDecimal parentBalance, final String savingsStatus) { this.gsimId = gsimId; this.groupId = groupId; this.accountNumber = accountNumber; @@ -72,4 +71,4 @@ public class GSIMContainer { public String getSavingsStatus() { return savingsStatus; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/GroupSavingsIndividualMonitoringAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/GroupSavingsIndividualMonitoringAccountData.java index a6f54731e..4d704f0b9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/GroupSavingsIndividualMonitoringAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/GroupSavingsIndividualMonitoringAccountData.java @@ -21,105 +21,101 @@ package org.apache.fineract.portfolio.savings.data; import java.math.BigDecimal; -public class GroupSavingsIndividualMonitoringAccountData -{ +public class GroupSavingsIndividualMonitoringAccountData { - private final BigDecimal gsimId; + private final BigDecimal gsimId; - private final BigDecimal groupId; + private final BigDecimal groupId; - private final BigDecimal clientId; + private final BigDecimal clientId; - private final String accountNumber; + private final String accountNumber; - private final BigDecimal childAccountId; + private final BigDecimal childAccountId; - private final String childAccountNumber; + private final String childAccountNumber; - private final BigDecimal childDeposit; + private final BigDecimal childDeposit; - private final BigDecimal parentDeposit; + private final BigDecimal parentDeposit; - private final Long childAccountsCount; + private final Long childAccountsCount; - private final String savingsStatus; + private final String savingsStatus; - private GroupSavingsIndividualMonitoringAccountData(final BigDecimal glimId,final BigDecimal groupId,final BigDecimal clientId,final String accountNumber,final BigDecimal childAccountId, final String childAccountNumber, - final BigDecimal childDeposit, final BigDecimal parentDeposit, - final Long childAccountsCount,final String savingsStatus) { - this.gsimId=glimId; - this.groupId=groupId; - this.clientId=clientId; - this.accountNumber = accountNumber; - this.childAccountId=childAccountId; - this.childAccountNumber = childAccountNumber; - this.childDeposit = childDeposit; - this.parentDeposit = parentDeposit; - this.childAccountsCount = childAccountsCount; - this.savingsStatus=savingsStatus; - } + private GroupSavingsIndividualMonitoringAccountData(final BigDecimal glimId, final BigDecimal groupId, final BigDecimal clientId, + final String accountNumber, final BigDecimal childAccountId, final String childAccountNumber, final BigDecimal childDeposit, + final BigDecimal parentDeposit, final Long childAccountsCount, final String savingsStatus) { + this.gsimId = glimId; + this.groupId = groupId; + this.clientId = clientId; + this.accountNumber = accountNumber; + this.childAccountId = childAccountId; + this.childAccountNumber = childAccountNumber; + this.childDeposit = childDeposit; + this.parentDeposit = parentDeposit; + this.childAccountsCount = childAccountsCount; + this.savingsStatus = savingsStatus; + } - public static GroupSavingsIndividualMonitoringAccountData getInstance(final BigDecimal glimId, final BigDecimal groupId,final String accountNumber, final String childAccountNumber, - final BigDecimal childDeposit, final BigDecimal parentDeposit, - final Long childAccountsCount,final String savingsStatus) - { - return new GroupSavingsIndividualMonitoringAccountData(glimId,groupId,null,accountNumber,null,childAccountNumber, - childDeposit,parentDeposit,childAccountsCount,savingsStatus); - } + public static GroupSavingsIndividualMonitoringAccountData getInstance(final BigDecimal glimId, final BigDecimal groupId, + final String accountNumber, final String childAccountNumber, final BigDecimal childDeposit, final BigDecimal parentDeposit, + final Long childAccountsCount, final String savingsStatus) { + return new GroupSavingsIndividualMonitoringAccountData(glimId, groupId, null, accountNumber, null, childAccountNumber, childDeposit, + parentDeposit, childAccountsCount, savingsStatus); + } - public static GroupSavingsIndividualMonitoringAccountData getInstance1(final BigDecimal glimId,final BigDecimal groupId,final String accountNumber, - final BigDecimal parentDeposit,final String savingsStatus) - { - return new GroupSavingsIndividualMonitoringAccountData(glimId,groupId,null,accountNumber,null,null,null,parentDeposit,null,savingsStatus); - } + public static GroupSavingsIndividualMonitoringAccountData getInstance1(final BigDecimal glimId, final BigDecimal groupId, + final String accountNumber, final BigDecimal parentDeposit, final String savingsStatus) { + return new GroupSavingsIndividualMonitoringAccountData(glimId, groupId, null, accountNumber, null, null, null, parentDeposit, null, + savingsStatus); + } - public static GroupSavingsIndividualMonitoringAccountData getInstance2(final BigDecimal glimId, final BigDecimal groupId,final BigDecimal clientId,final String accountNumber, final BigDecimal childAccountId,final String childAccountNumber, - final BigDecimal childDeposit, final BigDecimal parentDeposit, - final Long childAccountsCount,final String savingsStatus) - { - return new GroupSavingsIndividualMonitoringAccountData(glimId,groupId,clientId,accountNumber,childAccountId,childAccountNumber, - childDeposit,parentDeposit,childAccountsCount,savingsStatus); - } + public static GroupSavingsIndividualMonitoringAccountData getInstance2(final BigDecimal glimId, final BigDecimal groupId, + final BigDecimal clientId, final String accountNumber, final BigDecimal childAccountId, final String childAccountNumber, + final BigDecimal childDeposit, final BigDecimal parentDeposit, final Long childAccountsCount, final String savingsStatus) { + return new GroupSavingsIndividualMonitoringAccountData(glimId, groupId, clientId, accountNumber, childAccountId, childAccountNumber, + childDeposit, parentDeposit, childAccountsCount, savingsStatus); + } - public BigDecimal getGsimId() { - return gsimId; - } + public BigDecimal getGsimId() { + return gsimId; + } - public BigDecimal getGroupId() { - return groupId; - } + public BigDecimal getGroupId() { + return groupId; + } - public BigDecimal getClientId() { - return clientId; - } + public BigDecimal getClientId() { + return clientId; + } - public String getAccountNumber() { - return accountNumber; - } + public String getAccountNumber() { + return accountNumber; + } + public BigDecimal getChildAccountId() { + return childAccountId; + } - public BigDecimal getChildAccountId() { - return childAccountId; - } + public String getChildAccountNumber() { + return childAccountNumber; + } - public String getChildAccountNumber() { - return childAccountNumber; - } + public BigDecimal getChildDeposit() { + return childDeposit; + } - public BigDecimal getChildDeposit() { - return childDeposit; - } + public BigDecimal getParentDeposit() { + return parentDeposit; + } - public BigDecimal getParentDeposit() { - return parentDeposit; - } + public Long getChildAccountsCount() { + return childAccountsCount; + } - public Long getChildAccountsCount() { - return childAccountsCount; - } - - public String getSavingsStatus() { - return savingsStatus; - } + public String getSavingsStatus() { + return savingsStatus; + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/RecurringDepositAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/RecurringDepositAccountData.java index a3c911110..b11dac96e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/RecurringDepositAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/RecurringDepositAccountData.java @@ -74,40 +74,37 @@ public class RecurringDepositAccountData extends DepositAccountData { private final Collection onAccountClosureOptions; private final Collection paymentTypeOptions; - //import fields + // import fields private transient Integer rowIndex; private String dateFormat; private String locale; private LocalDate submittedOnDate; private Long depositPeriodFrequencyId; - public static RecurringDepositAccountData importInstance(Long clientId,Long productId,Long fieldOfficerId, - LocalDate submittedOnDate, - EnumOptionData interestCompoundingPeriodTypeEnum,EnumOptionData interestPostingPeriodTypeEnum, - EnumOptionData interestCalculationTypeEnum,EnumOptionData interestCalculationDaysInYearTypeEnum, - Integer lockinPeriodFrequency,EnumOptionData lockinPeriodFrequencyTypeEnum,BigDecimal depositAmount, - Integer depositPeriod,Long depositPeriodFrequencyId,LocalDate expectedFirstDepositOnDate, - Integer recurringFrequency,EnumOptionData recurringFrequencyTypeEnum,boolean isCalendarInherited, - boolean isMandatoryDeposit,boolean allowWithdrawal,boolean adjustAdvanceTowardsFuturePayments, - String externalId,Collection charges,Integer rowIndex,String locale, String dateFormat){ + public static RecurringDepositAccountData importInstance(Long clientId, Long productId, Long fieldOfficerId, LocalDate submittedOnDate, + EnumOptionData interestCompoundingPeriodTypeEnum, EnumOptionData interestPostingPeriodTypeEnum, + EnumOptionData interestCalculationTypeEnum, EnumOptionData interestCalculationDaysInYearTypeEnum, Integer lockinPeriodFrequency, + EnumOptionData lockinPeriodFrequencyTypeEnum, BigDecimal depositAmount, Integer depositPeriod, Long depositPeriodFrequencyId, + LocalDate expectedFirstDepositOnDate, Integer recurringFrequency, EnumOptionData recurringFrequencyTypeEnum, + boolean isCalendarInherited, boolean isMandatoryDeposit, boolean allowWithdrawal, boolean adjustAdvanceTowardsFuturePayments, + String externalId, Collection charges, Integer rowIndex, String locale, String dateFormat) { - return new RecurringDepositAccountData(clientId, productId, fieldOfficerId, submittedOnDate, - interestCompoundingPeriodTypeEnum,interestPostingPeriodTypeEnum,interestCalculationTypeEnum, - interestCalculationDaysInYearTypeEnum, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, - depositAmount, depositPeriod, depositPeriodFrequencyId, expectedFirstDepositOnDate, - recurringFrequency, recurringFrequencyTypeEnum, isCalendarInherited, isMandatoryDeposit, - allowWithdrawal, adjustAdvanceTowardsFuturePayments, externalId,charges, rowIndex,locale,dateFormat); + return new RecurringDepositAccountData(clientId, productId, fieldOfficerId, submittedOnDate, interestCompoundingPeriodTypeEnum, + interestPostingPeriodTypeEnum, interestCalculationTypeEnum, interestCalculationDaysInYearTypeEnum, lockinPeriodFrequency, + lockinPeriodFrequencyTypeEnum, depositAmount, depositPeriod, depositPeriodFrequencyId, expectedFirstDepositOnDate, + recurringFrequency, recurringFrequencyTypeEnum, isCalendarInherited, isMandatoryDeposit, allowWithdrawal, + adjustAdvanceTowardsFuturePayments, externalId, charges, rowIndex, locale, dateFormat); } - private RecurringDepositAccountData(Long clientId,Long productId,Long fieldofficerId,LocalDate submittedOnDate, - EnumOptionData interestCompoundingPeriodType,EnumOptionData interestPostingPeriodType, - EnumOptionData interestCalculationType,EnumOptionData interestCalculationDaysInYearType, - Integer lockinPeriodFrequency,EnumOptionData lockinPeriodFrequencyType,BigDecimal depositAmount, - Integer depositPeriod,Long depositPeriodFrequencyId,LocalDate expectedFirstDepositOnDate, - Integer recurringFrequency,EnumOptionData recurringFrequencyType,boolean isCalendarInherited, - boolean isMandatoryDeposit,boolean allowWithdrawal,boolean adjustAdvanceTowardsFuturePayments, - String externalId,Collection charges,Integer rowIndex,String locale, String dateFormat) { - super(clientId,productId,fieldofficerId,interestCompoundingPeriodType,interestPostingPeriodType,interestCalculationType, - interestCalculationDaysInYearType,lockinPeriodFrequency,lockinPeriodFrequencyType, externalId,charges); + + private RecurringDepositAccountData(Long clientId, Long productId, Long fieldofficerId, LocalDate submittedOnDate, + EnumOptionData interestCompoundingPeriodType, EnumOptionData interestPostingPeriodType, EnumOptionData interestCalculationType, + EnumOptionData interestCalculationDaysInYearType, Integer lockinPeriodFrequency, EnumOptionData lockinPeriodFrequencyType, + BigDecimal depositAmount, Integer depositPeriod, Long depositPeriodFrequencyId, LocalDate expectedFirstDepositOnDate, + Integer recurringFrequency, EnumOptionData recurringFrequencyType, boolean isCalendarInherited, boolean isMandatoryDeposit, + boolean allowWithdrawal, boolean adjustAdvanceTowardsFuturePayments, String externalId, + Collection charges, Integer rowIndex, String locale, String dateFormat) { + super(clientId, productId, fieldofficerId, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, + interestCalculationDaysInYearType, lockinPeriodFrequency, lockinPeriodFrequencyType, externalId, charges); this.preClosurePenalApplicable = false; this.preClosurePenalInterest = null; @@ -140,26 +137,25 @@ public class RecurringDepositAccountData extends DepositAccountData { this.onAccountClosureOptions = null; this.paymentTypeOptions = null; this.rowIndex = rowIndex; - this.dateFormat= dateFormat; - this.locale=locale; - this.submittedOnDate=submittedOnDate; - this.depositPeriodFrequencyId=depositPeriodFrequencyId; + this.dateFormat = dateFormat; + this.locale = locale; + this.submittedOnDate = submittedOnDate; + this.depositPeriodFrequencyId = depositPeriodFrequencyId; } public Integer getRowIndex() { return rowIndex; } - public static RecurringDepositAccountData instance(final DepositAccountData depositAccountData, - final boolean preClosurePenalApplicable, final BigDecimal preClosurePenalInterest, - final EnumOptionData preClosurePenalInterestOnType, final Integer minDepositTerm, final Integer maxDepositTerm, - final EnumOptionData minDepositTermType, final EnumOptionData maxDepositTermType, final Integer inMultiplesOfDepositTerm, - final EnumOptionData inMultiplesOfDepositTermType, final BigDecimal depositAmount, final BigDecimal maturityAmount, - final LocalDate maturityDate, final Integer depositPeriod, final EnumOptionData depositPeriodFrequency, - final BigDecimal mandatoryRecommendedDepositAmount, final EnumOptionData onAccountClosure, - final LocalDate expectedFirstDepositOnDate, final BigDecimal totalOverdueAmount, final Integer noOfOverdueInstallments, - final boolean isMandatoryDeposit, final boolean allowWithdrawal, final boolean adjustAdvanceTowardsFuturePayments, - final boolean isCalendarInherited) { + public static RecurringDepositAccountData instance(final DepositAccountData depositAccountData, final boolean preClosurePenalApplicable, + final BigDecimal preClosurePenalInterest, final EnumOptionData preClosurePenalInterestOnType, final Integer minDepositTerm, + final Integer maxDepositTerm, final EnumOptionData minDepositTermType, final EnumOptionData maxDepositTermType, + final Integer inMultiplesOfDepositTerm, final EnumOptionData inMultiplesOfDepositTermType, final BigDecimal depositAmount, + final BigDecimal maturityAmount, final LocalDate maturityDate, final Integer depositPeriod, + final EnumOptionData depositPeriodFrequency, final BigDecimal mandatoryRecommendedDepositAmount, + final EnumOptionData onAccountClosure, final LocalDate expectedFirstDepositOnDate, final BigDecimal totalOverdueAmount, + final Integer noOfOverdueInstallments, final boolean isMandatoryDeposit, final boolean allowWithdrawal, + final boolean adjustAdvanceTowardsFuturePayments, final boolean isCalendarInherited) { final Collection preClosurePenalInterestOnTypeOptions = null; final Collection periodFrequencyTypeOptions = null; @@ -288,8 +284,8 @@ public class RecurringDepositAccountData extends DepositAccountData { interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, account.accountChart, account.chartTemplate, account.preClosurePenalApplicable, account.preClosurePenalInterest, - account.preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, account.minDepositTerm, - account.maxDepositTerm, account.minDepositTermType, account.maxDepositTermType, account.inMultiplesOfDepositTerm, + account.preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, account.minDepositTerm, account.maxDepositTerm, + account.minDepositTermType, account.maxDepositTermType, account.inMultiplesOfDepositTerm, account.inMultiplesOfDepositTermType, account.depositAmount, account.maturityAmount, account.maturityDate, account.depositPeriod, account.depositPeriodFrequency, account.mandatoryRecommendedDepositAmount, periodFrequencyTypeOptions, account.depositType, account.onAccountClosure, account.onAccountClosureOptions, @@ -387,10 +383,9 @@ public class RecurringDepositAccountData extends DepositAccountData { preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, mandatoryRecommendedDepositAmount, - periodFrequencyTypeOptions, depositType, onAccountClosure, onAccountClosureOptions, paymentTypeOptions, - savingsAccountDatas, expectedFirstDepositOnDate, totalOverdueAmount, noOfOverdueInstallments, isMandatoryDeposit, - allowWithdrawal, adjustAdvanceTowardsFuturePayments, isCalendarInherited, recurringFrequency, recurringFrequencyType, - withHoldTax, taxGroup); + periodFrequencyTypeOptions, depositType, onAccountClosure, onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas, + expectedFirstDepositOnDate, totalOverdueAmount, noOfOverdueInstallments, isMandatoryDeposit, allowWithdrawal, + adjustAdvanceTowardsFuturePayments, isCalendarInherited, recurringFrequency, recurringFrequencyType, withHoldTax, taxGroup); } public static RecurringDepositAccountData preClosureDetails(final Long accountId, final BigDecimal maturityAmount, @@ -479,10 +474,9 @@ public class RecurringDepositAccountData extends DepositAccountData { preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, mandatoryRecommendedDepositAmount, - periodFrequencyTypeOptions, depositType, onAccountClosure, onAccountClosureOptions, paymentTypeOptions, - savingsAccountDatas, expectedFirstDepositOnDate, totalOverdueAmount, noOfOverdueInstallments, isMandatoryDeposit, - allowWithdrawal, adjustAdvanceTowardsFuturePayments, isCalendarInherited, recurringFrequency, recurringFrequencyType, - withHoldTax, taxGroup); + periodFrequencyTypeOptions, depositType, onAccountClosure, onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas, + expectedFirstDepositOnDate, totalOverdueAmount, noOfOverdueInstallments, isMandatoryDeposit, allowWithdrawal, + adjustAdvanceTowardsFuturePayments, isCalendarInherited, recurringFrequency, recurringFrequencyType, withHoldTax, taxGroup); } public static RecurringDepositAccountData withClosureTemplateDetails(final RecurringDepositAccountData account, @@ -517,11 +511,11 @@ public class RecurringDepositAccountData extends DepositAccountData { final SavingsAccountApplicationTimelineData timeline, final CurrencyData currency, final BigDecimal nominalAnnualInterestRate, final EnumOptionData interestPeriodType, final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, - final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, - final EnumOptionData lockinPeriodFrequencyType, final boolean withdrawalFeeForTransfers, - final BigDecimal minBalanceForInterestCalculation, final SavingsAccountSummaryData summary, - final Collection transactions, final Collection productOptions, - final Collection fieldOfficerOptions, final Collection interestCompoundingPeriodTypeOptions, + final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, + final boolean withdrawalFeeForTransfers, final BigDecimal minBalanceForInterestCalculation, + final SavingsAccountSummaryData summary, final Collection transactions, + final Collection productOptions, final Collection fieldOfficerOptions, + final Collection interestCompoundingPeriodTypeOptions, final Collection interestPostingPeriodTypeOptions, final Collection interestCalculationTypeOptions, final Collection interestCalculationDaysInYearTypeOptions, @@ -543,8 +537,8 @@ public class RecurringDepositAccountData extends DepositAccountData { final Integer recurringFrequency, final EnumOptionData recurringFrequencyType, final boolean withHoldTax, final TaxGroupData taxGroup) { - super(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldofficerId, - fieldofficerName, status, timeline, currency, nominalAnnualInterestRate, interestPeriodType, interestPostingPeriodType, + super(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldofficerId, fieldofficerName, + status, timeline, currency, nominalAnnualInterestRate, interestPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/RecurringDepositProductData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/RecurringDepositProductData.java index 87b8f89f9..b550c3f36 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/RecurringDepositProductData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/RecurringDepositProductData.java @@ -107,15 +107,14 @@ public class RecurringDepositProductData extends DepositProductData { return new RecurringDepositProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency, lockinPeriodFrequencyType, minBalanceForInterestCalculation, accountingRule, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, preClosurePenalApplicable, preClosurePenalInterest, - preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, - maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, isMandatoryDeposit, allowWithdrawal, - adjustAdvanceTowardsFuturePayments, periodFrequencyTypeOptions, minDepositAmount, depositAmount, maxDepositAmount, - withHoldTax, taxGroup, taxGroupOptions); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, + penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, + preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, + minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, + inMultiplesOfDepositTermType, isMandatoryDeposit, allowWithdrawal, adjustAdvanceTowardsFuturePayments, + periodFrequencyTypeOptions, minDepositAmount, depositAmount, maxDepositAmount, withHoldTax, taxGroup, taxGroupOptions); } public static RecurringDepositProductData withCharges(final RecurringDepositProductData existingProduct, @@ -185,8 +184,7 @@ public class RecurringDepositProductData extends DepositProductData { } public static RecurringDepositProductData withAccountingDetails(final RecurringDepositProductData existingProduct, - final Map accountingMappings, - final Collection paymentChannelToFundSourceMappings, + final Map accountingMappings, final Collection paymentChannelToFundSourceMappings, final Collection feeToIncomeAccountMappings, final Collection penaltyToIncomeAccountMappings) { @@ -209,27 +207,26 @@ public class RecurringDepositProductData extends DepositProductData { existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, existingProduct.minBalanceForInterestCalculation, existingProduct.accountingRule, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, existingProduct.interestRateCharts, existingProduct.chartTemplate, - existingProduct.preClosurePenalApplicable, existingProduct.preClosurePenalInterest, - existingProduct.preClosurePenalInterestOnType, existingProduct.preClosurePenalInterestOnTypeOptions, - existingProduct.minDepositTerm, existingProduct.maxDepositTerm, existingProduct.minDepositTermType, - existingProduct.maxDepositTermType, existingProduct.inMultiplesOfDepositTerm, existingProduct.inMultiplesOfDepositTermType, - existingProduct.isMandatoryDeposit, existingProduct.allowWithdrawal, existingProduct.adjustAdvanceTowardsFuturePayments, - existingProduct.periodFrequencyTypeOptions, existingProduct.minDepositAmount, existingProduct.depositAmount, - existingProduct.maxDepositAmount, existingProduct.withHoldTax, existingProduct.taxGroup, existingProduct.taxGroupOptions); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, existingProduct.charges, + chargeOptions, penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, + existingProduct.interestRateCharts, existingProduct.chartTemplate, existingProduct.preClosurePenalApplicable, + existingProduct.preClosurePenalInterest, existingProduct.preClosurePenalInterestOnType, + existingProduct.preClosurePenalInterestOnTypeOptions, existingProduct.minDepositTerm, existingProduct.maxDepositTerm, + existingProduct.minDepositTermType, existingProduct.maxDepositTermType, existingProduct.inMultiplesOfDepositTerm, + existingProduct.inMultiplesOfDepositTermType, existingProduct.isMandatoryDeposit, existingProduct.allowWithdrawal, + existingProduct.adjustAdvanceTowardsFuturePayments, existingProduct.periodFrequencyTypeOptions, + existingProduct.minDepositAmount, existingProduct.depositAmount, existingProduct.maxDepositAmount, + existingProduct.withHoldTax, existingProduct.taxGroup, existingProduct.taxGroupOptions); } - public static RecurringDepositProductData instance(final DepositProductData depositProductData, - final boolean preClosurePenalApplicable, final BigDecimal preClosurePenalInterest, - final EnumOptionData preClosurePenalInterestOnType, final Integer minDepositTerm, final Integer maxDepositTerm, - final EnumOptionData minDepositTermType, final EnumOptionData maxDepositTermType, final Integer inMultiplesOfDepositTerm, - final EnumOptionData inMultiplesOfDepositTermType, final boolean isMandatoryDeposit, boolean allowWithdrawal, - boolean adjustAdvanceTowardsFuturePayments, final BigDecimal minDepositAmount, final BigDecimal depositAmount, - final BigDecimal maxDepositAmount) { + public static RecurringDepositProductData instance(final DepositProductData depositProductData, final boolean preClosurePenalApplicable, + final BigDecimal preClosurePenalInterest, final EnumOptionData preClosurePenalInterestOnType, final Integer minDepositTerm, + final Integer maxDepositTerm, final EnumOptionData minDepositTermType, final EnumOptionData maxDepositTermType, + final Integer inMultiplesOfDepositTerm, final EnumOptionData inMultiplesOfDepositTermType, final boolean isMandatoryDeposit, + boolean allowWithdrawal, boolean adjustAdvanceTowardsFuturePayments, final BigDecimal minDepositAmount, + final BigDecimal depositAmount, final BigDecimal maxDepositAmount) { final Map accountingMappings = null; final Collection paymentChannelToFundSourceMappings = null; @@ -261,15 +258,15 @@ public class RecurringDepositProductData extends DepositProductData { depositProductData.interestCalculationType, depositProductData.interestCalculationDaysInYearType, depositProductData.lockinPeriodFrequency, depositProductData.lockinPeriodFrequencyType, depositProductData.minBalanceForInterestCalculation, depositProductData.accountingRule, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, preClosurePenalApplicable, preClosurePenalInterest, - preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, - maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, isMandatoryDeposit, allowWithdrawal, - adjustAdvanceTowardsFuturePayments, periodFrequencyTypeOptions, minDepositAmount, depositAmount, maxDepositAmount, - depositProductData.withHoldTax, depositProductData.taxGroup, taxGroupOptions); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, + penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, + preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, + minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, + inMultiplesOfDepositTermType, isMandatoryDeposit, allowWithdrawal, adjustAdvanceTowardsFuturePayments, + periodFrequencyTypeOptions, minDepositAmount, depositAmount, maxDepositAmount, depositProductData.withHoldTax, + depositProductData.taxGroup, taxGroupOptions); } public static RecurringDepositProductData lookup(final Long id, final String name) { @@ -332,15 +329,14 @@ public class RecurringDepositProductData extends DepositProductData { return new RecurringDepositProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency, lockinPeriodFrequencyType, minBalanceForInterestCalculation, accountingType, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, preClosurePenalApplicable, preClosurePenalInterest, - preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, - maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, isMandatoryDeposit, allowWithdrawal, - adjustAdvanceTowardsFuturePayments, periodFrequencyTypeOptions, minDepositAmount, depositAmount, maxDepositAmount, - withHoldTax, taxGroup, taxGroupOptions); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, + penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, + preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, + minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, + inMultiplesOfDepositTermType, isMandatoryDeposit, allowWithdrawal, adjustAdvanceTowardsFuturePayments, + periodFrequencyTypeOptions, minDepositAmount, depositAmount, maxDepositAmount, withHoldTax, taxGroup, taxGroupOptions); } public static RecurringDepositProductData withInterestChart(final RecurringDepositProductData product, @@ -388,8 +384,8 @@ public class RecurringDepositProductData extends DepositProductData { final EnumOptionData maxDepositTermType, final Integer inMultiplesOfDepositTerm, final EnumOptionData inMultiplesOfDepositTermType, final boolean isMandatoryDeposit, boolean allowWithdrawal, boolean adjustAdvanceTowardsFuturePayments, final Collection periodFrequencyTypeOptions, - final BigDecimal minDepositAmount, final BigDecimal depositAmount, final BigDecimal maxDepositAmount, - final boolean withHoldTax, final TaxGroupData taxGroup, final Collection taxGroupOptions) { + final BigDecimal minDepositAmount, final BigDecimal depositAmount, final BigDecimal maxDepositAmount, final boolean withHoldTax, + final TaxGroupData taxGroup, final Collection taxGroupOptions) { super(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency, @@ -480,4 +476,4 @@ public class RecurringDepositProductData extends DepositProductData { public boolean isAdjustAdvanceTowardsFuturePayments() { return adjustAdvanceTowardsFuturePayments; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountAnnualFeeData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountAnnualFeeData.java index 920f8c4fa..a83c75774 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountAnnualFeeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountAnnualFeeData.java @@ -54,4 +54,4 @@ public class SavingsAccountAnnualFeeData { public String getAccountNo() { return this.accountNo; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountApplicationTimelineData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountApplicationTimelineData.java index 16e474094..120917689 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountApplicationTimelineData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountApplicationTimelineData.java @@ -124,4 +124,4 @@ public class SavingsAccountApplicationTimelineData implements Serializable { public LocalDate getActivatedOnDate() { return activatedOnDate; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountChargeData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountChargeData.java index 29cddbb24..723ba2dd4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountChargeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountChargeData.java @@ -78,11 +78,11 @@ public class SavingsAccountChargeData implements Serializable { private final Collection chargeOptions; - public SavingsAccountChargeData(Long chargeId, BigDecimal amount,LocalDate dueDate) { + public SavingsAccountChargeData(Long chargeId, BigDecimal amount, LocalDate dueDate) { this.chargeId = chargeId; this.amount = amount; this.dueDate = dueDate; - this.id=null; + this.id = null; this.accountId = null; this.name = null; this.chargeTimeType = null; @@ -192,5 +192,4 @@ public class SavingsAccountChargeData implements Serializable { return this.amountOutstanding; } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountChargeDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountChargeDataValidator.java index f69421d34..9fc9bdb2e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountChargeDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountChargeDataValidator.java @@ -89,7 +89,8 @@ public class SavingsAccountChargeDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsAccountConstant.SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + SavingsAccountConstant.SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -125,7 +126,8 @@ public class SavingsAccountChargeDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsAccountConstant.SAVINGS_ACCOUNT_CHARGES_PAY_CHARGE_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + SavingsAccountConstant.SAVINGS_ACCOUNT_CHARGES_PAY_CHARGE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -145,4 +147,4 @@ public class SavingsAccountChargeDataValidator { private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountConstant.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountConstant.java index c503c50d9..dce547582 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountConstant.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountConstant.java @@ -30,19 +30,17 @@ public class SavingsAccountConstant extends SavingsApiConstants { * {@link SavingsProductData}. Where possible, we try to get response * parameters to match those of request parameters. */ - protected static final Set SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - localeParamName, dateFormatParamName, monthDayFormatParamName, staffIdParamName, isGSIM, isParentAccount,accountNoParamName, - externalIdParamName, clientIdParamName, groupIdParamName, productIdParamName, fieldOfficerIdParamName, - submittedOnDateParamName, nominalAnnualInterestRateParamName, interestCompoundingPeriodTypeParamName, - interestPostingPeriodTypeParamName, interestCalculationTypeParamName, - interestCalculationDaysInYearTypeParamName, minRequiredOpeningBalanceParamName, + protected static final Set SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(localeParamName, + dateFormatParamName, monthDayFormatParamName, staffIdParamName, isGSIM, isParentAccount, accountNoParamName, + externalIdParamName, clientIdParamName, groupIdParamName, productIdParamName, fieldOfficerIdParamName, submittedOnDateParamName, + nominalAnnualInterestRateParamName, interestCompoundingPeriodTypeParamName, interestPostingPeriodTypeParamName, + interestCalculationTypeParamName, interestCalculationDaysInYearTypeParamName, minRequiredOpeningBalanceParamName, lockinPeriodFrequencyParamName, lockinPeriodFrequencyTypeParamName, // withdrawalFeeAmountParamName, withdrawalFeeTypeParamName, - withdrawalFeeForTransfersParamName, feeAmountParamName, feeOnMonthDayParamName, chargesParamName, - allowOverdraftParamName, overdraftLimitParamName, minRequiredBalanceParamName, - enforceMinRequiredBalanceParamName, nominalAnnualInterestRateOverdraftParamName, - minOverdraftForInterestCalculationParamName, withHoldTaxParamName, datatables, gsimApplicationId, - gsimLastApplication)); + withdrawalFeeForTransfersParamName, feeAmountParamName, feeOnMonthDayParamName, chargesParamName, allowOverdraftParamName, + overdraftLimitParamName, minRequiredBalanceParamName, enforceMinRequiredBalanceParamName, + nominalAnnualInterestRateOverdraftParamName, minOverdraftForInterestCalculationParamName, withHoldTaxParamName, datatables, + gsimApplicationId, gsimLastApplication)); /** * These parameters will match the class level parameters of @@ -52,9 +50,8 @@ public class SavingsAccountConstant extends SavingsApiConstants { protected static final Set SAVINGS_ACCOUNT_TRANSACTION_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(localeParamName, dateFormatParamName, transactionDateParamName, transactionAmountParamName, - paymentTypeIdParamName, transactionAccountNumberParamName, checkNumberParamName, - routingCodeParamName, receiptNumberParamName, bankNumberParamName, retailEntriesParamName, - childAccountIdParamName, noteParamName)); + paymentTypeIdParamName, transactionAccountNumberParamName, checkNumberParamName, routingCodeParamName, + receiptNumberParamName, bankNumberParamName, retailEntriesParamName, childAccountIdParamName, noteParamName)); protected static final Set SAVINGS_ACCOUNT_TRANSACTION_RESPONSE_DATA_PARAMETERS = new HashSet<>( Arrays.asList(idParamName, accountNoParamName)); @@ -62,14 +59,14 @@ public class SavingsAccountConstant extends SavingsApiConstants { protected static final Set SAVINGS_ACCOUNT_ACTIVATION_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(localeParamName, dateFormatParamName, activatedOnDateParamName)); - protected static final Set SAVINGS_ACCOUNT_CLOSE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( - localeParamName, dateFormatParamName, closedOnDateParamName, noteParamName, paymentTypeIdParamName, - withdrawBalanceParamName, transactionAccountNumberParamName, checkNumberParamName, routingCodeParamName, - receiptNumberParamName, bankNumberParamName, postInterestValidationOnClosure)); + protected static final Set SAVINGS_ACCOUNT_CLOSE_REQUEST_DATA_PARAMETERS = new HashSet<>( + Arrays.asList(localeParamName, dateFormatParamName, closedOnDateParamName, noteParamName, paymentTypeIdParamName, + withdrawBalanceParamName, transactionAccountNumberParamName, checkNumberParamName, routingCodeParamName, + receiptNumberParamName, bankNumberParamName, postInterestValidationOnClosure)); protected static final Set SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(chargeIdParamName, amountParamName, dueAsOfDateParamName, dateFormatParamName, - localeParamName, feeOnMonthDayParamName, monthDayFormatParamName, feeIntervalParamName)); + Arrays.asList(chargeIdParamName, amountParamName, dueAsOfDateParamName, dateFormatParamName, localeParamName, + feeOnMonthDayParamName, monthDayFormatParamName, feeIntervalParamName)); protected static final Set SAVINGS_ACCOUNT_CHARGES_PAY_CHARGE_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(amountParamName, dueAsOfDateParamName, dateFormatParamName, localeParamName)); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountData.java index 31e034093..a22a9c144 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountData.java @@ -107,34 +107,33 @@ public class SavingsAccountData implements Serializable { private List datatables = null; - //import field + // import field private Long productId; private String locale; private String dateFormat; private transient Integer rowIndex; private LocalDate submittedOnDate; - public static SavingsAccountData importInstanceIndividual(Long clientId, Long productId, Long fieldOfficerId,LocalDate submittedOnDate, + public static SavingsAccountData importInstanceIndividual(Long clientId, Long productId, Long fieldOfficerId, LocalDate submittedOnDate, BigDecimal nominalAnnualInterestRate, EnumOptionData interestCompoundingPeriodTypeEnum, - EnumOptionData interestPostingPeriodTypeEnum,EnumOptionData interestCalculationTypeEnum, - EnumOptionData interestCalculationDaysInYearTypeEnum,BigDecimal minRequiredOpeningBalance, - Integer lockinPeriodFrequency,EnumOptionData lockinPeriodFrequencyTypeEnum, boolean applyWithdrawalFeeForTransfers, - Integer rowIndex,String externalId,Collection charges,boolean allowOverdraft, - BigDecimal overdraftLimit,String locale, String dateFormat){ + EnumOptionData interestPostingPeriodTypeEnum, EnumOptionData interestCalculationTypeEnum, + EnumOptionData interestCalculationDaysInYearTypeEnum, BigDecimal minRequiredOpeningBalance, Integer lockinPeriodFrequency, + EnumOptionData lockinPeriodFrequencyTypeEnum, boolean applyWithdrawalFeeForTransfers, Integer rowIndex, String externalId, + Collection charges, boolean allowOverdraft, BigDecimal overdraftLimit, String locale, + String dateFormat) { return new SavingsAccountData(clientId, productId, fieldOfficerId, submittedOnDate, nominalAnnualInterestRate, interestCompoundingPeriodTypeEnum, interestPostingPeriodTypeEnum, interestCalculationTypeEnum, interestCalculationDaysInYearTypeEnum, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, - applyWithdrawalFeeForTransfers, rowIndex, externalId, charges, allowOverdraft, overdraftLimit,locale,dateFormat); + applyWithdrawalFeeForTransfers, rowIndex, externalId, charges, allowOverdraft, overdraftLimit, locale, dateFormat); } - private SavingsAccountData(Long clientId, Long productId, Long fieldOfficerId,LocalDate submittedOnDate, - BigDecimal nominalAnnualInterestRate, EnumOptionData interestCompoundingPeriodType, - EnumOptionData interestPostingPeriodType,EnumOptionData interestCalculationType, - EnumOptionData interestCalculationDaysInYearType,BigDecimal minRequiredOpeningBalance, - Integer lockinPeriodFrequency,EnumOptionData lockinPeriodFrequencyType, boolean withdrawalFeeForTransfers, - Integer rowIndex,String externalId,Collection charges,boolean allowOverdraft, - BigDecimal overdraftLimit,String locale, String dateFormat) { + private SavingsAccountData(Long clientId, Long productId, Long fieldOfficerId, LocalDate submittedOnDate, + BigDecimal nominalAnnualInterestRate, EnumOptionData interestCompoundingPeriodType, EnumOptionData interestPostingPeriodType, + EnumOptionData interestCalculationType, EnumOptionData interestCalculationDaysInYearType, BigDecimal minRequiredOpeningBalance, + Integer lockinPeriodFrequency, EnumOptionData lockinPeriodFrequencyType, boolean withdrawalFeeForTransfers, Integer rowIndex, + String externalId, Collection charges, boolean allowOverdraft, BigDecimal overdraftLimit, + String locale, String dateFormat) { this.id = null; this.accountNo = null; this.depositType = null; @@ -191,11 +190,11 @@ public class SavingsAccountData implements Serializable { this.minOverdraftForInterestCalculation = null; this.datatables = null; this.productId = productId; - this.dateFormat=dateFormat; - this.locale= locale; + this.dateFormat = dateFormat; + this.locale = locale; this.rowIndex = rowIndex; - this.submittedOnDate=submittedOnDate; - this.savingsAmountOnHold=null; + this.submittedOnDate = submittedOnDate; + this.savingsAmountOnHold = null; } public static final Comparator ClientNameComparator = new Comparator() { @@ -232,30 +231,27 @@ public class SavingsAccountData implements Serializable { return timeline; } - public static SavingsAccountData importInstanceGroup(Long groupId, Long productId, Long fieldOfficerId, - LocalDate submittedOnDate, + public static SavingsAccountData importInstanceGroup(Long groupId, Long productId, Long fieldOfficerId, LocalDate submittedOnDate, BigDecimal nominalAnnualInterestRate, EnumOptionData interestCompoundingPeriodTypeEnum, - EnumOptionData interestPostingPeriodTypeEnum,EnumOptionData interestCalculationTypeEnum, - EnumOptionData interestCalculationDaysInYearTypeEnum,BigDecimal minRequiredOpeningBalance, - Integer lockinPeriodFrequency,EnumOptionData lockinPeriodFrequencyTypeEnum, - boolean applyWithdrawalFeeForTransfers, - Integer rowIndex,String externalId,Collection charges, - boolean allowOverdraft, - BigDecimal overdraftLimit,String locale, String dateFormat){ + EnumOptionData interestPostingPeriodTypeEnum, EnumOptionData interestCalculationTypeEnum, + EnumOptionData interestCalculationDaysInYearTypeEnum, BigDecimal minRequiredOpeningBalance, Integer lockinPeriodFrequency, + EnumOptionData lockinPeriodFrequencyTypeEnum, boolean applyWithdrawalFeeForTransfers, Integer rowIndex, String externalId, + Collection charges, boolean allowOverdraft, BigDecimal overdraftLimit, String locale, + String dateFormat) { return new SavingsAccountData(groupId, productId, fieldOfficerId, submittedOnDate, nominalAnnualInterestRate, interestCompoundingPeriodTypeEnum, interestPostingPeriodTypeEnum, interestCalculationTypeEnum, interestCalculationDaysInYearTypeEnum, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, - applyWithdrawalFeeForTransfers, rowIndex, externalId, charges, allowOverdraft, overdraftLimit,null,locale,dateFormat); + applyWithdrawalFeeForTransfers, rowIndex, externalId, charges, allowOverdraft, overdraftLimit, null, locale, dateFormat); } - private SavingsAccountData(Long groupId, Long productId, Long fieldOfficerId,LocalDate submittedOnDate, - BigDecimal nominalAnnualInterestRate, EnumOptionData interestCompoundingPeriodType, - EnumOptionData interestPostingPeriodType,EnumOptionData interestCalculationType, - EnumOptionData interestCalculationDaysInYearType,BigDecimal minRequiredOpeningBalance, - Integer lockinPeriodFrequency,EnumOptionData lockinPeriodFrequencyType, boolean withdrawalFeeForTransfers, - Integer rowIndex,String externalId,Collection charges,boolean allowOverdraft, - BigDecimal overdraftLimit,Long id,String locale, String dateFormat) { + + private SavingsAccountData(Long groupId, Long productId, Long fieldOfficerId, LocalDate submittedOnDate, + BigDecimal nominalAnnualInterestRate, EnumOptionData interestCompoundingPeriodType, EnumOptionData interestPostingPeriodType, + EnumOptionData interestCalculationType, EnumOptionData interestCalculationDaysInYearType, BigDecimal minRequiredOpeningBalance, + Integer lockinPeriodFrequency, EnumOptionData lockinPeriodFrequencyType, boolean withdrawalFeeForTransfers, Integer rowIndex, + String externalId, Collection charges, boolean allowOverdraft, BigDecimal overdraftLimit, Long id, + String locale, String dateFormat) { this.id = id; this.accountNo = null; this.depositType = null; @@ -312,11 +308,11 @@ public class SavingsAccountData implements Serializable { this.minOverdraftForInterestCalculation = null; this.datatables = null; this.productId = productId; - this.dateFormat= dateFormat; - this.locale= locale; + this.dateFormat = dateFormat; + this.locale = locale; this.rowIndex = rowIndex; - this.submittedOnDate=submittedOnDate; - this.savingsAmountOnHold=null; + this.submittedOnDate = submittedOnDate; + this.savingsAmountOnHold = null; } public Integer getRowIndex() { @@ -326,18 +322,18 @@ public class SavingsAccountData implements Serializable { public static SavingsAccountData instance(final Long id, final String accountNo, final EnumOptionData depositType, final String externalId, final Long groupId, final String groupName, final Long clientId, final String clientName, final Long productId, final String productName, final Long fieldOfficerId, final String fieldOfficerName, - final SavingsAccountStatusEnumData status, SavingsAccountSubStatusEnumData subStatus, final SavingsAccountApplicationTimelineData timeline, - final CurrencyData currency, final BigDecimal interestRate, + final SavingsAccountStatusEnumData status, SavingsAccountSubStatusEnumData subStatus, + final SavingsAccountApplicationTimelineData timeline, final CurrencyData currency, final BigDecimal interestRate, final EnumOptionData interestCompoundingPeriodType, final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, final boolean withdrawalFeeForTransfers, final SavingsAccountSummaryData summary, final boolean allowOverdraft, - final BigDecimal overdraftLimit, final BigDecimal minRequiredBalance, - final boolean enforceMinRequiredBalance, final BigDecimal minBalanceForInterestCalculation, - final BigDecimal onHoldFunds, final BigDecimal nominalAnnualInterestRateOverdraft, - final BigDecimal minOverdraftForInterestCalculation, final boolean withHoldTax, final TaxGroupData taxGroup, - final LocalDate lastActiveTransactionDate, final boolean isDormancyTrackingActive, final Integer daysToInactive, - final Integer daysToDormancy, final Integer daysToEscheat, final BigDecimal savingsAmountOnHold) { + final BigDecimal overdraftLimit, final BigDecimal minRequiredBalance, final boolean enforceMinRequiredBalance, + final BigDecimal minBalanceForInterestCalculation, final BigDecimal onHoldFunds, + final BigDecimal nominalAnnualInterestRateOverdraft, final BigDecimal minOverdraftForInterestCalculation, + final boolean withHoldTax, final TaxGroupData taxGroup, final LocalDate lastActiveTransactionDate, + final boolean isDormancyTrackingActive, final Integer daysToInactive, final Integer daysToDormancy, final Integer daysToEscheat, + final BigDecimal savingsAmountOnHold) { final Collection productOptions = null; final Collection fieldOfficerOptions = null; @@ -355,13 +351,13 @@ public class SavingsAccountData implements Serializable { return new SavingsAccountData(id, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, - minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions, - productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit, - minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds, - nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup, - lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat, savingsAmountOnHold); + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, + transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit, minRequiredBalance, + enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds, nominalAnnualInterestRateOverdraft, + minOverdraftForInterestCalculation, withHoldTax, taxGroup, lastActiveTransactionDate, isDormancyTrackingActive, + daysToInactive, daysToDormancy, daysToEscheat, savingsAmountOnHold); } public static SavingsAccountData lookup(final Long accountId, final String accountNo, final EnumOptionData depositType) { @@ -428,13 +424,13 @@ public class SavingsAccountData implements Serializable { return new SavingsAccountData(accountId, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, nominalAnnualInterestRate, interestPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, - minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions, - productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit, - minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds, - nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup, - lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat, savingsAmountOnHold); + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, + transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit, minRequiredBalance, + enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds, nominalAnnualInterestRateOverdraft, + minOverdraftForInterestCalculation, withHoldTax, taxGroup, lastActiveTransactionDate, isDormancyTrackingActive, + daysToInactive, daysToDormancy, daysToEscheat, savingsAmountOnHold); } public static SavingsAccountData lookupWithProductDetails(final Long accountId, final String accountNo, @@ -499,13 +495,13 @@ public class SavingsAccountData implements Serializable { return new SavingsAccountData(accountId, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, nominalAnnualInterestRate, interestPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, - minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions, - productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit, - minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds, - nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup, - lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat, savingsAmountOnHold); + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, + transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit, minRequiredBalance, + enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds, nominalAnnualInterestRateOverdraft, + minOverdraftForInterestCalculation, withHoldTax, taxGroup, lastActiveTransactionDate, isDormancyTrackingActive, + daysToInactive, daysToDormancy, daysToEscheat, savingsAmountOnHold); } public static SavingsAccountData withTemplateOptions(final SavingsAccountData account, final SavingsAccountData template, @@ -529,19 +525,18 @@ public class SavingsAccountData implements Serializable { return new SavingsAccountData(account.id, account.accountNo, account.depositType, account.externalId, account.groupId, account.groupName, account.clientId, account.clientName, account.savingsProductId, account.savingsProductName, - account.fieldOfficerId, account.fieldOfficerName, account.status, account.subStatus, account.timeline, - account.currency, account.nominalAnnualInterestRate, account.interestCompoundingPeriodType, - account.interestPostingPeriodType, account.interestCalculationType, account.interestCalculationDaysInYearType, - account.minRequiredOpeningBalance, account.lockinPeriodFrequency, account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers, - account.summary, transactions, template.productOptions, template.fieldOfficerOptions, - template.interestCompoundingPeriodTypeOptions, template.interestPostingPeriodTypeOptions, - template.interestCalculationTypeOptions, template.interestCalculationDaysInYearTypeOptions, - template.lockinPeriodFrequencyTypeOptions, template.withdrawalFeeTypeOptions, charges, template.chargeOptions, account.allowOverdraft, - account.overdraftLimit, account.minRequiredBalance, account.enforceMinRequiredBalance, - account.minBalanceForInterestCalculation, account.onHoldFunds, account.nominalAnnualInterestRateOverdraft, - account.minOverdraftForInterestCalculation, account.withHoldTax, account.taxGroup, - account.lastActiveTransactionDate, account.isDormancyTrackingActive, account.daysToInactive, - account.daysToDormancy, account.daysToEscheat, account.savingsAmountOnHold); + account.fieldOfficerId, account.fieldOfficerName, account.status, account.subStatus, account.timeline, account.currency, + account.nominalAnnualInterestRate, account.interestCompoundingPeriodType, account.interestPostingPeriodType, + account.interestCalculationType, account.interestCalculationDaysInYearType, account.minRequiredOpeningBalance, + account.lockinPeriodFrequency, account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers, account.summary, + transactions, template.productOptions, template.fieldOfficerOptions, template.interestCompoundingPeriodTypeOptions, + template.interestPostingPeriodTypeOptions, template.interestCalculationTypeOptions, + template.interestCalculationDaysInYearTypeOptions, template.lockinPeriodFrequencyTypeOptions, + template.withdrawalFeeTypeOptions, charges, template.chargeOptions, account.allowOverdraft, account.overdraftLimit, + account.minRequiredBalance, account.enforceMinRequiredBalance, account.minBalanceForInterestCalculation, + account.onHoldFunds, account.nominalAnnualInterestRateOverdraft, account.minOverdraftForInterestCalculation, + account.withHoldTax, account.taxGroup, account.lastActiveTransactionDate, account.isDormancyTrackingActive, + account.daysToInactive, account.daysToDormancy, account.daysToEscheat, account.savingsAmountOnHold); } public static SavingsAccountData withTemplateOptions(final SavingsAccountData account, @@ -556,17 +551,17 @@ public class SavingsAccountData implements Serializable { return new SavingsAccountData(account.id, account.accountNo, account.depositType, account.externalId, account.groupId, account.groupName, account.clientId, account.clientName, account.savingsProductId, account.savingsProductName, - account.fieldOfficerId, account.fieldOfficerName, account.status, account.subStatus, account.timeline, - account.currency, account.nominalAnnualInterestRate, account.interestCompoundingPeriodType, - account.interestPostingPeriodType, account.interestCalculationType, account.interestCalculationDaysInYearType, - account.minRequiredOpeningBalance, account.lockinPeriodFrequency, account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers, - account.summary, transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, account.allowOverdraft, - account.overdraftLimit, account.minRequiredBalance, account.enforceMinRequiredBalance, - account.minBalanceForInterestCalculation, account.onHoldFunds, account.nominalAnnualInterestRateOverdraft, - account.minOverdraftForInterestCalculation, account.withHoldTax, account.taxGroup, account.lastActiveTransactionDate, - account.isDormancyTrackingActive, account.daysToInactive, account.daysToDormancy, account.daysToEscheat, account.savingsAmountOnHold); + account.fieldOfficerId, account.fieldOfficerName, account.status, account.subStatus, account.timeline, account.currency, + account.nominalAnnualInterestRate, account.interestCompoundingPeriodType, account.interestPostingPeriodType, + account.interestCalculationType, account.interestCalculationDaysInYearType, account.minRequiredOpeningBalance, + account.lockinPeriodFrequency, account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers, account.summary, + transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, charges, chargeOptions, account.allowOverdraft, account.overdraftLimit, + account.minRequiredBalance, account.enforceMinRequiredBalance, account.minBalanceForInterestCalculation, + account.onHoldFunds, account.nominalAnnualInterestRateOverdraft, account.minOverdraftForInterestCalculation, + account.withHoldTax, account.taxGroup, account.lastActiveTransactionDate, account.isDormancyTrackingActive, + account.daysToInactive, account.daysToDormancy, account.daysToEscheat, account.savingsAmountOnHold); } public static SavingsAccountData withClientTemplate(final Long clientId, final String clientName, final Long groupId, @@ -633,37 +628,37 @@ public class SavingsAccountData implements Serializable { return new SavingsAccountData(id, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, nominalAnnualInterestRate, interestPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, - minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions, - productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit, - minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds, - nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup, - lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat, savingsAmountOnHold); + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, + transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit, minRequiredBalance, + enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds, nominalAnnualInterestRateOverdraft, + minOverdraftForInterestCalculation, withHoldTax, taxGroup, lastActiveTransactionDate, isDormancyTrackingActive, + daysToInactive, daysToDormancy, daysToEscheat, savingsAmountOnHold); } private SavingsAccountData(final Long id, final String accountNo, final EnumOptionData depositType, final String externalId, final Long groupId, final String groupName, final Long clientId, final String clientName, final Long productId, final String productName, final Long fieldOfficerId, final String fieldOfficerName, final SavingsAccountStatusEnumData status, - final SavingsAccountSubStatusEnumData subStatus, final SavingsAccountApplicationTimelineData timeline, final CurrencyData currency, - final BigDecimal nominalAnnualInterestRate, final EnumOptionData interestPeriodType, + final SavingsAccountSubStatusEnumData subStatus, final SavingsAccountApplicationTimelineData timeline, + final CurrencyData currency, final BigDecimal nominalAnnualInterestRate, final EnumOptionData interestPeriodType, final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, - final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, - final boolean withdrawalFeeForTransfers, final SavingsAccountSummaryData summary, - final Collection transactions, final Collection productOptions, - final Collection fieldOfficerOptions, + final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, final boolean withdrawalFeeForTransfers, + final SavingsAccountSummaryData summary, final Collection transactions, + final Collection productOptions, final Collection fieldOfficerOptions, final Collection interestCompoundingPeriodTypeOptions, final Collection interestPostingPeriodTypeOptions, final Collection interestCalculationTypeOptions, - final Collection interestCalculationDaysInYearTypeOptions, final Collection lockinPeriodFrequencyTypeOptions, - final Collection withdrawalFeeTypeOptions, final Collection charges, final Collection chargeOptions, - final boolean allowOverdraft, final BigDecimal overdraftLimit, final BigDecimal minRequiredBalance, - final boolean enforceMinRequiredBalance, final BigDecimal minBalanceForInterestCalculation, - final BigDecimal onHoldFunds, final BigDecimal nominalAnnualInterestRateOverdraft, - final BigDecimal minOverdraftForInterestCalculation, final boolean withHoldTax, final TaxGroupData taxGroup, - final LocalDate lastActiveTransactionDate, final boolean isDormancyTrackingActive, final Integer daysToInactive, - final Integer daysToDormancy, final Integer daysToEscheat, final BigDecimal savingsAmountOnHold) { + final Collection interestCalculationDaysInYearTypeOptions, + final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, + final Collection charges, final Collection chargeOptions, final boolean allowOverdraft, + final BigDecimal overdraftLimit, final BigDecimal minRequiredBalance, final boolean enforceMinRequiredBalance, + final BigDecimal minBalanceForInterestCalculation, final BigDecimal onHoldFunds, + final BigDecimal nominalAnnualInterestRateOverdraft, final BigDecimal minOverdraftForInterestCalculation, + final boolean withHoldTax, final TaxGroupData taxGroup, final LocalDate lastActiveTransactionDate, + final boolean isDormancyTrackingActive, final Integer daysToInactive, final Integer daysToDormancy, final Integer daysToEscheat, + final BigDecimal savingsAmountOnHold) { this.id = id; this.accountNo = accountNo; this.depositType = depositType; @@ -734,18 +729,14 @@ public class SavingsAccountData implements Serializable { private SavingsAccountChargeData getWithdrawalFee() { for (SavingsAccountChargeData charge : this.charges()) { - if (charge.isWithdrawalFee()) { - return charge; - } + if (charge.isWithdrawalFee()) { return charge; } } return null; } private SavingsAccountChargeData getAnnualFee() { for (SavingsAccountChargeData charge : this.charges()) { - if (charge.isAnnualFee()) { - return charge; - } + if (charge.isAnnualFee()) { return charge; } } return null; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountDataDTO.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountDataDTO.java old mode 100755 new mode 100644 index 6b213b862..f663f36c2 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountDataDTO.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountDataDTO.java @@ -33,8 +33,8 @@ public class SavingsAccountDataDTO { private final AppUser appliedBy; private final DateTimeFormatter fmt; - public SavingsAccountDataDTO(final Client client, final Group group, final Long savingsProductId, - final LocalDate applicationDate, final AppUser appliedBy, final DateTimeFormatter fmt) { + public SavingsAccountDataDTO(final Client client, final Group group, final Long savingsProductId, final LocalDate applicationDate, + final AppUser appliedBy, final DateTimeFormatter fmt) { this.client = client; this.group = group; this.savingsProductId = savingsProductId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountDataValidator.java index 248d6db3d..d67d7153c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountDataValidator.java @@ -139,15 +139,15 @@ public class SavingsAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { - final Integer interestCompoundingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCompoundingPeriodTypeParamName, element); + final Integer interestCompoundingPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(interestPostingPeriodTypeParamName, element)) { - final Integer interestPostingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestPostingPeriodTypeParamName, element); + final Integer interestPostingPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestPostingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestPostingPeriodTypeParamName).value(interestPostingPeriodType).notNull() .isOneOfTheseValues(SavingsPostingInterestPeriodType.integerValues()); } @@ -160,15 +160,15 @@ public class SavingsAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { - final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCalculationDaysInYearTypeParamName, element); + final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(SavingsInterestCalculationDaysInYearType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { - final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minRequiredOpeningBalanceParamName, element); + final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, + element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).zeroOrPositiveAmount(); } @@ -179,16 +179,16 @@ public class SavingsAccountDataValidator { baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).integerZeroOrGreater(); if (lockinPeriodFrequency != null) { - final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - lockinPeriodFrequencyTypeParamName, element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).notNull() .inMinMaxRange(0, 3); } } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { - final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - lockinPeriodFrequencyTypeParamName, element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); if (lockinPeriodFrequencyType != null) { @@ -200,8 +200,8 @@ public class SavingsAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { - final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper.extractBooleanNamed( - withdrawalFeeForTransfersParamName, element); + final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper + .extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } @@ -211,7 +211,7 @@ public class SavingsAccountDataValidator { baseDataValidator.reset().parameter(withHoldTaxParamName).value(withHoldTax).ignoreIfNull().validateForBooleanValue(); } - if(this.fromApiJsonHelper.parameterExists(SavingsApiConstants.datatables, element)){ + if (this.fromApiJsonHelper.parameterExists(SavingsApiConstants.datatables, element)) { final JsonArray datatables = this.fromApiJsonHelper.extractJsonArrayNamed(SavingsApiConstants.datatables, element); baseDataValidator.reset().parameter(SavingsApiConstants.datatables).value(datatables).notNull().jsonArrayNotEmpty(); } @@ -342,15 +342,15 @@ public class SavingsAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { - final Integer interestCompoundingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCompoundingPeriodTypeParamName, element); + final Integer interestCompoundingPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(interestPostingPeriodTypeParamName, element)) { - final Integer interestPostingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestPostingPeriodTypeParamName, element); + final Integer interestPostingPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestPostingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestPostingPeriodTypeParamName).value(interestPostingPeriodType).notNull() .isOneOfTheseValues(SavingsPostingInterestPeriodType.integerValues()); } @@ -363,15 +363,15 @@ public class SavingsAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { - final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCalculationDaysInYearTypeParamName, element); + final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(SavingsInterestCalculationDaysInYearType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { - final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minRequiredOpeningBalanceParamName, element); + final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, + element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } @@ -384,14 +384,14 @@ public class SavingsAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { - final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - lockinPeriodFrequencyTypeParamName, element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { - final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper.extractBooleanNamed( - withdrawalFeeForTransfersParamName, element); + final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper + .extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } @@ -421,13 +421,17 @@ public class SavingsAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(nominalAnnualInterestRateOverdraftParamName, element)) { - final BigDecimal nominalAnnualInterestRateOverdraft = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateOverdraftParamName, element); - baseDataValidator.reset().parameter(nominalAnnualInterestRateOverdraftParamName).value(nominalAnnualInterestRateOverdraft).ignoreIfNull().zeroOrPositiveAmount(); + final BigDecimal nominalAnnualInterestRateOverdraft = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateOverdraftParamName, element); + baseDataValidator.reset().parameter(nominalAnnualInterestRateOverdraftParamName).value(nominalAnnualInterestRateOverdraft) + .ignoreIfNull().zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(minOverdraftForInterestCalculationParamName, element)) { - final BigDecimal minOverdraftForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minOverdraftForInterestCalculationParamName, element); - baseDataValidator.reset().parameter(minOverdraftForInterestCalculationParamName).value(minOverdraftForInterestCalculation).ignoreIfNull().zeroOrPositiveAmount(); + final BigDecimal minOverdraftForInterestCalculation = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(minOverdraftForInterestCalculationParamName, element); + baseDataValidator.reset().parameter(minOverdraftForInterestCalculationParamName).value(minOverdraftForInterestCalculation) + .ignoreIfNull().zeroOrPositiveAmount(); } } @@ -436,13 +440,15 @@ public class SavingsAccountDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set supportedParameters = new HashSet<>(Arrays.asList("fromSavingsOfficerId","toSavingsOfficerId","assignmentDate","locale","dateFormat")); + final Set supportedParameters = new HashSet<>( + Arrays.asList("fromSavingsOfficerId", "toSavingsOfficerId", "assignmentDate", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); final JsonElement element = this.fromApiJsonHelper.parse(json); @@ -456,21 +462,24 @@ public class SavingsAccountDataValidator { final LocalDate assignmentDate = this.fromApiJsonHelper.extractLocalDateNamed("assignmentDate", element); baseDataValidator.reset().parameter("assignmentDate").value(assignmentDate).notNull(); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } } public void validateForUnAssignSavingsOfficer(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set supportedParameters = new HashSet<>(Arrays.asList("unassignedDate","locale","dateFormat")); + final Set supportedParameters = new HashSet<>(Arrays.asList("unassignedDate", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); final JsonElement element = this.fromApiJsonHelper.parse(json); @@ -481,7 +490,9 @@ public class SavingsAccountDataValidator { final LocalDate unassignedDate = this.fromApiJsonHelper.extractLocalDateNamed("unassignedDate", element); baseDataValidator.reset().parameter("unassignedDate").value(unassignedDate).notNull(); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); } + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", + dataValidationErrors); + } + } } -} \ No newline at end of file diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountStatusEnumData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountStatusEnumData.java index f9ba30709..22fb82683 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountStatusEnumData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountStatusEnumData.java @@ -72,4 +72,4 @@ public class SavingsAccountStatusEnumData implements Serializable { public Long id() { return this.id; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountSubStatusEnumData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountSubStatusEnumData.java index e0e929dbf..55aedaaab 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountSubStatusEnumData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountSubStatusEnumData.java @@ -45,8 +45,8 @@ public class SavingsAccountSubStatusEnumData implements Serializable { @SuppressWarnings("unused") private final boolean blockDebit; - public SavingsAccountSubStatusEnumData(final Long id, final String code, final String value, final boolean none, - final boolean inactive, final boolean dormant, final boolean escheat, final boolean block, final boolean blockCredit, final boolean blockDebit) { + public SavingsAccountSubStatusEnumData(final Long id, final String code, final String value, final boolean none, final boolean inactive, + final boolean dormant, final boolean escheat, final boolean block, final boolean blockCredit, final boolean blockDebit) { this.id = id; this.code = code; this.value = value; @@ -62,4 +62,4 @@ public class SavingsAccountSubStatusEnumData implements Serializable { public Long id() { return this.id; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountSummaryData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountSummaryData.java index 2cbb22c7b..ea4741b29 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountSummaryData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountSummaryData.java @@ -48,7 +48,7 @@ public class SavingsAccountSummaryData implements Serializable { public SavingsAccountSummaryData(final CurrencyData currency, final BigDecimal totalDeposits, final BigDecimal totalWithdrawals, final BigDecimal totalWithdrawalFees, final BigDecimal totalAnnualFees, final BigDecimal totalInterestEarned, final BigDecimal totalInterestPosted, final BigDecimal accountBalance, final BigDecimal totalFeeCharge, - final BigDecimal totalPenaltyCharge, final BigDecimal totalOverdraftInterestDerived,final BigDecimal totalWithholdTax, + final BigDecimal totalPenaltyCharge, final BigDecimal totalOverdraftInterestDerived, final BigDecimal totalWithholdTax, final BigDecimal interestNotPosted, final LocalDate lastInterestCalculationDate, final BigDecimal availableBalance) { this.currency = currency; this.totalDeposits = totalDeposits; @@ -66,4 +66,4 @@ public class SavingsAccountSummaryData implements Serializable { this.lastInterestCalculationDate = lastInterestCalculationDate; this.availableBalance = availableBalance; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionDTO.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionDTO.java old mode 100755 new mode 100644 index a0fc14b7f..6512bdc14 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionDTO.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionDTO.java @@ -37,7 +37,8 @@ public class SavingsAccountTransactionDTO { private final Integer depositAccountType; public SavingsAccountTransactionDTO(final DateTimeFormatter formatter, final LocalDate transactionDate, - final BigDecimal transactionAmount, final PaymentDetail paymentDetail, final Date createdDate, final AppUser appUser, final Integer depositAccountType) { + final BigDecimal transactionAmount, final PaymentDetail paymentDetail, final Date createdDate, final AppUser appUser, + final Integer depositAccountType) { this.formatter = formatter; this.transactionDate = transactionDate; this.transactionAmount = transactionAmount; @@ -102,5 +103,4 @@ public class SavingsAccountTransactionDTO { return this.depositAccountType; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionData.java index 21534f70f..a8681ce0c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionData.java @@ -52,12 +52,12 @@ public class SavingsAccountTransactionData implements Serializable { private final LocalDate submittedOnDate; private final boolean interestedPostedAsOn; private final String submittedByUsername; - private final String note ; + private final String note; // templates final Collection paymentTypeOptions; - //import fields + // import fields private transient Integer rowIndex; private transient Long savingsAccountId; private String dateFormat; @@ -71,18 +71,16 @@ public class SavingsAccountTransactionData implements Serializable { private String receiptNumber; private String bankNumber; - public static SavingsAccountTransactionData importInstance(BigDecimal transactionAmount,LocalDate transactionDate, - Long paymentTypeId,String accountNumber, String checkNumber, String routingCode, - String receiptNumber, String bankNumber,Long savingsAccountId, - SavingsAccountTransactionEnumData transactionType, Integer rowIndex,String locale,String dateFormat){ - return new SavingsAccountTransactionData(transactionAmount, transactionDate, paymentTypeId, accountNumber, - checkNumber, routingCode, receiptNumber, bankNumber, savingsAccountId, transactionType, rowIndex,locale,dateFormat); + public static SavingsAccountTransactionData importInstance(BigDecimal transactionAmount, LocalDate transactionDate, Long paymentTypeId, + String accountNumber, String checkNumber, String routingCode, String receiptNumber, String bankNumber, Long savingsAccountId, + SavingsAccountTransactionEnumData transactionType, Integer rowIndex, String locale, String dateFormat) { + return new SavingsAccountTransactionData(transactionAmount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode, + receiptNumber, bankNumber, savingsAccountId, transactionType, rowIndex, locale, dateFormat); } - private SavingsAccountTransactionData(BigDecimal transactionAmount,LocalDate transactionDate, - Long paymentTypeId,String accountNumber, String checkNumber, String routingCode, - String receiptNumber, String bankNumber,Long savingsAccountId, - SavingsAccountTransactionEnumData transactionType, Integer rowIndex,String locale,String dateFormat){ + private SavingsAccountTransactionData(BigDecimal transactionAmount, LocalDate transactionDate, Long paymentTypeId, String accountNumber, + String checkNumber, String routingCode, String receiptNumber, String bankNumber, Long savingsAccountId, + SavingsAccountTransactionEnumData transactionType, Integer rowIndex, String locale, String dateFormat) { this.id = null; this.transactionType = transactionType; this.accountId = null; @@ -98,9 +96,9 @@ public class SavingsAccountTransactionData implements Serializable { this.submittedOnDate = null; this.interestedPostedAsOn = false; this.rowIndex = rowIndex; - this.savingsAccountId=savingsAccountId; - this.dateFormat= dateFormat; - this.locale= locale; + this.savingsAccountId = savingsAccountId; + this.dateFormat = dateFormat; + this.locale = locale; this.transactionDate = transactionDate; this.transactionAmount = transactionAmount; this.paymentTypeId = paymentTypeId; @@ -128,18 +126,20 @@ public class SavingsAccountTransactionData implements Serializable { public static SavingsAccountTransactionData create(final Long id, final SavingsAccountTransactionEnumData transactionType, final PaymentDetailData paymentDetailData, final Long savingsId, final String savingsAccountNo, final LocalDate date, - final CurrencyData currency, final BigDecimal amount, final BigDecimal outstandingChargeAmount,final BigDecimal runningBalance, final boolean reversed, - final AccountTransferData transfer, final boolean interestedPostedAsOn, final String submittedByUsername, final String note) { + final CurrencyData currency, final BigDecimal amount, final BigDecimal outstandingChargeAmount, final BigDecimal runningBalance, + final boolean reversed, final AccountTransferData transfer, final boolean interestedPostedAsOn, + final String submittedByUsername, final String note) { final Collection paymentTypeOptions = null; return new SavingsAccountTransactionData(id, transactionType, paymentDetailData, savingsId, savingsAccountNo, date, currency, - amount, outstandingChargeAmount,runningBalance, reversed, transfer, paymentTypeOptions, interestedPostedAsOn, submittedByUsername, note); + amount, outstandingChargeAmount, runningBalance, reversed, transfer, paymentTypeOptions, interestedPostedAsOn, + submittedByUsername, note); } public static SavingsAccountTransactionData create(final Long id, final SavingsAccountTransactionEnumData transactionType, final PaymentDetailData paymentDetailData, final Long savingsId, final String savingsAccountNo, final LocalDate date, - final CurrencyData currency, final BigDecimal amount, final BigDecimal outstandingChargeAmount, - final BigDecimal runningBalance, final boolean reversed, final AccountTransferData transfer, final LocalDate submittedOnDate, - final boolean interestedPostedAsOn, final String submittedByUsername, final String note) { + final CurrencyData currency, final BigDecimal amount, final BigDecimal outstandingChargeAmount, final BigDecimal runningBalance, + final boolean reversed, final AccountTransferData transfer, final LocalDate submittedOnDate, final boolean interestedPostedAsOn, + final String submittedByUsername, final String note) { final Collection paymentTypeOptions = null; return new SavingsAccountTransactionData(id, transactionType, paymentDetailData, savingsId, savingsAccountNo, date, currency, amount, outstandingChargeAmount, runningBalance, reversed, transfer, paymentTypeOptions, submittedOnDate, @@ -158,9 +158,10 @@ public class SavingsAccountTransactionData implements Serializable { final Collection paymentTypeOptions = null; final boolean interestedPostedAsOn = false; final String submittedByUsername = null; - final String note = null ; + final String note = null; return new SavingsAccountTransactionData(id, transactionType, paymentDetailData, savingsId, savingsAccountNo, defaultLocalDate, - currency, amount, outstandingChargeAmount, runningBalance, reversed, null, null, interestedPostedAsOn, submittedByUsername, note); + currency, amount, outstandingChargeAmount, runningBalance, reversed, null, null, interestedPostedAsOn, submittedByUsername, + note); } public static SavingsAccountTransactionData templateOnTop(final SavingsAccountTransactionData savingsAccountTransactionData, @@ -168,16 +169,17 @@ public class SavingsAccountTransactionData implements Serializable { return new SavingsAccountTransactionData(savingsAccountTransactionData.id, savingsAccountTransactionData.transactionType, savingsAccountTransactionData.paymentDetailData, savingsAccountTransactionData.accountId, savingsAccountTransactionData.accountNo, savingsAccountTransactionData.date, savingsAccountTransactionData.currency, - savingsAccountTransactionData.amount,savingsAccountTransactionData.outstandingChargeAmount, savingsAccountTransactionData.runningBalance, savingsAccountTransactionData.reversed, + savingsAccountTransactionData.amount, savingsAccountTransactionData.outstandingChargeAmount, + savingsAccountTransactionData.runningBalance, savingsAccountTransactionData.reversed, savingsAccountTransactionData.transfer, paymentTypeOptions, savingsAccountTransactionData.interestedPostedAsOn, savingsAccountTransactionData.submittedByUsername, savingsAccountTransactionData.note); } private SavingsAccountTransactionData(final Long id, final SavingsAccountTransactionEnumData transactionType, final PaymentDetailData paymentDetailData, final Long savingsId, final String savingsAccountNo, final LocalDate date, - final CurrencyData currency, final BigDecimal amount, final BigDecimal outstandingChargeAmount, - final BigDecimal runningBalance, final boolean reversed, final AccountTransferData transfer, - final Collection paymentTypeOptions, final boolean interestedPostedAsOn, final String submittedByUsername, final String note) { + final CurrencyData currency, final BigDecimal amount, final BigDecimal outstandingChargeAmount, final BigDecimal runningBalance, + final boolean reversed, final AccountTransferData transfer, final Collection paymentTypeOptions, + final boolean interestedPostedAsOn, final String submittedByUsername, final String note) { this(id, transactionType, paymentDetailData, savingsId, savingsAccountNo, date, currency, amount, outstandingChargeAmount, runningBalance, reversed, transfer, paymentTypeOptions, null, interestedPostedAsOn, submittedByUsername, note); @@ -185,9 +187,9 @@ public class SavingsAccountTransactionData implements Serializable { private SavingsAccountTransactionData(final Long id, final SavingsAccountTransactionEnumData transactionType, final PaymentDetailData paymentDetailData, final Long savingsId, final String savingsAccountNo, final LocalDate date, - final CurrencyData currency, final BigDecimal amount,final BigDecimal outstandingChargeAmount, final BigDecimal runningBalance, final boolean reversed, - final AccountTransferData transfer, final Collection paymentTypeOptions, final LocalDate submittedOnDate, - final boolean interestedPostedAsOn, final String submittedByUsername, final String note) { + final CurrencyData currency, final BigDecimal amount, final BigDecimal outstandingChargeAmount, final BigDecimal runningBalance, + final boolean reversed, final AccountTransferData transfer, final Collection paymentTypeOptions, + final LocalDate submittedOnDate, final boolean interestedPostedAsOn, final String submittedByUsername, final String note) { this.id = id; this.transactionType = transactionType; this.paymentDetailData = paymentDetailData; @@ -196,15 +198,15 @@ public class SavingsAccountTransactionData implements Serializable { this.date = date; this.currency = currency; this.amount = amount; - this.outstandingChargeAmount= outstandingChargeAmount; + this.outstandingChargeAmount = outstandingChargeAmount; this.runningBalance = runningBalance; this.reversed = reversed; this.transfer = transfer; this.paymentTypeOptions = paymentTypeOptions; this.submittedOnDate = submittedOnDate; this.interestedPostedAsOn = interestedPostedAsOn; - this.submittedByUsername = submittedByUsername ; - this.note = note ; + this.submittedByUsername = submittedByUsername; + this.note = note; } public static SavingsAccountTransactionData withWithDrawalTransactionDetails( @@ -220,6 +222,7 @@ public class SavingsAccountTransactionData implements Serializable { savingsAccountTransactionData.amount, savingsAccountTransactionData.outstandingChargeAmount, savingsAccountTransactionData.runningBalance, savingsAccountTransactionData.reversed, savingsAccountTransactionData.transfer, savingsAccountTransactionData.paymentTypeOptions, - savingsAccountTransactionData.interestedPostedAsOn,savingsAccountTransactionData.submittedByUsername, savingsAccountTransactionData.note); + savingsAccountTransactionData.interestedPostedAsOn, savingsAccountTransactionData.submittedByUsername, + savingsAccountTransactionData.note); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionDataValidator.java index 74598b09c..43dd3111f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionDataValidator.java @@ -65,8 +65,8 @@ public class SavingsAccountTransactionDataValidator { private final FromJsonHelper fromApiJsonHelper; private static final Set SAVINGS_ACCOUNT_HOLD_AMOUNT_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(transactionDateParamName, SavingsApiConstants.dateFormatParamName, - SavingsApiConstants.localeParamName, transactionAmountParamName)); + Arrays.asList(transactionDateParamName, SavingsApiConstants.dateFormatParamName, SavingsApiConstants.localeParamName, + transactionAmountParamName)); @Autowired public SavingsAccountTransactionDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -145,8 +145,8 @@ public class SavingsAccountTransactionDataValidator { } if (account.getSavingsHoldAmount().compareTo(BigDecimal.ZERO) > 0) { - baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( - "amount.is.on.hold.release.the.amount.to.continue", account.getId()); + baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("amount.is.on.hold.release.the.amount.to.continue", + account.getId()); } validatePaymentTypeDetails(baseDataValidator, element); @@ -165,17 +165,18 @@ public class SavingsAccountTransactionDataValidator { final String paymentDetailParameterValue = this.fromApiJsonHelper.extractStringNamed(paymentDetailParameterName, element); baseDataValidator.reset().parameter(paymentDetailParameterName).value(paymentDetailParameterValue).ignoreIfNull() .notExceedingLengthOf(50); - if(paymentDetailParameterValue != null && !paymentDetailParameterValue.equals("")){ + if (paymentDetailParameterValue != null && !paymentDetailParameterValue.equals("")) { checkPaymentTypeDetails = true; } } - if(checkPaymentTypeDetails){ + if (checkPaymentTypeDetails) { baseDataValidator.reset().parameter(paymentTypeIdParamName).value(paymentTypeId).notBlank().integerGreaterThanZero(); } } - public SavingsAccountTransaction validateHoldAndAssembleForm(final String json, final SavingsAccount account, final AppUser createdUser) { + public SavingsAccountTransaction validateHoldAndAssembleForm(final String json, final SavingsAccount account, + final AppUser createdUser) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); @@ -198,7 +199,7 @@ public class SavingsAccountTransactionDataValidator { .failWithCodeNoParameterAddedToErrorCode(SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); } account.holdAmount(amount); - if (account.getWithdrawableBalance().compareTo(BigDecimal.ZERO) < 0){ + if (account.getWithdrawableBalance().compareTo(BigDecimal.ZERO) < 0) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("insufficient balance", account.getId()); } LocalDate lastTransactionDate = account.retrieveLastTransactionDate(); @@ -217,7 +218,8 @@ public class SavingsAccountTransactionDataValidator { return transaction; } - public SavingsAccountTransaction validateReleaseAmountAndAssembleForm(final SavingsAccountTransaction holdTransaction, final AppUser createdUser) { + public SavingsAccountTransaction validateReleaseAmountAndAssembleForm(final SavingsAccountTransaction holdTransaction, + final AppUser createdUser) { final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME); @@ -233,8 +235,7 @@ public class SavingsAccountTransactionDataValidator { boolean isActive = holdTransaction.getSavingsAccount().isActive(); if (!isActive) { baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) - .failWithCodeNoParameterAddedToErrorCode( - SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); + .failWithCodeNoParameterAddedToErrorCode(SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionEnumData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionEnumData.java index 773a59ca9..c7ab3b631 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionEnumData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountTransactionEnumData.java @@ -153,4 +153,4 @@ public class SavingsAccountTransactionEnumData implements Serializable { return this.amountRelease; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsActivation.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsActivation.java index 1752d8c0d..48dda824a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsActivation.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsActivation.java @@ -30,10 +30,11 @@ public class SavingsActivation { private final String locale; - public static SavingsActivation importInstance(LocalDate activatedOnDate, Integer rowIndex,String locale,String dateFormat){ - return new SavingsActivation(activatedOnDate,rowIndex,locale,dateFormat); + public static SavingsActivation importInstance(LocalDate activatedOnDate, Integer rowIndex, String locale, String dateFormat) { + return new SavingsActivation(activatedOnDate, rowIndex, locale, dateFormat); } - private SavingsActivation(LocalDate activatedOnDate, Integer rowIndex,String locale,String dateFormat ) { + + private SavingsActivation(LocalDate activatedOnDate, Integer rowIndex, String locale, String dateFormat) { this.activatedOnDate = activatedOnDate; this.rowIndex = rowIndex; this.dateFormat = dateFormat; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsApproval.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsApproval.java index 42037fda1..932170e7a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsApproval.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsApproval.java @@ -21,6 +21,7 @@ package org.apache.fineract.portfolio.savings.data; import org.joda.time.LocalDate; public class SavingsApproval { + private final transient Integer rowIndex; private final LocalDate approvedOnDate; @@ -31,11 +32,11 @@ public class SavingsApproval { private final String note; - public static SavingsApproval importInstance(LocalDate approvedOnDate, Integer rowIndex,String locale,String dateFormat){ - return new SavingsApproval(approvedOnDate, rowIndex,locale,dateFormat); + public static SavingsApproval importInstance(LocalDate approvedOnDate, Integer rowIndex, String locale, String dateFormat) { + return new SavingsApproval(approvedOnDate, rowIndex, locale, dateFormat); } - private SavingsApproval(LocalDate approvedOnDate, Integer rowIndex,String locale,String dateFormat ) { + private SavingsApproval(LocalDate approvedOnDate, Integer rowIndex, String locale, String dateFormat) { this.approvedOnDate = approvedOnDate; this.rowIndex = rowIndex; this.dateFormat = dateFormat; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsProductData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsProductData.java index cb4ce745b..83ac7c69e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsProductData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsProductData.java @@ -135,21 +135,21 @@ public class SavingsProductData implements Serializable { return new SavingsProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, accountingRule, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, allowOverdraft, overdraftLimit, minRequiredBalance, enforceMinRequiredBalance, - minBalanceForInterestCalculation, nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, - taxGroup, taxGroupOptions, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, + penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, allowOverdraft, overdraftLimit, + minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, nominalAnnualInterestRateOverdraft, + minOverdraftForInterestCalculation, withHoldTax, taxGroup, taxGroupOptions, isDormancyTrackingActive, daysToInactive, + daysToDormancy, daysToEscheat); } public static SavingsProductData withCharges(final SavingsProductData product, final Collection charges) { return new SavingsProductData(product.id, product.name, product.shortName, product.description, product.currency, product.nominalAnnualInterestRate, product.interestCompoundingPeriodType, product.interestPostingPeriodType, product.interestCalculationType, product.interestCalculationDaysInYearType, product.minRequiredOpeningBalance, - product.lockinPeriodFrequency, product.lockinPeriodFrequencyType, product.withdrawalFeeForTransfers, - product.accountingRule, product.accountingMappings, product.paymentChannelToFundSourceMappings, product.currencyOptions, + product.lockinPeriodFrequency, product.lockinPeriodFrequencyType, product.withdrawalFeeForTransfers, product.accountingRule, + product.accountingMappings, product.paymentChannelToFundSourceMappings, product.currencyOptions, product.interestCompoundingPeriodTypeOptions, product.interestPostingPeriodTypeOptions, product.interestCalculationTypeOptions, product.interestCalculationDaysInYearTypeOptions, product.lockinPeriodFrequencyTypeOptions, product.withdrawalFeeTypeOptions, product.paymentTypeOptions, @@ -157,8 +157,8 @@ public class SavingsProductData implements Serializable { product.feeToIncomeAccountMappings, product.penaltyToIncomeAccountMappings, product.allowOverdraft, product.overdraftLimit, product.minRequiredBalance, product.enforceMinRequiredBalance, product.minBalanceForInterestCalculation, product.nominalAnnualInterestRateOverdraft, product.minOverdraftForInterestCalculation, product.withHoldTax, - product.taxGroup, product.taxGroupOptions, product.isDormancyTrackingActive, product.daysToInactive, - product.daysToDormancy, product.daysToEscheat); + product.taxGroup, product.taxGroupOptions, product.isDormancyTrackingActive, product.daysToInactive, product.daysToDormancy, + product.daysToEscheat); } /** @@ -182,22 +182,21 @@ public class SavingsProductData implements Serializable { existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType, existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, existingProduct.minRequiredOpeningBalance, - existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, - existingProduct.withdrawalFeeForTransfers, existingProduct.accountingRule, existingProduct.accountingMappings, - existingProduct.paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, + existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, existingProduct.withdrawalFeeForTransfers, + existingProduct.accountingRule, existingProduct.accountingMappings, existingProduct.paymentChannelToFundSourceMappings, + currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, + interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, + accountingRuleOptions, accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, existingProduct.feeToIncomeAccountMappings, existingProduct.penaltyToIncomeAccountMappings, existingProduct.allowOverdraft, existingProduct.overdraftLimit, existingProduct.minRequiredBalance, existingProduct.enforceMinRequiredBalance, existingProduct.minBalanceForInterestCalculation, existingProduct.nominalAnnualInterestRateOverdraft, existingProduct.minOverdraftForInterestCalculation, existingProduct.withHoldTax, existingProduct.taxGroup, taxGroupOptions, - existingProduct.isDormancyTrackingActive, existingProduct.daysToInactive, existingProduct.daysToDormancy, existingProduct.daysToEscheat); + existingProduct.isDormancyTrackingActive, existingProduct.daysToInactive, existingProduct.daysToDormancy, + existingProduct.daysToEscheat); } public static SavingsProductData withAccountingDetails(final SavingsProductData existingProduct, - final Map accountingMappings, - final Collection paymentChannelToFundSourceMappings, + final Map accountingMappings, final Collection paymentChannelToFundSourceMappings, final Collection feeToIncomeAccountMappings, final Collection penaltyToIncomeAccountMappings) { @@ -218,13 +217,12 @@ public class SavingsProductData implements Serializable { existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType, existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, existingProduct.minRequiredOpeningBalance, - existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, - existingProduct.withdrawalFeeForTransfers, existingProduct.accountingRule, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, existingProduct.allowOverdraft, existingProduct.overdraftLimit, + existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, existingProduct.withdrawalFeeForTransfers, + existingProduct.accountingRule, accountingMappings, paymentChannelToFundSourceMappings, currencyOptions, + interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, + interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, + accountingRuleOptions, accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, + feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, existingProduct.allowOverdraft, existingProduct.overdraftLimit, existingProduct.minRequiredBalance, existingProduct.enforceMinRequiredBalance, existingProduct.minBalanceForInterestCalculation, existingProduct.nominalAnnualInterestRateOverdraft, existingProduct.minOverdraftForInterestCalculation, existingProduct.withHoldTax, existingProduct.taxGroup, @@ -238,10 +236,10 @@ public class SavingsProductData implements Serializable { final EnumOptionData interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, final boolean withdrawalFeeForTransfers, final EnumOptionData accountingType, final boolean allowOverdraft, final BigDecimal overdraftLimit, - final BigDecimal minRequiredBalance, final boolean enforceMinRequiredBalance, - final BigDecimal minBalanceForInterestCalculation, final BigDecimal nominalAnnualInterestRateOverdraft, - final BigDecimal minOverdraftForInterestCalculation, final boolean withHoldTax, final TaxGroupData taxGroup, - final Boolean isDormancyTrackingActive, final Long daysToInactive, final Long daysToDormancy, final Long daysToEscheat) { + final BigDecimal minRequiredBalance, final boolean enforceMinRequiredBalance, final BigDecimal minBalanceForInterestCalculation, + final BigDecimal nominalAnnualInterestRateOverdraft, final BigDecimal minOverdraftForInterestCalculation, + final boolean withHoldTax, final TaxGroupData taxGroup, final Boolean isDormancyTrackingActive, final Long daysToInactive, + final Long daysToDormancy, final Long daysToEscheat) { final Map accountingMappings = null; final Collection paymentChannelToFundSourceMappings = null; @@ -266,13 +264,13 @@ public class SavingsProductData implements Serializable { return new SavingsProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, accountingType, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, allowOverdraft, overdraftLimit, minRequiredBalance, enforceMinRequiredBalance, - minBalanceForInterestCalculation, nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, - taxGroup, taxGroupOptions, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, + penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, allowOverdraft, overdraftLimit, + minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, nominalAnnualInterestRateOverdraft, + minOverdraftForInterestCalculation, withHoldTax, taxGroup, taxGroupOptions, isDormancyTrackingActive, daysToInactive, + daysToDormancy, daysToEscheat); } public static SavingsProductData lookup(final Long id, final String name) { @@ -326,13 +324,13 @@ public class SavingsProductData implements Serializable { return new SavingsProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, accountingType, accountingMappings, - paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, - interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, - lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, - accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, - penaltyToIncomeAccountMappings, allowOverdraft, overdraftLimit, minRequiredBalance, enforceMinRequiredBalance, - minBalanceForInterestCalculation, nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, - taxGroup, taxGroupOptions, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat); + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, + interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, + withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, + penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, allowOverdraft, overdraftLimit, + minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, nominalAnnualInterestRateOverdraft, + minOverdraftForInterestCalculation, withHoldTax, taxGroup, taxGroupOptions, isDormancyTrackingActive, daysToInactive, + daysToDormancy, daysToEscheat); } private SavingsProductData(final Long id, final String name, final String shortName, final String description, @@ -425,9 +423,7 @@ public class SavingsProductData implements Serializable { @Override public boolean equals(final Object obj) { - if (!(obj instanceof SavingsProductData)) { - return false; - } + if (!(obj instanceof SavingsProductData)) { return false; } final SavingsProductData productData = (SavingsProductData) obj; return productData.id.compareTo(this.id) == 0; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsProductDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsProductDataValidator.java index 698d544f1..59fdd8079 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsProductDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsProductDataValidator.java @@ -83,34 +83,27 @@ import org.springframework.stereotype.Component; public class SavingsProductDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(SavingsApiConstants.localeParamName, SavingsApiConstants.monthDayFormatParamName, - nameParamName, shortNameParamName, descriptionParamName, currencyCodeParamName, - digitsAfterDecimalParamName, inMultiplesOfParamName, nominalAnnualInterestRateParamName, - interestCompoundingPeriodTypeParamName, interestPostingPeriodTypeParamName, - interestCalculationTypeParamName, interestCalculationDaysInYearTypeParamName, - minRequiredOpeningBalanceParamName, lockinPeriodFrequencyParamName, - lockinPeriodFrequencyTypeParamName, SavingsApiConstants.withdrawalFeeAmountParamName, - SavingsApiConstants.withdrawalFeeTypeParamName, withdrawalFeeForTransfersParamName, - feeAmountParamName, feeOnMonthDayParamName, SavingsApiConstants.accountingRuleParamName, - SavingsApiConstants.chargesParamName, SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), - SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), - SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), - SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), - SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), - SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), - SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), - SavingProductAccountingParams.FEE_INCOME_ACCOUNT_MAPPING.getValue(), - SavingProductAccountingParams.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(), - SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), - SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), - SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue(), - SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), isDormancyTrackingActiveParamName, - daysToDormancyParamName, daysToInactiveParamName, daysToEscheatParamName, allowOverdraftParamName, - overdraftLimitParamName, nominalAnnualInterestRateOverdraftParamName, - minOverdraftForInterestCalculationParamName, SavingsApiConstants.minRequiredBalanceParamName, - SavingsApiConstants.enforceMinRequiredBalanceParamName, minBalanceForInterestCalculationParamName, - withHoldTaxParamName, taxGroupIdParamName)); + private static final Set SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( + SavingsApiConstants.localeParamName, SavingsApiConstants.monthDayFormatParamName, nameParamName, shortNameParamName, + descriptionParamName, currencyCodeParamName, digitsAfterDecimalParamName, inMultiplesOfParamName, + nominalAnnualInterestRateParamName, interestCompoundingPeriodTypeParamName, interestPostingPeriodTypeParamName, + interestCalculationTypeParamName, interestCalculationDaysInYearTypeParamName, minRequiredOpeningBalanceParamName, + lockinPeriodFrequencyParamName, lockinPeriodFrequencyTypeParamName, SavingsApiConstants.withdrawalFeeAmountParamName, + SavingsApiConstants.withdrawalFeeTypeParamName, withdrawalFeeForTransfersParamName, feeAmountParamName, feeOnMonthDayParamName, + SavingsApiConstants.accountingRuleParamName, SavingsApiConstants.chargesParamName, + SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), + SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), + SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), + SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), + SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), SavingProductAccountingParams.FEE_INCOME_ACCOUNT_MAPPING.getValue(), + SavingProductAccountingParams.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(), + SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), + SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue(), + SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), isDormancyTrackingActiveParamName, daysToDormancyParamName, + daysToInactiveParamName, daysToEscheatParamName, allowOverdraftParamName, overdraftLimitParamName, + nominalAnnualInterestRateOverdraftParamName, minOverdraftForInterestCalculationParamName, + SavingsApiConstants.minRequiredBalanceParamName, SavingsApiConstants.enforceMinRequiredBalanceParamName, + minBalanceForInterestCalculationParamName, withHoldTaxParamName, taxGroupIdParamName)); @Autowired public SavingsProductDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -145,13 +138,13 @@ public class SavingsProductDataValidator { final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } - final BigDecimal nominalAnnualInterestRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - nominalAnnualInterestRateParamName, element); + final BigDecimal nominalAnnualInterestRate = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(nominalAnnualInterestRate).notNull() .zeroOrPositiveAmount(); - final Integer interestCompoundingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCompoundingPeriodTypeParamName, element); + final Integer interestCompoundingPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); @@ -165,8 +158,8 @@ public class SavingsProductDataValidator { baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .isOneOfTheseValues(SavingsInterestCalculationType.integerValues()); - final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCalculationDaysInYearTypeParamName, element); + final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType).notNull() .isOneOfTheseValues(SavingsInterestCalculationDaysInYearType.integerValues()); @@ -176,8 +169,8 @@ public class SavingsProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { - final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minRequiredOpeningBalanceParamName, element); + final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, + element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).zeroOrPositiveAmount(); } @@ -188,16 +181,16 @@ public class SavingsProductDataValidator { baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).integerZeroOrGreater(); if (lockinPeriodFrequency != null) { - final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - lockinPeriodFrequencyTypeParamName, element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).notNull() .inMinMaxRange(0, 3); } } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { - final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - lockinPeriodFrequencyTypeParamName, element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); if (lockinPeriodFrequencyType != null) { @@ -244,8 +237,8 @@ public class SavingsProductDataValidator { * .zeroOrPositiveAmount(); } } */ if (this.fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { - final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper.extractBooleanNamed( - withdrawalFeeForTransfersParamName, element); + final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper + .extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } @@ -269,10 +262,10 @@ public class SavingsProductDataValidator { } } - //dormancy + // dormancy final Boolean isDormancyActive = this.fromApiJsonHelper.extractBooleanNamed(isDormancyTrackingActiveParamName, element); - if(null != isDormancyActive && isDormancyActive){ + if (null != isDormancyActive && isDormancyActive) { final Long daysToInact = this.fromApiJsonHelper.extractLongNamed(daysToInactiveParamName, element); baseDataValidator.reset().parameter(daysToInactiveParamName).value(daysToInact).notNull().longGreaterThanZero(); @@ -282,9 +275,7 @@ public class SavingsProductDataValidator { final Long daysToEsc = this.fromApiJsonHelper.extractLongNamed(daysToEscheatParamName, element); baseDataValidator.reset().parameter(daysToEscheatParamName).value(daysToEsc).notNull().longGreaterThanZero(); - if(null != daysToInact - && null != daysToDor - && null != daysToEsc){ + if (null != daysToInact && null != daysToDor && null != daysToEsc) { baseDataValidator.reset().parameter(daysToDormancyParamName).value(daysToDor).longGreaterThanNumber(daysToInact); baseDataValidator.reset().parameter(daysToEscheatParamName).value(daysToEsc).longGreaterThanNumber(daysToDor); } @@ -296,54 +287,54 @@ public class SavingsProductDataValidator { if (isCashBasedAccounting(accountingRuleType)) { - final Long savingsControlAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_CONTROL.getValue()) - .value(savingsControlAccountId).notNull().integerGreaterThanZero(); + final Long savingsControlAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) + .notNull().integerGreaterThanZero(); - final Long savingsReferenceAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue()) - .value(savingsReferenceAccountId).notNull().integerGreaterThanZero(); + final Long savingsReferenceAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue()).value(savingsReferenceAccountId) + .notNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero(); - final Long interestOnSavingsAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); + final Long interestOnSavingsAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).notNull().integerGreaterThanZero(); - final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) + final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), + element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId).notNull() + .integerGreaterThanZero(); + + final Long incomeFromPenaltyId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .notNull().integerGreaterThanZero(); - final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue()) - .value(incomeFromPenaltyId).notNull().integerGreaterThanZero(); - - final Long overdraftControlAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), element); + final Long overdraftControlAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue()) .value(overdraftControlAccountId).notNull().integerGreaterThanZero(); - final Long incomeFromInterest = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue()) - .value(incomeFromInterest).notNull().integerGreaterThanZero(); - - final Long writtenoff = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue()).value(writtenoff) + final Long incomeFromInterest = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue()).value(incomeFromInterest) .notNull().integerGreaterThanZero(); - if(null != isDormancyActive && isDormancyActive){ - final Long escheatLiabilityAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), element); + final Long writtenoff = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), + element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue()).value(writtenoff).notNull() + .integerGreaterThanZero(); + + if (null != isDormancyActive && isDormancyActive) { + final Long escheatLiabilityAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue()) .value(escheatLiabilityAccountId).notNull().integerGreaterThanZero(); } @@ -355,8 +346,8 @@ public class SavingsProductDataValidator { validateOverdraftParams(baseDataValidator, element); if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { - final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minBalanceForInterestCalculationParamName, element); + final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } @@ -415,8 +406,8 @@ public class SavingsProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { - final Integer interestCompoundingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCompoundingPeriodTypeParamName, element); + final Integer interestCompoundingPeriodType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } @@ -424,20 +415,20 @@ public class SavingsProductDataValidator { if (this.fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); - baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() - .inMinMaxRange(1, 2); + baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull().inMinMaxRange(1, + 2); } if (this.fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { - final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - interestCalculationDaysInYearTypeParamName, element); + final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { - final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minRequiredOpeningBalanceParamName, element); + final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, + element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } @@ -450,14 +441,14 @@ public class SavingsProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { - final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( - lockinPeriodFrequencyTypeParamName, element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper + .extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { - final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper.extractBooleanNamed( - withdrawalFeeForTransfersParamName, element); + final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper + .extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } @@ -472,82 +463,80 @@ public class SavingsProductDataValidator { baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } - final Long savingsControlAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), element); + final Long savingsControlAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); - final Long savingsReferenceAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue()) - .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); + final Long savingsReferenceAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.SAVINGS_REFERENCE.getValue()).value(savingsReferenceAccountId) + .ignoreIfNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue()) - .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue()).value(transfersInSuspenseAccountId) + .ignoreIfNull().integerGreaterThanZero(); - final Long interestOnSavingsAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue()) - .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); + final Long interestOnSavingsAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INTEREST_ON_SAVINGS.getValue()).value(interestOnSavingsAccountId) + .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.INCOME_FROM_FEES.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) - .ignoreIfNull().integerGreaterThanZero(); + baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId).ignoreIfNull() + .integerGreaterThanZero(); - final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); + final Long incomeFromPenaltyId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); - final Long overdraftAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue()) - .value(overdraftAccountId).ignoreIfNull().integerGreaterThanZero(); + final Long overdraftAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue(), element); + baseDataValidator.reset().parameter(SavingProductAccountingParams.OVERDRAFT_PORTFOLIO_CONTROL.getValue()).value(overdraftAccountId) + .ignoreIfNull().integerGreaterThanZero(); - final Long incomeFromInterest = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue(), element); + final Long incomeFromInterest = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.INCOME_FROM_INTEREST.getValue()).value(incomeFromInterest) .ignoreIfNull().integerGreaterThanZero(); final Long writtenoff = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue(), element); - baseDataValidator.reset().parameter(SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue()).value(writtenoff) - .ignoreIfNull().integerGreaterThanZero(); + baseDataValidator.reset().parameter(SavingProductAccountingParams.LOSSES_WRITTEN_OFF.getValue()).value(writtenoff).ignoreIfNull() + .integerGreaterThanZero(); - //dormancy - final Boolean isDormancyActive = this.fromApiJsonHelper.parameterExists(isDormancyTrackingActiveParamName, element)? - this.fromApiJsonHelper.extractBooleanNamed(isDormancyTrackingActiveParamName, element): - product.isDormancyTrackingActive(); + // dormancy + final Boolean isDormancyActive = this.fromApiJsonHelper.parameterExists(isDormancyTrackingActiveParamName, element) + ? this.fromApiJsonHelper.extractBooleanNamed(isDormancyTrackingActiveParamName, element) + : product.isDormancyTrackingActive(); - if(null != isDormancyActive && isDormancyActive){ - final Long daysToInact = this.fromApiJsonHelper.parameterExists(daysToInactiveParamName, element)? - this.fromApiJsonHelper.extractLongNamed(daysToInactiveParamName, element): - product.getDaysToInactive(); + if (null != isDormancyActive && isDormancyActive) { + final Long daysToInact = this.fromApiJsonHelper.parameterExists(daysToInactiveParamName, element) + ? this.fromApiJsonHelper.extractLongNamed(daysToInactiveParamName, element) + : product.getDaysToInactive(); baseDataValidator.reset().parameter(daysToInactiveParamName).value(daysToInact).notNull().longGreaterThanZero(); - final Long daysToDor = this.fromApiJsonHelper.parameterExists(daysToDormancyParamName, element)? - this.fromApiJsonHelper.extractLongNamed(daysToDormancyParamName, element): - product.getDaysToDormancy(); + final Long daysToDor = this.fromApiJsonHelper.parameterExists(daysToDormancyParamName, element) + ? this.fromApiJsonHelper.extractLongNamed(daysToDormancyParamName, element) + : product.getDaysToDormancy(); baseDataValidator.reset().parameter(daysToDormancyParamName).value(daysToDor).notNull().longGreaterThanZero(); - final Long daysToEsc = this.fromApiJsonHelper.parameterExists(daysToEscheatParamName, element)? - this.fromApiJsonHelper.extractLongNamed(daysToEscheatParamName, element): - product.getDaysToEscheat(); + final Long daysToEsc = this.fromApiJsonHelper.parameterExists(daysToEscheatParamName, element) + ? this.fromApiJsonHelper.extractLongNamed(daysToEscheatParamName, element) + : product.getDaysToEscheat(); baseDataValidator.reset().parameter(daysToEscheatParamName).value(daysToEsc).notNull().longGreaterThanZero(); - if(null != daysToInact - && null != daysToDor - && null != daysToEsc){ + if (null != daysToInact && null != daysToDor && null != daysToEsc) { baseDataValidator.reset().parameter(daysToDormancyParamName).value(daysToDor).longGreaterThanNumber(daysToInact); baseDataValidator.reset().parameter(daysToEscheatParamName).value(daysToEsc).longGreaterThanNumber(daysToDor); } - if(this.fromApiJsonHelper.parameterExists(SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), element)){ - final Long escheatLiabilityAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), element); + if (this.fromApiJsonHelper.parameterExists(SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), element)) { + final Long escheatLiabilityAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), element); baseDataValidator.reset().parameter(SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue()) .value(escheatLiabilityAccountId).notNull().integerGreaterThanZero(); } @@ -558,8 +547,8 @@ public class SavingsProductDataValidator { validateOverdraftParams(baseDataValidator, element); if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { - final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minBalanceForInterestCalculationParamName, element); + final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } @@ -581,10 +570,9 @@ public class SavingsProductDataValidator { * Validation for advanced accounting options */ private void validatePaymentChannelFundSourceMappings(final DataValidatorBuilder baseDataValidator, final JsonElement element) { - if (this.fromApiJsonHelper.parameterExists(SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), - element)) { - final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( - SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); + if (this.fromApiJsonHelper.parameterExists(SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element)) { + final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper + .extractJsonArrayNamed(SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); if (paymentChannelMappingArray != null && paymentChannelMappingArray.size() > 0) { int i = 0; do { @@ -592,18 +580,14 @@ public class SavingsProductDataValidator { final Long paymentTypeId = jsonObject.get(SavingProductAccountingParams.PAYMENT_TYPE.getValue()).getAsLong(); final Long paymentSpecificFundAccountId = jsonObject.get(SavingProductAccountingParams.FUND_SOURCE.getValue()) .getAsLong(); - baseDataValidator - .reset() - .parameter( - SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." - + SavingProductAccountingParams.PAYMENT_TYPE.toString()).value(paymentTypeId).notNull() - .integerGreaterThanZero(); - baseDataValidator - .reset() - .parameter( - SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." - + SavingProductAccountingParams.FUND_SOURCE.getValue()).value(paymentSpecificFundAccountId) - .notNull().integerGreaterThanZero(); + baseDataValidator.reset() + .parameter(SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." + + SavingProductAccountingParams.PAYMENT_TYPE.toString()) + .value(paymentTypeId).notNull().integerGreaterThanZero(); + baseDataValidator.reset() + .parameter(SavingProductAccountingParams.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]." + + SavingProductAccountingParams.FUND_SOURCE.getValue()) + .value(paymentSpecificFundAccountId).notNull().integerGreaterThanZero(); i++; } while (i < paymentChannelMappingArray.size()); } @@ -633,10 +617,9 @@ public class SavingsProductDataValidator { final JsonObject jsonObject = chargeToIncomeAccountMappingArray.get(i).getAsJsonObject(); final Long chargeId = this.fromApiJsonHelper.extractLongNamed(SavingProductAccountingParams.CHARGE_ID.getValue(), jsonObject); - final Long incomeAccountId = this.fromApiJsonHelper.extractLongNamed( - SavingProductAccountingParams.INCOME_ACCOUNT_ID.getValue(), jsonObject); - baseDataValidator.reset() - .parameter(parameterName + "[" + i + "]." + SavingProductAccountingParams.CHARGE_ID.getValue()) + final Long incomeAccountId = this.fromApiJsonHelper + .extractLongNamed(SavingProductAccountingParams.INCOME_ACCOUNT_ID.getValue(), jsonObject); + baseDataValidator.reset().parameter(parameterName + "[" + i + "]." + SavingProductAccountingParams.CHARGE_ID.getValue()) .value(chargeId).notNull().integerGreaterThanZero(); baseDataValidator.reset() .parameter(parameterName + "[" + i + "]." + SavingProductAccountingParams.INCOME_ACCOUNT_ID.getValue()) @@ -659,15 +642,15 @@ public class SavingsProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(nominalAnnualInterestRateOverdraftParamName, element)) { - final BigDecimal nominalAnnualInterestRateOverdraft = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - nominalAnnualInterestRateOverdraftParamName, element); + final BigDecimal nominalAnnualInterestRateOverdraft = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateOverdraftParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateOverdraftParamName).value(nominalAnnualInterestRateOverdraft) .ignoreIfNull().zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(minOverdraftForInterestCalculationParamName, element)) { - final BigDecimal minOverdraftForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - minOverdraftForInterestCalculationParamName, element); + final BigDecimal minOverdraftForInterestCalculation = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(minOverdraftForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minOverdraftForInterestCalculationParamName).value(minOverdraftForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } @@ -699,4 +682,4 @@ public class SavingsProductDataValidator { } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/TransactionDateData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/TransactionDateData.java index 0a3cace50..5ef3e1d82 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/TransactionDateData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/TransactionDateData.java @@ -31,4 +31,4 @@ public class TransactionDateData { public TransactionDateData(final LocalDate date) { this.date = date; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountAssembler.java index 283bfd5df..c4624992c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountAssembler.java @@ -171,7 +171,6 @@ public class DepositAccountAssembler { if (product == null) { throw new SavingsProductNotFoundException(productId); } - Client client = null; Group group = null; Staff fieldOfficer = null; @@ -179,7 +178,14 @@ public class DepositAccountAssembler { final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); if (clientId != null) { final boolean isCalendarInherited = command.booleanPrimitiveValueOfParameterNamed(isCalendarInheritedParamName); - client = this.clientRepository.findOneWithNotFoundDetection(clientId, isCalendarInherited); //we need group collection if isCalendarInherited is true + client = this.clientRepository.findOneWithNotFoundDetection(clientId, isCalendarInherited); // we + // need + // group + // collection + // if + // isCalendarInherited + // is + // true accountType = AccountType.INDIVIDUAL; if (client.isNotActive()) { throw new ClientNotActiveException(clientId); } } @@ -296,12 +302,12 @@ public class DepositAccountAssembler { boolean withHoldTax = product.withHoldTax(); if (command.parameterExists(withHoldTaxParamName)) { withHoldTax = command.booleanPrimitiveValueOfParameterNamed(withHoldTaxParamName); - if(withHoldTax && product.getTaxGroup() == null){ + if (withHoldTax && product.getTaxGroup() == null) { throw new UnsupportedParameterException(Arrays.asList(withHoldTaxParamName)); } } - Integer depositRolloverId = null; - if(command.parameterExists(maturityInstructionIdParamName)){ + Integer depositRolloverId = null; + if (command.parameterExists(maturityInstructionIdParamName)) { depositRolloverId = command.integerValueOfParameterNamed(maturityInstructionIdParamName); } @@ -361,8 +367,8 @@ public class DepositAccountAssembler { public DepositAccountTermAndPreClosure assembleAccountTermAndPreClosure(final JsonCommand command, final DepositProductTermAndPreClosure productTermAndPreclosure) { - final DepositPreClosureDetail productPreClosure = (productTermAndPreclosure == null) ? null : productTermAndPreclosure - .depositPreClosureDetail(); + final DepositPreClosureDetail productPreClosure = (productTermAndPreclosure == null) ? null + : productTermAndPreclosure.depositPreClosureDetail(); final DepositTermDetail productTerm = (productTermAndPreclosure == null) ? null : productTermAndPreclosure.depositTermDetail(); final DepositPreClosureDetail updatedProductPreClosure = this.depositProductAssembler.assemblePreClosureDetail(command, @@ -382,8 +388,10 @@ public class DepositAccountAssembler { // account final LocalDate maturityDate = null;// calculated and updated in account final Integer accountOnClosureTypeId = command.integerValueOfParameterNamed(maturityInstructionIdParamName); - final DepositAccountOnClosureType accountOnClosureType = accountOnClosureTypeId != null ? DepositAccountOnClosureType.fromInt(accountOnClosureTypeId) :null; - final Long transferToSavingsId = command.longValueOfParameterNamed(transferToSavingsIdParamName); + final DepositAccountOnClosureType accountOnClosureType = accountOnClosureTypeId != null + ? DepositAccountOnClosureType.fromInt(accountOnClosureTypeId) + : null; + final Long transferToSavingsId = command.longValueOfParameterNamed(transferToSavingsIdParamName); return DepositAccountTermAndPreClosure.createNew(updatedProductPreClosure, updatedProductTerm, account, depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, expectedFirstDepositOnDate, accountOnClosureType, trasferInterest, transferToSavingsId); @@ -429,7 +437,8 @@ public class DepositAccountAssembler { return depositAccountRecurringDetail; } - public Collection assembleBulkMandatorySavingsAccountTransactionDTOs(final JsonCommand command,final PaymentDetail paymentDetail) { + public Collection assembleBulkMandatorySavingsAccountTransactionDTOs(final JsonCommand command, + final PaymentDetail paymentDetail) { AppUser user = getAppUserIfPresent(); final String json = command.json(); if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } @@ -451,8 +460,8 @@ public class DepositAccountAssembler { final Long savingsId = this.fromApiJsonHelper.extractLongNamed(savingsIdParamName, savingsTransactionElement); final BigDecimal dueAmount = this.fromApiJsonHelper.extractBigDecimalNamed(transactionAmountParamName, savingsTransactionElement, locale); - final Integer depositAccountType = this.fromApiJsonHelper.extractIntegerNamed( - CollectionSheetConstants.depositAccountTypeParamName, savingsTransactionElement, locale); + final Integer depositAccountType = this.fromApiJsonHelper + .extractIntegerNamed(CollectionSheetConstants.depositAccountTypeParamName, savingsTransactionElement, locale); PaymentDetail detail = paymentDetail; if (paymentDetail == null) { detail = this.paymentDetailAssembler.fetchPaymentDetail(savingsTransactionElement); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountDomainService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountDomainService.java index 40d4a5f59..4c2599f42 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountDomainService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountDomainService.java @@ -45,17 +45,16 @@ public interface DepositAccountDomainService { LocalDate tenantsTodayDate, Map changes); @Transactional - Long handleFDAccountMaturityClosure(FixedDepositAccount account, PaymentDetail paymentDetail, AppUser user, - LocalDate tenantsTodayDate, DateTimeFormatter fmt, - LocalDate closedDate, Integer onAccountClosureId, - Long toSavingsId, String transferDescription, Map changes); + Long handleFDAccountMaturityClosure(FixedDepositAccount account, PaymentDetail paymentDetail, AppUser user, LocalDate tenantsTodayDate, + DateTimeFormatter fmt, LocalDate closedDate, Integer onAccountClosureId, Long toSavingsId, String transferDescription, + Map changes); Long handleRDAccountClosure(RecurringDepositAccount account, PaymentDetail paymentDetail, AppUser user, JsonCommand command, - LocalDate tenantsTodayDate, Map changes); + LocalDate tenantsTodayDate, Map changes); Long handleFDAccountPreMatureClosure(FixedDepositAccount account, PaymentDetail paymentDetail, AppUser user, JsonCommand command, LocalDate tenantsTodayDate, Map changes); Long handleRDAccountPreMatureClosure(RecurringDepositAccount account, PaymentDetail paymentDetail, AppUser user, JsonCommand command, LocalDate tenantsTodayDate, Map changes); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountDomainServiceJpa.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountDomainServiceJpa.java index ee7b0eb3f..c54ece998 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountDomainServiceJpa.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountDomainServiceJpa.java @@ -84,7 +84,8 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi private final CalendarInstanceRepository calendarInstanceRepository; @Autowired - public DepositAccountDomainServiceJpa(final PlatformSecurityContext context,final SavingsAccountRepositoryWrapper savingsAccountRepository, + public DepositAccountDomainServiceJpa(final PlatformSecurityContext context, + final SavingsAccountRepositoryWrapper savingsAccountRepository, final ApplicationCurrencyRepositoryWrapper applicationCurrencyRepositoryWrapper, final JournalEntryWritePlatformService journalEntryWritePlatformService, final AccountNumberGenerator accountNumberGenerator, final DepositAccountAssembler depositAccountAssembler, final SavingsAccountDomainService savingsAccountDomainService, @@ -149,15 +150,16 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi final Set existingTransactionIds = new HashSet<>(); final Set existingReversedTransactionIds = new HashSet<>(); final boolean isAnyActivationChargesDue = isAnyActivationChargesDue(account); - if(isAnyActivationChargesDue){ + if (isAnyActivationChargesDue) { updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); account.processAccountUponActivation(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, user); this.savingsAccountRepository.saveAndFlush(account); } account.handleScheduleInstallments(deposit); - account.updateMaturityDateAndAmount(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); + account.updateMaturityDateAndAmount(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, + financialYearBeginningMonth); account.updateOverduePayments(DateUtils.getLocalDateOfTenant()); - if(isAnyActivationChargesDue){ + if (isAnyActivationChargesDue) { postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer); } return deposit; @@ -181,7 +183,9 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi private boolean isAnyActivationChargesDue(final RecurringDepositAccount account) { for (final SavingsAccountCharge savingsAccountCharge : account.charges()) { if (savingsAccountCharge.isSavingsActivation() && savingsAccountCharge.amoutOutstanding() != null - && savingsAccountCharge.amoutOutstanding().compareTo(BigDecimal.ZERO) > 0) { return true; } + && savingsAccountCharge.amoutOutstanding().compareTo(BigDecimal.ZERO) > 0) { + return true; + } } return false; } @@ -189,7 +193,7 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi @Transactional @Override public Long handleFDAccountClosure(final FixedDepositAccount account, final PaymentDetail paymentDetail, final AppUser user, - final JsonCommand command, final LocalDate tenantsTodayDate, final Map changes) { + final JsonCommand command, final LocalDate tenantsTodayDate, final Map changes) { final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); @@ -205,7 +209,7 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi */ updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); /* - * final SavingsAccountTransactionDTO transactionDTO = new + * final SavingsAccountTransactionDTO transactionDTO = new * SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, * paymentDetail, new Date()); final SavingsAccountTransaction deposit = * account.deposit(transactionDTO); boolean isInterestTransfer = false; @@ -264,10 +268,8 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi @Transactional @Override public Long handleFDAccountMaturityClosure(final FixedDepositAccount account, final PaymentDetail paymentDetail, final AppUser user, - final LocalDate tenantsTodayDate, final DateTimeFormatter fmt, - final LocalDate closedDate, final Integer onAccountClosureId, - final Long toSavingsId, final String transferDescription, - Map changes) { + final LocalDate tenantsTodayDate, final DateTimeFormatter fmt, final LocalDate closedDate, final Integer onAccountClosureId, + final Long toSavingsId, final String transferDescription, Map changes) { final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); @@ -289,14 +291,11 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi final DepositAccountOnClosureType onClosureType = DepositAccountOnClosureType.fromInt(onAccountClosureId); if (onClosureType.isReinvest()) { BigDecimal reInvestAmount; - if(onClosureType.isReinvestPrincipal()) - { - reInvestAmount = account.getDepositAmount(); - } - else - { - reInvestAmount = account.getAccountBalance(); - } + if (onClosureType.isReinvestPrincipal()) { + reInvestAmount = account.getDepositAmount(); + } else { + reInvestAmount = account.getAccountBalance(); + } FixedDepositAccount reinvestedDeposit = account.reInvest(reInvestAmount); this.depositAccountAssembler.assignSavingAccountHelpers(reinvestedDeposit); reinvestedDeposit.updateMaturityDateAndAmountBeforeAccountActivation(mc, isPreMatureClosure, @@ -304,8 +303,8 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi this.savingsAccountRepository.save(reinvestedDeposit); autoGenerateAccountNumber(reinvestedDeposit); - final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, reInvestAmount, - paymentDetail, false, isRegularTransaction); + final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, reInvestAmount, paymentDetail, + false, isRegularTransaction); savingsTransactionId = withdrawal.getId(); if (onClosureType.isReinvestPrincipalAndInterest()) { @@ -334,8 +333,8 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi savingsTransactionId = withdrawal.getId(); } - //if(!processMaturityInstructionOnly) - // account.close(user, command, tenantsTodayDate, changes); + // if(!processMaturityInstructionOnly) + // account.close(user, command, tenantsTodayDate, changes); this.savingsAccountRepository.save(account); @@ -374,14 +373,11 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi final DepositAccountOnClosureType onClosureType = DepositAccountOnClosureType.fromInt(onAccountClosureId); if (onClosureType.isReinvest()) { BigDecimal reInvestAmount; - if(onClosureType.isReinvestPrincipal()) - { - reInvestAmount = account.getDepositAmount(); - } - else - { - reInvestAmount = account.getAccountBalance(); - } + if (onClosureType.isReinvestPrincipal()) { + reInvestAmount = account.getDepositAmount(); + } else { + reInvestAmount = account.getAccountBalance(); + } RecurringDepositAccount reinvestedDeposit = account.reInvest(reInvestAmount); depositAccountAssembler.assignSavingAccountHelpers(reinvestedDeposit); this.savingsAccountRepository.save(reinvestedDeposit); @@ -486,7 +482,6 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); Long savingsTransactionId = null; - // post interest account.postPreMaturityInterest(closedDate, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); @@ -512,7 +507,6 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi savingsTransactionId = withdrawal.getId(); } - account.prematureClosure(user, command, tenantsTodayDate, changes); this.savingsAccountRepository.save(account); @@ -593,7 +587,7 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi } private void updateAlreadyPostedTransactions(final Set existingTransactionIds, final SavingsAccount savingsAccount) { - List transactions = savingsAccount.getTransactions() ; + List transactions = savingsAccount.getTransactions(); int size = transactions.size(); for (int i = size - 1;; i--) { SavingsAccountTransaction transaction = transactions.get(i); @@ -612,4 +606,4 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi } return user; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountInterestRateChart.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountInterestRateChart.java index 068d92624..bf60e4947 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountInterestRateChart.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountInterestRateChart.java @@ -50,7 +50,7 @@ public class DepositAccountInterestRateChart extends AbstractPersistableCustom { @JoinColumn(name = "savings_account_id", nullable = false) private SavingsAccount account; - @OneToMany(mappedBy = "depositAccountInterestRateChart", cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(mappedBy = "depositAccountInterestRateChart", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) private Set chartSlabs = new HashSet<>(); protected DepositAccountInterestRateChart() { @@ -154,4 +154,4 @@ public class DepositAccountInterestRateChart extends AbstractPersistableCustom { public boolean isPrimaryGroupingByAmount() { return this.chartFields.isPrimaryGroupingByAmount(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountInterestRateChartSlabs.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountInterestRateChartSlabs.java index 3c4c2920c..36cbfc038 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountInterestRateChartSlabs.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountInterestRateChartSlabs.java @@ -44,7 +44,7 @@ public class DepositAccountInterestRateChartSlabs extends AbstractPersistableCus @JoinColumn(name = "savings_account_interest_rate_chart_id", referencedColumnName = "id", nullable = false) private DepositAccountInterestRateChart depositAccountInterestRateChart; - @OneToMany(mappedBy = "depositAccountInterestRateChartSlabs", cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(mappedBy = "depositAccountInterestRateChartSlabs", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) private Set interestIncentives = new HashSet<>(); protected DepositAccountInterestRateChartSlabs() { @@ -52,7 +52,8 @@ public class DepositAccountInterestRateChartSlabs extends AbstractPersistableCus } private DepositAccountInterestRateChartSlabs(InterestRateChartSlabFields slabFields, - DepositAccountInterestRateChart depositAccountInterestRateChart, final Set interestIncentives) { + DepositAccountInterestRateChart depositAccountInterestRateChart, + final Set interestIncentives) { this.slabFields = slabFields; this.depositAccountInterestRateChart = depositAccountInterestRateChart; this.interestIncentives = interestIncentives; @@ -101,4 +102,4 @@ public class DepositAccountInterestRateChartSlabs extends AbstractPersistableCus public void updateChartReference(final DepositAccountInterestRateChart chart) { this.depositAccountInterestRateChart = chart; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountOnHoldTransaction.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountOnHoldTransaction.java old mode 100755 new mode 100644 index c321fc055..53439b1b6 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountOnHoldTransaction.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountOnHoldTransaction.java @@ -113,7 +113,7 @@ public class DepositAccountOnHoldTransaction extends AbstractPersistableCustom { public LocalDate getTransactionDate() { LocalDate transactionDate = null; - if(this.transactionDate !=null){ + if (this.transactionDate != null) { transactionDate = LocalDate.fromDateFields(this.transactionDate); } return transactionDate; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountOnHoldTransactionRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountOnHoldTransactionRepository.java old mode 100755 new mode 100644 index a2bc3327f..7bc05d8a2 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountOnHoldTransactionRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountOnHoldTransactionRepository.java @@ -22,8 +22,8 @@ import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface DepositAccountOnHoldTransactionRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface DepositAccountOnHoldTransactionRepository + extends JpaRepository, JpaSpecificationExecutor { - List findBySavingsAccountAndReversedFalseOrderByCreatedDateAsc(SavingsAccount account); + List findBySavingsAccountAndReversedFalseOrderByCreatedDateAsc(SavingsAccount account); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountRecurringDetail.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountRecurringDetail.java index 0a6c32efa..3e5806aa3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountRecurringDetail.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountRecurringDetail.java @@ -100,7 +100,8 @@ public class DepositAccountRecurringDetail extends AbstractPersistableCustom { public Map update(final JsonCommand command) { final Map actualChanges = new LinkedHashMap<>(10); - if (command.isChangeInBigDecimalParameterNamed(mandatoryRecommendedDepositAmountParamName, this.mandatoryRecommendedDepositAmount)) { + if (command.isChangeInBigDecimalParameterNamed(mandatoryRecommendedDepositAmountParamName, + this.mandatoryRecommendedDepositAmount)) { final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(mandatoryRecommendedDepositAmountParamName); actualChanges.put(mandatoryRecommendedDepositAmountParamName, newValue); this.mandatoryRecommendedDepositAmount = newValue; @@ -119,8 +120,8 @@ public class DepositAccountRecurringDetail extends AbstractPersistableCustom { RecurringDepositAccount depositAccount = (RecurringDepositAccount) this.account; if (depositAccount.isNotActive()) { final String defaultUserMessage = "Updates to the recommended deposit amount are allowed only when the underlying account is active."; - final ApiParameterError error = ApiParameterError.generalError("error.msg." - + DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESOURCE_NAME + ".is.not.active", defaultUserMessage); + final ApiParameterError error = ApiParameterError.generalError( + "error.msg." + DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESOURCE_NAME + ".is.not.active", defaultUserMessage); final List dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); @@ -173,4 +174,4 @@ public class DepositAccountRecurringDetail extends AbstractPersistableCustom { this.noOfOverdueInstallments = noOfOverdueInstallments; this.totalOverdueAmount = totalOverdueAmount.getAmount(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountTermAndPreClosure.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountTermAndPreClosure.java index 637e1c72a..42995846c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountTermAndPreClosure.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountTermAndPreClosure.java @@ -105,7 +105,8 @@ public class DepositAccountTermAndPreClosure extends AbstractPersistableCustom { final DepositAccountOnClosureType accountOnClosureType, Boolean trasferInterest, Long transferToSavingsId) { return new DepositAccountTermAndPreClosure(preClosureDetail, depositTermDetail, account, depositAmount, maturityAmount, - maturityDate, depositPeriod, depositPeriodFrequency, expectedFirstDepositOnDate, accountOnClosureType, trasferInterest, transferToSavingsId); + maturityDate, depositPeriod, depositPeriodFrequency, expectedFirstDepositOnDate, accountOnClosureType, trasferInterest, + transferToSavingsId); } private DepositAccountTermAndPreClosure(DepositPreClosureDetail preClosureDetail, DepositTermDetail depositTermDetail, @@ -164,18 +165,18 @@ public class DepositAccountTermAndPreClosure extends AbstractPersistableCustom { this.transferInterestToLinkedAccount = newValue; } - if (command.isChangeInIntegerParameterNamed(maturityInstructionIdParamName, this.onAccountClosureType) || command.integerValueOfParameterNamed( - maturityInstructionIdParamName) == null) { + if (command.isChangeInIntegerParameterNamed(maturityInstructionIdParamName, this.onAccountClosureType) + || command.integerValueOfParameterNamed(maturityInstructionIdParamName) == null) { final Integer newValue = command.integerValueOfParameterNamed(maturityInstructionIdParamName); actualChanges.put(maturityInstructionIdParamName, newValue); this.onAccountClosureType = newValue != null ? DepositAccountOnClosureType.fromInt(newValue).getValue() : null; } - if (command.isChangeInLongParameterNamed(transferToSavingsIdParamName, this.transferToSavingsAccountId) || command.integerValueOfParameterNamed( - transferToSavingsIdParamName) == null) { + if (command.isChangeInLongParameterNamed(transferToSavingsIdParamName, this.transferToSavingsAccountId) + || command.integerValueOfParameterNamed(transferToSavingsIdParamName) == null) { final Long newValue = command.longValueOfParameterNamed(transferToSavingsIdParamName); actualChanges.put(transferToSavingsIdParamName, newValue); - this.transferToSavingsAccountId = newValue ; + this.transferToSavingsAccountId = newValue; } if (this.preClosureDetail != null) { @@ -231,7 +232,6 @@ public class DepositAccountTermAndPreClosure extends AbstractPersistableCustom { this.depositAmount = depositAmount; } - public LocalDate getMaturityLocalDate() { LocalDate maturityLocalDate = null; if (this.maturityDate != null) { @@ -261,7 +261,9 @@ public class DepositAccountTermAndPreClosure extends AbstractPersistableCustom { } Integer actualDepositPeriod = this.depositPeriod; - if (depositFromDate == null || getMaturityLocalDate() == null || interestPostingUpToDate.isEqual(getMaturityLocalDate())) { return actualDepositPeriod; } + if (depositFromDate == null || getMaturityLocalDate() == null || interestPostingUpToDate.isEqual(getMaturityLocalDate())) { + return actualDepositPeriod; + } final SavingsPeriodFrequencyType depositPeriodFrequencyType = periodFrequencyType; switch (depositPeriodFrequencyType) { @@ -342,4 +344,4 @@ public class DepositAccountTermAndPreClosure extends AbstractPersistableCustom { public Long getTransferToSavingsAccountId() { return transferToSavingsAccountId; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositPreClosureDetail.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositPreClosureDetail.java index 29e4aa5a1..e8d786eef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositPreClosureDetail.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositPreClosureDetail.java @@ -134,4 +134,4 @@ public class DepositPreClosureDetail { return DepositPreClosureDetail.createFrom(preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestType); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductAmountDetails.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductAmountDetails.java index e08e2d4f6..955602019 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductAmountDetails.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductAmountDetails.java @@ -51,7 +51,8 @@ public class DepositProductAmountDetails { // } - public DepositProductAmountDetails(final BigDecimal minDepositAmount, final BigDecimal depositAmount, final BigDecimal maxDepositAmount) { + public DepositProductAmountDetails(final BigDecimal minDepositAmount, final BigDecimal depositAmount, + final BigDecimal maxDepositAmount) { this.minDepositAmount = minDepositAmount; this.depositAmount = depositAmount; this.maxDepositAmount = maxDepositAmount; @@ -102,4 +103,4 @@ public class DepositProductAmountDetails { return this.depositAmount; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductAssembler.java index 8db8dbc37..f981ff457 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductAssembler.java @@ -292,8 +292,8 @@ public class DepositProductAssembler { preClosurePenalInterest = command.bigDecimalValueOfParameterNamed(preClosurePenalInterestParamName); final Integer preClosurePenalInterestOnTypeId = command .integerValueOfParameterNamed(preClosurePenalInterestOnTypeIdParamName); - preClosurePenalInterestType = preClosurePenalInterestOnTypeId == null ? null : PreClosurePenalInterestOnType - .fromInt(preClosurePenalInterestOnTypeId); + preClosurePenalInterestType = preClosurePenalInterestOnTypeId == null ? null + : PreClosurePenalInterestOnType.fromInt(preClosurePenalInterestOnTypeId); } } @@ -329,8 +329,8 @@ public class DepositProductAssembler { preClosurePenalInterestOnTypeId = produPreClosureDetail.preClosurePenalInterestOnTypeId(); } - preClosurePenalInterestType = preClosurePenalInterestOnTypeId == null ? null : PreClosurePenalInterestOnType - .fromInt(preClosurePenalInterestOnTypeId); + preClosurePenalInterestType = preClosurePenalInterestOnTypeId == null ? null + : PreClosurePenalInterestOnType.fromInt(preClosurePenalInterestOnTypeId); DepositPreClosureDetail preClosureDetail1 = DepositPreClosureDetail.createFrom(preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestType); @@ -343,11 +343,11 @@ public class DepositProductAssembler { final Integer minDepositTerm = command.integerValueOfParameterNamed(minDepositTermParamName); final Integer maxDepositTerm = command.integerValueOfParameterNamed(maxDepositTermParamName); final Integer minDepositTermTypeId = command.integerValueOfParameterNamed(minDepositTermTypeIdParamName); - final SavingsPeriodFrequencyType minDepositTermType = (minDepositTermTypeId == null) ? null : SavingsPeriodFrequencyType - .fromInt(minDepositTermTypeId); + final SavingsPeriodFrequencyType minDepositTermType = (minDepositTermTypeId == null) ? null + : SavingsPeriodFrequencyType.fromInt(minDepositTermTypeId); final Integer maxDepositTermTypeId = command.integerValueOfParameterNamed(maxDepositTermTypeIdParamName); - final SavingsPeriodFrequencyType maxDepositTermType = (maxDepositTermTypeId == null) ? null : SavingsPeriodFrequencyType - .fromInt(maxDepositTermTypeId); + final SavingsPeriodFrequencyType maxDepositTermType = (maxDepositTermTypeId == null) ? null + : SavingsPeriodFrequencyType.fromInt(maxDepositTermTypeId); final Integer inMultiplesOfDepositTerm = command.integerValueOfParameterNamed(inMultiplesOfDepositTermParamName); final Integer inMultiplesOfDepositTermTypeId = command.integerValueOfParameterNamed(inMultiplesOfDepositTermTypeIdParamName); final SavingsPeriodFrequencyType inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null @@ -392,11 +392,11 @@ public class DepositProductAssembler { maxDepositTermTypeId = prodDepositTermDetail.maxDepositTermType(); } - final SavingsPeriodFrequencyType minDepositTermType = (minDepositTermTypeId == null) ? null : SavingsPeriodFrequencyType - .fromInt(minDepositTermTypeId); + final SavingsPeriodFrequencyType minDepositTermType = (minDepositTermTypeId == null) ? null + : SavingsPeriodFrequencyType.fromInt(minDepositTermTypeId); - final SavingsPeriodFrequencyType maxDepositTermType = (maxDepositTermTypeId == null) ? null : SavingsPeriodFrequencyType - .fromInt(maxDepositTermTypeId); + final SavingsPeriodFrequencyType maxDepositTermType = (maxDepositTermTypeId == null) ? null + : SavingsPeriodFrequencyType.fromInt(maxDepositTermTypeId); if (command.parameterExists(inMultiplesOfDepositTermParamName)) { inMultiplesOfDepositTerm = command.integerValueOfParameterNamed(inMultiplesOfDepositTermParamName); @@ -522,4 +522,4 @@ public class DepositProductAssembler { } return taxGroup; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductRecurringDetail.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductRecurringDetail.java index 70b755a80..3518a1638 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductRecurringDetail.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductRecurringDetail.java @@ -68,4 +68,4 @@ public class DepositProductRecurringDetail extends AbstractPersistableCustom { public void updateProductReference(final SavingsProduct product) { this.product = (RecurringDepositProduct) product; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductTermAndPreClosure.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductTermAndPreClosure.java index 869f4484e..3c4f5e97b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductTermAndPreClosure.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositProductTermAndPreClosure.java @@ -95,4 +95,4 @@ public class DepositProductTermAndPreClosure extends AbstractPersistableCustom { public void updateProductReference(final SavingsProduct product) { this.product = (FixedDepositProduct) product; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositRecurringDetail.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositRecurringDetail.java index cce623d28..1a8a03b7d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositRecurringDetail.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositRecurringDetail.java @@ -100,4 +100,4 @@ public class DepositRecurringDetail { public DepositRecurringDetail copy() { return DepositRecurringDetail.createFrom(this.isMandatoryDeposit, this.allowWithdrawal, this.adjustAdvanceTowardsFuturePayments); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositTermDetail.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositTermDetail.java index 2b5a6a204..2e6c43ca3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositTermDetail.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositTermDetail.java @@ -129,8 +129,8 @@ public class DepositTermDetail { } if (isMinDepositTermGreaterThanMaxDepositTerm()) { - baseDataValidator.parameter(minDepositTermParamName).value(this.minDepositTerm) - .failWithCode(".greater.than.maxDepositTerm", this.minDepositTerm, this.maxDepositTerm); + baseDataValidator.parameter(minDepositTermParamName).value(this.minDepositTerm).failWithCode(".greater.than.maxDepositTerm", + this.minDepositTerm, this.maxDepositTerm); } return actualChanges; @@ -181,7 +181,7 @@ public class DepositTermDetail { final Integer inMultiplesOfInDays = this.convertToSafeDays(this.inMultiplesOfDepositTerm(), SavingsPeriodFrequencyType.fromInt(this.inMultiplesOfDepositTermType())); final Integer minDepositInDays = this.convertToSafeDays(minDepositTerm, SavingsPeriodFrequencyType.fromInt(minDepositTermType)); - if(inMultiplesOfInDays!=0) { + if (inMultiplesOfInDays != 0) { isValidInMultiplesOfPeriod = ((depositPeriodInDays - minDepositInDays) % inMultiplesOfInDays == 0); } } @@ -190,18 +190,14 @@ public class DepositTermDetail { } private boolean isEqualOrGreaterThanMin(LocalDate depositStartDate, LocalDate depositEndDate) { - if (minDepositTerm() == null) { - return true; - } + if (minDepositTerm() == null) { return true; } final SavingsPeriodFrequencyType periodFrequencyType = SavingsPeriodFrequencyType.fromInt(this.minDepositTermType()); final Integer depositPeriod = depositPeriod(depositStartDate, depositEndDate, periodFrequencyType); return minDepositTerm() == null || depositPeriod.compareTo(minDepositTerm()) >= 0; } private boolean isEqualOrLessThanMax(LocalDate depositStartDate, LocalDate depositEndDate) { - if (maxDepositTerm() == null) { - return true; - } + if (maxDepositTerm() == null) { return true; } final SavingsPeriodFrequencyType periodFrequencyType = SavingsPeriodFrequencyType.fromInt(this.maxDepositTermType()); final Integer depositPeriod = depositPeriod(depositStartDate, depositEndDate, periodFrequencyType); return maxDepositTerm() == null || depositPeriod.compareTo(maxDepositTerm()) <= 0; @@ -260,10 +256,10 @@ public class DepositTermDetail { final SavingsPeriodFrequencyType minDepositTermType = SavingsPeriodFrequencyType.fromInt(this.minDepositTermType); final SavingsPeriodFrequencyType maxDepositTermType = SavingsPeriodFrequencyType.fromInt(this.maxDepositTermType); final Integer inMultiplesOfDepositTerm = this.inMultiplesOfDepositTerm; - final SavingsPeriodFrequencyType inMultiplesOfDepositTermType = SavingsPeriodFrequencyType.fromInt(this - .inMultiplesOfDepositTermType()); + final SavingsPeriodFrequencyType inMultiplesOfDepositTermType = SavingsPeriodFrequencyType + .fromInt(this.inMultiplesOfDepositTermType()); return DepositTermDetail.createFrom(minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositAccount.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositAccount.java index 298040eac..5549044f6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositAccount.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositAccount.java @@ -84,15 +84,16 @@ public class FixedDepositAccount extends SavingsAccount { // } - public static FixedDepositAccount createNewApplicationForSubmittal(final Client client, final Group group, - final SavingsProduct product, final Staff fieldOfficer, final String accountNo, final String externalId, - final AccountType accountType, final LocalDate submittedOnDate, final AppUser submittedBy, final BigDecimal interestRate, + public static FixedDepositAccount createNewApplicationForSubmittal(final Client client, final Group group, final SavingsProduct product, + final Staff fieldOfficer, final String accountNo, final String externalId, final AccountType accountType, + final LocalDate submittedOnDate, final AppUser submittedBy, final BigDecimal interestRate, final SavingsCompoundingInterestPeriodType interestCompoundingPeriodType, final SavingsPostingInterestPeriodType interestPostingPeriodType, final SavingsInterestCalculationType interestCalculationType, final SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final SavingsPeriodFrequencyType lockinPeriodFrequencyType, final boolean withdrawalFeeApplicableForTransfer, final Set savingsAccountCharges, - final DepositAccountTermAndPreClosure accountTermAndPreClosure, final DepositAccountInterestRateChart chart, boolean withHoldTax) { + final DepositAccountTermAndPreClosure accountTermAndPreClosure, final DepositAccountInterestRateChart chart, + boolean withHoldTax) { final SavingsAccountStatusType status = SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL; final boolean allowOverdraft = false; @@ -259,8 +260,6 @@ public class FixedDepositAccount extends SavingsAccount { } } - - public LocalDate calculateMaturityDate() { final LocalDate startDate = accountSubmittedOrActivationDate(); @@ -297,7 +296,7 @@ public class FixedDepositAccount extends SavingsAccount { final SavingsInterestCalculationDaysInYearType daysInYearType = SavingsInterestCalculationDaysInYearType .fromInt(this.interestCalculationDaysInYearType); - List postedAsOnTransactionDates= getManualPostingDates(); + List postedAsOnTransactionDates = getManualPostingDates(); final List postingPeriodIntervals = this.savingsHelper.determineInterestPostingPeriods( accountSubmittedOrActivationDate(), maturityDate, postingPeriodType, financialYearBeginningMonth, @@ -317,9 +316,9 @@ public class FixedDepositAccount extends SavingsAccount { if (postedAsOnTransactionDates.contains(periodInterval.endDate())) { isUserPosting = true; } - final PostingPeriod postingPeriod = PostingPeriod.createFrom(periodInterval, periodStartingBalance, transactions, - this.currency, compoundingPeriodType, interestCalculationType, interestRateAsFraction, daysInYearType.getValue(), - maturityDate, interestPostTransactions, isInterestTransfer, minBalanceForInterestCalculation, + final PostingPeriod postingPeriod = PostingPeriod.createFrom(periodInterval, periodStartingBalance, transactions, this.currency, + compoundingPeriodType, interestCalculationType, interestRateAsFraction, daysInYearType.getValue(), maturityDate, + interestPostTransactions, isInterestTransfer, minBalanceForInterestCalculation, isSavingsInterestPostingAtCurrentPeriodEnd, isUserPosting, financialYearBeginningMonth); periodStartingBalance = postingPeriod.closingBalance(); @@ -491,11 +490,11 @@ public class FixedDepositAccount extends SavingsAccount { // this.savingsAccountTransactionSummaryWrapper, this.transactions); } - public void updateClosedStatus(){ + public void updateClosedStatus() { this.status = SavingsAccountStatusType.CLOSED.getValue(); } - public void updateOnAccountClosureStatus(DepositAccountOnClosureType onClosureType){ + public void updateOnAccountClosureStatus(DepositAccountOnClosureType onClosureType) { this.accountTermAndPreClosure.updateOnAccountClosureStatus(onClosureType); } @@ -625,7 +624,7 @@ public class FixedDepositAccount extends SavingsAccount { @Override public List calculateInterestUsing(final MathContext mc, final LocalDate postingDate, boolean isInterestTransfer, final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth, - final LocalDate postAsInterestOn) { + final LocalDate postAsInterestOn) { final LocalDate interestPostingUpToDate = interestPostingUpToDate(postingDate); return super.calculateInterestUsing(mc, interestPostingUpToDate, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postAsInterestOn); @@ -706,8 +705,8 @@ public class FixedDepositAccount extends SavingsAccount { final boolean isMinTermGreaterThanMax = this.accountTermAndPreClosure.depositTermDetail() .isMinDepositTermGreaterThanMaxDepositTerm(); - final boolean isValidDepositPeriod = this.accountTermAndPreClosure.depositTermDetail().isDepositBetweenMinAndMax( - depositStartDate(), calculateMaturityDate()); + final boolean isValidDepositPeriod = this.accountTermAndPreClosure.depositTermDetail().isDepositBetweenMinAndMax(depositStartDate(), + calculateMaturityDate()); // deposit period should be within min and max deposit term if (isMinTermGreaterThanMax) { final Integer maxTerm = this.accountTermAndPreClosure.depositTermDetail().maxDepositTerm(); @@ -746,9 +745,9 @@ public class FixedDepositAccount extends SavingsAccount { BigDecimal applicableInterestRate = this.chart.getApplicableInterestRate(depositAmount, depositStartDate(), calculateMaturityDate(), this.client); - if (applicableInterestRate.compareTo(BigDecimal.ZERO) == 0 ? Boolean.TRUE:Boolean.FALSE) { - baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( - "no.applicable.interest.rate.is.found.based.on.amount.and.deposit.period"); + if (applicableInterestRate.compareTo(BigDecimal.ZERO) == 0 ? Boolean.TRUE : Boolean.FALSE) { + baseDataValidator.reset() + .failWithCodeNoParameterAddedToErrorCode("no.applicable.interest.rate.is.found.based.on.amount.and.deposit.period"); } } else if (this.nominalAnnualInterestRate == null || this.nominalAnnualInterestRate.compareTo(BigDecimal.ZERO) == 0) { @@ -766,7 +765,7 @@ public class FixedDepositAccount extends SavingsAccount { return this.accountTermAndPreClosure.isTransferToSavingsOnClosure(); } - public Integer getOnAccountClosureId(){ + public Integer getOnAccountClosureId() { return this.accountTermAndPreClosure.getOnAccountClosureType(); } @@ -799,8 +798,8 @@ public class FixedDepositAccount extends SavingsAccount { final FixedDepositAccount reInvestedAccount = FixedDepositAccount.createNewApplicationForSubmittal(client, group, product, savingsOfficer, accountNumber, externalId, accountType, getClosedOnDate(), closedBy, interestRate, compoundingPeriodType, postingPeriodType, interestCalculationType, daysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, - lockinPeriodFrequencyType, withdrawalFeeApplicableForTransfer, savingsAccountCharges, newAccountTermAndPreClosure, - newChart, withHoldTax); + lockinPeriodFrequencyType, withdrawalFeeApplicableForTransfer, savingsAccountCharges, newAccountTermAndPreClosure, newChart, + withHoldTax); newAccountTermAndPreClosure.updateAccountReference(reInvestedAccount); newChart.updateDepositAccountReference(reInvestedAccount); @@ -846,17 +845,19 @@ public class FixedDepositAccount extends SavingsAccount { @Override public void loadLazyCollections() { super.loadLazyCollections(); - this.chart.getId() ; + this.chart.getId(); } public BigDecimal getDepositAmount() { return this.accountTermAndPreClosure.depositAmount(); } + @Override public BigDecimal getAccountBalance() { return this.summary.getAccountBalance(this.currency).getAmount(); } - public boolean isMatured(){ + + public boolean isMatured() { return SavingsAccountStatusType.MATURED.getValue().equals(this.status); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositAccountRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositAccountRepository.java index 3e427baeb..a711fb792 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositAccountRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositAccountRepository.java @@ -21,7 +21,7 @@ package org.apache.fineract.portfolio.savings.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface FixedDepositAccountRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface FixedDepositAccountRepository + extends JpaRepository, JpaSpecificationExecutor { -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositProduct.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositProduct.java index 7be02f402..19964bb43 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositProduct.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositProduct.java @@ -97,8 +97,7 @@ public class FixedDepositProduct extends SavingsProduct { return new FixedDepositProduct(name, shortName, description, currency, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeApplicableForTransfer, accountingRuleType, charges, - productTermAndPreClosure, charts, allowOverdraft, overdraftLimit, minBalanceForInterestCalculation, withHoldTax, - taxGroup); + productTermAndPreClosure, charts, allowOverdraft, overdraftLimit, minBalanceForInterestCalculation, withHoldTax, taxGroup); } protected FixedDepositProduct(final String name, final String shortName, final String description, final MonetaryCurrency currency, @@ -282,24 +281,19 @@ public class FixedDepositProduct extends SavingsProduct { public void validateInterestPostingAndCompoundingPeriodTypes(final DataValidatorBuilder baseDataValidator) { Map> postingtoCompoundMap = new HashMap<>(); - postingtoCompoundMap.put( - SavingsPostingInterestPeriodType.MONTHLY, - Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, - SavingsCompoundingInterestPeriodType.MONTHLY })); + postingtoCompoundMap.put(SavingsPostingInterestPeriodType.MONTHLY, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { + SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY })); - postingtoCompoundMap.put( - SavingsPostingInterestPeriodType.QUATERLY, + postingtoCompoundMap.put(SavingsPostingInterestPeriodType.QUATERLY, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY, SavingsCompoundingInterestPeriodType.QUATERLY })); - postingtoCompoundMap.put( - SavingsPostingInterestPeriodType.BIANNUAL, + postingtoCompoundMap.put(SavingsPostingInterestPeriodType.BIANNUAL, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY, SavingsCompoundingInterestPeriodType.QUATERLY, SavingsCompoundingInterestPeriodType.BI_ANNUAL })); - postingtoCompoundMap.put( - SavingsPostingInterestPeriodType.ANNUAL, + postingtoCompoundMap.put(SavingsPostingInterestPeriodType.ANNUAL, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY, SavingsCompoundingInterestPeriodType.QUATERLY, SavingsCompoundingInterestPeriodType.BI_ANNUAL, SavingsCompoundingInterestPeriodType.ANNUAL })); @@ -345,4 +339,4 @@ public class FixedDepositProduct extends SavingsProduct { this.validateInterestPostingAndCompoundingPeriodTypes(baseDataValidator); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositProductRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositProductRepository.java index cc09aa92d..ecc8b8849 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositProductRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/FixedDepositProductRepository.java @@ -21,7 +21,7 @@ package org.apache.fineract.portfolio.savings.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface FixedDepositProductRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface FixedDepositProductRepository + extends JpaRepository, JpaSpecificationExecutor { -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/GSIMRepositoy.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/GSIMRepositoy.java index 35d7b049e..3000ada17 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/GSIMRepositoy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/GSIMRepositoy.java @@ -23,10 +23,12 @@ import java.math.BigDecimal; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface GSIMRepositoy extends JpaRepository, JpaSpecificationExecutor -{ +public interface GSIMRepositoy + extends JpaRepository, JpaSpecificationExecutor { GroupSavingsIndividualMonitoring findOneByIsAcceptingChild(boolean acceptingChild); - GroupSavingsIndividualMonitoring findOneByIsAcceptingChildAndApplicationId(boolean acceptingChild,BigDecimal applicationId); + + GroupSavingsIndividualMonitoring findOneByIsAcceptingChildAndApplicationId(boolean acceptingChild, BigDecimal applicationId); + GroupSavingsIndividualMonitoring findOneByAccountNumber(String accountNumber); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/GroupSavingsIndividualMonitoring.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/GroupSavingsIndividualMonitoring.java index 24920e8c3..8001edd1b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/GroupSavingsIndividualMonitoring.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/GroupSavingsIndividualMonitoring.java @@ -32,111 +32,107 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; import org.apache.fineract.portfolio.group.domain.Group; @Entity -@Table(name = "gsim_accounts", uniqueConstraints = { @UniqueConstraint(columnNames = { "account_number" }, name = "gsim_id")}) -public class GroupSavingsIndividualMonitoring extends AbstractPersistableCustom -{ +@Table(name = "gsim_accounts", uniqueConstraints = { @UniqueConstraint(columnNames = { "account_number" }, name = "gsim_id") }) +public class GroupSavingsIndividualMonitoring extends AbstractPersistableCustom { - @ManyToOne - @JoinColumn(name = "group_id", nullable = false) - private Group group; + @ManyToOne + @JoinColumn(name = "group_id", nullable = false) + private Group group; - @Column(name = "account_number", nullable = false) - private String accountNumber; + @Column(name = "account_number", nullable = false) + private String accountNumber; - @Column(name = "parent_deposit") - private BigDecimal parentDeposit; + @Column(name = "parent_deposit") + private BigDecimal parentDeposit; + @Column(name = "child_accounts_count") + private Long childAccountsCount; - @Column(name = "child_accounts_count") - private Long childAccountsCount; + @Column(name = "accepting_child") + private Boolean isAcceptingChild; - @Column(name = "accepting_child") - private Boolean isAcceptingChild; + @OneToMany + private Set childSaving; - @OneToMany - private Set childSaving; + @Column(name = "savings_status_id", nullable = false) + private Integer savingsStatus; - @Column(name = "savings_status_id", nullable = false) - private Integer savingsStatus; + @Column(name = "application_id", nullable = true) + private BigDecimal applicationId; - @Column(name = "application_id", nullable = true) - private BigDecimal applicationId; + private GroupSavingsIndividualMonitoring() {} - private GroupSavingsIndividualMonitoring() {} + private GroupSavingsIndividualMonitoring(String accountNumber, Group group, BigDecimal parentDeposit, Long childAccountsCount, + Boolean isAcceptingChild, Integer savingsStatus, BigDecimal applicationId) { + this.accountNumber = accountNumber; + this.group = group; + this.parentDeposit = parentDeposit; + this.childAccountsCount = childAccountsCount; + this.isAcceptingChild = isAcceptingChild; + this.savingsStatus = savingsStatus; + this.applicationId = applicationId; - private GroupSavingsIndividualMonitoring(String accountNumber,Group group,BigDecimal parentDeposit,Long childAccountsCount, - Boolean isAcceptingChild,Integer savingsStatus,BigDecimal applicationId) - { - this.accountNumber=accountNumber; - this.group=group; - this.parentDeposit=parentDeposit; - this.childAccountsCount=childAccountsCount; - this.isAcceptingChild=isAcceptingChild; - this.savingsStatus=savingsStatus; - this.applicationId=applicationId; + } - } + public static GroupSavingsIndividualMonitoring getInstance(String accountNumber, Group group, BigDecimal parentDeposit, + Long childAccountsCount, Boolean isAcceptingChild, Integer savingsStatus, BigDecimal applicationId) { + return new GroupSavingsIndividualMonitoring(accountNumber, group, parentDeposit, childAccountsCount, isAcceptingChild, + savingsStatus, applicationId); + } - public static GroupSavingsIndividualMonitoring getInstance(String accountNumber,Group group,BigDecimal parentDeposit,Long childAccountsCount, - Boolean isAcceptingChild,Integer savingsStatus,BigDecimal applicationId) - { - return new GroupSavingsIndividualMonitoring(accountNumber,group,parentDeposit,childAccountsCount, - isAcceptingChild,savingsStatus,applicationId); - } + public Group getGroup() { + return group; + } - public Group getGroup() { - return group; - } + public void setGroup(Group group) { + this.group = group; + } - public void setGroup(Group group) { - this.group = group; - } + public String getAccountNumber() { + return accountNumber; + } - public String getAccountNumber() { - return accountNumber; - } + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } - public void setAccountNumber(String accountNumber) { - this.accountNumber = accountNumber; - } + public BigDecimal getParentDeposit() { + return parentDeposit; + } - public BigDecimal getParentDeposit() { - return parentDeposit; - } + public void setParentDeposit(BigDecimal parentDeposit) { + this.parentDeposit = parentDeposit; + } - public void setParentDeposit(BigDecimal parentDeposit) { - this.parentDeposit = parentDeposit; - } + public Long getChildAccountsCount() { + return childAccountsCount; + } - public Long getChildAccountsCount() { - return childAccountsCount; - } + public void setChildAccountsCount(Long childAccountsCount) { + this.childAccountsCount = childAccountsCount; + } - public void setChildAccountsCount(Long childAccountsCount) { - this.childAccountsCount = childAccountsCount; - } + public Boolean getIsAcceptingChild() { + return isAcceptingChild; + } - public Boolean getIsAcceptingChild() { - return isAcceptingChild; - } + public void setIsAcceptingChild(Boolean isAcceptingChild) { + this.isAcceptingChild = isAcceptingChild; + } - public void setIsAcceptingChild(Boolean isAcceptingChild) { - this.isAcceptingChild = isAcceptingChild; - } + public Set getChildSaving() { + return childSaving; + } - public Set getChildSaving() { - return childSaving; - } + public void setChildSaving(Set childSaving) { + this.childSaving = childSaving; + } - public void setChildSaving(Set childSaving) { - this.childSaving = childSaving; - } + public Integer getSavingsStatus() { + return savingsStatus; + } - public Integer getSavingsStatus() { - return savingsStatus; - } - - public void setSavingsStatus(Integer savingsStatus) { - this.savingsStatus = savingsStatus; - } -} \ No newline at end of file + public void setSavingsStatus(Integer savingsStatus) { + this.savingsStatus = savingsStatus; + } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositAccount.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositAccount.java index 62499f2ac..26c191505 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositAccount.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositAccount.java @@ -86,7 +86,7 @@ public class RecurringDepositAccount extends SavingsAccount { @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "account") private DepositAccountInterestRateChart chart; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "account", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "account", orphanRemoval = true, fetch = FetchType.LAZY) private List depositScheduleInstallments = new ArrayList<>(); protected RecurringDepositAccount() { @@ -329,7 +329,7 @@ public class RecurringDepositAccount extends SavingsAccount { final SavingsInterestCalculationDaysInYearType daysInYearType = SavingsInterestCalculationDaysInYearType .fromInt(this.interestCalculationDaysInYearType); - List PostedAsOnDates = getManualPostingDates(); + List PostedAsOnDates = getManualPostingDates(); final List postingPeriodIntervals = this.savingsHelper.determineInterestPostingPeriods(depositStartDate(), maturityDate, postingPeriodType, financialYearBeginningMonth, PostedAsOnDates); @@ -347,9 +347,9 @@ public class RecurringDepositAccount extends SavingsAccount { if (PostedAsOnDates.contains(periodInterval.endDate())) { isUserPosting = true; } - final PostingPeriod postingPeriod = PostingPeriod.createFrom(periodInterval, periodStartingBalance, transactions, - this.currency, compoundingPeriodType, interestCalculationType, interestRateAsFraction, daysInYearType.getValue(), - maturityDate, interestPostTransactions, isInterestTransfer, minBalanceForInterestCalculation, + final PostingPeriod postingPeriod = PostingPeriod.createFrom(periodInterval, periodStartingBalance, transactions, this.currency, + compoundingPeriodType, interestCalculationType, interestRateAsFraction, daysInYearType.getValue(), maturityDate, + interestPostTransactions, isInterestTransfer, minBalanceForInterestCalculation, isSavingsInterestPostingAtCurrentPeriodEnd, isUserPosting, financialYearBeginningMonth); periodStartingBalance = postingPeriod.closingBalance(); @@ -370,7 +370,7 @@ public class RecurringDepositAccount extends SavingsAccount { allTransactions.addAll(retreiveOrderedNonInterestPostingTransactions()); LocalDate latestTransactionDate = null; for (final SavingsAccountTransaction installment : allTransactions) { - if(latestTransactionDate == null || latestTransactionDate.isBefore(installment.getTransactionLocalDate())){ + if (latestTransactionDate == null || latestTransactionDate.isBefore(installment.getTransactionLocalDate())) { latestTransactionDate = installment.getTransactionLocalDate(); } } @@ -378,12 +378,11 @@ public class RecurringDepositAccount extends SavingsAccount { for (RecurringDepositScheduleInstallment installment : depositScheduleInstallments()) { if (installment.isPrincipalNotCompleted(getCurrency())) { LocalDate dueDate = installment.dueDate(); - if(latestTransactionDate != null && dueDate.isBefore(latestTransactionDate)){ + if (latestTransactionDate != null && dueDate.isBefore(latestTransactionDate)) { dueDate = latestTransactionDate; } - final SavingsAccountTransaction transaction = SavingsAccountTransaction.deposit(null, office(), null, - dueDate, installment.getDepositAmountOutstanding(getCurrency()), installment.dueDate().toDate(), - null); + final SavingsAccountTransaction transaction = SavingsAccountTransaction.deposit(null, office(), null, dueDate, + installment.getDepositAmountOutstanding(getCurrency()), installment.dueDate().toDate(), null); allTransactions.add(transaction); } } @@ -421,9 +420,7 @@ public class RecurringDepositAccount extends SavingsAccount { public LocalDate depositStartDate() { final LocalDate depositStartDate = accountTermAndPreClosure.getExpectedFirstDepositOnDate(); - if (depositStartDate == null) { - return accountSubmittedOrActivationDate(); - } + if (depositStartDate == null) { return accountSubmittedOrActivationDate(); } return depositStartDate; } @@ -723,7 +720,8 @@ public class RecurringDepositAccount extends SavingsAccount { @Override public void postInterest(final MathContext mc, final LocalDate postingDate, final boolean isInterestTransfer, - final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth,final LocalDate postInterestAson) { + final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth, + final LocalDate postInterestAson) { final LocalDate interestPostingUpToDate = interestPostingUpToDate(postingDate); super.postInterest(mc, interestPostingUpToDate, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postInterestAson); @@ -731,7 +729,8 @@ public class RecurringDepositAccount extends SavingsAccount { @Override public List calculateInterestUsing(final MathContext mc, final LocalDate postingDate, boolean isInterestTransfer, - final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth,final LocalDate postAsInterestOn) { + final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth, + final LocalDate postAsInterestOn) { final LocalDate interestPostingUpToDate = interestPostingUpToDate(postingDate); return super.calculateInterestUsing(mc, interestPostingUpToDate, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postAsInterestOn); @@ -765,7 +764,7 @@ public class RecurringDepositAccount extends SavingsAccount { private Money totalInterestPosted() { Money interestPostedToDate = Money.zero(this.currency); - List trans = getTransactions() ; + List trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if (transaction.isInterestPostingAndNotReversed()) { interestPostedToDate = interestPostedToDate.plus(transaction.getAmount(currency)); @@ -833,8 +832,8 @@ public class RecurringDepositAccount extends SavingsAccount { if (isBeforeDepositStartDate(transactionDTO.getTransactionDate())) { final String defaultUserMessage = "Transaction is not allowed. Transaction date is on or after account activation and deposit start date."; final ApiParameterError error = ApiParameterError.parameterError( - "error.msg.recurring.deposit.account.transaction.date.is.before.account.activation.or.deposit.date", - defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter())); + "error.msg.recurring.deposit.account.transaction.date.is.before.account.activation.or.deposit.date", defaultUserMessage, + "transactionDate", transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter())); final List dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); @@ -977,8 +976,8 @@ public class RecurringDepositAccount extends SavingsAccount { } if (depositPeriod != null) { final SavingsPeriodFrequencyType depositPeriodFrequencyType = this.accountTermAndPreClosure.depositPeriodFrequencyType(); - final boolean isValidDepositPeriod = this.accountTermAndPreClosure.depositTermDetail().isDepositBetweenMinAndMax( - depositStartDate(), calculateMaturityDate()); + final boolean isValidDepositPeriod = this.accountTermAndPreClosure.depositTermDetail() + .isDepositBetweenMinAndMax(depositStartDate(), calculateMaturityDate()); if (!isValidDepositPeriod) { baseDataValidator.reset().parameter(depositPeriodParamName).value(depositPeriod) .failWithCodeNoParameterAddedToErrorCode("deposit.period.not.between.min.and.max.deposit.term"); @@ -994,12 +993,9 @@ public class RecurringDepositAccount extends SavingsAccount { } } if (isAccountLocked(calculateMaturityDate())) { - baseDataValidator - .reset() - .parameter(depositPeriodParamName) - .value(depositPeriod) - .failWithCode("deposit.period.must.be.greater.than.lock.in.period", - "Deposit period must be greater than account lock-in period."); + baseDataValidator.reset().parameter(depositPeriodParamName).value(depositPeriod).failWithCode( + "deposit.period.must.be.greater.than.lock.in.period", + "Deposit period must be greater than account lock-in period."); } } @@ -1042,9 +1038,9 @@ public class RecurringDepositAccount extends SavingsAccount { BigDecimal applicableInterestRate = this.chart.getApplicableInterestRate(maturityAmount, depositStartDate(), maturityDate, this.client); - if (applicableInterestRate.compareTo(BigDecimal.ZERO) == 0 ? Boolean.TRUE:Boolean.FALSE) { - baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( - "no.applicable.interest.rate.is.found.based.on.amount.and.deposit.period"); + if (applicableInterestRate.compareTo(BigDecimal.ZERO) == 0 ? Boolean.TRUE : Boolean.FALSE) { + baseDataValidator.reset() + .failWithCodeNoParameterAddedToErrorCode("no.applicable.interest.rate.is.found.based.on.amount.and.deposit.period"); } } else if (this.nominalAnnualInterestRate == null || this.nominalAnnualInterestRate.compareTo(BigDecimal.ZERO) == 0) { @@ -1097,10 +1093,10 @@ public class RecurringDepositAccount extends SavingsAccount { newAccountTermAndPreClosure.updateExpectedFirstDepositDate(now); RecurringDepositAccount rdAccount = RecurringDepositAccount.createNewActivatedAccount(client, group, product, savingsOfficer, - accountNumber, externalId, accountType, getClosedOnDate(), closedBy, interestRate, compoundingPeriodType, - postingPeriodType, interestCalculationType, daysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, - lockinPeriodFrequencyType, withdrawalFeeApplicableForTransfer, savingsAccountCharges, newAccountTermAndPreClosure, - recurringDetail, newChart, withHoldTax); + accountNumber, externalId, accountType, getClosedOnDate(), closedBy, interestRate, compoundingPeriodType, postingPeriodType, + interestCalculationType, daysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, + withdrawalFeeApplicableForTransfer, savingsAccountCharges, newAccountTermAndPreClosure, recurringDetail, newChart, + withHoldTax); rdAccount.setDatesFrom(now); newAccountTermAndPreClosure.updateAccountReference(rdAccount); @@ -1112,9 +1108,7 @@ public class RecurringDepositAccount extends SavingsAccount { private boolean firstDepositDateBeforeAccountSubmittedOrActivationDate() { final LocalDate expectedFirstDepositLocalDate = accountTermAndPreClosure.getExpectedFirstDepositOnDate(); - if (expectedFirstDepositLocalDate == null) { - return false; - } + if (expectedFirstDepositLocalDate == null) { return false; } return expectedFirstDepositLocalDate.isBefore(accountSubmittedOrActivationDate()); } @@ -1154,8 +1148,8 @@ public class RecurringDepositAccount extends SavingsAccount { final LocalDate maturityDate = calcualteScheduleTillDate(frequency, recurringEvery); final BigDecimal depositAmount = this.recurringDetail.mandatoryRecommendedDepositAmount(); while (maturityDate.isAfter(installmentDate)) { - final RecurringDepositScheduleInstallment installment = RecurringDepositScheduleInstallment.installment(this, - installmentNumber, installmentDate.toDate(), depositAmount); + final RecurringDepositScheduleInstallment installment = RecurringDepositScheduleInstallment.installment(this, installmentNumber, + installmentDate.toDate(), depositAmount); addDepositScheduleInstallment(installment); installmentDate = DepositAccountUtils.calculateNextDepositDate(installmentDate, frequency, recurringEvery); installmentNumber += 1; @@ -1167,18 +1161,18 @@ public class RecurringDepositAccount extends SavingsAccount { LocalDate tillDate = calculateMaturityDate(); if (tillDate == null) { final LocalDate today = DateUtils.getLocalDateOfTenant(); - tillDate = DepositAccountUtils.calculateNextDepositDate(today, frequency, recurringEvery - * (DepositAccountUtils.GENERATE_MINIMUM_NUMBER_OF_FUTURE_INSTALMENTS + 1)); + tillDate = DepositAccountUtils.calculateNextDepositDate(today, frequency, + recurringEvery * (DepositAccountUtils.GENERATE_MINIMUM_NUMBER_OF_FUTURE_INSTALMENTS + 1)); } return tillDate; } private List depositScheduleInstallments() { - return this.depositScheduleInstallments ; + return this.depositScheduleInstallments; } private void addDepositScheduleInstallment(final RecurringDepositScheduleInstallment installment) { - this.depositScheduleInstallments.add(installment) ; + this.depositScheduleInstallments.add(installment); } public boolean isCalendarInherited() { @@ -1226,15 +1220,15 @@ public class RecurringDepositAccount extends SavingsAccount { @Override public int compare(final RecurringDepositScheduleInstallment o1, final RecurringDepositScheduleInstallment o2) { final int comparsion = o1.installmentNumber().compareTo(o2.installmentNumber()); - return comparsion ; + return comparsion; } } @Override public void loadLazyCollections() { - this.depositScheduleInstallments.size() ; + this.depositScheduleInstallments.size(); super.loadLazyCollections(); - this.chart.getId() ; + this.chart.getId(); } public BigDecimal getDepositAmount() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositAccountRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositAccountRepository.java index 2ed6b17dd..6d8c89028 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositAccountRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositAccountRepository.java @@ -21,7 +21,7 @@ package org.apache.fineract.portfolio.savings.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface RecurringDepositAccountRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface RecurringDepositAccountRepository + extends JpaRepository, JpaSpecificationExecutor { -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositProduct.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositProduct.java index fcac4749d..aa0b806e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositProduct.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositProduct.java @@ -165,4 +165,4 @@ public class RecurringDepositProduct extends FixedDepositProduct { this.validateInterestPostingAndCompoundingPeriodTypes(baseDataValidator); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositProductRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositProductRepository.java index c46f6fe09..3e60adbed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositProductRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositProductRepository.java @@ -21,7 +21,7 @@ package org.apache.fineract.portfolio.savings.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface RecurringDepositProductRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface RecurringDepositProductRepository + extends JpaRepository, JpaSpecificationExecutor { // -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositScheduleInstallment.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositScheduleInstallment.java index 15f0d93b2..cc1d18ac5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositScheduleInstallment.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/RecurringDepositScheduleInstallment.java @@ -92,8 +92,8 @@ public class RecurringDepositScheduleInstallment extends AbstractAuditableCustom * @param obligationsMet * @param obligationsMetOnDate */ - private RecurringDepositScheduleInstallment(final RecurringDepositAccount account, final Integer installmentNumber, - final Date fromDate, final Date dueDate, final BigDecimal depositAmount, final BigDecimal depositAmountCompleted, + private RecurringDepositScheduleInstallment(final RecurringDepositAccount account, final Integer installmentNumber, final Date fromDate, + final Date dueDate, final BigDecimal depositAmount, final BigDecimal depositAmountCompleted, final BigDecimal totalPaidInAdvance, final BigDecimal totalPaidLate, final boolean obligationsMet, final Date obligationsMetOnDate) { this.account = account; @@ -112,8 +112,8 @@ public class RecurringDepositScheduleInstallment extends AbstractAuditableCustom final Date fromDate, final Date dueDate, final BigDecimal depositAmount, final BigDecimal depositAmountCompleted, final BigDecimal totalPaidInAdvance, final BigDecimal totalPaidLate, final boolean obligationsMet, final Date obligationsMetOnDate) { - return new RecurringDepositScheduleInstallment(account, installmentNumber, fromDate, dueDate, depositAmount, - depositAmountCompleted, totalPaidInAdvance, totalPaidLate, obligationsMet, obligationsMetOnDate); + return new RecurringDepositScheduleInstallment(account, installmentNumber, fromDate, dueDate, depositAmount, depositAmountCompleted, + totalPaidInAdvance, totalPaidLate, obligationsMet, obligationsMetOnDate); } public static RecurringDepositScheduleInstallment installment(final RecurringDepositAccount account, final Integer installmentNumber, @@ -126,8 +126,8 @@ public class RecurringDepositScheduleInstallment extends AbstractAuditableCustom final boolean obligationsMet = false; final Date obligationsMetOnDate = null; - return new RecurringDepositScheduleInstallment(account, installmentNumber, fromDate, dueDate, depositAmount, - depositAmountCompleted, totalPaidInAdvance, totalPaidLate, obligationsMet, obligationsMetOnDate); + return new RecurringDepositScheduleInstallment(account, installmentNumber, fromDate, dueDate, depositAmount, depositAmountCompleted, + totalPaidInAdvance, totalPaidLate, obligationsMet, obligationsMetOnDate); } private BigDecimal defaultToNullIfZero(final BigDecimal value) { @@ -240,6 +240,6 @@ public class RecurringDepositScheduleInstallment extends AbstractAuditableCustom } public Integer installmentNumber() { - return this.installmentNumber ; + return this.installmentNumber; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccount.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccount.java old mode 100755 new mode 100644 index c0700e8ed..183a3a0a8 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccount.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccount.java @@ -140,11 +140,11 @@ public class SavingsAccount extends AbstractPersistableCustom { @JoinColumn(name = "client_id", nullable = true) protected Client client; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "group_id", nullable = true) protected Group group; - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "gsim_id", nullable = true) private GroupSavingsIndividualMonitoring gsim; @@ -152,7 +152,7 @@ public class SavingsAccount extends AbstractPersistableCustom { @JoinColumn(name = "product_id", nullable = false) protected SavingsProduct product; - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "field_officer_id", nullable = true) protected Staff savingsOfficer; @@ -169,7 +169,7 @@ public class SavingsAccount extends AbstractPersistableCustom { @Column(name = "submittedon_date", nullable = true) protected Date submittedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "submittedon_userid", nullable = true) protected AppUser submittedBy; @@ -177,7 +177,7 @@ public class SavingsAccount extends AbstractPersistableCustom { @Column(name = "rejectedon_date") protected Date rejectedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "rejectedon_userid", nullable = true) protected AppUser rejectedBy; @@ -185,7 +185,7 @@ public class SavingsAccount extends AbstractPersistableCustom { @Column(name = "withdrawnon_date") protected Date withdrawnOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "withdrawnon_userid", nullable = true) protected AppUser withdrawnBy; @@ -193,7 +193,7 @@ public class SavingsAccount extends AbstractPersistableCustom { @Column(name = "approvedon_date") protected Date approvedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "approvedon_userid", nullable = true) protected AppUser approvedBy; @@ -201,7 +201,7 @@ public class SavingsAccount extends AbstractPersistableCustom { @Column(name = "activatedon_date", nullable = true) protected Date activatedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "activatedon_userid", nullable = true) protected AppUser activatedBy; @@ -209,7 +209,7 @@ public class SavingsAccount extends AbstractPersistableCustom { @Column(name = "closedon_date") protected Date closedOnDate; - @ManyToOne(optional = true, fetch=FetchType.LAZY) + @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "closedon_userid", nullable = true) protected AppUser closedBy; @@ -241,7 +241,6 @@ public class SavingsAccount extends AbstractPersistableCustom { @Column(name = "interest_calculation_type_enum", nullable = false) protected Integer interestCalculationType; - /** * A value from the {@link SavingsInterestCalculationDaysInYearType} * enumeration. @@ -299,13 +298,13 @@ public class SavingsAccount extends AbstractPersistableCustom { protected SavingsAccountSummary summary; @OrderBy(value = "dateOf, createdDate, id") - @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccount", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccount", orphanRemoval = true, fetch = FetchType.LAZY) protected List transactions = new ArrayList<>(); - @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccount", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccount", orphanRemoval = true, fetch = FetchType.LAZY) protected Set charges = new HashSet<>(); - @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccount", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccount", orphanRemoval = true, fetch = FetchType.LAZY) private Set savingsOfficerHistory = new HashSet<>(); @Transient @@ -331,7 +330,7 @@ public class SavingsAccount extends AbstractPersistableCustom { @Column(name = "total_savings_amount_on_hold", scale = 6, precision = 19, nullable = true) private BigDecimal savingsOnHoldAmount; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "account", orphanRemoval = true, fetch=FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "account", orphanRemoval = true, fetch = FetchType.LAZY) protected List identifiers = new ArrayList<>(); protected SavingsAccount() { @@ -428,7 +427,7 @@ public class SavingsAccount extends AbstractPersistableCustom { this.enforceMinRequiredBalance = enforceMinRequiredBalance; this.minRequiredBalance = minRequiredBalance; this.minBalanceForInterestCalculation = product.minBalanceForInterestCalculation(); - //this.savingsOfficerHistory = null; + // this.savingsOfficerHistory = null; this.withHoldTax = withHoldTax; this.taxGroup = product.getTaxGroup(); } @@ -485,7 +484,8 @@ public class SavingsAccount extends AbstractPersistableCustom { } public void postInterest(final MathContext mc, final LocalDate interestPostingUpToDate, final boolean isInterestTransfer, - final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth, final LocalDate postInterestOnDate) { + final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth, + final LocalDate postInterestOnDate) { final List postingPeriods = calculateInterestUsing(mc, interestPostingUpToDate, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postInterestOnDate); Money interestPostedToDate = Money.zero(this.currency); @@ -571,7 +571,7 @@ public class SavingsAccount extends AbstractPersistableCustom { protected List findWithHoldTransactions() { final List withholdTransactions = new ArrayList<>(); - List trans = getTransactions() ; + List trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if (transaction.isWithHoldTaxAndNotReversed()) { withholdTransactions.add(transaction); @@ -586,7 +586,7 @@ public class SavingsAccount extends AbstractPersistableCustom { protected SavingsAccountTransaction findInterestPostingTransactionFor(final LocalDate postingDate) { SavingsAccountTransaction postingTransation = null; - List trans = getTransactions() ; + List trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if ((transaction.isInterestPostingAndNotReversed() || transaction.isOverdraftInterestAndNotReversed()) && transaction.occursOn(postingDate)) { @@ -597,7 +597,8 @@ public class SavingsAccount extends AbstractPersistableCustom { return postingTransation; } - protected SavingsAccountTransaction findTransactionFor(final LocalDate postingDate, final List transactions) { + protected SavingsAccountTransaction findTransactionFor(final LocalDate postingDate, + final List transactions) { SavingsAccountTransaction transaction = null; for (final SavingsAccountTransaction savingsAccountTransaction : transactions) { if (savingsAccountTransaction.occursOn(postingDate)) { @@ -651,7 +652,7 @@ public class SavingsAccount extends AbstractPersistableCustom { protected SavingsAccountTransaction findLastTransaction(final LocalDate date) { SavingsAccountTransaction savingsTransaction = null; - List trans = getTransactions() ; + List trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if (transaction.isNotReversed() && transaction.occursOn(date)) { savingsTransaction = transaction; @@ -691,7 +692,8 @@ public class SavingsAccount extends AbstractPersistableCustom { */ public List calculateInterestUsing(final MathContext mc, final LocalDate upToInterestCalculationDate, - boolean isInterestTransfer, final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth,final LocalDate postInterestOnDate) { + boolean isInterestTransfer, final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth, + final LocalDate postInterestOnDate) { // no openingBalance concept supported yet but probably will to allow // for migrations. @@ -713,10 +715,10 @@ public class SavingsAccount extends AbstractPersistableCustom { final SavingsInterestCalculationDaysInYearType daysInYearType = SavingsInterestCalculationDaysInYearType .fromInt(this.interestCalculationDaysInYearType); - List postedAsOnDates= getManualPostingDates(); - if(postInterestOnDate != null){ - postedAsOnDates.add(postInterestOnDate); - } + List postedAsOnDates = getManualPostingDates(); + if (postInterestOnDate != null) { + postedAsOnDates.add(postInterestOnDate); + } final List postingPeriodIntervals = this.savingsHelper.determineInterestPostingPeriods( getStartInterestCalculationDate(), upToInterestCalculationDate, postingPeriodType, financialYearBeginningMonth, postedAsOnDates); @@ -758,7 +760,7 @@ public class SavingsAccount extends AbstractPersistableCustom { for (final LocalDateInterval periodInterval : postingPeriodIntervals) { boolean isUserPosting = false; - if(postedAsOnDates.contains(periodInterval.endDate().plusDays(1))){ + if (postedAsOnDates.contains(periodInterval.endDate().plusDays(1))) { isUserPosting = true; } @@ -853,13 +855,11 @@ public class SavingsAccount extends AbstractPersistableCustom { transaction.updateOverdraftAmount(overdraftAmount.getAmount()); } else if (overdraftAmount.isNotEqualTo(transaction.getOverdraftAmount(getCurrency()))) { SavingsAccountTransaction accountTransaction = SavingsAccountTransaction.copyTransaction(transaction); - if(transaction.isChargeTransaction()){ + if (transaction.isChargeTransaction()) { Set chargesPaidBy = transaction.getSavingsAccountChargesPaid(); final Set newChargePaidBy = new HashSet<>(); - chargesPaidBy.forEach(x-> - newChargePaidBy.add(SavingsAccountChargePaidBy.instance(accountTransaction,x.getSavingsAccountCharge(), - x.getAmount())) - ); + chargesPaidBy.forEach(x -> newChargePaidBy + .add(SavingsAccountChargePaidBy.instance(accountTransaction, x.getSavingsAccountCharge(), x.getAmount()))); accountTransaction.getSavingsAccountChargesPaid().addAll(newChargePaidBy); } transaction.reverse(); @@ -909,9 +909,9 @@ public class SavingsAccount extends AbstractPersistableCustom { final String resourceTypeName = depositAccountType().resourceName(); if (isNotActive()) { final String defaultUserMessage = "Transaction is not allowed. Account is not active."; - final ApiParameterError error = ApiParameterError.parameterError("error.msg." + resourceTypeName - + ".transaction.account.is.not.active", defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate() - .toString(transactionDTO.getFormatter())); + final ApiParameterError error = ApiParameterError.parameterError( + "error.msg." + resourceTypeName + ".transaction.account.is.not.active", defaultUserMessage, "transactionDate", + transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter())); final List dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); @@ -921,9 +921,8 @@ public class SavingsAccount extends AbstractPersistableCustom { if (isDateInTheFuture(transactionDTO.getTransactionDate())) { final String defaultUserMessage = "Transaction date cannot be in the future."; - final ApiParameterError error = ApiParameterError.parameterError( - "error.msg." + resourceTypeName + ".transaction.in.the.future", defaultUserMessage, "transactionDate", transactionDTO - .getTransactionDate().toString(transactionDTO.getFormatter())); + final ApiParameterError error = ApiParameterError.parameterError("error.msg." + resourceTypeName + ".transaction.in.the.future", + defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter())); final List dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); @@ -935,8 +934,9 @@ public class SavingsAccount extends AbstractPersistableCustom { final Object[] defaultUserArgs = Arrays.asList(transactionDTO.getTransactionDate().toString(transactionDTO.getFormatter()), getActivationLocalDate().toString(transactionDTO.getFormatter())).toArray(); final String defaultUserMessage = "Transaction date cannot be before accounts activation date."; - final ApiParameterError error = ApiParameterError.parameterError("error.msg." + resourceTypeName - + ".transaction.before.activation.date", defaultUserMessage, "transactionDate", defaultUserArgs); + final ApiParameterError error = ApiParameterError.parameterError( + "error.msg." + resourceTypeName + ".transaction.before.activation.date", defaultUserMessage, "transactionDate", + defaultUserArgs); final List dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); @@ -953,8 +953,8 @@ public class SavingsAccount extends AbstractPersistableCustom { addTransaction(transaction); this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); - if(this.sub_status.equals(SavingsAccountSubStatusEnum.INACTIVE.getValue()) - || this.sub_status.equals(SavingsAccountSubStatusEnum.DORMANT.getValue())){ + if (this.sub_status.equals(SavingsAccountSubStatusEnum.INACTIVE.getValue()) + || this.sub_status.equals(SavingsAccountSubStatusEnum.DORMANT.getValue())) { this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); } @@ -1047,8 +1047,8 @@ public class SavingsAccount extends AbstractPersistableCustom { // auto pay withdrawal fee payWithdrawalFee(transactionDTO.getTransactionAmount(), transactionDTO.getTransactionDate(), transactionDTO.getAppUser()); } - if(this.sub_status.equals(SavingsAccountSubStatusEnum.INACTIVE.getValue()) - || this.sub_status.equals(SavingsAccountSubStatusEnum.DORMANT.getValue())){ + if (this.sub_status.equals(SavingsAccountSubStatusEnum.INACTIVE.getValue()) + || this.sub_status.equals(SavingsAccountSubStatusEnum.DORMANT.getValue())) { this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); } return transaction; @@ -1102,7 +1102,7 @@ public class SavingsAccount extends AbstractPersistableCustom { runningBalance = runningBalance.plus(transaction.getAmount(this.currency)); } else if (transaction.isNotReversed() && transaction.isDebit()) { runningBalance = runningBalance.minus(transaction.getAmount(this.currency)); - }else { + } else { continue; } @@ -1114,8 +1114,8 @@ public class SavingsAccount extends AbstractPersistableCustom { if (depositAccountOnHoldTransactions != null) { for (final DepositAccountOnHoldTransaction onHoldTransaction : depositAccountOnHoldTransactions) { // Compare the balance of the on hold: - if ((onHoldTransaction.getTransactionDate().isBefore(transaction.transactionLocalDate()) || onHoldTransaction - .getTransactionDate().isEqual(transaction.transactionLocalDate())) + if ((onHoldTransaction.getTransactionDate().isBefore(transaction.transactionLocalDate()) + || onHoldTransaction.getTransactionDate().isEqual(transaction.transactionLocalDate())) && (lastSavingsDate == null || onHoldTransaction.getTransactionDate().isAfter(lastSavingsDate))) { if (onHoldTransaction.getTransactionType().isHold()) { minRequiredBalance = minRequiredBalance.plus(onHoldTransaction.getAmountMoney(this.currency)); @@ -1129,24 +1129,27 @@ public class SavingsAccount extends AbstractPersistableCustom { // deal with potential minRequiredBalance and // enforceMinRequiredBalance if (!isException && transaction.canProcessBalanceCheck() && !isOverdraft()) { - if (runningBalance.minus(minRequiredBalance).isLessThanZero()) { throw new InsufficientAccountBalanceException( - "transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); } + if (runningBalance.minus(minRequiredBalance).isLessThanZero()) { + throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, + transactionAmount); + } } lastSavingsDate = transaction.transactionLocalDate(); } - //In overdraft cases, minRequiredBalance can be in violation after interest posting - //and should be checked after processing all transactions - if(isOverdraft()) { - if (runningBalance.minus(minRequiredBalance).isLessThanZero()) { throw new InsufficientAccountBalanceException( - "transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); } + // In overdraft cases, minRequiredBalance can be in violation after + // interest posting + // and should be checked after processing all transactions + if (isOverdraft()) { + if (runningBalance.minus(minRequiredBalance).isLessThanZero()) { + throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); + } } if (this.getSavingsHoldAmount().compareTo(BigDecimal.ZERO) > 0) { if (runningBalance.minus(this.getSavingsHoldAmount()).isLessThanZero()) { - throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, - transactionAmount); + throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); } } } @@ -1173,8 +1176,8 @@ public class SavingsAccount extends AbstractPersistableCustom { if (depositAccountOnHoldTransactions != null) { for (final DepositAccountOnHoldTransaction onHoldTransaction : depositAccountOnHoldTransactions) { // Compare the balance of the on hold: - if ((onHoldTransaction.getTransactionDate().isBefore(transaction.transactionLocalDate()) || onHoldTransaction - .getTransactionDate().isEqual(transaction.transactionLocalDate())) + if ((onHoldTransaction.getTransactionDate().isBefore(transaction.transactionLocalDate()) + || onHoldTransaction.getTransactionDate().isEqual(transaction.transactionLocalDate())) && (lastSavingsDate == null || onHoldTransaction.getTransactionDate().isAfter(lastSavingsDate))) { if (onHoldTransaction.getTransactionType().isHold()) { minRequiredBalance = minRequiredBalance.plus(onHoldTransaction.getAmountMoney(this.currency)); @@ -1204,9 +1207,10 @@ public class SavingsAccount extends AbstractPersistableCustom { BigDecimal withdrawalFee = null; BigDecimal transactionAmount = null; - if(isOverdraft()) { - if (runningBalance.minus(minRequiredBalance).isLessThanZero()) { throw new InsufficientAccountBalanceException( - "transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); } + if (isOverdraft()) { + if (runningBalance.minus(minRequiredBalance).isLessThanZero()) { + throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); + } } } @@ -1313,7 +1317,8 @@ public class SavingsAccount extends AbstractPersistableCustom { actualChanges.put(SavingsApiConstants.interestCompoundingPeriodTypeParamName, this.interestCompoundingPeriodType); } - if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestPostingPeriodTypeParamName, this.interestPostingPeriodType)) { + if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestPostingPeriodTypeParamName, + this.interestPostingPeriodType)) { final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestPostingPeriodTypeParamName); this.interestPostingPeriodType = newValue != null ? SavingsPostingInterestPeriodType.fromInt(newValue).getValue() : newValue; actualChanges.put(SavingsApiConstants.interestPostingPeriodTypeParamName, this.interestPostingPeriodType); @@ -1328,8 +1333,9 @@ public class SavingsAccount extends AbstractPersistableCustom { if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestCalculationDaysInYearTypeParamName, this.interestCalculationDaysInYearType)) { final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestCalculationDaysInYearTypeParamName); - this.interestCalculationDaysInYearType = newValue != null ? SavingsInterestCalculationDaysInYearType.fromInt(newValue) - .getValue() : newValue; + this.interestCalculationDaysInYearType = newValue != null + ? SavingsInterestCalculationDaysInYearType.fromInt(newValue).getValue() + : newValue; actualChanges.put(SavingsApiConstants.interestCalculationDaysInYearTypeParamName, this.interestCalculationDaysInYearType); } @@ -1351,7 +1357,8 @@ public class SavingsAccount extends AbstractPersistableCustom { this.lockinPeriodFrequency = newValue; } - if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.lockinPeriodFrequencyTypeParamName, this.lockinPeriodFrequencyType)) { + if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.lockinPeriodFrequencyTypeParamName, + this.lockinPeriodFrequencyType)) { final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.lockinPeriodFrequencyTypeParamName); actualChanges.put(SavingsApiConstants.lockinPeriodFrequencyTypeParamName, newValue); this.lockinPeriodFrequencyType = newValue != null ? SavingsPeriodFrequencyType.fromInt(newValue).getValue() : newValue; @@ -1490,7 +1497,7 @@ public class SavingsAccount extends AbstractPersistableCustom { accountingBridgeData.put("isAccountTransfer", isAccountTransfer); final List> newSavingsTransactions = new ArrayList<>(); - List trans = getTransactions() ; + List trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if (transaction.isReversed() && !existingReversedTransactionIds.contains(transaction.getId())) { newSavingsTransactions.add(transaction.toMapData(currencyData)); @@ -1506,7 +1513,7 @@ public class SavingsAccount extends AbstractPersistableCustom { public Collection findExistingTransactionIds() { final Collection ids = new ArrayList<>(); - List trans = getTransactions() ; + List trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { ids.add(transaction.getId()); } @@ -1517,7 +1524,7 @@ public class SavingsAccount extends AbstractPersistableCustom { public Collection findExistingReversedTransactionIds() { final Collection ids = new ArrayList<>(); - List trans = getTransactions() ; + List trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if (transaction.isReversed()) { ids.add(transaction.getId()); @@ -1618,14 +1625,14 @@ public class SavingsAccount extends AbstractPersistableCustom { } public GroupSavingsIndividualMonitoring getGsim() { - return gsim; - } + return gsim; + } - public void setGsim(GroupSavingsIndividualMonitoring gsim) { - this.gsim = gsim; - } + public void setGsim(GroupSavingsIndividualMonitoring gsim) { + this.gsim = gsim; + } - public Long hasSavingsOfficerId() { + public Long hasSavingsOfficerId() { Long id = null; if (this.savingsOfficer != null) { id = this.savingsOfficer.getId(); @@ -1788,8 +1795,8 @@ public class SavingsAccount extends AbstractPersistableCustom { final LocalDate submittedOn = getSubmittedOnLocalDate(); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(resourceName - + SavingsApiConstants.summitalAction); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(resourceName + SavingsApiConstants.summitalAction); validateLockinDetails(baseDataValidator); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } @@ -2113,8 +2120,8 @@ public class SavingsAccount extends AbstractPersistableCustom { final Map actualChanges = new LinkedHashMap<>(); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(depositAccountType() - .resourceName() + SavingsApiConstants.activateAction); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(depositAccountType().resourceName() + SavingsApiConstants.activateAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.APPROVED.hasStateOf(currentStatus)) { @@ -2234,7 +2241,7 @@ public class SavingsAccount extends AbstractPersistableCustom { if (isSavingsChargeApplied) { final MathContext mc = MathContext.DECIMAL64; boolean isInterestTransfer = false; - LocalDate postInterestAsOnDate = null; + LocalDate postInterestAsOnDate = null; if (this.isBeforeLastPostingPeriod(getActivationLocalDate())) { final LocalDate today = DateUtils.getLocalDateOfTenant(); this.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, @@ -2308,14 +2315,16 @@ public class SavingsAccount extends AbstractPersistableCustom { protected void validateActivityNotBeforeClientOrGroupTransferDate(final SavingsEvent event, final LocalDate activityDate) { if (this.client != null && this.client.getOfficeJoiningLocalDate() != null) { final LocalDate clientOfficeJoiningDate = this.client.getOfficeJoiningLocalDate(); - if (activityDate.isBefore(clientOfficeJoiningDate)) { throw new SavingsActivityPriorToClientTransferException(event.toString(), - clientOfficeJoiningDate); } + if (activityDate.isBefore(clientOfficeJoiningDate)) { + throw new SavingsActivityPriorToClientTransferException(event.toString(), clientOfficeJoiningDate); + } } } private void validateAttemptToUndoTransferRelatedTransactions(final SavingsAccountTransaction savingsAccountTransaction) { - if (savingsAccountTransaction.isTransferRelatedTransaction()) { throw new SavingsTransferTransactionsCannotBeUndoneException( - savingsAccountTransaction.getId()); } + if (savingsAccountTransaction.isTransferRelatedTransaction()) { + throw new SavingsTransferTransactionsCannotBeUndoneException(savingsAccountTransaction.getId()); + } } private Date calculateDateAccountIsLockedUntil(final LocalDate activationLocalDate) { @@ -2461,7 +2470,8 @@ public class SavingsAccount extends AbstractPersistableCustom { } - public void addCharge(final DateTimeFormatter formatter, final SavingsAccountCharge savingsAccountCharge, final Charge chargeDefinition) { + public void addCharge(final DateTimeFormatter formatter, final SavingsAccountCharge savingsAccountCharge, + final Charge chargeDefinition) { final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -2473,8 +2483,8 @@ public class SavingsAccount extends AbstractPersistableCustom { } if (!hasCurrencyCodeOf(chargeDefinition.getCurrencyCode())) { - baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( - "transaction.invalid.account.currency.and.charge.currency.not.same"); + baseDataValidator.reset() + .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.currency.and.charge.currency.not.same"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } @@ -2535,18 +2545,14 @@ public class SavingsAccount extends AbstractPersistableCustom { private boolean isWithDrawalFeeExists() { for (SavingsAccountCharge charge : this.charges()) { - if (charge.isWithdrawalFee()) { - return true; - } + if (charge.isWithdrawalFee()) { return true; } } return false; } private boolean isAnnualFeeExists() { for (SavingsAccountCharge charge : this.charges()) { - if (charge.isAnnualFee()) { - return true; - } + if (charge.isAnnualFee()) { return true; } } return false; } @@ -2586,8 +2592,8 @@ public class SavingsAccount extends AbstractPersistableCustom { } if (savingsAccountCharge.isSavingsActivation()) { - baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( - "transaction.not.valid.cannot.pay.activation.time.charge.is.automated"); + baseDataValidator.reset() + .failWithCodeNoParameterAddedToErrorCode("transaction.not.valid.cannot.pay.activation.time.charge.is.automated"); throw new PlatformApiDataValidationException(dataValidationErrors); } @@ -2660,8 +2666,8 @@ public class SavingsAccount extends AbstractPersistableCustom { private void handleChargeTransactions(final SavingsAccountCharge savingsAccountCharge, final SavingsAccountTransaction transaction) { // Provide a link between transaction and savings charge for which // amount is waived. - final SavingsAccountChargePaidBy chargePaidBy = SavingsAccountChargePaidBy.instance(transaction, savingsAccountCharge, transaction - .getAmount(this.getCurrency()).getAmount()); + final SavingsAccountChargePaidBy chargePaidBy = SavingsAccountChargePaidBy.instance(transaction, savingsAccountCharge, + transaction.getAmount(this.getCurrency()).getAmount()); transaction.getSavingsAccountChargesPaid().add(chargePaidBy); this.transactions.add(transaction); } @@ -2725,24 +2731,19 @@ public class SavingsAccount extends AbstractPersistableCustom { public void validateInterestPostingAndCompoundingPeriodTypes(final DataValidatorBuilder baseDataValidator) { Map> postingtoCompoundMap = new HashMap<>(); - postingtoCompoundMap.put( - SavingsPostingInterestPeriodType.MONTHLY, - Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, - SavingsCompoundingInterestPeriodType.MONTHLY })); + postingtoCompoundMap.put(SavingsPostingInterestPeriodType.MONTHLY, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { + SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY })); - postingtoCompoundMap.put( - SavingsPostingInterestPeriodType.QUATERLY, + postingtoCompoundMap.put(SavingsPostingInterestPeriodType.QUATERLY, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY, SavingsCompoundingInterestPeriodType.QUATERLY })); - postingtoCompoundMap.put( - SavingsPostingInterestPeriodType.BIANNUAL, + postingtoCompoundMap.put(SavingsPostingInterestPeriodType.BIANNUAL, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY, SavingsCompoundingInterestPeriodType.QUATERLY, SavingsCompoundingInterestPeriodType.BI_ANNUAL })); - postingtoCompoundMap.put( - SavingsPostingInterestPeriodType.ANNUAL, + postingtoCompoundMap.put(SavingsPostingInterestPeriodType.ANNUAL, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY, SavingsCompoundingInterestPeriodType.QUATERLY, SavingsCompoundingInterestPeriodType.BI_ANNUAL, SavingsCompoundingInterestPeriodType.ANNUAL })); @@ -2776,28 +2777,16 @@ public class SavingsAccount extends AbstractPersistableCustom { } public boolean isTransactionAllowed(SavingsAccountTransactionType transactionType, LocalDate transactionDate) { - if (!isTransactionsAllowed()) { - return false; - } + if (!isTransactionsAllowed()) { return false; } Client client = getClient(); - if (client != null && !client.isActive()) { - return false; - } + if (client != null && !client.isActive()) { return false; } Group group = group(); - if (group != null && !group.isActive()) { - return false; - } + if (group != null && !group.isActive()) { return false; } - if (transactionDate == null) { - return true; - } - if (DateUtils.isDateInTheFuture(transactionDate) || transactionDate.isBefore(getActivationLocalDate())) { - return false; - } - if (transactionType.isCredit()) { - return true; - } + if (transactionDate == null) { return true; } + if (DateUtils.isDateInTheFuture(transactionDate) || transactionDate.isBefore(getActivationLocalDate())) { return false; } + if (transactionType.isCredit()) { return true; } return !isAccountLocked(transactionDate); } @@ -2860,7 +2849,8 @@ public class SavingsAccount extends AbstractPersistableCustom { } public BigDecimal getWithdrawableBalance() { - return getAccountBalance().subtract(minRequiredBalanceDerived(getCurrency()).getAmount()).subtract(this.getOnHoldFunds()).subtract(this.getSavingsHoldAmount()); + return getAccountBalance().subtract(minRequiredBalanceDerived(getCurrency()).getAmount()).subtract(this.getOnHoldFunds()) + .subtract(this.getSavingsHoldAmount()); } public TaxGroup getTaxGroup() { @@ -2904,7 +2894,6 @@ public class SavingsAccount extends AbstractPersistableCustom { this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); } - public void setSubStatusDormant() { this.sub_status = SavingsAccountSubStatusEnum.DORMANT.getValue(); } @@ -2914,9 +2903,9 @@ public class SavingsAccount extends AbstractPersistableCustom { this.sub_status = SavingsAccountSubStatusEnum.ESCHEAT.getValue(); this.closedOnDate = DateUtils.getDateOfTenant(); this.closedBy = appUser; - boolean postInterestAsOnDate = false; + boolean postInterestAsOnDate = false; LocalDate transactionDate = DateUtils.getLocalDateOfTenant(); - if(this.getSummary().getAccountBalance(this.getCurrency()).isGreaterThanZero()){ + if (this.getSummary().getAccountBalance(this.getCurrency()).isGreaterThanZero()) { SavingsAccountTransaction transaction = SavingsAccountTransaction.escheat(this, transactionDate, appUser, postInterestAsOnDate); this.transactions.add(transaction); } @@ -2928,7 +2917,9 @@ public class SavingsAccount extends AbstractPersistableCustom { transactions.size(); charges.size(); savingsOfficerHistory.size(); - if(group != null) { Office dummyOffice = group.getOffice(); } // Ensure lazy loading of group if set + if (group != null) { + Office dummyOffice = group.getOffice(); + } // Ensure lazy loading of group if set } public void updateSavingsAccountSummary(final List transactions) { @@ -3001,8 +2992,8 @@ public class SavingsAccount extends AbstractPersistableCustom { } if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { - baseDataValidator.reset().parameter(SavingsApiConstants.subStatusParamName).value(SavingsAccountSubStatusEnum.fromInt(currentSubstatus)) - .failWithCodeNoParameterAddedToErrorCode("currently.set"); + baseDataValidator.reset().parameter(SavingsApiConstants.subStatusParamName) + .value(SavingsAccountSubStatusEnum.fromInt(currentSubstatus)).failWithCodeNoParameterAddedToErrorCode("currently.set"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } if (SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { @@ -3060,8 +3051,8 @@ public class SavingsAccount extends AbstractPersistableCustom { } if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { - baseDataValidator.reset().parameter(SavingsApiConstants.subStatusParamName).value(SavingsAccountSubStatusEnum.fromInt(currentSubstatus)) - .failWithCodeNoParameterAddedToErrorCode("currently.set"); + baseDataValidator.reset().parameter(SavingsApiConstants.subStatusParamName) + .value(SavingsAccountSubStatusEnum.fromInt(currentSubstatus)).failWithCodeNoParameterAddedToErrorCode("currently.set"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } if (SavingsAccountSubStatusEnum.BLOCK_CREDIT.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { @@ -3121,14 +3112,16 @@ public class SavingsAccount extends AbstractPersistableCustom { public void validateForDebitBlock() { final SavingsAccountSubStatusEnum currentSubStatus = SavingsAccountSubStatusEnum.fromInt(this.getSubStatus()); - if (SavingsAccountSubStatusEnum.BLOCK_DEBIT - .hasStateOf(currentSubStatus)) { throw new SavingsAccountDebitsBlockedException(this.getId()); } + if (SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(currentSubStatus)) { + throw new SavingsAccountDebitsBlockedException(this.getId()); + } } public void validateForCreditBlock() { final SavingsAccountSubStatusEnum currentSubStatus = SavingsAccountSubStatusEnum.fromInt(this.getSubStatus()); - if (SavingsAccountSubStatusEnum.BLOCK_CREDIT - .hasStateOf(currentSubStatus)) { throw new SavingsAccountCreditsBlockedException(this.getId()); } + if (SavingsAccountSubStatusEnum.BLOCK_CREDIT.hasStateOf(currentSubStatus)) { + throw new SavingsAccountCreditsBlockedException(this.getId()); + } } public LocalDate retrieveLastTransactionDate() { @@ -3161,14 +3154,14 @@ public class SavingsAccount extends AbstractPersistableCustom { } public Integer getAccountTypes() { - return accountType; - } + return accountType; + } public void setAccountType(Integer accountType) { - this.accountType = accountType; - } + this.accountType = accountType; + } private boolean isOverdraft() { - return allowOverdraft; + return allowOverdraft; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountAssembler.java index f1fe45bce..a42c0cc55 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountAssembler.java @@ -129,7 +129,6 @@ public class SavingsAccountAssembler { Staff fieldOfficer = null; AccountType accountType = AccountType.INVALID; - final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); if (clientId != null) { client = this.clientRepository.findOneWithNotFoundDetection(clientId); @@ -152,13 +151,11 @@ public class SavingsAccountAssembler { accountType = AccountType.JLG; } - if((Boolean)command.booleanPrimitiveValueOfParameterNamed("isGSIM")!=null) - { - LOG.info("setting system to gsim"); - if(command.booleanPrimitiveValueOfParameterNamed("isGSIM")) - { - accountType = AccountType.GSIM; - } + if ((Boolean) command.booleanPrimitiveValueOfParameterNamed("isGSIM") != null) { + LOG.info("setting system to gsim"); + if (command.booleanPrimitiveValueOfParameterNamed("isGSIM")) { + accountType = AccountType.GSIM; + } } final Long fieldOfficerId = this.fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); @@ -286,7 +283,7 @@ public class SavingsAccountAssembler { boolean withHoldTax = product.withHoldTax(); if (command.parameterExists(withHoldTaxParamName)) { withHoldTax = command.booleanPrimitiveValueOfParameterNamed(withHoldTaxParamName); - if(withHoldTax && product.getTaxGroup() == null){ + if (withHoldTax && product.getTaxGroup() == null) { throw new UnsupportedParameterException(Arrays.asList(withHoldTaxParamName)); } } @@ -312,7 +309,6 @@ public class SavingsAccountAssembler { return account; } - public void setHelpers(final SavingsAccount account) { account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountCharge.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountCharge.java index 115c728cb..25706ea49 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountCharge.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountCharge.java @@ -223,8 +223,7 @@ public class SavingsAccountCharge extends AbstractPersistableCustom { populateDerivedFields(transactionAmount, chargeAmount); - if (this.isWithdrawalFee() - || this.isSavingsNoActivity()) { + if (this.isWithdrawalFee() || this.isSavingsNoActivity()) { this.amountOutstanding = BigDecimal.ZERO; } @@ -426,8 +425,7 @@ public class SavingsAccountCharge extends AbstractPersistableCustom { } } - - @SuppressFBWarnings(value="NP_NULL_PARAM_DEREF_NONVIRTUAL") // https://issues.apache.org/jira/browse/FINERACT-987 + @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF_NONVIRTUAL") // https://issues.apache.org/jira/browse/FINERACT-987 public Map update(final JsonCommand command) { final Map actualChanges = new LinkedHashMap<>(7); @@ -662,7 +660,7 @@ public class SavingsAccountCharge extends AbstractPersistableCustom { return ChargeTimeType.fromInt(this.chargeTime).isSavingsActivation(); } - public boolean isSavingsNoActivity(){ + public boolean isSavingsNoActivity() { return ChargeTimeType.fromInt(this.chargeTime).isSavingsNoActivityFee(); } @@ -697,38 +695,26 @@ public class SavingsAccountCharge extends AbstractPersistableCustom { @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof SavingsAccountCharge)) { - return false; - } + if (this == o) { return true; } + if (!(o instanceof SavingsAccountCharge)) { return false; } SavingsAccountCharge that = (SavingsAccountCharge) o; - return Objects.equals(penaltyCharge, that.penaltyCharge) && - Objects.equals(paid, that.paid) && - Objects.equals(waived, that.waived) && - Objects.equals(status, that.status) && - Objects.equals(savingsAccount, that.savingsAccount) && - Objects.equals(charge, that.charge) && - Objects.equals(chargeTime, that.chargeTime) && - Objects.equals(dueDate, that.dueDate) && - Objects.equals(feeOnMonth, that.feeOnMonth) && - Objects.equals(feeOnDay, that.feeOnDay) && - Objects.equals(feeInterval, that.feeInterval) && - Objects.equals(chargeCalculation, that.chargeCalculation) && - Objects.equals(percentage, that.percentage) && - Objects.equals(amountPercentageAppliedTo, that.amountPercentageAppliedTo) && - Objects.equals(amount, that.amount) && - Objects.equals(amountPaid, that.amountPaid) && - Objects.equals(amountWaived, that.amountWaived) && - Objects.equals(amountWrittenOff, that.amountWrittenOff) && - Objects.equals(amountOutstanding, that.amountOutstanding) && - Objects.equals(inactivationDate, that.inactivationDate); + return Objects.equals(penaltyCharge, that.penaltyCharge) && Objects.equals(paid, that.paid) && Objects.equals(waived, that.waived) + && Objects.equals(status, that.status) && Objects.equals(savingsAccount, that.savingsAccount) + && Objects.equals(charge, that.charge) && Objects.equals(chargeTime, that.chargeTime) + && Objects.equals(dueDate, that.dueDate) && Objects.equals(feeOnMonth, that.feeOnMonth) + && Objects.equals(feeOnDay, that.feeOnDay) && Objects.equals(feeInterval, that.feeInterval) + && Objects.equals(chargeCalculation, that.chargeCalculation) && Objects.equals(percentage, that.percentage) + && Objects.equals(amountPercentageAppliedTo, that.amountPercentageAppliedTo) && Objects.equals(amount, that.amount) + && Objects.equals(amountPaid, that.amountPaid) && Objects.equals(amountWaived, that.amountWaived) + && Objects.equals(amountWrittenOff, that.amountWrittenOff) && Objects.equals(amountOutstanding, that.amountOutstanding) + && Objects.equals(inactivationDate, that.inactivationDate); } @Override public int hashCode() { - return Objects.hash(savingsAccount, charge, chargeTime, dueDate, feeOnMonth, feeOnDay, feeInterval, chargeCalculation, percentage, amountPercentageAppliedTo, amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, penaltyCharge, paid, waived, status, inactivationDate); + return Objects.hash(savingsAccount, charge, chargeTime, dueDate, feeOnMonth, feeOnDay, feeInterval, chargeCalculation, percentage, + amountPercentageAppliedTo, amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, penaltyCharge, paid, + waived, status, inactivationDate); } public BigDecimal calculateWithdralFeeAmount(@NotNull BigDecimal transactionAmount) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeAssembler.java index 5d0d66acf..9240144c0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeAssembler.java @@ -86,15 +86,15 @@ public class SavingsAccountChargeAssembler { final Long id = this.fromApiJsonHelper.extractLongNamed(idParamName, savingsChargeElement); final Long chargeId = this.fromApiJsonHelper.extractLongNamed(chargeIdParamName, savingsChargeElement); final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed(amountParamName, savingsChargeElement, locale); - final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed(chargeTimeTypeParamName, - savingsChargeElement, locale); + final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed(chargeTimeTypeParamName, savingsChargeElement, + locale); final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed(chargeCalculationTypeParamName, savingsChargeElement, locale); final LocalDate dueDate = this.fromApiJsonHelper.extractLocalDateNamed(dueAsOfDateParamName, savingsChargeElement, dateFormat, locale); - final MonthDay feeOnMonthDay = this.fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, - savingsChargeElement, monthDayFormat, locale); + final MonthDay feeOnMonthDay = this.fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, savingsChargeElement, + monthDayFormat, locale); final Integer feeInterval = this.fromApiJsonHelper.extractIntegerNamed(feeIntervalParamName, savingsChargeElement, locale); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeRepository.java index 177fe3a3e..3b0c5dbef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeRepository.java @@ -25,8 +25,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface SavingsAccountChargeRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface SavingsAccountChargeRepository + extends JpaRepository, JpaSpecificationExecutor { @Query("select sac from SavingsAccountCharge sac where sac.id =:id and sac.savingsAccount.id = :savingsAccountId") SavingsAccountCharge findByIdAndSavingsAccountId(@Param("id") Long id, @Param("savingsAccountId") Long savingsAccountId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeRepositoryWrapper.java index 1a33ca25d..29c179d07 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountChargeRepositoryWrapper.java @@ -41,8 +41,7 @@ public class SavingsAccountChargeRepositoryWrapper { } public SavingsAccountCharge findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new SavingsAccountChargeNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new SavingsAccountChargeNotFoundException(id)); } public SavingsAccountCharge findOneWithNotFoundDetection(final Long id, final Long savingsAccountId) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountDomainService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountDomainService.java index 003f6c394..389a01165 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountDomainService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountDomainService.java @@ -37,4 +37,4 @@ public interface SavingsAccountDomainService { SavingsAccountTransaction handleDividendPayout(SavingsAccount account, LocalDate transactionDate, BigDecimal transactionAmount); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountDomainServiceJpa.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountDomainServiceJpa.java old mode 100755 new mode 100644 index f77e80fef..599f5e8b5 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountDomainServiceJpa.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountDomainServiceJpa.java @@ -90,8 +90,9 @@ public class SavingsAccountDomainServiceJpa implements SavingsAccountDomainServi final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth(); - if (transactionBooleanValues.isRegularTransaction() && !account.allowWithdrawal()) { throw new DepositAccountTransactionNotAllowedException( - account.getId(), "withdraw", account.depositAccountType()); } + if (transactionBooleanValues.isRegularTransaction() && !account.allowWithdrawal()) { + throw new DepositAccountTransactionNotAllowedException(account.getId(), "withdraw", account.depositAccountType()); + } final Set existingTransactionIds = new HashSet<>(); final LocalDate postInterestOnDate = null; final Set existingReversedTransactionIds = new HashSet<>(); @@ -134,7 +135,6 @@ public class SavingsAccountDomainServiceJpa implements SavingsAccountDomainServi return user; } - @Transactional @Override public SavingsAccountTransaction handleDeposit(final SavingsAccount account, final DateTimeFormatter fmt, @@ -156,8 +156,9 @@ public class SavingsAccountDomainServiceJpa implements SavingsAccountDomainServi .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth(); - if (isRegularTransaction && !account.allowDeposit()) { throw new DepositAccountTransactionNotAllowedException(account.getId(), - "deposit", account.depositAccountType()); } + if (isRegularTransaction && !account.allowDeposit()) { + throw new DepositAccountTransactionNotAllowedException(account.getId(), "deposit", account.depositAccountType()); + } boolean isInterestTransfer = false; final Set existingTransactionIds = new HashSet<>(); final Set existingReversedTransactionIds = new HashSet<>(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountRepository.java index c8bbff031..0de9ce8d4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountRepository.java @@ -54,7 +54,7 @@ public interface SavingsAccountRepository extends JpaRepository findByStatus(Integer status,Pageable pageable); + Page findByStatus(Integer status, Pageable pageable); SavingsAccount findByExternalId(String externalId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountRepositoryWrapper.java index f6f0e0622..71c08248f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountRepositoryWrapper.java @@ -43,7 +43,6 @@ import org.springframework.transaction.annotation.Transactional; @Service public class SavingsAccountRepositoryWrapper { - private final SavingsAccountRepository repository; @Autowired @@ -51,7 +50,7 @@ public class SavingsAccountRepositoryWrapper { this.repository = repository; } - @Transactional(readOnly=true) + @Transactional(readOnly = true) public SavingsAccount findOneWithNotFoundDetection(final Long savingsId) { final SavingsAccount account = this.repository.findById(savingsId) .orElseThrow(() -> new SavingsAccountNotFoundException(savingsId)); @@ -59,7 +58,7 @@ public class SavingsAccountRepositoryWrapper { return account; } - @Transactional(readOnly=true) + @Transactional(readOnly = true) public SavingsAccount findOneWithNotFoundDetection(final Long savingsId, final DepositAccountType depositAccountType) { final SavingsAccount account = this.repository.findByIdAndDepositAccountType(savingsId, depositAccountType.getValue()); if (account == null) { throw new SavingsAccountNotFoundException(savingsId); } @@ -67,48 +66,48 @@ public class SavingsAccountRepositoryWrapper { return account; } - @Transactional(readOnly=true) + @Transactional(readOnly = true) public List findSavingAccountByClientId(@Param("clientId") Long clientId) { - List accounts = this.repository.findSavingAccountByClientId(clientId) ; + List accounts = this.repository.findSavingAccountByClientId(clientId); loadLazyCollections(accounts); - return accounts ; + return accounts; } - @Transactional(readOnly=true) + @Transactional(readOnly = true) public List findSavingAccountByStatus(@Param("status") Integer status) { - List accounts = this.repository.findSavingAccountByStatus(status) ; + List accounts = this.repository.findSavingAccountByStatus(status); loadLazyCollections(accounts); - return accounts ; + return accounts; } - @Transactional(readOnly=true) + @Transactional(readOnly = true) public Page findByStatus(Integer status, Pageable pageable) { Page accounts = this.repository.findByStatus(status, pageable); loadLazyCollections(accounts); return accounts; } - //Root Entities are enough + // Root Entities are enough public List findByClientIdAndGroupId(@Param("clientId") Long clientId, @Param("groupId") Long groupId) { - return this.repository.findByClientIdAndGroupId(clientId, groupId) ; + return this.repository.findByClientIdAndGroupId(clientId, groupId); } public boolean doNonClosedSavingAccountsExistForClient(@Param("clientId") Long clientId) { - return this.repository.doNonClosedSavingAccountsExistForClient(clientId) ; + return this.repository.doNonClosedSavingAccountsExistForClient(clientId); } - //Root Entities are enough + // Root Entities are enough public List findByGroupId(@Param("groupId") Long groupId) { - return this.repository.findByGroupId(groupId) ; + return this.repository.findByGroupId(groupId); } public List findByGsimId(@Param("gsimId") Long gsimId) { return this.repository.findSavingAccountByGsimId(gsimId); } - //Root Entity is enough + // Root Entity is enough public SavingsAccount findNonClosedAccountByAccountNumber(@Param("accountNumber") String accountNumber) { - return this.repository.findNonClosedAccountByAccountNumber(accountNumber) ; + return this.repository.findNonClosedAccountByAccountNumber(accountNumber); } public SavingsAccount save(final SavingsAccount account) { @@ -124,8 +123,8 @@ public class SavingsAccountRepositoryWrapper { } private void loadLazyCollections(final List accounts) { - if(accounts != null && accounts.size() >0) { - for(SavingsAccount account: accounts) { + if (accounts != null && accounts.size() > 0) { + for (SavingsAccount account : accounts) { account.loadLazyCollections(); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountStatusType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountStatusType.java index 45d2b15e2..15e832fa3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountStatusType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountStatusType.java @@ -139,4 +139,4 @@ public enum SavingsAccountStatusType { public boolean isPreMatureClosure() { return this.value.equals(SavingsAccountStatusType.PRE_MATURE_CLOSURE.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountSubStatusEnum.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountSubStatusEnum.java index 299e0a733..0a052884d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountSubStatusEnum.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountSubStatusEnum.java @@ -25,11 +25,9 @@ public enum SavingsAccountSubStatusEnum { NONE(0, "SavingsAccountSubStatusEnum.none"), // INACTIVE(100, "SavingsAccountSubStatusEnum.inactive"), // - DORMANT(200, "SavingsAccountSubStatusEnum.dormant"), - ESCHEAT(300,"SavingsAccountSubStatusEnum.escheat"), - BLOCK(400, "SavingsAccountSubStatusEnum.block"), - BLOCK_CREDIT(500, "SavingsAccountSubStatusEnum.blockCredit"), - BLOCK_DEBIT(600, "SavingsAccountSubStatusEnum.blockDebit"); + DORMANT(200, "SavingsAccountSubStatusEnum.dormant"), ESCHEAT(300, "SavingsAccountSubStatusEnum.escheat"), BLOCK(400, + "SavingsAccountSubStatusEnum.block"), BLOCK_CREDIT(500, + "SavingsAccountSubStatusEnum.blockCredit"), BLOCK_DEBIT(600, "SavingsAccountSubStatusEnum.blockDebit"); private final Integer value; private final String code; @@ -37,7 +35,7 @@ public enum SavingsAccountSubStatusEnum { public static SavingsAccountSubStatusEnum fromInt(final Integer type) { SavingsAccountSubStatusEnum enumeration = SavingsAccountSubStatusEnum.NONE; - if(null != type){ + if (null != type) { switch (type) { case 100: enumeration = SavingsAccountSubStatusEnum.INACTIVE; @@ -106,4 +104,4 @@ public enum SavingsAccountSubStatusEnum { public boolean isSubStatusDebitBlocked() { return this.value.equals(SavingsAccountSubStatusEnum.BLOCK_DEBIT.getValue()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountSummary.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountSummary.java index 7842911bb..557f9b74a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountSummary.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountSummary.java @@ -102,7 +102,6 @@ public final class SavingsAccountSummary { this.totalOverdraftInterestDerived = wrapper.calculateTotalOverdraftInterest(currency, transactions); this.totalWithholdTax = wrapper.calculateTotalWithholdTaxWithdrawal(currency, transactions); - this.accountBalance = Money.of(currency, this.totalDeposits).plus(this.totalInterestPosted).minus(this.totalWithdrawals) .minus(this.totalWithdrawalFees).minus(this.totalAnnualFees).minus(this.totalFeeCharge).minus(this.totalPenaltyCharge) .minus(totalOverdraftInterestDerived).minus(totalWithholdTax).getAmount(); @@ -138,4 +137,4 @@ public final class SavingsAccountSummary { return this.totalInterestPosted; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransaction.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransaction.java index 0d4d4646f..065c12d52 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransaction.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransaction.java @@ -63,7 +63,7 @@ import org.springframework.util.CollectionUtils; public final class SavingsAccountTransaction extends AbstractPersistableCustom { @ManyToOne(optional = false) - @JoinColumn(name = "savings_account_id", referencedColumnName="id", nullable = false) + @JoinColumn(name = "savings_account_id", referencedColumnName = "id", nullable = false) private SavingsAccount savingsAccount; @ManyToOne @@ -79,7 +79,7 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { @Temporal(TemporalType.DATE) @Column(name = "transaction_date", nullable = false) - private Date dateOf; + private Date dateOf; @Column(name = "amount", scale = 6, precision = 19, nullable = false) private BigDecimal amount; @@ -100,7 +100,7 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { @Column(name = "balance_number_of_days_derived", nullable = true) private Integer balanceNumberOfDays; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccountTransaction", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccountTransaction", orphanRemoval = true, fetch = FetchType.EAGER) private Set savingsAccountChargesPaid = new HashSet<>(); @Column(name = "overdraft_amount_derived", scale = 6, precision = 19, nullable = true) @@ -120,8 +120,7 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { @Column(name = "is_loan_disbursement", length = 1, nullable = true) private boolean isLoanDisbursement; - - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "savings_transaction_id", referencedColumnName = "id", nullable = false) private List taxDetails = new ArrayList<>(); @@ -152,7 +151,7 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { final boolean isReversed = false; final boolean isManualTransaction = false; return new SavingsAccountTransaction(savingsAccount, office, paymentDetail, savingsAccountTransactionType.getValue(), date, - createdDate, amount, isReversed, appUser,isManualTransaction); + createdDate, amount, isReversed, appUser, isManualTransaction); } public static SavingsAccountTransaction withdrawal(final SavingsAccount savingsAccount, final Office office, @@ -164,14 +163,14 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { } public static SavingsAccountTransaction interestPosting(final SavingsAccount savingsAccount, final Office office, final LocalDate date, - final Money amount,final boolean isManualTransaction) { + final Money amount, final boolean isManualTransaction) { final boolean isReversed = false; return new SavingsAccountTransaction(savingsAccount, office, SavingsAccountTransactionType.INTEREST_POSTING.getValue(), date, amount, isReversed, null, isManualTransaction); } public static SavingsAccountTransaction overdraftInterest(final SavingsAccount savingsAccount, final Office office, - final LocalDate date, final Money amount,final boolean isManualTransaction) { + final LocalDate date, final Money amount, final boolean isManualTransaction) { final boolean isReversed = false; return new SavingsAccountTransaction(savingsAccount, office, SavingsAccountTransactionType.OVERDRAFT_INTEREST.getValue(), date, amount, isReversed, null, isManualTransaction); @@ -209,14 +208,14 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { isReversed, appUser, isManualTransaction); } - public static SavingsAccountTransaction initiateTransfer(final SavingsAccount savingsAccount, final Office office, - final LocalDate date, final AppUser appUser) { + public static SavingsAccountTransaction initiateTransfer(final SavingsAccount savingsAccount, final Office office, final LocalDate date, + final AppUser appUser) { final boolean isReversed = false; final boolean isManualTransaction = false; final PaymentDetail paymentDetail = null; return new SavingsAccountTransaction(savingsAccount, office, paymentDetail, - SavingsAccountTransactionType.INITIATE_TRANSFER.getValue(), date, new Date(), savingsAccount.getSummary() - .getAccountBalance(), isReversed, appUser, isManualTransaction); + SavingsAccountTransactionType.INITIATE_TRANSFER.getValue(), date, new Date(), + savingsAccount.getSummary().getAccountBalance(), isReversed, appUser, isManualTransaction); } public static SavingsAccountTransaction approveTransfer(final SavingsAccount savingsAccount, final Office office, final LocalDate date, @@ -225,18 +224,18 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { final boolean isManualTransaction = false; final PaymentDetail paymentDetail = null; return new SavingsAccountTransaction(savingsAccount, office, paymentDetail, - SavingsAccountTransactionType.APPROVE_TRANSFER.getValue(), date, new Date(), savingsAccount.getSummary() - .getAccountBalance(), isReversed, appUser, isManualTransaction); + SavingsAccountTransactionType.APPROVE_TRANSFER.getValue(), date, new Date(), + savingsAccount.getSummary().getAccountBalance(), isReversed, appUser, isManualTransaction); } - public static SavingsAccountTransaction withdrawTransfer(final SavingsAccount savingsAccount, final Office office, - final LocalDate date, final AppUser appUser) { + public static SavingsAccountTransaction withdrawTransfer(final SavingsAccount savingsAccount, final Office office, final LocalDate date, + final AppUser appUser) { final boolean isReversed = false; final boolean isManualTransaction = false; final PaymentDetail paymentDetail = null; return new SavingsAccountTransaction(savingsAccount, office, paymentDetail, - SavingsAccountTransactionType.WITHDRAW_TRANSFER.getValue(), date, new Date(), savingsAccount.getSummary() - .getAccountBalance(), isReversed, appUser, isManualTransaction); + SavingsAccountTransactionType.WITHDRAW_TRANSFER.getValue(), date, new Date(), + savingsAccount.getSummary().getAccountBalance(), isReversed, appUser, isManualTransaction); } public static SavingsAccountTransaction withHoldTax(final SavingsAccount savingsAccount, final Office office, final LocalDate date, @@ -249,16 +248,17 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { return accountTransaction; } - public static SavingsAccountTransaction escheat(final SavingsAccount savingsAccount, final LocalDate date, - final AppUser appUser,final boolean accountTransaction) { + public static SavingsAccountTransaction escheat(final SavingsAccount savingsAccount, final LocalDate date, final AppUser appUser, + final boolean accountTransaction) { final boolean isReversed = false; final PaymentDetail paymentDetail = null; return new SavingsAccountTransaction(savingsAccount, savingsAccount.office(), paymentDetail, - SavingsAccountTransactionType.ESCHEAT.getValue(), date, new Date(), savingsAccount.getSummary() - .getAccountBalance(), isReversed, appUser,accountTransaction); + SavingsAccountTransactionType.ESCHEAT.getValue(), date, new Date(), savingsAccount.getSummary().getAccountBalance(), + isReversed, appUser, accountTransaction); } - public static void updateTaxDetails(final Map taxDetails, final SavingsAccountTransaction accountTransaction) { + public static void updateTaxDetails(final Map taxDetails, + final SavingsAccountTransaction accountTransaction) { if (taxDetails != null) { for (Map.Entry mapEntry : taxDetails.entrySet()) { accountTransaction.getTaxDetails().add(new SavingsAccountTransactionTaxDetails(mapEntry.getKey(), mapEntry.getValue())); @@ -267,14 +267,14 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { } public static SavingsAccountTransaction copyTransaction(SavingsAccountTransaction accountTransaction) { - return new SavingsAccountTransaction(accountTransaction.savingsAccount, accountTransaction.office, - accountTransaction.paymentDetail, accountTransaction.typeOf, accountTransaction.transactionLocalDate(), - accountTransaction.createdDate, accountTransaction.amount, accountTransaction.reversed, accountTransaction.appUser, - accountTransaction.isManualTransaction); + return new SavingsAccountTransaction(accountTransaction.savingsAccount, accountTransaction.office, accountTransaction.paymentDetail, + accountTransaction.typeOf, accountTransaction.transactionLocalDate(), accountTransaction.createdDate, + accountTransaction.amount, accountTransaction.reversed, accountTransaction.appUser, accountTransaction.isManualTransaction); } private SavingsAccountTransaction(final SavingsAccount savingsAccount, final Office office, final Integer typeOf, - final LocalDate transactionLocalDate, final Money amount, final boolean isReversed, final AppUser appUser,final boolean isManualTransaction) { + final LocalDate transactionLocalDate, final Money amount, final boolean isReversed, final AppUser appUser, + final boolean isManualTransaction) { this(savingsAccount, office, null, typeOf, transactionLocalDate, new Date(), amount, isReversed, appUser, isManualTransaction); } @@ -308,11 +308,11 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { date, createdDate, amount, isReversed, appUser, isManualTransaction); } - public static SavingsAccountTransaction releaseAmount(SavingsAccountTransaction accountTransaction,LocalDate transactionDate, Date createdDate, - final AppUser appUser) { + public static SavingsAccountTransaction releaseAmount(SavingsAccountTransaction accountTransaction, LocalDate transactionDate, + Date createdDate, final AppUser appUser) { return new SavingsAccountTransaction(accountTransaction.savingsAccount, accountTransaction.office, accountTransaction.paymentDetail, - SavingsAccountTransactionType.AMOUNT_RELEASE.getValue(),transactionDate , createdDate, - accountTransaction.amount, accountTransaction.reversed, appUser, accountTransaction.isManualTransaction); + SavingsAccountTransactionType.AMOUNT_RELEASE.getValue(), transactionDate, createdDate, accountTransaction.amount, + accountTransaction.reversed, appUser, accountTransaction.isManualTransaction); } public LocalDate transactionLocalDate() { @@ -363,6 +363,7 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { return SavingsAccountTransactionType.fromInt(this.typeOf).isInterestPosting() || SavingsAccountTransactionType.fromInt(this.typeOf).isOverDraftInterestPosting(); } + public boolean isWithdrawalFeeAndNotReversed() { return SavingsAccountTransactionType.fromInt(this.typeOf).isWithdrawalFee() && isNotReversed(); } @@ -788,7 +789,7 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { } public PaymentDetail getPaymentDetail() { - return this.paymentDetail ; + return this.paymentDetail; } public void updateReleaseId(Long releaseId) { @@ -802,4 +803,4 @@ public final class SavingsAccountTransaction extends AbstractPersistableCustom { public boolean isAmountOnHoldNotReleased() { return (isAmountOnHold() && getReleaseIdOfHoldAmountTransaction() == null); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransactionComparator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransactionComparator.java index d04600c33..8fa1d6a60 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransactionComparator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransactionComparator.java @@ -42,4 +42,4 @@ public class SavingsAccountTransactionComparator implements Comparator, - JpaSpecificationExecutor { +public interface SavingsAccountTransactionRepository + extends JpaRepository, JpaSpecificationExecutor { @Query("select sat from SavingsAccountTransaction sat where sat.id = :transactionId and sat.savingsAccount.id = :savingsId") SavingsAccountTransaction findOneByIdAndSavingsAccountId(Long transactionId, Long savingsId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransactionSummaryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransactionSummaryWrapper.java index f1c7a11ca..d72a2b1e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransactionSummaryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccountTransactionSummaryWrapper.java @@ -111,7 +111,8 @@ public final class SavingsAccountTransactionSummaryWrapper { return total.getAmountDefaultedToNullIfZero(); } - public BigDecimal calculateTotalPenaltyChargeWaived(final MonetaryCurrency currency, final List transactions) { + public BigDecimal calculateTotalPenaltyChargeWaived(final MonetaryCurrency currency, + final List transactions) { Money total = Money.zero(currency); for (final SavingsAccountTransaction transaction : transactions) { if (transaction.isWaivePenaltyChargeAndNotReversed()) { @@ -130,6 +131,7 @@ public final class SavingsAccountTransactionSummaryWrapper { } return total.getAmountDefaultedToNullIfZero(); } + public BigDecimal calculateTotalWithholdTaxWithdrawal(MonetaryCurrency currency, List transactions) { Money total = Money.zero(currency); for (final SavingsAccountTransaction transaction : transactions) { @@ -139,4 +141,4 @@ public final class SavingsAccountTransactionSummaryWrapper { } return total.getAmountDefaultedToNullIfZero(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsHelper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsHelper.java index 60863e03f..b6fb0bbfc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsHelper.java @@ -47,7 +47,7 @@ public final class SavingsHelper { public List determineInterestPostingPeriods(final LocalDate startInterestCalculationLocalDate, final LocalDate interestPostingUpToDate, final SavingsPostingInterestPeriodType postingPeriodType, - final Integer financialYearBeginningMonth,List postInterestAsOn) { + final Integer financialYearBeginningMonth, List postInterestAsOn) { final List postingPeriods = new ArrayList<>(); LocalDate periodStartDate = startInterestCalculationLocalDate; @@ -56,7 +56,7 @@ public final class SavingsHelper { while (!periodStartDate.isAfter(interestPostingUpToDate) && !periodEndDate.isAfter(interestPostingUpToDate)) { - final LocalDate interestPostingLocalDate = determineInterestPostingPeriodEndDateFrom(periodStartDate, postingPeriodType, + final LocalDate interestPostingLocalDate = determineInterestPostingPeriodEndDateFrom(periodStartDate, postingPeriodType, interestPostingUpToDate, financialYearBeginningMonth); periodEndDate = interestPostingLocalDate.minusDays(1); @@ -64,8 +64,7 @@ public final class SavingsHelper { if (!postInterestAsOn.isEmpty()) { for (LocalDate transactiondate : postInterestAsOn) { if (periodStartDate.isBefore(transactiondate) - && (periodEndDate.isAfter(transactiondate) || periodEndDate - .isEqual(transactiondate))) { + && (periodEndDate.isAfter(transactiondate) || periodEndDate.isEqual(transactiondate))) { periodEndDate = transactiondate.minusDays(1); actualPeriodStartDate = periodEndDate; break; @@ -75,13 +74,12 @@ public final class SavingsHelper { postingPeriods.add(LocalDateInterval.create(periodStartDate, periodEndDate)); - if (actualPeriodStartDate.isEqual(periodEndDate)) - { + if (actualPeriodStartDate.isEqual(periodEndDate)) { periodEndDate = actualPeriodStartDate.plusDays(1); periodStartDate = actualPeriodStartDate.plusDays(1); - }else{ - periodEndDate = interestPostingLocalDate; - periodStartDate = interestPostingLocalDate; + } else { + periodEndDate = interestPostingLocalDate; + periodStartDate = interestPostingLocalDate; } } @@ -89,7 +87,7 @@ public final class SavingsHelper { } private LocalDate determineInterestPostingPeriodEndDateFrom(final LocalDate periodStartDate, - final SavingsPostingInterestPeriodType interestPostingPeriodType, final LocalDate interestPostingUpToDate, + final SavingsPostingInterestPeriodType interestPostingPeriodType, final LocalDate interestPostingUpToDate, Integer financialYearBeginningMonth) { LocalDate periodEndDate = interestPostingUpToDate; @@ -173,4 +171,4 @@ public final class SavingsHelper { public Collection fetchPostInterestTransactionIds(Long accountId) { return this.accountTransfersReadPlatformService.fetchPostInterestTransactionIds(accountId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProduct.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProduct.java index 6dede7375..e4bcd1ffb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProduct.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProduct.java @@ -213,16 +213,16 @@ public class SavingsProduct extends AbstractPersistableCustom { final boolean withdrawalFeeApplicableForTransfer, final AccountingRuleType accountingRuleType, final Set charges, final boolean allowOverdraft, final BigDecimal overdraftLimit, final boolean enforceMinRequiredBalance, final BigDecimal minRequiredBalance, final BigDecimal minBalanceForInterestCalculation, - final BigDecimal nominalAnnualInterestRateOverdraft, final BigDecimal minOverdraftForInterestCalculation, - boolean withHoldTax, TaxGroup taxGroup, - final Boolean isDormancyTrackingActive, final Long daysToInactive, final Long daysToDormancy, final Long daysToEscheat) { + final BigDecimal nominalAnnualInterestRateOverdraft, final BigDecimal minOverdraftForInterestCalculation, boolean withHoldTax, + TaxGroup taxGroup, final Boolean isDormancyTrackingActive, final Long daysToInactive, final Long daysToDormancy, + final Long daysToEscheat) { return new SavingsProduct(name, shortName, description, currency, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeApplicableForTransfer, accountingRuleType, charges, allowOverdraft, overdraftLimit, enforceMinRequiredBalance, minRequiredBalance, minBalanceForInterestCalculation, - nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup, - isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat); + nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup, isDormancyTrackingActive, + daysToInactive, daysToDormancy, daysToEscheat); } protected SavingsProduct() { @@ -236,8 +236,8 @@ public class SavingsProduct extends AbstractPersistableCustom { final SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final SavingsPeriodFrequencyType lockinPeriodFrequencyType, final boolean withdrawalFeeApplicableForTransfer, final AccountingRuleType accountingRuleType, final Set charges, - final boolean allowOverdraft, final BigDecimal overdraftLimit, BigDecimal minBalanceForInterestCalculation, - boolean withHoldTax, TaxGroup taxGroup) { + final boolean allowOverdraft, final BigDecimal overdraftLimit, BigDecimal minBalanceForInterestCalculation, boolean withHoldTax, + TaxGroup taxGroup) { this(name, shortName, description, currency, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeApplicableForTransfer, accountingRuleType, charges, allowOverdraft, overdraftLimit, @@ -253,8 +253,8 @@ public class SavingsProduct extends AbstractPersistableCustom { final boolean allowOverdraft, final BigDecimal overdraftLimit, final boolean enforceMinRequiredBalance, final BigDecimal minRequiredBalance, BigDecimal minBalanceForInterestCalculation, final BigDecimal nominalAnnualInterestRateOverdraft, final BigDecimal minOverdraftForInterestCalculation, - final boolean withHoldTax, final TaxGroup taxGroup, - final Boolean isDormancyTrackingActive, final Long daysToInactive, final Long daysToDormancy, final Long daysToEscheat) { + final boolean withHoldTax, final TaxGroup taxGroup, final Boolean isDormancyTrackingActive, final Long daysToInactive, + final Long daysToDormancy, final Long daysToEscheat) { this.name = name; this.shortName = shortName; @@ -300,9 +300,9 @@ public class SavingsProduct extends AbstractPersistableCustom { this.withHoldTax = withHoldTax; this.taxGroup = taxGroup; - if(isDormancyTrackingActive == null) { - this.isDormancyTrackingActive = Boolean.FALSE ; - }else { + if (isDormancyTrackingActive == null) { + this.isDormancyTrackingActive = Boolean.FALSE; + } else { this.isDormancyTrackingActive = isDormancyTrackingActive; } @@ -568,31 +568,31 @@ public class SavingsProduct extends AbstractPersistableCustom { this.taxGroup = null; } - if(command.isChangeInBooleanParameterNamed(isDormancyTrackingActiveParamName, this.isDormancyTrackingActive)){ + if (command.isChangeInBooleanParameterNamed(isDormancyTrackingActiveParamName, this.isDormancyTrackingActive)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(isDormancyTrackingActiveParamName); actualChanges.put(isDormancyTrackingActiveParamName, newValue); this.isDormancyTrackingActive = newValue; } - if(command.isChangeInLongParameterNamed(daysToInactiveParamName, this.daysToInactive)){ + if (command.isChangeInLongParameterNamed(daysToInactiveParamName, this.daysToInactive)) { final Long newValue = command.longValueOfParameterNamed(daysToInactiveParamName); actualChanges.put(daysToInactiveParamName, newValue); this.daysToInactive = newValue; } - if(command.isChangeInLongParameterNamed(daysToDormancyParamName, this.daysToDormancy)){ + if (command.isChangeInLongParameterNamed(daysToDormancyParamName, this.daysToDormancy)) { final Long newValue = command.longValueOfParameterNamed(daysToDormancyParamName); actualChanges.put(daysToDormancyParamName, newValue); this.daysToDormancy = newValue; } - if(command.isChangeInLongParameterNamed(daysToEscheatParamName, this.daysToEscheat)){ + if (command.isChangeInLongParameterNamed(daysToEscheatParamName, this.daysToEscheat)) { final Long newValue = command.longValueOfParameterNamed(daysToEscheatParamName); actualChanges.put(daysToEscheatParamName, newValue); this.daysToEscheat = newValue; } - if(this.isDormancyTrackingActive == null || !this.isDormancyTrackingActive){ + if (this.isDormancyTrackingActive == null || !this.isDormancyTrackingActive) { this.daysToInactive = null; this.daysToDormancy = null; this.daysToEscheat = null; @@ -721,23 +721,20 @@ public class SavingsProduct extends AbstractPersistableCustom { return this.minOverdraftForInterestCalculation; } - public TaxGroup getTaxGroup() { return this.taxGroup; } - public void setTaxGroup(TaxGroup taxGroup) { this.taxGroup = taxGroup; } - public boolean withHoldTax() { return this.withHoldTax; } public boolean isDormancyTrackingActive() { - return null == this.isDormancyTrackingActive? false: this.isDormancyTrackingActive; + return null == this.isDormancyTrackingActive ? false : this.isDormancyTrackingActive; } public Long getDaysToInactive() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductAssembler.java index ca939c597..00bc484d8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductAssembler.java @@ -185,8 +185,8 @@ public class SavingsProductAssembler { interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, accountingRuleType, charges, allowOverdraft, overdraftLimit, enforceMinRequiredBalance, minRequiredBalance, minBalanceForInterestCalculation, - nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup, - isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat); + nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup, isDormancyTrackingActive, + daysToInactive, daysToDormancy, daysToEscheat); } public Set assembleListOfSavingsProductCharges(final JsonCommand command, final String savingsProductCurrencyCode) { @@ -231,4 +231,4 @@ public class SavingsProductAssembler { } return taxGroup; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductChargeAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductChargeAssembler.java index 587545fe3..7a8f5abe4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductChargeAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductChargeAssembler.java @@ -78,14 +78,14 @@ public class SavingsProductChargeAssembler { final Long id = this.fromApiJsonHelper.extractLongNamed(idParamName, savingsChargeElement); final Long chargeId = this.fromApiJsonHelper.extractLongNamed(chargeIdParamName, savingsChargeElement); final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed(amountParamName, savingsChargeElement, locale); - final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed(chargeTimeTypeParamName, - savingsChargeElement, locale); + final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed(chargeTimeTypeParamName, savingsChargeElement, + locale); final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed(chargeCalculationTypeParamName, savingsChargeElement, locale); final LocalDate dueDate = this.fromApiJsonHelper.extractLocalDateNamed(dueAsOfDateParamName, savingsChargeElement, dateFormat, locale); - final MonthDay feeOnMonthDay = this.fromApiJsonHelper - .extractMonthDayNamed(feeOnMonthDayParamName, savingsChargeElement); + final MonthDay feeOnMonthDay = this.fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, + savingsChargeElement); final Integer feeInterval = this.fromApiJsonHelper.extractIntegerNamed(feeIntervalParamName, savingsChargeElement, locale); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductRepository.java index 072dd9c6f..b7c14bd8a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsProductRepository.java @@ -23,4 +23,4 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface SavingsProductRepository extends JpaRepository, JpaSpecificationExecutor { // -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/AnnualCompoundingPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/AnnualCompoundingPeriod.java index efab50761..3fd24db74 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/AnnualCompoundingPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/AnnualCompoundingPeriod.java @@ -87,19 +87,21 @@ public class AnnualCompoundingPeriod implements CompoundingPeriod { final BigDecimal averageDailyBalance = cumulativeBalance.divide(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64) .setScale(9, MoneyHelper.getRoundingMode()); - if(averageDailyBalance.compareTo(BigDecimal.ZERO) >= 0){ + if (averageDailyBalance.compareTo(BigDecimal.ZERO) >= 0) { if (averageDailyBalance.compareTo(minBalanceForInterestCalculation) >= 0) { final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); final BigDecimal dailyInterestRate = interestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), + MathContext.DECIMAL64); interestEarned = averageDailyBalance.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } - }else{ + } else { if (averageDailyBalance.compareTo(minOverdraftForInterestCalculation.negate()) < 0) { final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); final BigDecimal dailyInterestRate = overdraftInterestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), + MathContext.DECIMAL64); interestEarned = averageDailyBalance.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } @@ -121,7 +123,8 @@ public class AnnualCompoundingPeriod implements CompoundingPeriod { switch (compoundingInterestPeriodType) { case DAILY: interestOnBalanceUnrounded = balance.calculateInterestOnBalanceAndInterest(interestToCompound, interestRateAsFraction, - daysInYear, minBalanceForInterestCalculation, overdraftInterestRateAsFraction, minOverdraftForInterestCalculation); + daysInYear, minBalanceForInterestCalculation, overdraftInterestRateAsFraction, + minOverdraftForInterestCalculation); break; case MONTHLY: interestOnBalanceUnrounded = balance.calculateInterestOnBalance(interestToCompound, interestRateAsFraction, daysInYear, @@ -182,4 +185,4 @@ public class AnnualCompoundingPeriod implements CompoundingPeriod { public LocalDateInterval getPeriodInterval() { return this.periodInterval; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/BiAnnualCompoundingPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/BiAnnualCompoundingPeriod.java index 14911c338..49e15dffd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/BiAnnualCompoundingPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/BiAnnualCompoundingPeriod.java @@ -87,19 +87,21 @@ public class BiAnnualCompoundingPeriod implements CompoundingPeriod { final BigDecimal averageDailyBalance = cumulativeBalance.divide(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64) .setScale(9, MoneyHelper.getRoundingMode()); - if(averageDailyBalance.compareTo(BigDecimal.ZERO) >= 0){ + if (averageDailyBalance.compareTo(BigDecimal.ZERO) >= 0) { if (averageDailyBalance.compareTo(minBalanceForInterestCalculation) >= 0) { final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); final BigDecimal dailyInterestRate = interestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), + MathContext.DECIMAL64); interestEarned = averageDailyBalance.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } - }else{ + } else { if (averageDailyBalance.compareTo(minOverdraftForInterestCalculation.negate()) < 0) { final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); final BigDecimal dailyInterestRate = overdraftInterestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), + MathContext.DECIMAL64); interestEarned = averageDailyBalance.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } @@ -121,7 +123,8 @@ public class BiAnnualCompoundingPeriod implements CompoundingPeriod { switch (compoundingInterestPeriodType) { case DAILY: interestOnBalanceUnrounded = balance.calculateInterestOnBalanceAndInterest(interestToCompound, interestRateAsFraction, - daysInYear, minBalanceForInterestCalculation, overdraftInterestRateAsFraction, minOverdraftForInterestCalculation); + daysInYear, minBalanceForInterestCalculation, overdraftInterestRateAsFraction, + minOverdraftForInterestCalculation); break; case MONTHLY: interestOnBalanceUnrounded = balance.calculateInterestOnBalance(interestToCompound, interestRateAsFraction, daysInYear, @@ -182,4 +185,4 @@ public class BiAnnualCompoundingPeriod implements CompoundingPeriod { public LocalDateInterval getPeriodInterval() { return this.periodInterval; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundInterestHelper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundInterestHelper.java index 36983aff0..0d026cb47 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundInterestHelper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundInterestHelper.java @@ -47,8 +47,7 @@ public class CompoundInterestHelper { // total interest earned in previous periods but not yet recognised BigDecimal compoundedInterest = BigDecimal.ZERO; BigDecimal unCompoundedInterest = BigDecimal.ZERO; - final CompoundInterestValues compoundInterestValues = new CompoundInterestValues(compoundedInterest, - unCompoundedInterest); + final CompoundInterestValues compoundInterestValues = new CompoundInterestValues(compoundedInterest, unCompoundedInterest); for (final PostingPeriod postingPeriod : allPeriods) { final BigDecimal interestEarnedThisPeriod = postingPeriod.calculateInterest(compoundInterestValues); @@ -68,4 +67,4 @@ public class CompoundInterestHelper { return interestEarned; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundingPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundingPeriod.java index dd0620494..206341710 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundingPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/CompoundingPeriod.java @@ -29,5 +29,6 @@ public interface CompoundingPeriod { SavingsInterestCalculationType interestCalculationType, BigDecimal interestFromPreviousPostingPeriod, BigDecimal interestRateAsFraction, long daysInYear, BigDecimal minBalanceForInterestCalculation, BigDecimal overdraftInterestRateAsFraction, BigDecimal minOverdraftForInterestCalculation); + LocalDateInterval getPeriodInterval(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/DailyCompoundingPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/DailyCompoundingPeriod.java index 1a423d5cb..515ae11b6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/DailyCompoundingPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/DailyCompoundingPeriod.java @@ -35,8 +35,8 @@ public class DailyCompoundingPeriod implements CompoundingPeriod { public static DailyCompoundingPeriod create(final LocalDateInterval periodInterval, final List allEndOfDayBalances, final LocalDate upToInterestCalculationDate) { - final List endOfDayBalancesWithinPeriod = endOfDayBalancesWithinPeriodInterval(periodInterval, - allEndOfDayBalances, upToInterestCalculationDate); + final List endOfDayBalancesWithinPeriod = endOfDayBalancesWithinPeriodInterval(periodInterval, allEndOfDayBalances, + upToInterestCalculationDate); return new DailyCompoundingPeriod(periodInterval, endOfDayBalancesWithinPeriod); } @@ -74,11 +74,9 @@ public class DailyCompoundingPeriod implements CompoundingPeriod { } @Override - public BigDecimal calculateInterest( - final SavingsCompoundingInterestPeriodType compoundingInterestPeriodType, - final SavingsInterestCalculationType interestCalculationType, - final BigDecimal interestFromPreviousPostingPeriod, final BigDecimal interestRateAsFraction, final long daysInYear, - final BigDecimal minBalanceForInterestCalculation, + public BigDecimal calculateInterest(final SavingsCompoundingInterestPeriodType compoundingInterestPeriodType, + final SavingsInterestCalculationType interestCalculationType, final BigDecimal interestFromPreviousPostingPeriod, + final BigDecimal interestRateAsFraction, final long daysInYear, final BigDecimal minBalanceForInterestCalculation, final BigDecimal overdraftInterestRateAsFraction, final BigDecimal minOverdraftForInterestCalculation) { BigDecimal interestEarned = BigDecimal.ZERO; @@ -100,4 +98,4 @@ public class DailyCompoundingPeriod implements CompoundingPeriod { public LocalDateInterval getPeriodInterval() { return this.periodInterval; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/EndOfDayBalance.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/EndOfDayBalance.java index 792a55d96..16e6b73be 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/EndOfDayBalance.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/EndOfDayBalance.java @@ -60,16 +60,17 @@ public class EndOfDayBalance { } public BigDecimal calculateInterestOnBalance(final BigDecimal interestToCompound, final BigDecimal interestRateAsFraction, - final long daysInYear, final BigDecimal minBalanceForInterestCalculation, - final BigDecimal overdraftInterestRateAsFraction, final BigDecimal minOverdraftForInterestCalculation) { + final long daysInYear, final BigDecimal minBalanceForInterestCalculation, final BigDecimal overdraftInterestRateAsFraction, + final BigDecimal minOverdraftForInterestCalculation) { BigDecimal interest = BigDecimal.ZERO.setScale(9, MoneyHelper.getRoundingMode()); final BigDecimal realBalanceForInterestCalculation = this.endOfDayBalance.getAmount().add(interestToCompound); - if(realBalanceForInterestCalculation.compareTo(BigDecimal.ZERO) >= 0){ + if (realBalanceForInterestCalculation.compareTo(BigDecimal.ZERO) >= 0) { if (realBalanceForInterestCalculation.compareTo(minBalanceForInterestCalculation) >= 0) { final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); final BigDecimal dailyInterestRate = interestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(this.numberOfDays), MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(this.numberOfDays), + MathContext.DECIMAL64); interest = realBalanceForInterestCalculation.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } @@ -77,7 +78,8 @@ public class EndOfDayBalance { if (realBalanceForInterestCalculation.compareTo(minOverdraftForInterestCalculation.negate()) < 0) { final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); final BigDecimal dailyInterestRate = overdraftInterestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(this.numberOfDays), MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(this.numberOfDays), + MathContext.DECIMAL64); interest = realBalanceForInterestCalculation.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } @@ -100,7 +102,7 @@ public class EndOfDayBalance { final BigDecimal presentValue = this.endOfDayBalance.getAmount().add(interestToCompound); BigDecimal futureValue = presentValue.setScale(9, MoneyHelper.getRoundingMode()); - if(presentValue.compareTo(BigDecimal.ZERO) >= 0){ + if (presentValue.compareTo(BigDecimal.ZERO) >= 0) { if (presentValue.compareTo(minBalanceForInterestCalculation) >= 0) { final BigDecimal r = interestRateAsFraction.multiply(multiplicand); @@ -111,7 +113,7 @@ public class EndOfDayBalance { futureValue = presentValue.multiply(BigDecimal.valueOf(interestRateForCompoundingPeriodPowered), MathContext.DECIMAL64) .setScale(9, MoneyHelper.getRoundingMode()); } - }else{ + } else { if (presentValue.compareTo(minOverdraftForInterestCalculation.negate()) < 0) { final BigDecimal r = overdraftInterestRateAsFraction.multiply(multiplicand); @@ -177,4 +179,4 @@ public class EndOfDayBalance { public Integer getNumberOfDays() { return Integer.valueOf(this.numberOfDays); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/MonthlyCompoundingPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/MonthlyCompoundingPeriod.java index f4f46f6ed..4307165e2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/MonthlyCompoundingPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/MonthlyCompoundingPeriod.java @@ -87,19 +87,21 @@ public class MonthlyCompoundingPeriod implements CompoundingPeriod { final BigDecimal averageDailyBalance = cumulativeBalance.divide(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64) .setScale(9, MoneyHelper.getRoundingMode()); - if(averageDailyBalance.compareTo(BigDecimal.ZERO) >= 0){ + if (averageDailyBalance.compareTo(BigDecimal.ZERO) >= 0) { if (averageDailyBalance.compareTo(minBalanceForInterestCalculation) >= 0) { final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); final BigDecimal dailyInterestRate = interestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), + MathContext.DECIMAL64); interestEarned = averageDailyBalance.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } - }else{ + } else { if (averageDailyBalance.compareTo(minOverdraftForInterestCalculation.negate()) < 0) { final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); final BigDecimal dailyInterestRate = overdraftInterestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), + MathContext.DECIMAL64); interestEarned = averageDailyBalance.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } @@ -121,7 +123,8 @@ public class MonthlyCompoundingPeriod implements CompoundingPeriod { switch (compoundingInterestPeriodType) { case DAILY: interestOnBalanceUnrounded = balance.calculateInterestOnBalanceAndInterest(interestToCompound, interestRateAsFraction, - daysInYear, minBalanceForInterestCalculation, overdraftInterestRateAsFraction, minOverdraftForInterestCalculation); + daysInYear, minBalanceForInterestCalculation, overdraftInterestRateAsFraction, + minOverdraftForInterestCalculation); break; case MONTHLY: interestOnBalanceUnrounded = balance.calculateInterestOnBalance(interestToCompound, interestRateAsFraction, daysInYear, @@ -178,4 +181,4 @@ public class MonthlyCompoundingPeriod implements CompoundingPeriod { public LocalDateInterval getPeriodInterval() { return this.periodInterval; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/PostingPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/PostingPeriod.java index 40890f5e9..320d97783 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/PostingPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/PostingPeriod.java @@ -68,15 +68,15 @@ public class PostingPeriod { final SavingsCompoundingInterestPeriodType interestCompoundingPeriodType, final SavingsInterestCalculationType interestCalculationType, final BigDecimal interestRateAsFraction, final long daysInYear, final LocalDate upToInterestCalculationDate, Collection interestPostTransactions, boolean isInterestTransfer, - final Money minBalanceForInterestCalculation, final boolean isSavingsInterestPostingAtCurrentPeriodEnd,final boolean isUserPosting, Integer financialYearBeginningMonth) { + final Money minBalanceForInterestCalculation, final boolean isSavingsInterestPostingAtCurrentPeriodEnd, + final boolean isUserPosting, Integer financialYearBeginningMonth) { final BigDecimal overdraftInterestRateAsFraction = BigDecimal.ZERO; final Money minOverdraftForInterestCalculation = Money.zero(currency); - return createFrom(periodInterval, periodStartingBalance, orderedListOfTransactions, currency, - interestCompoundingPeriodType, interestCalculationType, interestRateAsFraction, daysInYear, - upToInterestCalculationDate, interestPostTransactions, isInterestTransfer, - minBalanceForInterestCalculation, isSavingsInterestPostingAtCurrentPeriodEnd, + return createFrom(periodInterval, periodStartingBalance, orderedListOfTransactions, currency, interestCompoundingPeriodType, + interestCalculationType, interestRateAsFraction, daysInYear, upToInterestCalculationDate, interestPostTransactions, + isInterestTransfer, minBalanceForInterestCalculation, isSavingsInterestPostingAtCurrentPeriodEnd, overdraftInterestRateAsFraction, minOverdraftForInterestCalculation, isUserPosting, financialYearBeginningMonth); } @@ -88,7 +88,8 @@ public class PostingPeriod { final SavingsInterestCalculationType interestCalculationType, final BigDecimal interestRateAsFraction, final long daysInYear, final LocalDate upToInterestCalculationDate, Collection interestPostTransactions, boolean isInterestTransfer, final Money minBalanceForInterestCalculation, final boolean isSavingsInterestPostingAtCurrentPeriodEnd, - final BigDecimal overdraftInterestRateAsFraction, final Money minOverdraftForInterestCalculation, boolean isUserPosting, int financialYearBeginningMonth) { + final BigDecimal overdraftInterestRateAsFraction, final Money minOverdraftForInterestCalculation, boolean isUserPosting, + int financialYearBeginningMonth) { final List accountEndOfDayBalances = new ArrayList<>(); boolean interestTransfered = false; @@ -149,8 +150,8 @@ public class PostingPeriod { return new PostingPeriod(periodInterval, currency, periodStartingBalance, openingDayBalance, interestCompoundingPeriodType, interestCalculationType, interestRateAsFraction, daysInYear, compoundingPeriods, interestTransfered, - minBalanceForInterestCalculation, isSavingsInterestPostingAtCurrentPeriodEnd, - overdraftInterestRateAsFraction, minOverdraftForInterestCalculation, isUserPosting, financialYearBeginningMonth); + minBalanceForInterestCalculation, isSavingsInterestPostingAtCurrentPeriodEnd, overdraftInterestRateAsFraction, + minOverdraftForInterestCalculation, isUserPosting, financialYearBeginningMonth); } private PostingPeriod(final LocalDateInterval periodInterval, final MonetaryCurrency currency, final Money openingBalance, @@ -206,21 +207,20 @@ public class PostingPeriod { for (final CompoundingPeriod compoundingPeriod : this.compoundingPeriods) { final BigDecimal interestUnrounded = compoundingPeriod.calculateInterest(this.interestCompoundingType, - this.interestCalculationType, compoundInterestValues.getcompoundedInterest(), this.interestRateAsFraction, this.daysInYear, - this.minBalanceForInterestCalculation.getAmount(), this.overdraftInterestRateAsFraction, + this.interestCalculationType, compoundInterestValues.getcompoundedInterest(), this.interestRateAsFraction, + this.daysInYear, this.minBalanceForInterestCalculation.getAmount(), this.overdraftInterestRateAsFraction, this.minOverdraftForInterestCalculation.getAmount()); BigDecimal unCompoundedInterest = compoundInterestValues.getuncompoundedInterest().add(interestUnrounded); compoundInterestValues.setuncompoundedInterest(unCompoundedInterest); LocalDate compoundingPeriodEndDate = compoundingPeriod.getPeriodInterval().endDate(); if (!SavingsCompoundingInterestPeriodType.DAILY.equals(this.interestCompoundingType)) { - compoundingPeriodEndDate = determineInterestPeriodEndDateFrom( - compoundingPeriod.getPeriodInterval().startDate(), this.interestCompoundingType, - compoundingPeriod.getPeriodInterval().endDate(), this.getFinancialYearBeginningMonth()); + compoundingPeriodEndDate = determineInterestPeriodEndDateFrom(compoundingPeriod.getPeriodInterval().startDate(), + this.interestCompoundingType, compoundingPeriod.getPeriodInterval().endDate(), + this.getFinancialYearBeginningMonth()); } if (compoundingPeriodEndDate.equals(compoundingPeriod.getPeriodInterval().endDate())) { - BigDecimal interestCompounded = compoundInterestValues.getcompoundedInterest() - .add(unCompoundedInterest); + BigDecimal interestCompounded = compoundInterestValues.getcompoundedInterest().add(unCompoundedInterest); compoundInterestValues.setcompoundedInterest(interestCompounded); compoundInterestValues.setZeroForInterestToBeUncompounded(); } @@ -260,7 +260,8 @@ public class PostingPeriod { while (!periodStartDate.isAfter(postingPeriodEndDate) && !periodEndDate.isAfter(postingPeriodEndDate)) { - periodEndDate = determineInterestPeriodEndDateFrom(periodStartDate, interestPeriodType, upToInterestCalculationDate, financialYearBeginningMonth); + periodEndDate = determineInterestPeriodEndDateFrom(periodStartDate, interestPeriodType, upToInterestCalculationDate, + financialYearBeginningMonth); if (periodEndDate.isAfter(postingPeriodEndDate)) { periodEndDate = postingPeriodEndDate; } @@ -289,7 +290,8 @@ public class PostingPeriod { while (!periodStartDate.isAfter(qPostingPeriodEndDate) && !periodEndDate.isAfter(qPostingPeriodEndDate)) { - periodEndDate = determineInterestPeriodEndDateFrom(periodStartDate, interestPeriodType, upToInterestCalculationDate, financialYearBeginningMonth); + periodEndDate = determineInterestPeriodEndDateFrom(periodStartDate, interestPeriodType, upToInterestCalculationDate, + financialYearBeginningMonth); if (periodEndDate.isAfter(qPostingPeriodEndDate)) { periodEndDate = qPostingPeriodEndDate; } @@ -314,7 +316,8 @@ public class PostingPeriod { while (!periodStartDate.isAfter(bPostingPeriodEndDate) && !periodEndDate.isAfter(bPostingPeriodEndDate)) { - periodEndDate = determineInterestPeriodEndDateFrom(periodStartDate, interestPeriodType, upToInterestCalculationDate, financialYearBeginningMonth); + periodEndDate = determineInterestPeriodEndDateFrom(periodStartDate, interestPeriodType, upToInterestCalculationDate, + financialYearBeginningMonth); if (periodEndDate.isAfter(bPostingPeriodEndDate)) { periodEndDate = bPostingPeriodEndDate; } @@ -339,7 +342,8 @@ public class PostingPeriod { while (!periodStartDate.isAfter(aPostingPeriodEndDate) && !periodEndDate.isAfter(aPostingPeriodEndDate)) { - periodEndDate = determineInterestPeriodEndDateFrom(periodStartDate, interestPeriodType, upToInterestCalculationDate, financialYearBeginningMonth); + periodEndDate = determineInterestPeriodEndDateFrom(periodStartDate, interestPeriodType, upToInterestCalculationDate, + financialYearBeginningMonth); if (periodEndDate.isAfter(aPostingPeriodEndDate)) { periodEndDate = aPostingPeriodEndDate; } @@ -356,19 +360,20 @@ public class PostingPeriod { periodStartDate = periodEndDate.plusDays(1); } break; - // case NO_COMPOUNDING_SIMPLE_INTEREST: - // break; + // case NO_COMPOUNDING_SIMPLE_INTEREST: + // break; } return compoundingPeriods; } private static LocalDate determineInterestPeriodEndDateFrom(final LocalDate periodStartDate, - final SavingsCompoundingInterestPeriodType interestPeriodType, final LocalDate upToInterestCalculationDate, int financialYearBeginningMonth) { + final SavingsCompoundingInterestPeriodType interestPeriodType, final LocalDate upToInterestCalculationDate, + int financialYearBeginningMonth) { LocalDate periodEndDate = upToInterestCalculationDate; - int previousMonth = financialYearBeginningMonth-1; - if(previousMonth==0){ + int previousMonth = financialYearBeginningMonth - 1; + if (previousMonth == 0) { previousMonth = 12; } int periodsInMonth = 1; @@ -402,15 +407,15 @@ public class PostingPeriod { case ANNUAL: periodEndDate = periodStartDate.withMonthOfYear(previousMonth); periodEndDate = periodEndDate.dayOfMonth().withMaximumValue(); - if(periodEndDate.isBefore(periodStartDate)){ + if (periodEndDate.isBefore(periodStartDate)) { periodEndDate = periodEndDate.plusYears(1); } break; - // case NO_COMPOUNDING_SIMPLE_INTEREST: - // periodEndDate = periodStartDate.monthOfYear().withMaximumValue(); - // periodEndDate = periodEndDate.dayOfMonth().withMaximumValue(); - // break; + // case NO_COMPOUNDING_SIMPLE_INTEREST: + // periodEndDate = periodStartDate.monthOfYear().withMaximumValue(); + // periodEndDate = periodEndDate.dayOfMonth().withMaximumValue(); + // break; } return periodEndDate; @@ -423,29 +428,34 @@ public class PostingPeriod { TreeSet monthSet = new TreeSet<>(); date = date.withMonthOfYear(previousMonth); monthSet.add(date.getMonthOfYear()); - int count =0; - while(count<(periodsInMonth-1)){ - date = date.plusMonths((12/periodsInMonth)); + int count = 0; + while (count < (periodsInMonth - 1)) { + date = date.plusMonths((12 / periodsInMonth)); monthSet.add(date.getMonthOfYear()); count++; } boolean notInRange = true; /* - * if strt date is 2016-10-05 - * if financial year set to 4 then applicable month will be march and september that is (3,9) - * if start date fall in month of oct,nov or dec then month will be 10, 11 or 12 - * so period end date should be taken from next year for march month + * if strt date is 2016-10-05 if financial year set to 4 then applicable + * month will be march and september that is (3,9) if start date fall in + * month of oct,nov or dec then month will be 10, 11 or 12 so period end + * date should be taken from next year for march month */ for (Integer month : monthSet) { - if(monthofYear<=month.intValue()){ - periodEndDate = new DateTime().withDate(year, month, DateUtils.getLocalDateOfTenant().withMonthOfYear(month).dayOfMonth().withMaximumValue().getDayOfMonth()).toLocalDate(); + if (monthofYear <= month.intValue()) { + periodEndDate = new DateTime() + .withDate(year, month, + DateUtils.getLocalDateOfTenant().withMonthOfYear(month).dayOfMonth().withMaximumValue().getDayOfMonth()) + .toLocalDate(); notInRange = false; break; } } - if(notInRange){ - periodEndDate = new DateTime().withDate(year+1, monthSet.first(), DateUtils.getLocalDateOfTenant().withMonthOfYear(monthSet.first()).dayOfMonth().withMaximumValue().getDayOfMonth()).toLocalDate(); + if (notInRange) { + periodEndDate = new DateTime().withDate(year + 1, monthSet.first(), + DateUtils.getLocalDateOfTenant().withMonthOfYear(monthSet.first()).dayOfMonth().withMaximumValue().getDayOfMonth()) + .toLocalDate(); } return periodEndDate; } @@ -462,10 +472,8 @@ public class PostingPeriod { return this.isUserPosting; } - public Integer getFinancialYearBeginningMonth() { return this.financialYearBeginningMonth; } - -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/QuarterlyCompoundingPeriod.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/QuarterlyCompoundingPeriod.java index 0446f5ca6..bf54af203 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/QuarterlyCompoundingPeriod.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/interest/QuarterlyCompoundingPeriod.java @@ -86,19 +86,21 @@ public class QuarterlyCompoundingPeriod implements CompoundingPeriod { final BigDecimal averageDailyBalance = cumulativeBalance.divide(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64) .setScale(9, MoneyHelper.getRoundingMode()); - if(averageDailyBalance.compareTo(BigDecimal.ZERO) >= 0){ + if (averageDailyBalance.compareTo(BigDecimal.ZERO) >= 0) { if (averageDailyBalance.compareTo(minBalanceForInterestCalculation) >= 0) { final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); final BigDecimal dailyInterestRate = interestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), + MathContext.DECIMAL64); interestEarned = averageDailyBalance.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } - }else{ + } else { if (averageDailyBalance.compareTo(minOverdraftForInterestCalculation.negate()) < 0) { final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); final BigDecimal dailyInterestRate = overdraftInterestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), + MathContext.DECIMAL64); interestEarned = averageDailyBalance.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, MoneyHelper.getRoundingMode()); } @@ -120,7 +122,8 @@ public class QuarterlyCompoundingPeriod implements CompoundingPeriod { switch (compoundingInterestPeriodType) { case DAILY: interestOnBalanceUnrounded = balance.calculateInterestOnBalanceAndInterest(interestToCompound, interestRateAsFraction, - daysInYear, minBalanceForInterestCalculation, overdraftInterestRateAsFraction, minOverdraftForInterestCalculation); + daysInYear, minBalanceForInterestCalculation, overdraftInterestRateAsFraction, + minOverdraftForInterestCalculation); break; case MONTHLY: interestOnBalanceUnrounded = balance.calculateInterestOnBalance(interestToCompound, interestRateAsFraction, daysInYear, @@ -181,4 +184,4 @@ public class QuarterlyCompoundingPeriod implements CompoundingPeriod { public LocalDateInterval getPeriodInterval() { return this.periodInterval; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountInterestRateChartNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountInterestRateChartNotFoundException.java index c8431431b..c6a67404e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountInterestRateChartNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountInterestRateChartNotFoundException.java @@ -23,7 +23,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class DepositAccountInterestRateChartNotFoundException extends AbstractPlatformResourceNotFoundException { public DepositAccountInterestRateChartNotFoundException(final Long id) { - super("error.msg.deposit.account.interest.rate.chart.id.invalid", "Deposit Account Interest rate chart with identifier " + id - + " does not exist", id); + super("error.msg.deposit.account.interest.rate.chart.id.invalid", + "Deposit Account Interest rate chart with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountNotFoundException.java index 9540b80f5..786af8cc2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountNotFoundException.java @@ -25,7 +25,7 @@ import org.apache.fineract.portfolio.savings.DepositAccountType; public class DepositAccountNotFoundException extends AbstractPlatformResourceNotFoundException { public DepositAccountNotFoundException(final DepositAccountType accountType, final Long id) { - super("error.msg." + accountType.getCode().toLowerCase() + ".id.invalid", StringUtils.capitalize(accountType.toString() - .toLowerCase()) + " account with identifier " + id + " does not exist", id); + super("error.msg." + accountType.getCode().toLowerCase() + ".id.invalid", + StringUtils.capitalize(accountType.toString().toLowerCase()) + " account with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountTransactionNotAllowedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountTransactionNotAllowedException.java index 500227686..997051236 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountTransactionNotAllowedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/DepositAccountTransactionNotAllowedException.java @@ -29,7 +29,9 @@ import org.apache.fineract.portfolio.savings.service.SavingsEnumerations; public class DepositAccountTransactionNotAllowedException extends AbstractPlatformServiceUnavailableException { public DepositAccountTransactionNotAllowedException(final Long accountId, final String action, final DepositAccountType type) { - super("error.msg." + type.resourceName() + ".account.trasaction." + action + ".notallowed", SavingsEnumerations.depositType(type) - .getValue() + "account " + action + " transaction not allowed with account identifier " + accountId, accountId); + super("error.msg." + type.resourceName() + ".account.trasaction." + action + ".notallowed", + SavingsEnumerations.depositType(type).getValue() + "account " + action + " transaction not allowed with account identifier " + + accountId, + accountId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/FixedDepositProductNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/FixedDepositProductNotFoundException.java index 786a9503f..4381e3ef5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/FixedDepositProductNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/FixedDepositProductNotFoundException.java @@ -25,4 +25,4 @@ public class FixedDepositProductNotFoundException extends AbstractPlatformResour public FixedDepositProductNotFoundException(final Long id) { super("error.msg.fixeddepositproduct.id.invalid", "Fixed deposit product with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/InsufficientAccountBalanceException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/InsufficientAccountBalanceException.java index d04f518b0..f7194fe0a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/InsufficientAccountBalanceException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/InsufficientAccountBalanceException.java @@ -33,4 +33,4 @@ public class InsufficientAccountBalanceException extends AbstractPlatformDomainR : "error.msg.savingsaccount.transaction.insufficient.account.balance", "Insufficient account balance.", paramName, accountBalance, withdrawalFee, transactionAmount); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/PostInterestAsOnDateException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/PostInterestAsOnDateException.java index 0761821ff..1bcccf04d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/PostInterestAsOnDateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/PostInterestAsOnDateException.java @@ -18,13 +18,14 @@ */ package org.apache.fineract.portfolio.savings.exception; - import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; +public class PostInterestAsOnDateException extends AbstractPlatformDomainRuleException { -public class PostInterestAsOnDateException extends AbstractPlatformDomainRuleException{ public static enum PostInterestAsOnExceptionType { + FUTURE_DATE, VALID_DATE, ACTIVATION_DATE, LAST_TRANSACTION_DATE; + public String errorMessage() { if (name().toString().equalsIgnoreCase("FUTURE_DATE")) { return "Cannot Post Interest in future Dates"; @@ -35,27 +36,23 @@ public class PostInterestAsOnDateException extends AbstractPlatformDomainRuleExc } else if (name().toString().equalsIgnoreCase("LAST_TRANSACTION_DATE")) { return "Cannot Post Interest before last transaction date"; } - return name().toString(); - } + return name().toString(); + } - public String errorCode() { - if (name().toString().equalsIgnoreCase("FUTURE_DATE")) { - return "error.msg.futureDate"; - } else if (name().toString().equalsIgnoreCase("VALID_DATE")) { + public String errorCode() { + if (name().toString().equalsIgnoreCase("FUTURE_DATE")) { + return "error.msg.futureDate"; + } else if (name().toString().equalsIgnoreCase("VALID_DATE")) { return "error.msg.nullDatePassed"; } else if (name().toString().equalsIgnoreCase("ACTIVATION_DATE")) { return "error.msg.before activation date"; - } else if (name().toString().equalsIgnoreCase("LAST_TRANSACTION_DATE")) { - return "error.msg.countInterest"; - } + } else if (name().toString().equalsIgnoreCase("LAST_TRANSACTION_DATE")) { return "error.msg.countInterest"; } return name().toString(); } } - public PostInterestAsOnDateException(final PostInterestAsOnExceptionType reason) { super(reason.errorCode(), reason.errorMessage()); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/RecurringDepositProductNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/RecurringDepositProductNotFoundException.java index 9e7645ce6..3f420c980 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/RecurringDepositProductNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/RecurringDepositProductNotFoundException.java @@ -25,4 +25,4 @@ public class RecurringDepositProductNotFoundException extends AbstractPlatformRe public RecurringDepositProductNotFoundException(final Long id) { super("error.msg.recurringdepositproduct.id.invalid", "Recurring deposit product with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsAccountNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsAccountNotFoundException.java index c42e99d6c..6f12b08c0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsAccountNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsAccountNotFoundException.java @@ -27,6 +27,7 @@ public class SavingsAccountNotFoundException extends AbstractPlatformResourceNot } public SavingsAccountNotFoundException(final String externalId) { - super("error.msg.saving.account.id.invalid", "Savings account with external identifier " + externalId + " does not exist", externalId); + super("error.msg.saving.account.id.invalid", "Savings account with external identifier " + externalId + " does not exist", + externalId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsAccountTransactionNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsAccountTransactionNotFoundException.java old mode 100755 new mode 100644 index 69eab8749..fc22a8c8c --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsAccountTransactionNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsAccountTransactionNotFoundException.java @@ -23,8 +23,9 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class SavingsAccountTransactionNotFoundException extends AbstractPlatformResourceNotFoundException { public SavingsAccountTransactionNotFoundException(final Long savingsId, final Long transactionId) { - super("error.msg.saving.account.trasaction.id.invalid", "Savings account with savings identifier " + savingsId - + " and trasaction identifier " + transactionId + " does not exist", savingsId, transactionId); + super("error.msg.saving.account.trasaction.id.invalid", + "Savings account with savings identifier " + savingsId + " and trasaction identifier " + transactionId + " does not exist", + savingsId, transactionId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsActivityPriorToClientTransferException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsActivityPriorToClientTransferException.java index 2a89dbb99..7c4b7d59a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsActivityPriorToClientTransferException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsActivityPriorToClientTransferException.java @@ -31,4 +31,4 @@ public class SavingsActivityPriorToClientTransferException extends AbstractPlatf "Transactions on savings account prior to the customer joining date are not permitted", defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerAssignmentDateException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerAssignmentDateException.java index 1449f3b64..bc1c6f02f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerAssignmentDateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerAssignmentDateException.java @@ -22,8 +22,9 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class SavingsOfficerAssignmentDateException extends AbstractPlatformDomainRuleException { - public SavingsOfficerAssignmentDateException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { + public SavingsOfficerAssignmentDateException(final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg.savings.assignment.date." + postFix, defaultUserMessage, defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerUnassignmentDateException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerUnassignmentDateException.java index a6add1f00..65d967cde 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerUnassignmentDateException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerUnassignmentDateException.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.portfolio.savings.exception; - import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; public class SavingsOfficerUnassignmentDateException extends AbstractPlatformDomainRuleException { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerUnassignmentException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerUnassignmentException.java index 8bf91506c..780682c2c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerUnassignmentException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsOfficerUnassignmentException.java @@ -23,6 +23,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class SavingsOfficerUnassignmentException extends AbstractPlatformDomainRuleException { public SavingsOfficerUnassignmentException(final Long accountId) { - super("error.msg.savings.account.not.assigned.to.savings.officer", "Savings Account Identifier" + accountId + " is not assigned to any savings officer."); + super("error.msg.savings.account.not.assigned.to.savings.officer", + "Savings Account Identifier" + accountId + " is not assigned to any savings officer."); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsProductNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsProductNotFoundException.java index 8f6bed3bf..0a2658a91 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsProductNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsProductNotFoundException.java @@ -25,4 +25,4 @@ public class SavingsProductNotFoundException extends AbstractPlatformResourceNot 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/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsTransferTransactionsCannotBeUndoneException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsTransferTransactionsCannotBeUndoneException.java index 65d7c3bef..2179302e4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsTransferTransactionsCannotBeUndoneException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/SavingsTransferTransactionsCannotBeUndoneException.java @@ -31,4 +31,4 @@ public class SavingsTransferTransactionsCannotBeUndoneException extends Abstract "Transactions related to savings account transfers cannot be undone", transactionId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/TransactionUpdateNotAllowedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/TransactionUpdateNotAllowedException.java old mode 100755 new mode 100644 index 7a052c3ea..6fc76f120 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/TransactionUpdateNotAllowedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/exception/TransactionUpdateNotAllowedException.java @@ -28,6 +28,7 @@ public class TransactionUpdateNotAllowedException extends AbstractPlatformServic public TransactionUpdateNotAllowedException(final Long savingsId, final Long transactionId) { super("error.msg.saving.account.trasaction.update.notallowed", "Savings Account transaction update not allowed with savings identifier " + savingsId + " and trasaction identifier " - + transactionId, savingsId, transactionId); + + transactionId, + savingsId, transactionId); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateFixedDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateFixedDepositAccountCommandHandler.java index 8b8a2c798..437ad8109 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateFixedDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateFixedDepositAccountCommandHandler.java @@ -43,4 +43,4 @@ public class ActivateFixedDepositAccountCommandHandler implements NewCommandSour public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.activateFDAccount(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateRecurringDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateRecurringDepositAccountCommandHandler.java index f6634ad26..bab80747c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateRecurringDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateRecurringDepositAccountCommandHandler.java @@ -43,4 +43,4 @@ public class ActivateRecurringDepositAccountCommandHandler implements NewCommand public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.activateRDAccount(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateSavingsAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateSavingsAccountCommandHandler.java index 3f7d467ab..a7b9ba296 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateSavingsAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ActivateSavingsAccountCommandHandler.java @@ -43,4 +43,4 @@ public class ActivateSavingsAccountCommandHandler implements NewCommandSourceHan public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.activate(command.getSavingsId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/AddSavingsAccountChargeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/AddSavingsAccountChargeCommandHandler.java index c14967fc4..6e4b3f9c5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/AddSavingsAccountChargeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/AddSavingsAccountChargeCommandHandler.java @@ -44,4 +44,4 @@ public class AddSavingsAccountChargeCommandHandler implements NewCommandSourceHa return this.writePlatformService.addSavingsAccountCharge(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ApplyAnnualFeeSavingsAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ApplyAnnualFeeSavingsAccountCommandHandler.java index bf1253f1d..23af445c5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ApplyAnnualFeeSavingsAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/ApplyAnnualFeeSavingsAccountCommandHandler.java @@ -52,4 +52,4 @@ public class ApplyAnnualFeeSavingsAccountCommandHandler implements NewCommandSou // annualFeeTransactionDate); return null; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestFixedDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestFixedDepositAccountCommandHandler.java index d1549217d..81215b74c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestFixedDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestFixedDepositAccountCommandHandler.java @@ -44,4 +44,4 @@ public class CalculateInterestFixedDepositAccountCommandHandler implements NewCo public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.calculateInterest(command.entityId(), DepositAccountType.FIXED_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestRecurringDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestRecurringDepositAccountCommandHandler.java index 0d1856c99..199df549e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestRecurringDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestRecurringDepositAccountCommandHandler.java @@ -45,4 +45,4 @@ public class CalculateInterestRecurringDepositAccountCommandHandler implements N public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.calculateInterest(command.entityId(), DepositAccountType.RECURRING_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestSavingsAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestSavingsAccountCommandHandler.java index b91937b16..b05798542 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestSavingsAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CalculateInterestSavingsAccountCommandHandler.java @@ -43,4 +43,4 @@ public class CalculateInterestSavingsAccountCommandHandler implements NewCommand public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.calculateInterest(command.getSavingsId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseFixedDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseFixedDepositAccountCommandHandler.java index 8fba9dbf6..8b105b5a8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseFixedDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseFixedDepositAccountCommandHandler.java @@ -43,4 +43,4 @@ public class CloseFixedDepositAccountCommandHandler implements NewCommandSourceH public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.closeFDAccount(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseGSIMCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseGSIMCommandHandler.java index 9b88cee47..7e70c9ab9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseGSIMCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseGSIMCommandHandler.java @@ -28,13 +28,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - - @Service @CommandType(entity = "GSIMACCOUNT", action = "CLOSE") -public class CloseGSIMCommandHandler implements NewCommandSourceHandler -{ - +public class CloseGSIMCommandHandler implements NewCommandSourceHandler { private final SavingsAccountWritePlatformService writePlatformService; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseRecurringDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseRecurringDepositAccountCommandHandler.java index a2f16a330..c259d8499 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseRecurringDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CloseRecurringDepositAccountCommandHandler.java @@ -43,4 +43,4 @@ public class CloseRecurringDepositAccountCommandHandler implements NewCommandSou public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.closeRDAccount(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateFixedDepositProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateFixedDepositProductCommandHandler.java index 75d98a35e..5d2a5886d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateFixedDepositProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateFixedDepositProductCommandHandler.java @@ -41,4 +41,4 @@ public class CreateFixedDepositProductCommandHandler implements NewCommandSource public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.create(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateRecurringDepositProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateRecurringDepositProductCommandHandler.java index b051efc60..db60e07d2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateRecurringDepositProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateRecurringDepositProductCommandHandler.java @@ -41,4 +41,4 @@ public class CreateRecurringDepositProductCommandHandler implements NewCommandSo public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.create(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateSavingsProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateSavingsProductCommandHandler.java index 3df4c15cb..8ba4dfe3b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateSavingsProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/CreateSavingsProductCommandHandler.java @@ -41,4 +41,4 @@ public class CreateSavingsProductCommandHandler implements NewCommandSourceHandl public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.create(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteFixedDepositProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteFixedDepositProductCommandHandler.java index 57a094472..50594ecad 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteFixedDepositProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteFixedDepositProductCommandHandler.java @@ -41,4 +41,4 @@ public class DeleteFixedDepositProductCommandHandler implements NewCommandSource public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.delete(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteRecurringDepositProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteRecurringDepositProductCommandHandler.java index 42dba9bcb..b4d277c2a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteRecurringDepositProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteRecurringDepositProductCommandHandler.java @@ -41,4 +41,4 @@ public class DeleteRecurringDepositProductCommandHandler implements NewCommandSo public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.delete(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteSavingsAccountChargeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteSavingsAccountChargeCommandHandler.java index 0524eff32..af5941e78 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteSavingsAccountChargeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteSavingsAccountChargeCommandHandler.java @@ -44,4 +44,4 @@ public class DeleteSavingsAccountChargeCommandHandler implements NewCommandSourc return this.writePlatformService.deleteSavingsAccountCharge(command.getSavingsId(), command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteSavingsProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteSavingsProductCommandHandler.java index a2fa5e65c..113cb2a93 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteSavingsProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DeleteSavingsProductCommandHandler.java @@ -41,4 +41,4 @@ public class DeleteSavingsProductCommandHandler implements NewCommandSourceHandl public CommandProcessingResult processCommand(final JsonCommand command) { return this.savingProductWritePlatformService.delete(command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DepositSavingsAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DepositSavingsAccountCommandHandler.java index a71136b65..e3f3aa304 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DepositSavingsAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/DepositSavingsAccountCommandHandler.java @@ -43,4 +43,4 @@ public class DepositSavingsAccountCommandHandler implements NewCommandSourceHand public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.deposit(command.getSavingsId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationApprovalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationApprovalCommandHandler.java index 6b7beb612..90bac20d2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationApprovalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationApprovalCommandHandler.java @@ -45,4 +45,4 @@ public class FixedDepositAccountApplicationApprovalCommandHandler implements New public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.approveApplication(command.entityId(), command, DepositAccountType.FIXED_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationApprovalUndoCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationApprovalUndoCommandHandler.java index 2b45c7a25..3ed356e5f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationApprovalUndoCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationApprovalUndoCommandHandler.java @@ -46,4 +46,4 @@ public class FixedDepositAccountApplicationApprovalUndoCommandHandler implements return this.depositAccountWritePlatformService.undoApplicationApproval(command.entityId(), command, DepositAccountType.FIXED_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationDeletionCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationDeletionCommandHandler.java index b4e8a1124..078d95afb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationDeletionCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationDeletionCommandHandler.java @@ -45,4 +45,4 @@ public class FixedDepositAccountApplicationDeletionCommandHandler implements New public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.deleteApplication(command.entityId(), DepositAccountType.FIXED_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationModificationCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationModificationCommandHandler.java index 7330f6f7f..9bfe88caf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationModificationCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationModificationCommandHandler.java @@ -44,4 +44,4 @@ public class FixedDepositAccountApplicationModificationCommandHandler implements public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.modifyFDApplication(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationRejectedCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationRejectedCommandHandler.java index 339eec968..d6917c486 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationRejectedCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationRejectedCommandHandler.java @@ -45,4 +45,4 @@ public class FixedDepositAccountApplicationRejectedCommandHandler implements New public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.rejectApplication(command.entityId(), command, DepositAccountType.FIXED_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationSubmittalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationSubmittalCommandHandler.java index badad9f54..a9be193b7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationSubmittalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationSubmittalCommandHandler.java @@ -44,4 +44,4 @@ public class FixedDepositAccountApplicationSubmittalCommandHandler implements Ne public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.submitFDApplication(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationWithdrawnByApplicantCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationWithdrawnByApplicantCommandHandler.java index 529f7fa15..0555d88fa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationWithdrawnByApplicantCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountApplicationWithdrawnByApplicantCommandHandler.java @@ -46,4 +46,4 @@ public class FixedDepositAccountApplicationWithdrawnByApplicantCommandHandler im return this.depositAccountWritePlatformService.applicantWithdrawsFromApplication(command.entityId(), command, DepositAccountType.FIXED_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountDepositCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountDepositCommandHandler.java index 46bba980b..0fc699a34 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountDepositCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositAccountDepositCommandHandler.java @@ -43,4 +43,4 @@ public class FixedDepositAccountDepositCommandHandler implements NewCommandSourc public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.depositToFDAccount(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositTransactionAdjustmentCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositTransactionAdjustmentCommandHandler.java index c048b6aa5..ecfce2207 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositTransactionAdjustmentCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/FixedDepositTransactionAdjustmentCommandHandler.java @@ -44,4 +44,4 @@ public class FixedDepositTransactionAdjustmentCommandHandler implements NewComma final Long transactionId = Long.valueOf(command.getTransactionId()); return this.depositAccountWritePlatformService.adjustFDTransaction(command.entityId(), transactionId, command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMAccountActivationCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMAccountActivationCommandHandler.java index 819801937..d7e9bb3bf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMAccountActivationCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMAccountActivationCommandHandler.java @@ -31,18 +31,18 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "GSIMACCOUNT", action = "ACTIVATE") public class GSIMAccountActivationCommandHandler implements NewCommandSourceHandler { + private final SavingsAccountWritePlatformService savingAccountWritePlatformService; @Autowired - public GSIMAccountActivationCommandHandler( - final SavingsAccountWritePlatformService savingAccountWritePlatformService) { + public GSIMAccountActivationCommandHandler(final SavingsAccountWritePlatformService savingAccountWritePlatformService) { this.savingAccountWritePlatformService = savingAccountWritePlatformService; } @Transactional @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.savingAccountWritePlatformService.gsimActivate(command.getSavingsId(),command); + return this.savingAccountWritePlatformService.gsimActivate(command.getSavingsId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationApprovalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationApprovalCommandHandler.java index c4a9d60d2..0efbd8d0d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationApprovalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationApprovalCommandHandler.java @@ -30,20 +30,18 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "GSIMACCOUNT", action = "APPROVE") -public class GSIMApplicationApprovalCommandHandler implements NewCommandSourceHandler -{ +public class GSIMApplicationApprovalCommandHandler implements NewCommandSourceHandler { private final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService; @Autowired - public GSIMApplicationApprovalCommandHandler( - final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { + public GSIMApplicationApprovalCommandHandler(final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { this.savingAccountWritePlatformService = savingAccountWritePlatformService; } @Transactional @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.savingAccountWritePlatformService.approveGSIMApplication(command.getSavingsId(),command); + return this.savingAccountWritePlatformService.approveGSIMApplication(command.getSavingsId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationModificationCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationModificationCommandHandler.java index cac5ee820..5ebc45a7c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationModificationCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationModificationCommandHandler.java @@ -29,21 +29,20 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "GSIMACCOUNT", action = "UPDATE") -public class GSIMApplicationModificationCommandHandler implements NewCommandSourceHandler -{ +public class GSIMApplicationModificationCommandHandler implements NewCommandSourceHandler { - private final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService; + private final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService; - @Autowired - public GSIMApplicationModificationCommandHandler( - final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { - this.savingAccountWritePlatformService = savingAccountWritePlatformService; - } + @Autowired + public GSIMApplicationModificationCommandHandler( + final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { + this.savingAccountWritePlatformService = savingAccountWritePlatformService; + } - @Transactional - @Override - public CommandProcessingResult processCommand(final JsonCommand command) { - return this.savingAccountWritePlatformService.modifyGSIMApplication(command.entityId(), command); - } + @Transactional + @Override + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.savingAccountWritePlatformService.modifyGSIMApplication(command.entityId(), command); + } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationRejectionHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationRejectionHandler.java index 2f0c88fe9..c84ce1a5c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationRejectionHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationRejectionHandler.java @@ -28,24 +28,21 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - @Service @CommandType(entity = "GSIMACCOUNT", action = "REJECT") -public class GSIMApplicationRejectionHandler implements NewCommandSourceHandler -{ +public class GSIMApplicationRejectionHandler implements NewCommandSourceHandler { private final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService; @Autowired - public GSIMApplicationRejectionHandler( - final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { + public GSIMApplicationRejectionHandler(final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { this.savingAccountWritePlatformService = savingAccountWritePlatformService; } @Transactional @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.savingAccountWritePlatformService.rejectGSIMApplication(command.entityId(),command); + return this.savingAccountWritePlatformService.rejectGSIMApplication(command.entityId(), command); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationSubmittalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationSubmittalCommandHandler.java index 476f196e8..9a653130b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationSubmittalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMApplicationSubmittalCommandHandler.java @@ -29,15 +29,12 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "GSIMACCOUNT", action = "CREATE") -public class GSIMApplicationSubmittalCommandHandler implements NewCommandSourceHandler -{ - +public class GSIMApplicationSubmittalCommandHandler implements NewCommandSourceHandler { private final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService; @Autowired - public GSIMApplicationSubmittalCommandHandler( - final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { + public GSIMApplicationSubmittalCommandHandler(final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { this.savingAccountWritePlatformService = savingAccountWritePlatformService; } @@ -46,4 +43,4 @@ public class GSIMApplicationSubmittalCommandHandler implements NewCommandSource public CommandProcessingResult processCommand(final JsonCommand command) { return this.savingAccountWritePlatformService.submitGSIMApplication(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMDepositCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMDepositCommandHandler.java index 342871581..b2bc49479 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMDepositCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMDepositCommandHandler.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.fineract.portfolio.savings.handler; import org.apache.fineract.commands.annotation.CommandType; @@ -29,7 +28,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - @Service @CommandType(entity = "GSIMACCOUNT", action = "DEPOSIT") public class GSIMDepositCommandHandler implements NewCommandSourceHandler { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMUndoApprovalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMUndoApprovalCommandHandler.java index 09e8e4c8a..1a62fd439 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMUndoApprovalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/GSIMUndoApprovalCommandHandler.java @@ -28,11 +28,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - @Service @CommandType(entity = "GSIMACCOUNT", action = "APPROVALUNDO") -public class GSIMUndoApprovalCommandHandler implements NewCommandSourceHandler -{ +public class GSIMUndoApprovalCommandHandler implements NewCommandSourceHandler { private final SavingsApplicationProcessWritePlatformService writePlatformService; @@ -48,4 +46,4 @@ public class GSIMUndoApprovalCommandHandler implements NewCommandSourceHandler return this.writePlatformService.undoGSIMApplicationApproval(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PaySavingsAccountChargeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PaySavingsAccountChargeCommandHandler.java index ab3a5854d..e0e28091d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PaySavingsAccountChargeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PaySavingsAccountChargeCommandHandler.java @@ -44,4 +44,4 @@ public class PaySavingsAccountChargeCommandHandler implements NewCommandSourceHa return this.writePlatformService.payCharge(command.getSavingsId(), command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestFixedDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestFixedDepositAccountCommandHandler.java index 9a0eed1b2..507470f33 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestFixedDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestFixedDepositAccountCommandHandler.java @@ -44,4 +44,4 @@ public class PostInterestFixedDepositAccountCommandHandler implements NewCommand public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.postInterest(command.entityId(), DepositAccountType.FIXED_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestRecurringDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestRecurringDepositAccountCommandHandler.java index 96e05ecab..3822733db 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestRecurringDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestRecurringDepositAccountCommandHandler.java @@ -44,4 +44,4 @@ public class PostInterestRecurringDepositAccountCommandHandler implements NewCom public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.postInterest(command.entityId(), DepositAccountType.RECURRING_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestSavingsAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestSavingsAccountCommandHandler.java index 7ff81d070..434c7d541 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestSavingsAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PostInterestSavingsAccountCommandHandler.java @@ -43,4 +43,4 @@ public class PostInterestSavingsAccountCommandHandler implements NewCommandSourc public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.postInterest(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PrematureCloseFixedDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PrematureCloseFixedDepositAccountCommandHandler.java index b403c4bac..cb509a3a7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PrematureCloseFixedDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PrematureCloseFixedDepositAccountCommandHandler.java @@ -43,4 +43,4 @@ public class PrematureCloseFixedDepositAccountCommandHandler implements NewComma public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.prematureCloseFDAccount(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PrematureCloseRecurringDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PrematureCloseRecurringDepositAccountCommandHandler.java index 2f164316f..15044fe43 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PrematureCloseRecurringDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/PrematureCloseRecurringDepositAccountCommandHandler.java @@ -34,7 +34,8 @@ public class PrematureCloseRecurringDepositAccountCommandHandler implements NewC private final DepositAccountWritePlatformService depositAccountWritePlatformService; @Autowired - public PrematureCloseRecurringDepositAccountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { + public PrematureCloseRecurringDepositAccountCommandHandler( + final DepositAccountWritePlatformService depositAccountWritePlatformService) { this.depositAccountWritePlatformService = depositAccountWritePlatformService; } @@ -43,4 +44,4 @@ public class PrematureCloseRecurringDepositAccountCommandHandler implements NewC public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.prematureCloseRDAccount(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationApprovalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationApprovalCommandHandler.java index 9aaae929e..1d96193d0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationApprovalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationApprovalCommandHandler.java @@ -43,7 +43,7 @@ public class RecurringDepositAccountApplicationApprovalCommandHandler implements @Transactional @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return this.depositAccountWritePlatformService - .approveApplication(command.entityId(), command, DepositAccountType.RECURRING_DEPOSIT); + return this.depositAccountWritePlatformService.approveApplication(command.entityId(), command, + DepositAccountType.RECURRING_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationApprovalUndoCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationApprovalUndoCommandHandler.java index a869ba3f4..44df9527d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationApprovalUndoCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationApprovalUndoCommandHandler.java @@ -46,4 +46,4 @@ public class RecurringDepositAccountApplicationApprovalUndoCommandHandler implem return this.depositAccountWritePlatformService.undoApplicationApproval(command.entityId(), command, DepositAccountType.RECURRING_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationDeletionCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationDeletionCommandHandler.java index c62d37013..e40de701f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationDeletionCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationDeletionCommandHandler.java @@ -45,4 +45,4 @@ public class RecurringDepositAccountApplicationDeletionCommandHandler implements public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.deleteApplication(command.entityId(), DepositAccountType.RECURRING_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationModificationCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationModificationCommandHandler.java index 34aa93c95..24ffc2559 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationModificationCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationModificationCommandHandler.java @@ -44,4 +44,4 @@ public class RecurringDepositAccountApplicationModificationCommandHandler implem public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.modifyRDApplication(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationRejectedCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationRejectedCommandHandler.java index 5a59d6685..4bdfa3c3d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationRejectedCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationRejectedCommandHandler.java @@ -45,4 +45,4 @@ public class RecurringDepositAccountApplicationRejectedCommandHandler implements public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.rejectApplication(command.entityId(), command, DepositAccountType.RECURRING_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationSubmittalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationSubmittalCommandHandler.java index 181c34969..b3b19e640 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationSubmittalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationSubmittalCommandHandler.java @@ -44,4 +44,4 @@ public class RecurringDepositAccountApplicationSubmittalCommandHandler implement public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.submitRDApplication(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationWithdrawnByApplicantCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationWithdrawnByApplicantCommandHandler.java index 357893feb..fa7f701df 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationWithdrawnByApplicantCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountApplicationWithdrawnByApplicantCommandHandler.java @@ -46,4 +46,4 @@ public class RecurringDepositAccountApplicationWithdrawnByApplicantCommandHandle return this.depositAccountWritePlatformService.applicantWithdrawsFromApplication(command.entityId(), command, DepositAccountType.RECURRING_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountDepositCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountDepositCommandHandler.java index eeaa108dc..8b9cfc9f2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountDepositCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountDepositCommandHandler.java @@ -43,4 +43,4 @@ public class RecurringDepositAccountDepositCommandHandler implements NewCommandS public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.depositToRDAccount(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountUpdateDepositAmountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountUpdateDepositAmountCommandHandler.java index 4419f273d..b7155f148 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountUpdateDepositAmountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositAccountUpdateDepositAmountCommandHandler.java @@ -44,4 +44,4 @@ public class RecurringDepositAccountUpdateDepositAmountCommandHandler implements public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.updateDepositAmountForRDAccount(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositTransactionAdjustmentCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositTransactionAdjustmentCommandHandler.java index 748617e17..a97ac0803 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositTransactionAdjustmentCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/RecurringDepositTransactionAdjustmentCommandHandler.java @@ -34,7 +34,8 @@ public class RecurringDepositTransactionAdjustmentCommandHandler implements NewC private final DepositAccountWritePlatformService depositAccountWritePlatformService; @Autowired - public RecurringDepositTransactionAdjustmentCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { + public RecurringDepositTransactionAdjustmentCommandHandler( + final DepositAccountWritePlatformService depositAccountWritePlatformService) { this.depositAccountWritePlatformService = depositAccountWritePlatformService; } @@ -44,4 +45,4 @@ public class RecurringDepositTransactionAdjustmentCommandHandler implements NewC final Long transactionId = Long.valueOf(command.getTransactionId()); return this.depositAccountWritePlatformService.adjustRDTransaction(command.entityId(), transactionId, command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationApprovalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationApprovalCommandHandler.java index 32e8982a5..6e8db21fc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationApprovalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationApprovalCommandHandler.java @@ -44,4 +44,4 @@ public class SavingsAccountApplicationApprovalCommandHandler implements NewComma return this.writePlatformService.approveApplication(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationApprovalUndoCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationApprovalUndoCommandHandler.java index d074f17ae..c638938c3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationApprovalUndoCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationApprovalUndoCommandHandler.java @@ -44,4 +44,4 @@ public class SavingsAccountApplicationApprovalUndoCommandHandler implements NewC return this.writePlatformService.undoApplicationApproval(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationModificationCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationModificationCommandHandler.java index 3450740d3..3ac279bf4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationModificationCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationModificationCommandHandler.java @@ -44,4 +44,4 @@ public class SavingsAccountApplicationModificationCommandHandler implements NewC public CommandProcessingResult processCommand(final JsonCommand command) { return this.savingAccountWritePlatformService.modifyApplication(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationRejectedCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationRejectedCommandHandler.java index cc0ace00b..353cd72c0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationRejectedCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationRejectedCommandHandler.java @@ -44,4 +44,4 @@ public class SavingsAccountApplicationRejectedCommandHandler implements NewComma return this.writePlatformService.rejectApplication(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationSubmittalCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationSubmittalCommandHandler.java index c0a73ec57..846deddea 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationSubmittalCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationSubmittalCommandHandler.java @@ -44,4 +44,4 @@ public class SavingsAccountApplicationSubmittalCommandHandler implements NewComm public CommandProcessingResult processCommand(final JsonCommand command) { return this.savingAccountWritePlatformService.submitApplication(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationWithdrawnByApplicantCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationWithdrawnByApplicantCommandHandler.java index 223e2d371..9c165f0a9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationWithdrawnByApplicantCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/SavingsAccountApplicationWithdrawnByApplicantCommandHandler.java @@ -45,4 +45,4 @@ public class SavingsAccountApplicationWithdrawnByApplicantCommandHandler impleme return this.writePlatformService.applicantWithdrawsFromApplication(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionFixedDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionFixedDepositAccountCommandHandler.java index 20ade559e..76f3b6a07 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionFixedDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionFixedDepositAccountCommandHandler.java @@ -44,4 +44,4 @@ public class UndoTransactionFixedDepositAccountCommandHandler implements NewComm final Long transactionId = Long.valueOf(command.getTransactionId()); return this.depositAccountWritePlatformService.undoFDTransaction(command.entityId(), transactionId, false); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionRecurringDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionRecurringDepositAccountCommandHandler.java index 53ae3301b..76e054c82 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionRecurringDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionRecurringDepositAccountCommandHandler.java @@ -34,7 +34,8 @@ public class UndoTransactionRecurringDepositAccountCommandHandler implements New private final DepositAccountWritePlatformService depositAccountWritePlatformService; @Autowired - public UndoTransactionRecurringDepositAccountCommandHandler(final DepositAccountWritePlatformService depositAccountWritePlatformService) { + public UndoTransactionRecurringDepositAccountCommandHandler( + final DepositAccountWritePlatformService depositAccountWritePlatformService) { this.depositAccountWritePlatformService = depositAccountWritePlatformService; } @@ -44,4 +45,4 @@ public class UndoTransactionRecurringDepositAccountCommandHandler implements New final Long transactionId = Long.valueOf(command.getTransactionId()); return this.depositAccountWritePlatformService.undoRDTransaction(command.entityId(), transactionId, false); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionSavingsAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionSavingsAccountCommandHandler.java index 338a85402..084cbac32 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionSavingsAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UndoTransactionSavingsAccountCommandHandler.java @@ -44,4 +44,4 @@ public class UndoTransactionSavingsAccountCommandHandler implements NewCommandSo final Long transactionId = Long.valueOf(command.getTransactionId()); return this.writePlatformService.undoTransaction(command.getSavingsId(), transactionId, false); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateFixedDepositProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateFixedDepositProductCommandHandler.java index 8bd7a542c..b7be725ac 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateFixedDepositProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateFixedDepositProductCommandHandler.java @@ -41,4 +41,4 @@ public class UpdateFixedDepositProductCommandHandler implements NewCommandSource public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.update(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateRecurringDepositProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateRecurringDepositProductCommandHandler.java index f2239cb62..826a8627c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateRecurringDepositProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateRecurringDepositProductCommandHandler.java @@ -41,4 +41,4 @@ public class UpdateRecurringDepositProductCommandHandler implements NewCommandSo public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.update(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateSavingsAccountChargeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateSavingsAccountChargeCommandHandler.java index 1f6182c24..5c43d709a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateSavingsAccountChargeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateSavingsAccountChargeCommandHandler.java @@ -44,4 +44,4 @@ public class UpdateSavingsAccountChargeCommandHandler implements NewCommandSourc return this.writePlatformService.updateSavingsAccountCharge(command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateSavingsProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateSavingsProductCommandHandler.java index 470740ec3..a7cffd38d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateSavingsProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateSavingsProductCommandHandler.java @@ -41,4 +41,4 @@ public class UpdateSavingsProductCommandHandler implements NewCommandSourceHandl public CommandProcessingResult processCommand(final JsonCommand command) { return this.savingProductWritePlatformService.update(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateWithHoldTaxSavingsAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateWithHoldTaxSavingsAccountCommandHandler.java index ce0f91882..e8e1e6b05 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateWithHoldTaxSavingsAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/UpdateWithHoldTaxSavingsAccountCommandHandler.java @@ -43,4 +43,4 @@ public class UpdateWithHoldTaxSavingsAccountCommandHandler implements NewCommand public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.modifyWithHoldTax(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WaiveSavingsAccountChargeCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WaiveSavingsAccountChargeCommandHandler.java index cd193caf0..e361ac77d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WaiveSavingsAccountChargeCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WaiveSavingsAccountChargeCommandHandler.java @@ -44,4 +44,4 @@ public class WaiveSavingsAccountChargeCommandHandler implements NewCommandSource return this.writePlatformService.waiveCharge(command.getSavingsId(), command.entityId()); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawSavingsAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawSavingsAccountCommandHandler.java index 2faea4083..cba0c1f23 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawSavingsAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawSavingsAccountCommandHandler.java @@ -43,4 +43,4 @@ public class WithdrawSavingsAccountCommandHandler implements NewCommandSourceHan public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.withdrawal(command.getSavingsId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawalFixedDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawalFixedDepositAccountCommandHandler.java index 97e3a0ae8..1de312544 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawalFixedDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawalFixedDepositAccountCommandHandler.java @@ -44,4 +44,4 @@ public class WithdrawalFixedDepositAccountCommandHandler implements NewCommandSo public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.withdrawal(command.entityId(), command, DepositAccountType.FIXED_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawalRecurringDepositAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawalRecurringDepositAccountCommandHandler.java index 44324ac74..d904035b8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawalRecurringDepositAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/handler/WithdrawalRecurringDepositAccountCommandHandler.java @@ -44,4 +44,4 @@ public class WithdrawalRecurringDepositAccountCommandHandler implements NewComma public CommandProcessingResult processCommand(final JsonCommand command) { return this.depositAccountWritePlatformService.withdrawal(command.entityId(), command, DepositAccountType.RECURRING_DEPOSIT); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountInterestRateChartReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountInterestRateChartReadPlatformServiceImpl.java index cce44755a..d76b10dff 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountInterestRateChartReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountInterestRateChartReadPlatformServiceImpl.java @@ -173,8 +173,8 @@ public class DepositAccountInterestRateChartReadPlatformServiceImpl implements D clientClassificationOptions); } - private static final class DepositAccountInterestRateChartExtractor implements - ResultSetExtractor> { + private static final class DepositAccountInterestRateChartExtractor + implements ResultSetExtractor> { DepositAccountInterestRateChartMapper chartMapper = new DepositAccountInterestRateChartMapper(); InterestRateChartSlabExtractor chartSlabsMapper = new InterestRateChartSlabExtractor(); @@ -188,8 +188,7 @@ public class DepositAccountInterestRateChartReadPlatformServiceImpl implements D private DepositAccountInterestRateChartExtractor() { final StringBuilder sqlBuilder = new StringBuilder(400); - sqlBuilder - .append("irc.id as ircId, irc.name as ircName, irc.description as ircDescription,") + sqlBuilder.append("irc.id as ircId, irc.name as ircName, irc.description as ircDescription,") .append("irc.from_date as ircFromDate, irc.end_date as ircEndDate, ") .append("irc.is_primary_grouping_by_amount as isPrimaryGroupingByAmount,") .append("ircd.id as ircdId, ircd.description as ircdDescription, ircd.period_type_enum ircdPeriodTypeId, ") @@ -197,12 +196,10 @@ public class DepositAccountInterestRateChartReadPlatformServiceImpl implements D .append("ircd.amount_range_to as ircdAmountRangeTo, ircd.annual_interest_rate as ircdAnnualInterestRate, ") .append("curr.code as currencyCode, curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ") .append("curr.display_symbol as currencyDisplaySymbol, curr.decimal_places as currencyDigits, curr.currency_multiplesof as inMultiplesOf, ") - .append("sa.id as accountId, sa.account_no as accountNumber, ") - .append("iri.id as iriId, ") + .append("sa.id as accountId, sa.account_no as accountNumber, ").append("iri.id as iriId, ") .append(" iri.entiry_type as entityType, iri.attribute_name as attributeName ,") .append(" iri.condition_type as conditionType, iri.attribute_value as attributeValue, ") - .append(" iri.incentive_type as incentiveType, iri.amount as amount, ") - .append("code.code_value as attributeValueDesc ") + .append(" iri.incentive_type as incentiveType, iri.amount as amount, ").append("code.code_value as attributeValueDesc ") .append("from ") .append("m_savings_account_interest_rate_chart irc left join m_savings_account_interest_rate_slab ircd on irc.id=ircd.savings_account_interest_rate_chart_id ") .append(" left join m_savings_interest_incentives iri on iri.deposit_account_interest_rate_slab_id =ircd.id ") @@ -364,8 +361,8 @@ public class DepositAccountInterestRateChartReadPlatformServiceImpl implements D final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); // currency - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); return DepositAccountInterestRateChartSlabData.instance(id, description, periodType, fromPeriod, toPeriod, amountRangeFrom, amountRangeTo, annualInterestRate, currency); @@ -404,4 +401,4 @@ public class DepositAccountInterestRateChartReadPlatformServiceImpl implements D } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountOnHoldTransactionReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountOnHoldTransactionReadPlatformServiceImpl.java old mode 100755 new mode 100644 index ef1322112..ca95c893b --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountOnHoldTransactionReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountOnHoldTransactionReadPlatformServiceImpl.java @@ -54,7 +54,8 @@ public class DepositAccountOnHoldTransactionReadPlatformServiceImpl implements D } @Override - public Page retriveAll(Long savingsId, Long guarantorFundingId, SearchParameters searchParameters) { + public Page retriveAll(Long savingsId, Long guarantorFundingId, + SearchParameters searchParameters) { final StringBuilder sqlBuilder = new StringBuilder(200); List paramObj = new ArrayList<>(2); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountPreMatureCalculationPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountPreMatureCalculationPlatformServiceImpl.java index 85760588e..46f971223 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountPreMatureCalculationPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountPreMatureCalculationPlatformServiceImpl.java @@ -86,8 +86,8 @@ public class DepositAccountPreMatureCalculationPlatformServiceImpl implements De .depositAccountOnClosureType(new DepositAccountOnClosureType[] { DepositAccountOnClosureType.WITHDRAW_DEPOSIT, DepositAccountOnClosureType.TRANSFER_TO_SAVINGS }); final Collection paymentTypeOptions = this.paymentTypeReadPlatformService.retrieveAllPaymentTypes(); - final Collection savingsAccountDatas = this.savingsAccountReadPlatformService.retrieveActiveForLookup( - account.clientId(), DepositAccountType.SAVINGS_DEPOSIT); + final Collection savingsAccountDatas = this.savingsAccountReadPlatformService + .retrieveActiveForLookup(account.clientId(), DepositAccountType.SAVINGS_DEPOSIT); final JsonElement element = this.fromJsonHelper.parse(query.json()); final LocalDate preMaturityDate = this.fromJsonHelper.extractLocalDateNamed(closedOnDateParamName, element); // calculate interest before one day of closure date @@ -96,16 +96,18 @@ public class DepositAccountPreMatureCalculationPlatformServiceImpl implements De if (depositAccountType.isFixedDeposit()) { final FixedDepositAccount fd = (FixedDepositAccount) account; - accountData = FixedDepositAccountData.preClosureDetails(account.getId(), fd.calculatePreMatureAmount(interestCalculatedToDate, - isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth), onAccountClosureOptions, - paymentTypeOptions, savingsAccountDatas); + accountData = FixedDepositAccountData.preClosureDetails( + account.getId(), fd.calculatePreMatureAmount(interestCalculatedToDate, isPreMatureClosure, + isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth), + onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas); } else if (depositAccountType.isRecurringDeposit()) { final RecurringDepositAccount rd = (RecurringDepositAccount) account; - accountData = RecurringDepositAccountData.preClosureDetails(account.getId(), rd.calculatePreMatureAmount( - interestCalculatedToDate, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth), + accountData = RecurringDepositAccountData.preClosureDetails( + account.getId(), rd.calculatePreMatureAmount(interestCalculatedToDate, isPreMatureClosure, + isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth), onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas); } return accountData; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountReadPlatformService.java index 554007ba8..521271025 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountReadPlatformService.java @@ -29,7 +29,8 @@ import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionData; public interface DepositAccountReadPlatformService { - Collection retrieveAll(final DepositAccountType depositAccountType, final PaginationParameters paginationParameters); + Collection retrieveAll(final DepositAccountType depositAccountType, + final PaginationParameters paginationParameters); Page retrieveAllPaged(final DepositAccountType depositAccountType, final PaginationParameters paginationParameters); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountReadPlatformServiceImpl.java index cc3b3ccee..a54431b96 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountReadPlatformServiceImpl.java @@ -124,8 +124,7 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead private final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); private final PaymentTypeReadPlatformService paymentTypeReadPlatformService; // allowed column names for sorting the query result - private final static Set supportedOrderByValues = new HashSet<>(Arrays.asList("id", "accountNumbr", - "officeId", "officeName")); + private final static Set supportedOrderByValues = new HashSet<>(Arrays.asList("id", "accountNumbr", "officeId", "officeName")); @Autowired public DepositAccountReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, @@ -166,9 +165,7 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead this.context.authenticatedUser(); final DepositAccountMapper depositAccountMapper = this.getDepositAccountMapper(depositAccountType); - if (depositAccountMapper == null) { - return null; - } + if (depositAccountMapper == null) { return null; } final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("select "); @@ -188,9 +185,7 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead depositAccountType.resourceName()); final DepositAccountMapper depositAccountMapper = this.getDepositAccountMapper(depositAccountType); - if (depositAccountMapper == null) { - return null; - } + if (depositAccountMapper == null) { return null; } final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); @@ -226,9 +221,7 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead LocalDate today = DateUtils.getLocalDateOfTenant(); - return this.jdbcTemplate.query( - sqlBuilder.toString(), - this.depositAccountForMaturityRowMapper, + return this.jdbcTemplate.query(sqlBuilder.toString(), this.depositAccountForMaturityRowMapper, new Object[] { formatter.print(today), DepositAccountType.FIXED_DEPOSIT.getValue(), DepositAccountType.RECURRING_DEPOSIT.getValue(), SavingsAccountStatusType.ACTIVE.getValue() }); } @@ -239,17 +232,15 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead this.context.authenticatedUser(); final DepositAccountMapper depositAccountMapper = this.getDepositAccountMapper(depositAccountType); - if (depositAccountMapper == null) { - return null; - } + if (depositAccountMapper == null) { return null; } final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("select "); sqlBuilder.append(depositAccountMapper.schema()); sqlBuilder.append(" where sa.id = ? and sa.deposit_type_enum = ? "); - return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), depositAccountMapper, new Object[] { accountId, - depositAccountType.getValue() }); + return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), depositAccountMapper, + new Object[] { accountId, depositAccountType.getValue() }); } catch (final EmptyResultDataAccessException e) { throw new DepositAccountNotFoundException(depositAccountType, accountId); @@ -262,22 +253,20 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead this.context.authenticatedUser(); final DepositAccountMapper depositAccountMapper = this.getDepositAccountMapper(depositAccountType); - if (depositAccountMapper == null) { - return null; - } + if (depositAccountMapper == null) { return null; } final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("select "); sqlBuilder.append(depositAccountMapper.schema()); sqlBuilder.append(" where sa.id = ? and sa.deposit_type_enum = ? "); - DepositAccountData account = this.jdbcTemplate.queryForObject(sqlBuilder.toString(), depositAccountMapper, new Object[] { - accountId, depositAccountType.getValue() }); + DepositAccountData account = this.jdbcTemplate.queryForObject(sqlBuilder.toString(), depositAccountMapper, + new Object[] { accountId, depositAccountType.getValue() }); Collection onAccountClosureOptions = SavingsEnumerations .depositAccountOnClosureType(DepositAccountOnClosureType.values()); final Collection paymentTypeOptions = this.paymentTypeReadPlatformService.retrieveAllPaymentTypes(); - final Collection savingsAccountDatas = this.savingsAccountReadPlatformService.retrieveActiveForLookup( - account.clientId(), DepositAccountType.SAVINGS_DEPOSIT); + final Collection savingsAccountDatas = this.savingsAccountReadPlatformService + .retrieveActiveForLookup(account.clientId(), DepositAccountType.SAVINGS_DEPOSIT); if (depositAccountType.isFixedDeposit()) { account = FixedDepositAccountData.withClosureTemplateDetails((FixedDepositAccountData) account, onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas); @@ -384,9 +373,11 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final Collection charges = fromChargesToSavingsCharges(productCharges); final boolean feeChargesOnly = false; - final Collection chargeOptions = this.chargeReadPlatformService.retrieveSavingsProductApplicableCharges(feeChargesOnly); + final Collection chargeOptions = this.chargeReadPlatformService + .retrieveSavingsProductApplicableCharges(feeChargesOnly); - final Collection maturityInstructionOptions = this.depositsDropdownReadPlatformService.maturityInstructionOptions(); + final Collection maturityInstructionOptions = this.depositsDropdownReadPlatformService + .maturityInstructionOptions(); Collection fieldOfficerOptions = null; @@ -415,7 +406,7 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead } // retrieve chart Slabs - final InterestRateChartData productChartData = this.productChartReadPlatformService.retrieveActiveChartWithTemplate(productId); + final InterestRateChartData productChartData = this.productChartReadPlatformService.retrieveActiveChartWithTemplate(productId); final DepositAccountInterestRateChartData accountChart = DepositAccountInterestRateChartData.from(productChartData); if (depositAccountType.isFixedDeposit()) { @@ -460,10 +451,11 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final Collection transactions = null; final Collection charges = null; - final Collection maturityInstructionOptions = null; + final Collection maturityInstructionOptions = null; final boolean feeChargesOnly = true; - final Collection chargeOptions = this.chargeReadPlatformService.retrieveSavingsProductApplicableCharges(feeChargesOnly); + final Collection chargeOptions = this.chargeReadPlatformService + .retrieveSavingsProductApplicableCharges(feeChargesOnly); if (depositAccountType.isFixedDeposit()) { @@ -495,8 +487,8 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead try { final String sql = "select " + this.rdTransactionTemplateMapper.schema() + " where sa.id = ? and sa.deposit_type_enum = ? order by mss.installment limit 1"; - return this.jdbcTemplate.queryForObject(sql, this.rdTransactionTemplateMapper, new Object[] { accountId, accountId, - DepositAccountType.RECURRING_DEPOSIT.getValue() }); + return this.jdbcTemplate.queryForObject(sql, this.rdTransactionTemplateMapper, + new Object[] { accountId, accountId, DepositAccountType.RECURRING_DEPOSIT.getValue() }); } catch (final EmptyResultDataAccessException e) { throw new DepositAccountNotFoundException(DepositAccountType.RECURRING_DEPOSIT, accountId); } @@ -509,10 +501,10 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead sqlBuilder.append("SELECT "); sqlBuilder.append(mapper.schema()); sqlBuilder.append(" where da.transfer_interest_to_linked_account = 1 and "); - sqlBuilder - .append("st.transaction_date > (select IFNULL(max(sat.transaction_date),sa.activatedon_date) from m_savings_account_transaction sat where sat.transaction_type_enum = ? and sat.savings_account_id = sa.id and sat.is_reversed=0) "); - sqlBuilder - .append("and st.transaction_type_enum = ? and sa.status_enum = ? and st.is_reversed=0 and st.transaction_date > IFNULL(sa.lockedin_until_date_derived,sa.activatedon_date)"); + sqlBuilder.append( + "st.transaction_date > (select IFNULL(max(sat.transaction_date),sa.activatedon_date) from m_savings_account_transaction sat where sat.transaction_type_enum = ? and sat.savings_account_id = sa.id and sat.is_reversed=0) "); + sqlBuilder.append( + "and st.transaction_type_enum = ? and sa.status_enum = ? and st.is_reversed=0 and st.transaction_date > IFNULL(sa.lockedin_until_date_derived,sa.activatedon_date)"); return this.jdbcTemplate.query(sqlBuilder.toString(), mapper, new Object[] { SavingsAccountTransactionType.WITHDRAWAL.getValue(), SavingsAccountTransactionType.INTEREST_POSTING.getValue(), SavingsAccountStatusType.ACTIVE.getValue() }); @@ -573,8 +565,8 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead selectFieldsSqlBuilder.append("sa.closedon_date as closedOnDate,"); selectFieldsSqlBuilder.append("cbu.username as closedByUsername,"); selectFieldsSqlBuilder.append("cbu.firstname as closedByFirstname, cbu.lastname as closedByLastname,"); - selectFieldsSqlBuilder - .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); + selectFieldsSqlBuilder.append( + "sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); selectFieldsSqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); selectFieldsSqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); selectFieldsSqlBuilder.append("sa.nominal_annual_interest_rate as nominalAnnualInterestRate, "); @@ -601,7 +593,6 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead selectFieldsSqlBuilder.append("sa.withhold_tax as withHoldTax,"); selectFieldsSqlBuilder.append("tg.id as taxGroupId, tg.name as taxGroupName "); - this.selectFieldsSql = selectFieldsSqlBuilder.toString(); final StringBuilder selectTablesSqlBuilder = new StringBuilder(400); @@ -684,11 +675,10 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final String closedByLastname = rs.getString("closedByLastname"); final SavingsAccountApplicationTimelineData timeline = new SavingsAccountApplicationTimelineData(submittedOnDate, - submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, - rejectedByFirstname, rejectedByLastname, withdrawnOnDate, withdrawnByUsername, withdrawnByFirstname, - withdrawnByLastname, approvedOnDate, approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, - activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, - closedByLastname); + submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, rejectedByFirstname, + rejectedByLastname, withdrawnOnDate, withdrawnByUsername, withdrawnByFirstname, withdrawnByLastname, approvedOnDate, + approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, activatedByUsername, activatedByFirstname, + activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, closedByLastname); final Integer depositTypeId = JdbcSupport.getInteger(rs, "depositTypeId"); final EnumOptionData depositType = (depositTypeId == null) ? null : SavingsEnumerations.depositType(depositTypeId); @@ -699,24 +689,22 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final BigDecimal nominalAnnualInterestRate = rs.getBigDecimal("nominalAnnualInterestRate"); - final EnumOptionData interestCompoundingPeriodType = SavingsEnumerations - .compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, - "interestCompoundingPeriodType"))); + final EnumOptionData interestCompoundingPeriodType = SavingsEnumerations.compoundingInterestPeriodType( + SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, "interestCompoundingPeriodType"))); - final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType - .fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType"))); + final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType( + SavingsPostingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType"))); - final EnumOptionData interestCalculationType = SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType - .fromInt(JdbcSupport.getInteger(rs, "interestCalculationType"))); + final EnumOptionData interestCalculationType = SavingsEnumerations + .interestCalculationType(SavingsInterestCalculationType.fromInt(JdbcSupport.getInteger(rs, "interestCalculationType"))); - final EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations - .interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs, - "interestCalculationDaysInYearType"))); + final EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations.interestCalculationDaysInYearType( + SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs, "interestCalculationDaysInYearType"))); final BigDecimal minRequiredOpeningBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "minRequiredOpeningBalance"); @@ -809,38 +797,37 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final boolean preClosurePenalApplicable = rs.getBoolean("preClosurePenalApplicable"); final BigDecimal preClosurePenalInterest = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "preClosurePenalInterest"); final Integer preClosurePenalInterestOnTypeId = JdbcSupport.getInteger(rs, "preClosurePenalInterestOnId"); - final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null : SavingsEnumerations - .preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); + final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null + : SavingsEnumerations.preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); final Integer minDepositTerm = JdbcSupport.getInteger(rs, "minDepositTerm"); final Integer maxDepositTerm = JdbcSupport.getInteger(rs, "maxDepositTerm"); final Integer minDepositTermTypeId = JdbcSupport.getInteger(rs, "minDepositTermTypeId"); - final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(minDepositTermTypeId); + final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(minDepositTermTypeId); final Integer maxDepositTermTypeId = JdbcSupport.getInteger(rs, "maxDepositTermTypeId"); - final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(maxDepositTermTypeId); + final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(maxDepositTermTypeId); final Integer inMultiplesOfDepositTerm = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTerm"); final Integer inMultiplesOfDepositTermTypeId = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTermTypeId"); - final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(inMultiplesOfDepositTermTypeId); + final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(inMultiplesOfDepositTermTypeId); final BigDecimal depositAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "depositAmount"); final BigDecimal maturityAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "maturityAmount"); final LocalDate maturityDate = JdbcSupport.getLocalDate(rs, "maturityDate"); final Integer depositPeriod = JdbcSupport.getInteger(rs, "depositPeriod"); final Integer depositPeriodFrequencyTypeId = JdbcSupport.getInteger(rs, "depositPeriodFrequencyTypeId"); - final EnumOptionData depositPeriodFrequencyType = (depositPeriodFrequencyTypeId == null) ? null : SavingsEnumerations - .depositPeriodFrequency(depositPeriodFrequencyTypeId); + final EnumOptionData depositPeriodFrequencyType = (depositPeriodFrequencyTypeId == null) ? null + : SavingsEnumerations.depositPeriodFrequency(depositPeriodFrequencyTypeId); final Integer onAccountClosureId = JdbcSupport.getInteger(rs, "onAccountClosureId"); - final EnumOptionData onAccountClosureType = (onAccountClosureId == null) ? null : SavingsEnumerations - .depositAccountOnClosureType(onAccountClosureId); + final EnumOptionData onAccountClosureType = (onAccountClosureId == null) ? null + : SavingsEnumerations.depositAccountOnClosureType(onAccountClosureId); final Boolean transferInterestToSavings = rs.getBoolean("transferInterestToSavings"); final Long transferToSavingsId = JdbcSupport.getLong(rs, "transferToSavingsId"); - return FixedDepositAccountData.instance(depositAccountData, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, depositAmount, maturityAmount, maturityDate, depositPeriod, @@ -899,28 +886,28 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final boolean preClosurePenalApplicable = rs.getBoolean("preClosurePenalApplicable"); final BigDecimal preClosurePenalInterest = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "preClosurePenalInterest"); final Integer preClosurePenalInterestOnTypeId = JdbcSupport.getInteger(rs, "preClosurePenalInterestOnId"); - final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null : SavingsEnumerations - .preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); + final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null + : SavingsEnumerations.preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); final Integer minDepositTerm = JdbcSupport.getInteger(rs, "minDepositTerm"); final Integer maxDepositTerm = JdbcSupport.getInteger(rs, "maxDepositTerm"); final Integer minDepositTermTypeId = JdbcSupport.getInteger(rs, "minDepositTermTypeId"); - final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(minDepositTermTypeId); + final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(minDepositTermTypeId); final Integer maxDepositTermTypeId = JdbcSupport.getInteger(rs, "maxDepositTermTypeId"); - final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(maxDepositTermTypeId); + final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(maxDepositTermTypeId); final Integer inMultiplesOfDepositTerm = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTerm"); final Integer inMultiplesOfDepositTermTypeId = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTermTypeId"); - final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(inMultiplesOfDepositTermTypeId); + final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(inMultiplesOfDepositTermTypeId); final BigDecimal depositAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "depositAmount"); final BigDecimal maturityAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "maturityAmount"); final LocalDate maturityDate = JdbcSupport.getLocalDate(rs, "maturityDate"); final Integer depositPeriod = JdbcSupport.getInteger(rs, "depositPeriod"); final Integer depositPeriodFrequencyTypeId = JdbcSupport.getInteger(rs, "depositPeriodFrequencyTypeId"); - final EnumOptionData depositPeriodFrequencyType = (depositPeriodFrequencyTypeId == null) ? null : SavingsEnumerations - .depositPeriodFrequency(depositPeriodFrequencyTypeId); + final EnumOptionData depositPeriodFrequencyType = (depositPeriodFrequencyTypeId == null) ? null + : SavingsEnumerations.depositPeriodFrequency(depositPeriodFrequencyTypeId); final BigDecimal mandatoryRecommendedDepositAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "mandatoryRecommendedDepositAmount"); final BigDecimal totalOverdueAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalOverdueAmount"); @@ -931,8 +918,8 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final boolean isCalendarInherited = rs.getBoolean("isCalendarInherited"); final Integer onAccountClosureId = JdbcSupport.getInteger(rs, "onAccountClosureId"); - final EnumOptionData onAccountClosureType = (onAccountClosureId == null) ? null : SavingsEnumerations - .depositAccountOnClosureType(onAccountClosureId); + final EnumOptionData onAccountClosureType = (onAccountClosureId == null) ? null + : SavingsEnumerations.depositAccountOnClosureType(onAccountClosureId); final LocalDate expectedFirstDepositOnDate = JdbcSupport.getLocalDate(rs, "expectedFirstDepositOnDate"); return RecurringDepositAccountData.instance(depositAccountData, preClosurePenalApplicable, preClosurePenalInterest, @@ -990,8 +977,8 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead sqlBuilder.append(" au.username as submittedByUsername, "); sqlBuilder.append("pd.payment_type_id as paymentType,pd.account_number as accountNumber,pd.check_number as checkNumber, "); sqlBuilder.append("pd.receipt_number as receiptNumber, pd.bank_number as bankNumber,pd.routing_code as routingCode, "); - sqlBuilder - .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); + sqlBuilder.append( + "sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); sqlBuilder.append("pt.value as paymentTypeName "); @@ -1047,8 +1034,8 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); AccountTransferData transfer = null; final Long fromTransferId = JdbcSupport.getLong(rs, "fromTransferId"); @@ -1072,7 +1059,7 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead } final boolean postInterestAsOn = false; final String submittedByUsername = rs.getString("submittedByUsername"); - final String note = null ; + final String note = null; return SavingsAccountTransactionData.create(id, transactionType, paymentDetailData, savingsId, accountNo, date, currency, amount, outstandingChargeAmount, runningBalance, reversed, transfer, postInterestAsOn, submittedByUsername, note); } @@ -1092,8 +1079,8 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final StringBuilder selectFieldsSqlBuilder = new StringBuilder(400); selectFieldsSqlBuilder.append("sa.id as productId, sa.name as productName, "); - selectFieldsSqlBuilder - .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); + selectFieldsSqlBuilder.append( + "sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); selectFieldsSqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); selectFieldsSqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); selectFieldsSqlBuilder.append("sa.nominal_annual_interest_rate as nominalAnnualIterestRate, "); @@ -1118,7 +1105,6 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead selectTablesSqlBuilder.append("join m_currency curr on curr.code = sa.currency_code "); selectTablesSqlBuilder.append("left join m_tax_group tg on tg.id = sa.tax_group_id "); - this.selectTablesSql = selectTablesSqlBuilder.toString(); } @@ -1148,24 +1134,22 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final BigDecimal nominalAnnualIterestRate = rs.getBigDecimal("nominalAnnualIterestRate"); - final EnumOptionData interestCompoundingPeriodType = SavingsEnumerations - .compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, - "interestCompoundingPeriodType"))); + final EnumOptionData interestCompoundingPeriodType = SavingsEnumerations.compoundingInterestPeriodType( + SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, "interestCompoundingPeriodType"))); - final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType - .fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType"))); + final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType( + SavingsPostingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType"))); - final EnumOptionData interestCalculationType = SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType - .fromInt(JdbcSupport.getInteger(rs, "interestCalculationType"))); + final EnumOptionData interestCalculationType = SavingsEnumerations + .interestCalculationType(SavingsInterestCalculationType.fromInt(JdbcSupport.getInteger(rs, "interestCalculationType"))); - final EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations - .interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs, - "interestCalculationDaysInYearType"))); + final EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations.interestCalculationDaysInYearType( + SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs, "interestCalculationDaysInYearType"))); final BigDecimal minRequiredOpeningBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "minRequiredOpeningBalance"); @@ -1254,21 +1238,21 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final boolean preClosurePenalApplicable = rs.getBoolean("preClosurePenalApplicable"); final BigDecimal preClosurePenalInterest = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "preClosurePenalInterest"); final Integer preClosurePenalInterestOnTypeId = JdbcSupport.getInteger(rs, "preClosurePenalInterestOnId"); - final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null : SavingsEnumerations - .preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); + final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null + : SavingsEnumerations.preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); final Integer minDepositTerm = JdbcSupport.getInteger(rs, "minDepositTerm"); final Integer maxDepositTerm = JdbcSupport.getInteger(rs, "maxDepositTerm"); final Integer minDepositTermTypeId = JdbcSupport.getInteger(rs, "minDepositTermTypeId"); - final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(minDepositTermTypeId); + final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(minDepositTermTypeId); final Integer maxDepositTermTypeId = JdbcSupport.getInteger(rs, "maxDepositTermTypeId"); - final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(maxDepositTermTypeId); + final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(maxDepositTermTypeId); final Integer inMultiplesOfDepositTerm = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTerm"); final Integer inMultiplesOfDepositTermTypeId = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTermTypeId"); - final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(inMultiplesOfDepositTermTypeId); + final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(inMultiplesOfDepositTermTypeId); final BigDecimal depositAmount = null; final BigDecimal maturityAmount = null; @@ -1326,21 +1310,21 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final boolean preClosurePenalApplicable = rs.getBoolean("preClosurePenalApplicable"); final BigDecimal preClosurePenalInterest = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "preClosurePenalInterest"); final Integer preClosurePenalInterestOnTypeId = JdbcSupport.getInteger(rs, "preClosurePenalInterestOnId"); - final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null : SavingsEnumerations - .preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); + final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null + : SavingsEnumerations.preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); final Integer minDepositTerm = JdbcSupport.getInteger(rs, "minDepositTerm"); final Integer maxDepositTerm = JdbcSupport.getInteger(rs, "maxDepositTerm"); final Integer minDepositTermTypeId = JdbcSupport.getInteger(rs, "minDepositTermTypeId"); - final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(minDepositTermTypeId); + final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(minDepositTermTypeId); final Integer maxDepositTermTypeId = JdbcSupport.getInteger(rs, "maxDepositTermTypeId"); - final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(maxDepositTermTypeId); + final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(maxDepositTermTypeId); final Integer inMultiplesOfDepositTerm = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTerm"); final Integer inMultiplesOfDepositTermTypeId = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTermTypeId"); - final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(inMultiplesOfDepositTermTypeId); + final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(inMultiplesOfDepositTermTypeId); final boolean isMandatoryDeposit = rs.getBoolean("isMandatoryDeposit"); final boolean allowWithdrawal = rs.getBoolean("allowWithdrawal"); final boolean adjustAdvanceTowardsFuturePayments = rs.getBoolean("adjustAdvanceTowardsFuturePayments"); @@ -1422,8 +1406,8 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead public RecurringAccountDepositTransactionTemplateMapper() { final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("sa.id as id, sa.account_no as accountNo, "); - sqlBuilder - .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); + sqlBuilder.append( + "sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); sqlBuilder.append("sa.account_balance_derived as runningBalance, "); @@ -1461,18 +1445,19 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final SavingsAccountTransactionEnumData transactionType = SavingsEnumerations .transactionType(SavingsAccountTransactionType.DEPOSIT.getValue()); final PaymentDetailData paymentDetailData = null; final AccountTransferData transfer = null; final BigDecimal runningBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "runningBalance"); final boolean postInterestAsOn = false; - final String submittedByUsername = null ; - final String note = null ; + final String submittedByUsername = null; + final String note = null; return SavingsAccountTransactionData.create(savingsId, transactionType, paymentDetailData, savingsId, accountNo, duedate, - currency, dueamount, outstandingChargeAmount, runningBalance, false, transfer, postInterestAsOn, submittedByUsername, note); + currency, dueamount, outstandingChargeAmount, runningBalance, false, transfer, postInterestAsOn, submittedByUsername, + note); } } @@ -1482,8 +1467,8 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead public AccountTransferMapper() { final StringBuilder sqlBuilder = new StringBuilder(400); - sqlBuilder - .append("sa.id as fromAcc ,aa.linked_savings_account_id as toAcc,st.amount as amount, st.transaction_date as transactionDate ") + sqlBuilder.append( + "sa.id as fromAcc ,aa.linked_savings_account_id as toAcc,st.amount as amount, st.transaction_date as transactionDate ") .append(" from m_deposit_account_term_and_preclosure da ") .append(" inner join m_savings_account sa on da.savings_account_id = sa.id") .append(" inner join m_savings_account_transaction st on st.savings_account_id = sa.id") @@ -1510,4 +1495,4 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountWritePlatformService.java index 3a37eea41..3b1386199 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountWritePlatformService.java @@ -90,4 +90,4 @@ public interface DepositAccountWritePlatformService { void transferInterestToSavings() throws JobExecutionException; SavingsAccountTransaction mandatorySavingsAccountDeposit(final SavingsAccountTransactionDTO accountTransactionDTO); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index 1455080fe..4245e3694 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositAccountWritePlatformServiceJpaRepositoryImpl.java @@ -242,7 +242,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo } final boolean isInterestTransfer = false; final LocalDate postInterestOnDate = null; - if(activationChargeAmount.isGreaterThanZero()){ + if (activationChargeAmount.isGreaterThanZero()) { payActivationCharge(account, user); } if (account.isBeforeLastPostingPeriod(account.getActivationLocalDate())) { @@ -292,7 +292,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo return activationChargeAmount; } - private void payActivationCharge(final FixedDepositAccount account, AppUser user){ + private void payActivationCharge(final FixedDepositAccount account, AppUser user) { for (SavingsAccountCharge savingsAccountCharge : account.charges()) { if (savingsAccountCharge.isSavingsActivation()) { account.payCharge(savingsAccountCharge, savingsAccountCharge.getAmount(account.getCurrency()), @@ -371,8 +371,8 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo final LocalDate postInterestOnDate = null; if (account.isBeforeLastPostingPeriod(account.getActivationLocalDate())) { final LocalDate today = DateUtils.getLocalDateOfTenant(); - account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, - financialYearBeginningMonth, postInterestOnDate); + account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, + postInterestOnDate); } else { final LocalDate today = DateUtils.getLocalDateOfTenant(); account.calculateInterestUsing(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, @@ -424,8 +424,8 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo final LocalDate depositAmountUpdateEffectiveFromDate = command .localDateValueOfParameterNamed(DepositsApiConstants.effectiveDateParamName); - final RecurringDepositAccount recurringDepositAccount = (RecurringDepositAccount) this.depositAccountAssembler.assembleFrom( - savingsId, DepositAccountType.RECURRING_DEPOSIT); + final RecurringDepositAccount recurringDepositAccount = (RecurringDepositAccount) this.depositAccountAssembler + .assembleFrom(savingsId, DepositAccountType.RECURRING_DEPOSIT); DepositAccountRecurringDetail recurringDetail = recurringDepositAccount.getRecurringDetail(); Map changes = recurringDetail.updateMandatoryRecommendedDepositAmount(mandatoryRecommendedDepositAmount, depositAmountUpdateEffectiveFromDate, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); @@ -479,7 +479,8 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo @Transactional @Override - public CommandProcessingResult withdrawal(final Long savingsId, final JsonCommand command, final DepositAccountType depositAccountType) { + public CommandProcessingResult withdrawal(final Long savingsId, final JsonCommand command, + final DepositAccountType depositAccountType) { boolean isRegularTransaction = true; @@ -586,10 +587,12 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo try { this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); } catch (final PlatformApiDataValidationException e) { - LOG.error("Validation exception while trasfering Interest from {} to {}", accountTransferDTO.getFromAccountId(), accountTransferDTO.getToAccountId(), e); + LOG.error("Validation exception while trasfering Interest from {} to {}", accountTransferDTO.getFromAccountId(), + accountTransferDTO.getToAccountId(), e); errors.add(e); } catch (final InsufficientAccountBalanceException e) { - LOG.error("InsufficientAccountBalanceException while trasfering Interest from {} to {} ", accountTransferDTO.getFromAccountId(), accountTransferDTO.getToAccountId(), e); + LOG.error("InsufficientAccountBalanceException while trasfering Interest from {} to {} ", + accountTransferDTO.getFromAccountId(), accountTransferDTO.getToAccountId(), e); errors.add(e); } } @@ -622,9 +625,11 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo if (savingsAccountTransaction == null) { throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId); } if (!allowAccountTransferModification - && this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)) { throw new PlatformServiceUnavailableException( - "error.msg.recurring.deposit.account.transfer.transaction.update.not.allowed", "Recurring deposit account transaction:" - + transactionId + " update not allowed as it involves in account transfer", transactionId); } + && this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)) { + throw new PlatformServiceUnavailableException("error.msg.recurring.deposit.account.transfer.transaction.update.not.allowed", + "Recurring deposit account transaction:" + transactionId + " update not allowed as it involves in account transfer", + transactionId); + } final LocalDate today = DateUtils.getLocalDateOfTenant(); final MathContext mc = MathContext.DECIMAL64; @@ -653,7 +658,8 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo account.validateAccountBalanceDoesNotBecomeNegative(SavingsApiConstants.undoTransactionAction, depositAccountOnHoldTransactions); // account.activateAccountBasedOnBalance(); final boolean isPreMatureClosure = false; - account.updateMaturityDateAndAmount(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); + account.updateMaturityDateAndAmount(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, + financialYearBeginningMonth); final LocalDate overdueUptoDate = DateUtils.getLocalDateOfTenant(); @@ -697,12 +703,16 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo .findOneByIdAndSavingsAccountId(transactionId, savingsId); if (savingsAccountTransaction == null) { throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId); } - if ((!savingsAccountTransaction.isDeposit() && !savingsAccountTransaction.isWithdrawal()) || savingsAccountTransaction.isReversed()) { throw new TransactionUpdateNotAllowedException( - savingsId, transactionId); } + if ((!savingsAccountTransaction.isDeposit() && !savingsAccountTransaction.isWithdrawal()) + || savingsAccountTransaction.isReversed()) { + throw new TransactionUpdateNotAllowedException(savingsId, transactionId); + } - if (this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)) { throw new PlatformServiceUnavailableException( - "error.msg.saving.account.transfer.transaction.update.not.allowed", "Deposit account transaction:" + transactionId - + " update not allowed as it involves in account transfer", transactionId); } + if (this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)) { + throw new PlatformServiceUnavailableException("error.msg.saving.account.transfer.transaction.update.not.allowed", + "Deposit account transaction:" + transactionId + " update not allowed as it involves in account transfer", + transactionId); + } final LocalDate today = DateUtils.getLocalDateOfTenant(); @@ -803,14 +813,14 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo this.depositAccountTransactionDataValidator.validateClosing(command, DepositAccountType.FIXED_DEPOSIT, isPreMatureClose); final Map changes = new LinkedHashMap<>(); - final PaymentDetail - paymentDetail = this.paymentDetailWritePlatformService.createAndPersistPaymentDetail(command, changes); + final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService.createAndPersistPaymentDetail(command, changes); final FixedDepositAccount account = (FixedDepositAccount) this.depositAccountAssembler.assembleFrom(savingsId, DepositAccountType.FIXED_DEPOSIT); checkClientOrGroupActive(account); - this.depositAccountDomainService.handleFDAccountClosure(account, paymentDetail, user, command, DateUtils.getLocalDateOfTenant(), changes); + this.depositAccountDomainService.handleFDAccountClosure(account, paymentDetail, user, command, DateUtils.getLocalDateOfTenant(), + changes); final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { @@ -949,7 +959,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth(); final SavingsAccount savingsAccount = this.depositAccountAssembler.assembleFrom(accountId, depositAccountType); - final LocalDate postInterestOnDate = null; + final LocalDate postInterestOnDate = null; final Set existingTransactionIds = new HashSet<>(); final Set existingReversedTransactionIds = new HashSet<>(); updateExistingTransactionsDetails(savingsAccount, existingTransactionIds, existingReversedTransactionIds); @@ -1079,14 +1089,14 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo if (!this.configurationDomainService.allowTransactionsOnHolidayEnabled() && this.holidayRepository.isHoliday(savingsAccount.officeId(), savingsAccountCharge.getDueLocalDate())) { baseDataValidator.reset().parameter(dueAsOfDateParamName).value(savingsAccountCharge.getDueLocalDate().toString(fmt)) - .failWithCodeNoParameterAddedToErrorCode("charge.due.date.is.on.holiday"); + .failWithCodeNoParameterAddedToErrorCode("charge.due.date.is.on.holiday"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (!this.configurationDomainService.allowTransactionsOnNonWorkingDayEnabled() && !this.workingDaysRepository.isWorkingDay(savingsAccountCharge.getDueLocalDate())) { baseDataValidator.reset().parameter(dueAsOfDateParamName).value(savingsAccountCharge.getDueLocalDate().toString(fmt)) - .failWithCodeNoParameterAddedToErrorCode("charge.due.date.is.a.nonworking.day"); + .failWithCodeNoParameterAddedToErrorCode("charge.due.date.is.a.nonworking.day"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } @@ -1134,14 +1144,14 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo if (!this.configurationDomainService.allowTransactionsOnHolidayEnabled() && this.holidayRepository.isHoliday(savingsAccount.officeId(), savingsAccountCharge.getDueLocalDate())) { baseDataValidator.reset().parameter(dueAsOfDateParamName).value(savingsAccountCharge.getDueLocalDate().toString(fmt)) - .failWithCodeNoParameterAddedToErrorCode("charge.due.date.is.on.holiday"); + .failWithCodeNoParameterAddedToErrorCode("charge.due.date.is.on.holiday"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (!this.configurationDomainService.allowTransactionsOnNonWorkingDayEnabled() && !this.workingDaysRepository.isWorkingDay(savingsAccountCharge.getDueLocalDate())) { baseDataValidator.reset().parameter(dueAsOfDateParamName).value(savingsAccountCharge.getDueLocalDate().toString(fmt)) - .failWithCodeNoParameterAddedToErrorCode("charge.due.date.is.a.nonworking.day"); + .failWithCodeNoParameterAddedToErrorCode("charge.due.date.is.a.nonworking.day"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } @@ -1169,8 +1179,8 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth(); - final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOneWithNotFoundDetection( - savingsAccountChargeId, savingsAccountId); + final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository + .findOneWithNotFoundDetection(savingsAccountChargeId, savingsAccountId); // Get Savings account from savings charge final SavingsAccount account = savingsAccountCharge.savingsAccount(); @@ -1223,8 +1233,8 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo final SavingsAccount savingsAccount = this.depositAccountAssembler.assembleFrom(savingsAccountId, depositAccountType); checkClientOrGroupActive(savingsAccount); - final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOneWithNotFoundDetection( - savingsAccountChargeId, savingsAccountId); + final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository + .findOneWithNotFoundDetection(savingsAccountChargeId, savingsAccountId); savingsAccount.removeCharge(savingsAccountCharge); this.savingAccountRepositoryWrapper.saveAndFlush(savingsAccount); @@ -1250,8 +1260,8 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo final BigDecimal amountPaid = command.bigDecimalValueOfParameterNamed(amountParamName); final LocalDate transactionDate = command.localDateValueOfParameterNamed(dueAsOfDateParamName); - final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOneWithNotFoundDetection( - savingsAccountChargeId, savingsAccountId); + final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository + .findOneWithNotFoundDetection(savingsAccountChargeId, savingsAccountId); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -1261,14 +1271,14 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo if (!this.configurationDomainService.allowTransactionsOnHolidayEnabled() && this.holidayRepository.isHoliday(savingsAccountCharge.savingsAccount().officeId(), transactionDate)) { baseDataValidator.reset().parameter(dueAsOfDateParamName).value(transactionDate.toString(fmt)) - .failWithCodeNoParameterAddedToErrorCode("transaction.not.allowed.transaction.date.is.on.holiday"); + .failWithCodeNoParameterAddedToErrorCode("transaction.not.allowed.transaction.date.is.on.holiday"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (!this.configurationDomainService.allowTransactionsOnNonWorkingDayEnabled() && !this.workingDaysRepository.isWorkingDay(transactionDate)) { baseDataValidator.reset().parameter(dueAsOfDateParamName).value(transactionDate.toString(fmt)) - .failWithCodeNoParameterAddedToErrorCode("transaction.not.allowed.transaction.date.is.a.nonworking.day"); + .failWithCodeNoParameterAddedToErrorCode("transaction.not.allowed.transaction.date.is.a.nonworking.day"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } @@ -1289,8 +1299,8 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo @SuppressWarnings("unused") final DepositAccountType depositAccountType) { // always use current date as transaction date for batch job final LocalDate transactionDate = DateUtils.getLocalDateOfTenant(); - final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOneWithNotFoundDetection( - savingsAccountChargeId, accountId); + final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository + .findOneWithNotFoundDetection(savingsAccountChargeId, accountId); final DateTimeFormatter fmt = DateTimeFormat.forPattern("dd MM yyyy"); @@ -1358,26 +1368,25 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo if (depositAccountType.isFixedDeposit()) { ((FixedDepositAccount) account).updateMaturityStatus(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); FixedDepositAccount fdAccount = ((FixedDepositAccount) account); - //handle maturity instructions + // handle maturity instructions - if(fdAccount.isMatured() && (fdAccount.isReinvestOnClosure() || fdAccount.isTransferToSavingsOnClosure())){ + if (fdAccount.isMatured() && (fdAccount.isReinvestOnClosure() || fdAccount.isTransferToSavingsOnClosure())) { DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd"); Map changes = new HashMap<>(); AppUser user = context.authenticatedUser(); Long toSavingsId = fdAccount.getTransferToSavingsAccountId(); - this.depositAccountDomainService.handleFDAccountMaturityClosure(fdAccount, null, user, - fdAccount.maturityDate(), fmt, fdAccount.maturityDate(), - fdAccount.getOnAccountClosureId(), toSavingsId, "Apply maturity instructions", changes); + this.depositAccountDomainService.handleFDAccountMaturityClosure(fdAccount, null, user, fdAccount.maturityDate(), fmt, + fdAccount.maturityDate(), fdAccount.getOnAccountClosureId(), toSavingsId, "Apply maturity instructions", changes); - if(changes.get("reinvestedDepositId") != null) { + if (changes.get("reinvestedDepositId") != null) { Long reinvestedDepositId = (Long) changes.get("reinvestedDepositId"); Money amountForDeposit = account.activateWithBalance(); - final FixedDepositAccount reinvestAccount = (FixedDepositAccount) this.depositAccountAssembler.assembleFrom(reinvestedDepositId, - DepositAccountType.FIXED_DEPOSIT); + final FixedDepositAccount reinvestAccount = (FixedDepositAccount) this.depositAccountAssembler + .assembleFrom(reinvestedDepositId, DepositAccountType.FIXED_DEPOSIT); Money activationChargeAmount = getActivationCharge(reinvestAccount); - if(activationChargeAmount.isGreaterThanZero()){ + if (activationChargeAmount.isGreaterThanZero()) { payActivationCharge(reinvestAccount, user); - amountForDeposit = amountForDeposit.plus(activationChargeAmount); + amountForDeposit = amountForDeposit.plus(activationChargeAmount); } this.depositAccountDomainService.handleFDDeposit(reinvestAccount, fmt, fdAccount.maturityDate(), amountForDeposit.getAmount(), null); @@ -1387,7 +1396,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo ((RecurringDepositAccount) account).updateMaturityStatus(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); } - this.savingAccountRepositoryWrapper.saveAndFlush(account) ; + this.savingAccountRepositoryWrapper.saveAndFlush(account); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds); } @@ -1417,8 +1426,8 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo this.paymentDetailWritePlatformService.persistPaymentDetail(paymentDetail); } if (accountTransactionDTO.getAccountType().equals(DepositAccountType.RECURRING_DEPOSIT.getValue())) { - RecurringDepositAccount account = (RecurringDepositAccount) this.depositAccountAssembler.assembleFrom( - accountTransactionDTO.getSavingsAccountId(), DepositAccountType.RECURRING_DEPOSIT); + RecurringDepositAccount account = (RecurringDepositAccount) this.depositAccountAssembler + .assembleFrom(accountTransactionDTO.getSavingsAccountId(), DepositAccountType.RECURRING_DEPOSIT); return this.depositAccountDomainService.handleRDDeposit(account, accountTransactionDTO.getFormatter(), accountTransactionDTO.getTransactionDate(), accountTransactionDTO.getTransactionAmount(), paymentDetail, isRegularTransaction); @@ -1437,7 +1446,6 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo } - private AppUser getAppUserIfPresent() { AppUser user = null; if (this.context != null) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositApplicationProcessWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositApplicationProcessWritePlatformService.java index e2f91017b..6e2ae91e5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositApplicationProcessWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositApplicationProcessWritePlatformService.java @@ -41,4 +41,4 @@ public interface DepositApplicationProcessWritePlatformService { CommandProcessingResult rejectApplication(Long accountId, JsonCommand command, DepositAccountType depositAccountType); CommandProcessingResult applicantWithdrawsFromApplication(Long accountId, JsonCommand command, DepositAccountType depositAccountType); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl.java index cea6f3c98..80aa784fd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl.java @@ -175,15 +175,15 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl 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); + 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); + throw new PlatformDataIntegrityException(errorCodeBuilder.toString(), + "Savings account with externalId " + externalId + " already exists", "externalId", externalId); } errorCodeBuilder.append(".unknown.data.integrity.issue"); @@ -232,10 +232,10 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } final Long savingsId = account.getId(); - this.businessEventNotifierService.notifyBusinessEventWasExecuted( BusinessEvents.FIXED_DEPOSIT_ACCOUNT_CREATE, + this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.FIXED_DEPOSIT_ACCOUNT_CREATE, constructEntityMap(BusinessEntity.DEPOSIT_ACCOUNT, account)); - this.businessEventNotifierService.notifyBusinessEventWasExecuted( BusinessEvents.FIXED_DEPOSIT_ACCOUNT_CREATE, + this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.FIXED_DEPOSIT_ACCOUNT_CREATE, constructEntityMap(BusinessEntity.DEPOSIT_ACCOUNT, account)); return new CommandProcessingResultBuilder() // @@ -249,8 +249,8 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } catch (final DataAccessException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -295,10 +295,10 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl financialYearBeginningMonth); account.validateApplicableInterestRate(); this.savingAccountRepository.save(account); - this.businessEventNotifierService.notifyBusinessEventWasExecuted( BusinessEvents.RECURRING_DEPOSIT_ACCOUNT_CREATE, + this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.RECURRING_DEPOSIT_ACCOUNT_CREATE, constructEntityMap(BusinessEntity.DEPOSIT_ACCOUNT, account)); - this.businessEventNotifierService.notifyBusinessEventWasExecuted( BusinessEvents.RECURRING_DEPOSIT_ACCOUNT_CREATE, + this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.RECURRING_DEPOSIT_ACCOUNT_CREATE, constructEntityMap(BusinessEntity.DEPOSIT_ACCOUNT, account)); return new CommandProcessingResultBuilder() // @@ -312,8 +312,8 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } catch (final DataAccessException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -333,9 +333,8 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl defaultUserMessage, account.clientId()); } else if (groups.size() > 1) { final String defaultUserMessage = "Client belongs to more than one group. Cannot support recurring deposit."; - throw new GeneralPlatformDomainRuleException( - "error.msg.recurring.deposit.account.cannot.create.belongs.to.multiple.groups", defaultUserMessage, - account.clientId()); + throw new GeneralPlatformDomainRuleException("error.msg.recurring.deposit.account.cannot.create.belongs.to.multiple.groups", + defaultUserMessage, account.clientId()); } else { Group group = groups.iterator().next(); Group parent = group.getParent(); @@ -346,13 +345,13 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } else { groupId = group.getId(); } - CalendarInstance parentCalendarInstance = this.calendarInstanceRepository.findByEntityIdAndEntityTypeIdAndCalendarTypeId( - groupId, entityType, CalendarType.COLLECTION.getValue()); - if(parentCalendarInstance == null){ + CalendarInstance parentCalendarInstance = this.calendarInstanceRepository + .findByEntityIdAndEntityTypeIdAndCalendarTypeId(groupId, entityType, CalendarType.COLLECTION.getValue()); + if (parentCalendarInstance == null) { final String defaultUserMessage = "Meeting frequency is not attached to the Group/Center to which the client belongs to."; throw new GeneralPlatformDomainRuleException( - "error.msg.meeting.frequency.not.attached.to.group.to.which.client.belongs.to", - defaultUserMessage, account.clientId()); + "error.msg.meeting.frequency.not.attached.to.group.to.which.client.belongs.to", defaultUserMessage, + account.clientId()); } calendarInstance = CalendarInstance.from(parentCalendarInstance.getCalendar(), account.getId(), CalendarEntityType.SAVINGS.getValue()); @@ -462,8 +461,8 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } catch (final DataAccessException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return new CommandProcessingResult((long) -1); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return new CommandProcessingResult((long) -1); } @@ -533,8 +532,8 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } catch (final DataAccessException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return new CommandProcessingResult(Long.valueOf(-1)); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return new CommandProcessingResult(Long.valueOf(-1)); } @@ -557,8 +556,7 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl if (changes.containsKey(SavingsApiConstants.groupIdParamName)) { final Long groupId = command.longValueOfParameterNamed(SavingsApiConstants.groupIdParamName); if (groupId != null) { - final Group group = this.groupRepository.findById(groupId) - .orElseThrow(() -> new GroupNotFoundException(groupId)); + final Group group = this.groupRepository.findById(groupId).orElseThrow(() -> new GroupNotFoundException(groupId)); if (group.isNotActive()) { if (group.isCenter()) { throw new CenterNotActiveException(groupId); } throw new GroupNotActiveException(groupId); @@ -590,8 +588,8 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } if (changes.containsKey("charges")) { - final Set charges = this.savingsAccountChargeAssembler.fromParsedJson(command.parsedJson(), account - .getCurrency().getCode()); + final Set charges = this.savingsAccountChargeAssembler.fromParsedJson(command.parsedJson(), + account.getCurrency().getCode()); final boolean updated = account.update(charges); if (!updated) { changes.remove("charges"); @@ -609,8 +607,8 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl if (account.isNotSubmittedAndPendingApproval()) { final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(depositAccountType - .resourceName() + DepositsApiConstants.deleteApplicationAction); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(depositAccountType.resourceName() + DepositsApiConstants.deleteApplicationAction); baseDataValidator.reset().parameter(DepositsApiConstants.activatedOnDateParamName) .failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state"); @@ -786,7 +784,8 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } } - private Map constructEntityMap(final BusinessEntity entityEvent, Object entity) { + private Map constructEntityMap(final BusinessEntity entityEvent, + Object entity) { Map map = new HashMap<>(1); map.put(entityEvent, entity); return map; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositProductReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositProductReadPlatformServiceImpl.java index 89eab9d73..9acf281b8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositProductReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositProductReadPlatformServiceImpl.java @@ -65,9 +65,7 @@ public class DepositProductReadPlatformServiceImpl implements DepositProductRead this.context.authenticatedUser(); final DepositProductMapper depositProductMapper = this.getDepositProductMapper(depositAccountType); - if (depositProductMapper == null) { - return null; - } + if (depositProductMapper == null) { return null; } final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("select "); @@ -95,17 +93,15 @@ public class DepositProductReadPlatformServiceImpl implements DepositProductRead this.context.authenticatedUser(); final DepositProductMapper depositProductMapper = this.getDepositProductMapper(depositAccountType); - if (depositProductMapper == null) { - return null; - } + if (depositProductMapper == null) { return null; } final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("select "); sqlBuilder.append(depositProductMapper.schema()); sqlBuilder.append(" where sp.id = ? and sp.deposit_type_enum = ? "); - return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), depositProductMapper, new Object[] { fixedDepositProductId, - depositAccountType.getValue() }); + return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), depositProductMapper, + new Object[] { fixedDepositProductId, depositAccountType.getValue() }); } catch (final EmptyResultDataAccessException e) { throw new FixedDepositProductNotFoundException(fixedDepositProductId); @@ -136,8 +132,8 @@ public class DepositProductReadPlatformServiceImpl implements DepositProductRead public DepositProductMapper() { final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("sp.id as id, sp.name as name, sp.short_name as shortName, sp.description as description, "); - sqlBuilder - .append("sp.currency_code as currencyCode, sp.currency_digits as currencyDigits, sp.currency_multiplesof as inMultiplesOf, "); + sqlBuilder.append( + "sp.currency_code as currencyCode, sp.currency_digits as currencyDigits, sp.currency_multiplesof as inMultiplesOf, "); sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); sqlBuilder.append("sp.nominal_annual_interest_rate as nominalAnnualInterestRate, "); @@ -171,8 +167,8 @@ public class DepositProductReadPlatformServiceImpl implements DepositProductRead final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final BigDecimal nominalAnnualInterestRate = rs.getBigDecimal("nominalAnnualInterestRate"); final Integer compoundingInterestPeriodTypeValue = JdbcSupport.getInteger(rs, "compoundingInterestPeriodType"); @@ -257,21 +253,21 @@ public class DepositProductReadPlatformServiceImpl implements DepositProductRead final boolean preClosurePenalApplicable = rs.getBoolean("preClosurePenalApplicable"); final BigDecimal preClosurePenalInterest = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "preClosurePenalInterest"); final Integer preClosurePenalInterestOnTypeId = JdbcSupport.getInteger(rs, "preClosurePenalInterestOnId"); - final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null : SavingsEnumerations - .preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); + final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null + : SavingsEnumerations.preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); final Integer minDepositTerm = JdbcSupport.getInteger(rs, "minDepositTerm"); final Integer maxDepositTerm = JdbcSupport.getInteger(rs, "maxDepositTerm"); final Integer minDepositTermTypeId = JdbcSupport.getInteger(rs, "minDepositTermTypeId"); - final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(minDepositTermTypeId); + final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(minDepositTermTypeId); final Integer maxDepositTermTypeId = JdbcSupport.getInteger(rs, "maxDepositTermTypeId"); - final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(maxDepositTermTypeId); + final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(maxDepositTermTypeId); final Integer inMultiplesOfDepositTerm = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTerm"); final Integer inMultiplesOfDepositTermTypeId = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTermTypeId"); - final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(inMultiplesOfDepositTermTypeId); + final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(inMultiplesOfDepositTermTypeId); final BigDecimal minDepositAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "minDepositAmount"); final BigDecimal depositAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "depositAmount"); final BigDecimal maxDepositAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "maxDepositAmount"); @@ -329,23 +325,23 @@ public class DepositProductReadPlatformServiceImpl implements DepositProductRead final boolean preClosurePenalApplicable = rs.getBoolean("preClosurePenalApplicable"); final BigDecimal preClosurePenalInterest = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "preClosurePenalInterest"); final Integer preClosurePenalInterestOnTypeId = JdbcSupport.getInteger(rs, "preClosurePenalInterestOnId"); - final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null : SavingsEnumerations - .preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); + final EnumOptionData preClosurePenalInterestOnType = (preClosurePenalInterestOnTypeId == null) ? null + : SavingsEnumerations.preClosurePenaltyInterestOnType(preClosurePenalInterestOnTypeId); final BigDecimal minDepositAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "minDepositAmount"); final BigDecimal depositAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "depositAmount"); final BigDecimal maxDepositAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "maxDepositAmount"); final Integer minDepositTerm = JdbcSupport.getInteger(rs, "minDepositTerm"); final Integer maxDepositTerm = JdbcSupport.getInteger(rs, "maxDepositTerm"); final Integer minDepositTermTypeId = JdbcSupport.getInteger(rs, "minDepositTermTypeId"); - final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(minDepositTermTypeId); + final EnumOptionData minDepositTermType = (minDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(minDepositTermTypeId); final Integer maxDepositTermTypeId = JdbcSupport.getInteger(rs, "maxDepositTermTypeId"); - final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(maxDepositTermTypeId); + final EnumOptionData maxDepositTermType = (maxDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(maxDepositTermTypeId); final Integer inMultiplesOfDepositTerm = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTerm"); final Integer inMultiplesOfDepositTermTypeId = JdbcSupport.getInteger(rs, "inMultiplesOfDepositTermTypeId"); - final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null : SavingsEnumerations - .depositTermFrequencyType(inMultiplesOfDepositTermTypeId); + final EnumOptionData inMultiplesOfDepositTermType = (inMultiplesOfDepositTermTypeId == null) ? null + : SavingsEnumerations.depositTermFrequencyType(inMultiplesOfDepositTermTypeId); return RecurringDepositProductData.instance(depositProductData, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, @@ -376,4 +372,4 @@ public class DepositProductReadPlatformServiceImpl implements DepositProductRead } else if (depositAccountType.isRecurringDeposit()) { return this.recurringDepositProductRowMapper; } return null; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositsDropdownReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositsDropdownReadPlatformService.java index 07c041f74..c80b3cbdc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositsDropdownReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositsDropdownReadPlatformService.java @@ -37,4 +37,4 @@ public interface DepositsDropdownReadPlatformService { * Collection retrieveDepositPeriodFrequencyOptions(); */ -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositsDropdownReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositsDropdownReadPlatformServiceImpl.java index 7c172e09a..84e39f92d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositsDropdownReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/DepositsDropdownReadPlatformServiceImpl.java @@ -50,14 +50,12 @@ public class DepositsDropdownReadPlatformServiceImpl implements DepositsDropdown * .recurringDepositFrequencyType(SavingsPeriodFrequencyType.values()); } */ - @Override public Collection maturityInstructionOptions() { - return Arrays.asList( - SavingsEnumerations.depositAccountOnClosureType(DepositAccountOnClosureType.WITHDRAW_DEPOSIT), - SavingsEnumerations.depositAccountOnClosureType(DepositAccountOnClosureType.TRANSFER_TO_SAVINGS), - SavingsEnumerations.depositAccountOnClosureType(DepositAccountOnClosureType.REINVEST_PRINCIPAL_AND_INTEREST), - SavingsEnumerations.depositAccountOnClosureType(DepositAccountOnClosureType.REINVEST_PRINCIPAL_ONLY)); + return Arrays.asList(SavingsEnumerations.depositAccountOnClosureType(DepositAccountOnClosureType.WITHDRAW_DEPOSIT), + SavingsEnumerations.depositAccountOnClosureType(DepositAccountOnClosureType.TRANSFER_TO_SAVINGS), + SavingsEnumerations.depositAccountOnClosureType(DepositAccountOnClosureType.REINVEST_PRINCIPAL_AND_INTEREST), + SavingsEnumerations.depositAccountOnClosureType(DepositAccountOnClosureType.REINVEST_PRINCIPAL_ONLY)); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/FixedDepositProductWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/FixedDepositProductWritePlatformService.java index 36f46144d..92ca7cd51 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/FixedDepositProductWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/FixedDepositProductWritePlatformService.java @@ -28,4 +28,4 @@ public interface FixedDepositProductWritePlatformService { CommandProcessingResult update(Long productId, JsonCommand command); CommandProcessingResult delete(Long productId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/FixedDepositProductWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/FixedDepositProductWritePlatformServiceJpaRepositoryImpl.java index 1675f4174..c79e07807 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/FixedDepositProductWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/FixedDepositProductWritePlatformServiceJpaRepositoryImpl.java @@ -101,8 +101,8 @@ public class FixedDepositProductWritePlatformServiceJpaRepositoryImpl implements } catch (final DataAccessException e) { handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -123,8 +123,8 @@ public class FixedDepositProductWritePlatformServiceJpaRepositoryImpl implements final Map changes = product.update(command); if (changes.containsKey(chargesParamName)) { - final Set savingsProductCharges = this.depositProductAssembler.assembleListOfSavingsProductCharges(command, product - .currency().getCode()); + final Set savingsProductCharges = this.depositProductAssembler.assembleListOfSavingsProductCharges(command, + product.currency().getCode()); final boolean updated = product.update(savingsProductCharges); if (!updated) { changes.remove(chargesParamName); @@ -161,8 +161,8 @@ public class FixedDepositProductWritePlatformServiceJpaRepositoryImpl implements } catch (final DataAccessException e) { handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -192,13 +192,13 @@ public class FixedDepositProductWritePlatformServiceJpaRepositoryImpl implements 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); + throw new PlatformDataIntegrityException("error.msg.product.savings.duplicate.name", + "Savings product with name `" + name + "` already exists", "name", name); } else if (realCause.getMessage().contains("sp_unq_short_name")) { final String shortName = command.stringValueOfParameterNamed("shortName"); - throw new PlatformDataIntegrityException("error.msg.product.savings.duplicate.short.name", "Savings product with short name `" - + shortName + "` already exists", "shortName", shortName); + throw new PlatformDataIntegrityException("error.msg.product.savings.duplicate.short.name", + "Savings product with short name `" + shortName + "` already exists", "shortName", shortName); } logAsErrorUnexpectedDataIntegrityException(dae); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GSIMReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GSIMReadPlatformService.java index 201fdfcc3..0fefef9fa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GSIMReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GSIMReadPlatformService.java @@ -37,9 +37,7 @@ public interface GSIMReadPlatformService { Collection findGsimAccountContainerbyGsimAccountNumber(String accountNumber); - - Collection findGsimAccountByGroupIdandAccountNo(String groupId, - String accountNo); + Collection findGsimAccountByGroupIdandAccountNo(String groupId, String accountNo); List findGsimAccountContainerbyGsimAccountId(Long parentAccountId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GSIMReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GSIMReadPlatformServiceImpl.java index 7e7da33ca..ca6d4f2bd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GSIMReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GSIMReadPlatformServiceImpl.java @@ -48,342 +48,335 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class GSIMReadPlatformServiceImpl implements GSIMReadPlatformService -{ +public class GSIMReadPlatformServiceImpl implements GSIMReadPlatformService { - private final JdbcTemplate jdbcTemplate; - private final PlatformSecurityContext context; - private final ColumnValidator columnValidator; + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; + private final ColumnValidator columnValidator; + @Autowired + public GSIMReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, + final ColumnValidator columnValidator) { + this.context = context; + this.jdbcTemplate = new JdbcTemplate(dataSource); + this.columnValidator = columnValidator; + } - @Autowired - public GSIMReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource - ,final ColumnValidator columnValidator) { - this.context = context; - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.columnValidator = columnValidator; + private static final class GSIMFieldsMapper implements RowMapper { - } + public String schema() { + return "gsim.id as gsimId,sv.group_id as groupId,sv.client_id as clientId,gsim.account_number as accountNumber, sv.id as childAccountId,sv.account_no as childAccountNumber,sv.account_balance_derived as childBalance,gsim.parent_deposit as parentBalance,gsim.child_accounts_count as childAccountsCount," + + "gsim.savings_status_id as savingsStatus from gsim_accounts gsim,m_savings_account sv where gsim.id=sv.gsim_id"; + } - private static final class GSIMFieldsMapper implements RowMapper { - public String schema() { - return "gsim.id as gsimId,sv.group_id as groupId,sv.client_id as clientId,gsim.account_number as accountNumber, sv.id as childAccountId,sv.account_no as childAccountNumber,sv.account_balance_derived as childBalance,gsim.parent_deposit as parentBalance,gsim.child_accounts_count as childAccountsCount," - +"gsim.savings_status_id as savingsStatus from gsim_accounts gsim,m_savings_account sv where gsim.id=sv.gsim_id"; - } + @Override + public GroupSavingsIndividualMonitoringAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) + throws SQLException { - @Override - public GroupSavingsIndividualMonitoringAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + final BigDecimal gsimId = rs.getBigDecimal("gsimId"); + final BigDecimal groupId = rs.getBigDecimal("groupId"); + final BigDecimal clientId = rs.getBigDecimal("clientId"); + final String accountNumber = rs.getString("accountNumber"); + final BigDecimal childAccountId = rs.getBigDecimal("childAccountId"); + final String childAccountNumber = rs.getString("childAccountNumber"); + final Long childAccountsCount = rs.getLong("childAccountsCount"); + final BigDecimal parentBalance = rs.getBigDecimal("parentBalance"); + final BigDecimal childBalance = rs.getBigDecimal("childBalance"); + final String savingsStatus = SavingsAccountStatusType.fromInt((int) rs.getLong("savingsStatus")).toString(); + return GroupSavingsIndividualMonitoringAccountData.getInstance2(gsimId, groupId, clientId, accountNumber, childAccountId, + childAccountNumber, parentBalance, childBalance, childAccountsCount, savingsStatus); + } + } - final BigDecimal gsimId=rs.getBigDecimal("gsimId"); - final BigDecimal groupId=rs.getBigDecimal("groupId"); - final BigDecimal clientId=rs.getBigDecimal("clientId"); - final String accountNumber=rs.getString("accountNumber"); - final BigDecimal childAccountId=rs.getBigDecimal("childAccountId"); - final String childAccountNumber=rs.getString("childAccountNumber"); - final Long childAccountsCount=rs.getLong("childAccountsCount"); - final BigDecimal parentBalance=rs.getBigDecimal("parentBalance"); - final BigDecimal childBalance=rs.getBigDecimal("childBalance"); - final String savingsStatus=SavingsAccountStatusType.fromInt((int)rs.getLong("savingsStatus")).toString(); - return GroupSavingsIndividualMonitoringAccountData.getInstance2(gsimId,groupId,clientId,accountNumber,childAccountId,childAccountNumber,parentBalance,childBalance, - childAccountsCount,savingsStatus); - } - } + private static final class GSIMMapper implements RowMapper { - private static final class GSIMMapper implements RowMapper { - public String schema() { - return "gsim.id as gsimId,gsim.group_id as groupId,gsim.account_number as accountNumber,gsim.parent_deposit as parentDeposit,gsim.child_accounts_count as childAccountsCount," - +"gsim.savings_status_id as savingsStatus from gsim_accounts gsim"; - } + public String schema() { + return "gsim.id as gsimId,gsim.group_id as groupId,gsim.account_number as accountNumber,gsim.parent_deposit as parentDeposit,gsim.child_accounts_count as childAccountsCount," + + "gsim.savings_status_id as savingsStatus from gsim_accounts gsim"; + } - @Override - public GroupSavingsIndividualMonitoringAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) - throws SQLException { + @Override + public GroupSavingsIndividualMonitoringAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) + throws SQLException { - final BigDecimal glimId=rs.getBigDecimal("gsimId"); + final BigDecimal glimId = rs.getBigDecimal("gsimId"); - final BigDecimal groupId=rs.getBigDecimal("groupId"); + final BigDecimal groupId = rs.getBigDecimal("groupId"); - final String accountNumber=rs.getString("accountNumber"); + final String accountNumber = rs.getString("accountNumber"); - final BigDecimal parentDeposit=rs.getBigDecimal("parentDeposit"); + final BigDecimal parentDeposit = rs.getBigDecimal("parentDeposit"); - final String loanStatus=LoanStatus.fromInt((int)rs.getLong("savingsStatus")).toString(); + final String loanStatus = LoanStatus.fromInt((int) rs.getLong("savingsStatus")).toString(); - return GroupSavingsIndividualMonitoringAccountData.getInstance1(glimId,groupId, accountNumber, parentDeposit,loanStatus); + return GroupSavingsIndividualMonitoringAccountData.getInstance1(glimId, groupId, accountNumber, parentDeposit, loanStatus); - } - } + } + } - @Override - public Collection findGSIMAccountContainerByGroupId(Long groupId) { - this.context.authenticatedUser(); - Collection gsimInfo=findGSIMAccountsByGroupId(groupId+""); + @Override + public Collection findGSIMAccountContainerByGroupId(Long groupId) { + this.context.authenticatedUser(); + Collection gsimInfo = findGSIMAccountsByGroupId(groupId + ""); - //List glimAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new Object[] { groupId }); - String savingswhereClauseForGroup; + // List glimAccounts = + // retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new + // Object[] { groupId }); + String savingswhereClauseForGroup; - List gsimAccounts=new ArrayList(); - List childSavings; - for(GroupSavingsIndividualMonitoringAccountData gsimAccount:gsimInfo) - { - BigDecimal gsimId = gsimAccount.getGsimId(); - savingswhereClauseForGroup = " where sa.group_id = ? and sa.gsim_id = ? order by sa.status_enum ASC, sa.account_no ASC"; + List gsimAccounts = new ArrayList(); + List childSavings; + for (GroupSavingsIndividualMonitoringAccountData gsimAccount : gsimInfo) { + BigDecimal gsimId = gsimAccount.getGsimId(); + savingswhereClauseForGroup = " where sa.group_id = ? and sa.gsim_id = ? order by sa.status_enum ASC, sa.account_no ASC"; - childSavings=retrieveAccountDetails(savingswhereClauseForGroup,new Object[] { groupId , gsimId}); + childSavings = retrieveAccountDetails(savingswhereClauseForGroup, new Object[] { groupId, gsimId }); - gsimAccounts.add(new GSIMContainer(gsimAccount.getGsimId(),gsimAccount.getGroupId(), gsimAccount.getAccountNumber(), - childSavings, gsimAccount.getParentDeposit(),gsimAccount.getSavingsStatus())); - } + gsimAccounts.add(new GSIMContainer(gsimAccount.getGsimId(), gsimAccount.getGroupId(), gsimAccount.getAccountNumber(), + childSavings, gsimAccount.getParentDeposit(), gsimAccount.getSavingsStatus())); + } - return gsimAccounts; - } + return gsimAccounts; + } + @Override + public Collection findGsimAccountContainerbyGsimAccountNumber(String accountNumber) { + this.context.authenticatedUser(); + Collection gsimInfo = findGsimAccountByParentAccountNumber(accountNumber); - @Override - public Collection findGsimAccountContainerbyGsimAccountNumber(String accountNumber) { - this.context.authenticatedUser(); - Collection gsimInfo=findGsimAccountByParentAccountNumber(accountNumber); + // List glimAccounts = + // retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new + // Object[] { groupId }); + final String savingswhereClauseForGroup = " where gsim.account_number = ? order by sa.status_enum ASC, sa.account_no ASC"; - //List glimAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new Object[] { groupId }); - final String savingswhereClauseForGroup = " where gsim.account_number = ? order by sa.status_enum ASC, sa.account_no ASC"; + List gsimAccounts = new ArrayList(); + for (GroupSavingsIndividualMonitoringAccountData gsimAccount : gsimInfo) { - List gsimAccounts=new ArrayList(); - for(GroupSavingsIndividualMonitoringAccountData gsimAccount:gsimInfo) - { + List childSavings = retrieveAccountDetails(savingswhereClauseForGroup, new Object[] { accountNumber }); - List childSavings=retrieveAccountDetails(savingswhereClauseForGroup,new Object[] { accountNumber }); + gsimAccounts.add(new GSIMContainer(gsimAccount.getGsimId(), gsimAccount.getGroupId(), gsimAccount.getAccountNumber(), + childSavings, gsimAccount.getParentDeposit(), gsimAccount.getSavingsStatus())); + } - gsimAccounts.add(new GSIMContainer(gsimAccount.getGsimId(),gsimAccount.getGroupId(), gsimAccount.getAccountNumber(), - childSavings, gsimAccount.getParentDeposit(),gsimAccount.getSavingsStatus())); - } + return gsimAccounts; + } - return gsimAccounts; - } + @Override + public List findGsimAccountContainerbyGsimAccountId(Long parentAccountId) { + this.context.authenticatedUser(); + GroupSavingsIndividualMonitoringAccountData gsimAccount = findGSIMAccountByGSIMId(parentAccountId); + // List glimAccounts = + // retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new + // Object[] { groupId }); + final String savingswhereClauseForGroup = " where sa.gsim_id = ? order by sa.status_enum ASC, sa.account_no ASC"; - @Override - public List findGsimAccountContainerbyGsimAccountId(Long parentAccountId) { - this.context.authenticatedUser(); - GroupSavingsIndividualMonitoringAccountData gsimAccount=findGSIMAccountByGSIMId(parentAccountId); + List childSavings = retrieveAccountDetails(savingswhereClauseForGroup, new Object[] { parentAccountId }); - //List glimAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroupAndLoanType, new Object[] { groupId }); - final String savingswhereClauseForGroup = " where sa.gsim_id = ? order by sa.status_enum ASC, sa.account_no ASC"; + List parentGsim = new ArrayList(); - List childSavings=retrieveAccountDetails(savingswhereClauseForGroup,new Object[] { parentAccountId }); + parentGsim.add(new GSIMContainer(gsimAccount.getGsimId(), gsimAccount.getGroupId(), gsimAccount.getAccountNumber(), childSavings, + gsimAccount.getParentDeposit(), gsimAccount.getSavingsStatus())); - List parentGsim=new ArrayList(); + return parentGsim; - parentGsim.add(new GSIMContainer(gsimAccount.getGsimId(),gsimAccount.getGroupId(), gsimAccount.getAccountNumber(), - childSavings, gsimAccount.getParentDeposit(),gsimAccount.getSavingsStatus())); + } - return parentGsim ; + @Override + public Collection findGSIMAccountsByGSIMId(final Long gsimId) { + this.context.authenticatedUser(); - } + final GSIMFieldsMapper rm = new GSIMFieldsMapper(); + final String sql = "select " + rm.schema() + " and gsim.id=?"; + return this.jdbcTemplate.query(sql, rm, new Object[] { gsimId }); + } - @Override - public Collection findGSIMAccountsByGSIMId(final Long gsimId) { - this.context.authenticatedUser(); + @Override + public GroupSavingsIndividualMonitoringAccountData findGSIMAccountByGSIMId(final Long gsimId) { + this.context.authenticatedUser(); - final GSIMFieldsMapper rm = new GSIMFieldsMapper(); - final String sql = "select " + rm.schema() + " and gsim.id=?"; + final GSIMMapper rm = new GSIMMapper(); + final String sql = "select " + rm.schema() + " where gsim.id=?"; - return this.jdbcTemplate.query(sql, rm, new Object[] { gsimId }); - } + return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { gsimId }); + } - @Override - public GroupSavingsIndividualMonitoringAccountData findGSIMAccountByGSIMId(final Long gsimId) { - this.context.authenticatedUser(); + @Override + public Collection findGSIMAccountsByGroupId(String groupId) { + this.context.authenticatedUser(); - final GSIMMapper rm = new GSIMMapper(); - final String sql = "select " + rm.schema() + " where gsim.id=?"; + final GSIMMapper rm = new GSIMMapper(); + final String sql = "select " + rm.schema() + " where gsim.group_id=?"; - return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { gsimId }); - } + return this.jdbcTemplate.query(sql, rm, new Object[] { groupId }); + } + @Override + public Collection findGsimAccountByParentAccountNumber(String parentAccountIds) { + this.context.authenticatedUser(); - @Override - public Collection findGSIMAccountsByGroupId(String groupId) { - this.context.authenticatedUser(); + final GSIMMapper rm = new GSIMMapper(); + final String sql = "select " + rm.schema() + " where gsim.account_number=?"; - final GSIMMapper rm = new GSIMMapper(); - final String sql = "select " + rm.schema() + " where gsim.group_id=?"; - - return this.jdbcTemplate.query(sql, rm, new Object[] { groupId }); - } - - - @Override - public Collection findGsimAccountByParentAccountNumber(String parentAccountIds) { - this.context.authenticatedUser(); - - final GSIMMapper rm = new GSIMMapper(); - final String sql = "select " + rm.schema() + " where gsim.account_number=?"; - - return this.jdbcTemplate.query(sql, rm, new Object[] { parentAccountIds }); - } - - - @Override - public Collection findGsimAccountByGroupIdandAccountNo(String groupId,String accountNo) { - this.context.authenticatedUser(); - - GSIMMapper rm=new GSIMMapper(); - - final String sql="select "+rm.schema()+" where gsim.group_id=? and gsim.account_number=?"; - - return this.jdbcTemplate.query(sql, rm, new Object[] { accountNo }); - } - - - - private List retrieveAccountDetails(final String savingswhereClause, final Object[] inputs) { - final SavingsAccountSummaryDataMapper savingsAccountSummaryDataMapper = new SavingsAccountSummaryDataMapper(); - final String savingsSql = "select " + savingsAccountSummaryDataMapper.schema() + savingswhereClause; - this.columnValidator.validateSqlInjection(savingsAccountSummaryDataMapper.schema() , savingswhereClause); - return this.jdbcTemplate.query(savingsSql, savingsAccountSummaryDataMapper, inputs); - } - - - private static final class SavingsAccountSummaryDataMapper implements RowMapper { - - final String schemaSql; - - public SavingsAccountSummaryDataMapper() { - final StringBuilder accountsSummary = new StringBuilder(); - accountsSummary.append("sa.id as id, CONCAT('(',clnt.id,') ',clnt.display_name) as displayName,sa.account_no as accountNo, sa.external_id as externalId, sa.gsim_id as gsimId,gsim.account_number as parentAccountNo,sa.status_enum as statusEnum, "); - accountsSummary.append("sa.account_type_enum as accountType, "); - accountsSummary.append("sa.account_balance_derived as accountBalance, "); - - accountsSummary.append("sa.submittedon_date as submittedOnDate,"); - accountsSummary.append("sbu.username as submittedByUsername,"); - accountsSummary.append("sbu.firstname as submittedByFirstname, sbu.lastname as submittedByLastname,"); - - accountsSummary.append("sa.rejectedon_date as rejectedOnDate,"); - accountsSummary.append("rbu.username as rejectedByUsername,"); - accountsSummary.append("rbu.firstname as rejectedByFirstname, rbu.lastname as rejectedByLastname,"); - - accountsSummary.append("sa.withdrawnon_date as withdrawnOnDate,"); - accountsSummary.append("wbu.username as withdrawnByUsername,"); - accountsSummary.append("wbu.firstname as withdrawnByFirstname, wbu.lastname as withdrawnByLastname,"); - - accountsSummary.append("sa.approvedon_date as approvedOnDate,"); - accountsSummary.append("abu.username as approvedByUsername,"); - accountsSummary.append("abu.firstname as approvedByFirstname, abu.lastname as approvedByLastname,"); - - accountsSummary.append("sa.activatedon_date as activatedOnDate,"); - accountsSummary.append("avbu.username as activatedByUsername,"); - accountsSummary.append("avbu.firstname as activatedByFirstname, avbu.lastname as activatedByLastname,"); - - accountsSummary.append("sa.sub_status_enum as subStatusEnum, "); - accountsSummary.append("(select IFNULL(max(sat.transaction_date),sa.activatedon_date) "); - accountsSummary.append("from m_savings_account_transaction as sat "); - accountsSummary.append("where sat.is_reversed = 0 "); - accountsSummary.append("and sat.transaction_type_enum in (1,2) "); - accountsSummary.append("and sat.savings_account_id = sa.id) as lastActiveTransactionDate, "); - - accountsSummary.append("sa.closedon_date as closedOnDate,"); - accountsSummary.append("cbu.username as closedByUsername,"); - accountsSummary.append("cbu.firstname as closedByFirstname, cbu.lastname as closedByLastname,"); - - accountsSummary - .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); - accountsSummary.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); - accountsSummary.append("curr.display_symbol as currencyDisplaySymbol, "); - accountsSummary.append("sa.product_id as productId, p.name as productName, p.short_name as shortProductName, "); - accountsSummary.append("sa.deposit_type_enum as depositType "); - accountsSummary.append("from m_savings_account sa "); - accountsSummary.append("join m_savings_product as p on p.id = sa.product_id "); - accountsSummary.append("join m_currency curr on curr.code = sa.currency_code "); - accountsSummary.append("left join m_appuser sbu on sbu.id = sa.submittedon_userid "); - accountsSummary.append("left join m_appuser rbu on rbu.id = sa.rejectedon_userid "); - accountsSummary.append("left join m_appuser wbu on wbu.id = sa.withdrawnon_userid "); - accountsSummary.append("left join m_appuser abu on abu.id = sa.approvedon_userid "); - accountsSummary.append("left join m_appuser avbu on rbu.id = sa.activatedon_userid "); - accountsSummary.append("left join m_appuser cbu on cbu.id = sa.closedon_userid "); - accountsSummary.append("left join gsim_accounts gsim on gsim.id=sa.gsim_id "); - accountsSummary.append("left join m_client clnt on clnt.id=sa.client_id "); - - - this.schemaSql = accountsSummary.toString(); - } - - public String schema() { - return this.schemaSql; - } - - @Override - public SavingsSummaryCustom mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - - final Long id = JdbcSupport.getLong(rs, "id"); - final String accountNo = rs.getString("accountNo"); - final String displayName=rs.getString("displayName"); - final String externalId = rs.getString("externalId"); - final Long productId = JdbcSupport.getLong(rs, "productId"); - final String productName = rs.getString("productName"); - final String shortProductName = rs.getString("shortProductName"); - final Integer statusId = JdbcSupport.getInteger(rs, "statusEnum"); - final BigDecimal accountBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "accountBalance"); - final SavingsAccountStatusEnumData status = SavingsEnumerations.status(statusId); - final Integer accountType = JdbcSupport.getInteger(rs, "accountType"); - final EnumOptionData accountTypeData = AccountEnumerations.loanType(accountType); - final Integer depositTypeId = JdbcSupport.getInteger(rs, "depositType"); - final EnumOptionData depositTypeData = SavingsEnumerations.depositType(depositTypeId); - - 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 Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); - - final LocalDate submittedOnDate = JdbcSupport.getLocalDate(rs, "submittedOnDate"); - final String submittedByUsername = rs.getString("submittedByUsername"); - final String submittedByFirstname = rs.getString("submittedByFirstname"); - final String submittedByLastname = rs.getString("submittedByLastname"); - - final LocalDate rejectedOnDate = JdbcSupport.getLocalDate(rs, "rejectedOnDate"); - final String rejectedByUsername = rs.getString("rejectedByUsername"); - final String rejectedByFirstname = rs.getString("rejectedByFirstname"); - final String rejectedByLastname = rs.getString("rejectedByLastname"); - - final LocalDate withdrawnOnDate = JdbcSupport.getLocalDate(rs, "withdrawnOnDate"); - final String withdrawnByUsername = rs.getString("withdrawnByUsername"); - final String withdrawnByFirstname = rs.getString("withdrawnByFirstname"); - final String withdrawnByLastname = rs.getString("withdrawnByLastname"); - - final LocalDate approvedOnDate = JdbcSupport.getLocalDate(rs, "approvedOnDate"); - final String approvedByUsername = rs.getString("approvedByUsername"); - final String approvedByFirstname = rs.getString("approvedByFirstname"); - final String approvedByLastname = rs.getString("approvedByLastname"); - - final LocalDate activatedOnDate = JdbcSupport.getLocalDate(rs, "activatedOnDate"); - final String activatedByUsername = rs.getString("activatedByUsername"); - final String activatedByFirstname = rs.getString("activatedByFirstname"); - final String activatedByLastname = rs.getString("activatedByLastname"); - - final LocalDate closedOnDate = JdbcSupport.getLocalDate(rs, "closedOnDate"); - final String closedByUsername = rs.getString("closedByUsername"); - final String closedByFirstname = rs.getString("closedByFirstname"); - final String closedByLastname = rs.getString("closedByLastname"); - final Integer subStatusEnum = JdbcSupport.getInteger(rs, "subStatusEnum"); - final SavingsAccountSubStatusEnumData subStatus = SavingsEnumerations.subStatus(subStatusEnum); - - final LocalDate lastActiveTransactionDate = JdbcSupport.getLocalDate(rs, "lastActiveTransactionDate"); - - final SavingsAccountApplicationTimelineData timeline = new SavingsAccountApplicationTimelineData(submittedOnDate, - submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, - rejectedByFirstname, rejectedByLastname, withdrawnOnDate, withdrawnByUsername, withdrawnByFirstname, - withdrawnByLastname, approvedOnDate, approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, - activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, - closedByLastname); - - return new SavingsSummaryCustom(id,displayName, accountNo, externalId, productId, productName, shortProductName, status, currency, accountBalance, - accountTypeData, timeline, depositTypeData, subStatus, lastActiveTransactionDate); - } - } + return this.jdbcTemplate.query(sql, rm, new Object[] { parentAccountIds }); + } + + @Override + public Collection findGsimAccountByGroupIdandAccountNo(String groupId, String accountNo) { + this.context.authenticatedUser(); + + GSIMMapper rm = new GSIMMapper(); + + final String sql = "select " + rm.schema() + " where gsim.group_id=? and gsim.account_number=?"; + + return this.jdbcTemplate.query(sql, rm, new Object[] { accountNo }); + } + + private List retrieveAccountDetails(final String savingswhereClause, final Object[] inputs) { + final SavingsAccountSummaryDataMapper savingsAccountSummaryDataMapper = new SavingsAccountSummaryDataMapper(); + final String savingsSql = "select " + savingsAccountSummaryDataMapper.schema() + savingswhereClause; + this.columnValidator.validateSqlInjection(savingsAccountSummaryDataMapper.schema(), savingswhereClause); + return this.jdbcTemplate.query(savingsSql, savingsAccountSummaryDataMapper, inputs); + } + + private static final class SavingsAccountSummaryDataMapper implements RowMapper { + + final String schemaSql; + + public SavingsAccountSummaryDataMapper() { + final StringBuilder accountsSummary = new StringBuilder(); + accountsSummary.append( + "sa.id as id, CONCAT('(',clnt.id,') ',clnt.display_name) as displayName,sa.account_no as accountNo, sa.external_id as externalId, sa.gsim_id as gsimId,gsim.account_number as parentAccountNo,sa.status_enum as statusEnum, "); + accountsSummary.append("sa.account_type_enum as accountType, "); + accountsSummary.append("sa.account_balance_derived as accountBalance, "); + + accountsSummary.append("sa.submittedon_date as submittedOnDate,"); + accountsSummary.append("sbu.username as submittedByUsername,"); + accountsSummary.append("sbu.firstname as submittedByFirstname, sbu.lastname as submittedByLastname,"); + + accountsSummary.append("sa.rejectedon_date as rejectedOnDate,"); + accountsSummary.append("rbu.username as rejectedByUsername,"); + accountsSummary.append("rbu.firstname as rejectedByFirstname, rbu.lastname as rejectedByLastname,"); + + accountsSummary.append("sa.withdrawnon_date as withdrawnOnDate,"); + accountsSummary.append("wbu.username as withdrawnByUsername,"); + accountsSummary.append("wbu.firstname as withdrawnByFirstname, wbu.lastname as withdrawnByLastname,"); + + accountsSummary.append("sa.approvedon_date as approvedOnDate,"); + accountsSummary.append("abu.username as approvedByUsername,"); + accountsSummary.append("abu.firstname as approvedByFirstname, abu.lastname as approvedByLastname,"); + + accountsSummary.append("sa.activatedon_date as activatedOnDate,"); + accountsSummary.append("avbu.username as activatedByUsername,"); + accountsSummary.append("avbu.firstname as activatedByFirstname, avbu.lastname as activatedByLastname,"); + + accountsSummary.append("sa.sub_status_enum as subStatusEnum, "); + accountsSummary.append("(select IFNULL(max(sat.transaction_date),sa.activatedon_date) "); + accountsSummary.append("from m_savings_account_transaction as sat "); + accountsSummary.append("where sat.is_reversed = 0 "); + accountsSummary.append("and sat.transaction_type_enum in (1,2) "); + accountsSummary.append("and sat.savings_account_id = sa.id) as lastActiveTransactionDate, "); + + accountsSummary.append("sa.closedon_date as closedOnDate,"); + accountsSummary.append("cbu.username as closedByUsername,"); + accountsSummary.append("cbu.firstname as closedByFirstname, cbu.lastname as closedByLastname,"); + + accountsSummary.append( + "sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); + accountsSummary.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); + accountsSummary.append("curr.display_symbol as currencyDisplaySymbol, "); + accountsSummary.append("sa.product_id as productId, p.name as productName, p.short_name as shortProductName, "); + accountsSummary.append("sa.deposit_type_enum as depositType "); + accountsSummary.append("from m_savings_account sa "); + accountsSummary.append("join m_savings_product as p on p.id = sa.product_id "); + accountsSummary.append("join m_currency curr on curr.code = sa.currency_code "); + accountsSummary.append("left join m_appuser sbu on sbu.id = sa.submittedon_userid "); + accountsSummary.append("left join m_appuser rbu on rbu.id = sa.rejectedon_userid "); + accountsSummary.append("left join m_appuser wbu on wbu.id = sa.withdrawnon_userid "); + accountsSummary.append("left join m_appuser abu on abu.id = sa.approvedon_userid "); + accountsSummary.append("left join m_appuser avbu on rbu.id = sa.activatedon_userid "); + accountsSummary.append("left join m_appuser cbu on cbu.id = sa.closedon_userid "); + accountsSummary.append("left join gsim_accounts gsim on gsim.id=sa.gsim_id "); + accountsSummary.append("left join m_client clnt on clnt.id=sa.client_id "); + + this.schemaSql = accountsSummary.toString(); + } + + public String schema() { + return this.schemaSql; + } + + @Override + public SavingsSummaryCustom mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { + + final Long id = JdbcSupport.getLong(rs, "id"); + final String accountNo = rs.getString("accountNo"); + final String displayName = rs.getString("displayName"); + final String externalId = rs.getString("externalId"); + final Long productId = JdbcSupport.getLong(rs, "productId"); + final String productName = rs.getString("productName"); + final String shortProductName = rs.getString("shortProductName"); + final Integer statusId = JdbcSupport.getInteger(rs, "statusEnum"); + final BigDecimal accountBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "accountBalance"); + final SavingsAccountStatusEnumData status = SavingsEnumerations.status(statusId); + final Integer accountType = JdbcSupport.getInteger(rs, "accountType"); + final EnumOptionData accountTypeData = AccountEnumerations.loanType(accountType); + final Integer depositTypeId = JdbcSupport.getInteger(rs, "depositType"); + final EnumOptionData depositTypeData = SavingsEnumerations.depositType(depositTypeId); + + 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 Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); + + final LocalDate submittedOnDate = JdbcSupport.getLocalDate(rs, "submittedOnDate"); + final String submittedByUsername = rs.getString("submittedByUsername"); + final String submittedByFirstname = rs.getString("submittedByFirstname"); + final String submittedByLastname = rs.getString("submittedByLastname"); + + final LocalDate rejectedOnDate = JdbcSupport.getLocalDate(rs, "rejectedOnDate"); + final String rejectedByUsername = rs.getString("rejectedByUsername"); + final String rejectedByFirstname = rs.getString("rejectedByFirstname"); + final String rejectedByLastname = rs.getString("rejectedByLastname"); + + final LocalDate withdrawnOnDate = JdbcSupport.getLocalDate(rs, "withdrawnOnDate"); + final String withdrawnByUsername = rs.getString("withdrawnByUsername"); + final String withdrawnByFirstname = rs.getString("withdrawnByFirstname"); + final String withdrawnByLastname = rs.getString("withdrawnByLastname"); + + final LocalDate approvedOnDate = JdbcSupport.getLocalDate(rs, "approvedOnDate"); + final String approvedByUsername = rs.getString("approvedByUsername"); + final String approvedByFirstname = rs.getString("approvedByFirstname"); + final String approvedByLastname = rs.getString("approvedByLastname"); + + final LocalDate activatedOnDate = JdbcSupport.getLocalDate(rs, "activatedOnDate"); + final String activatedByUsername = rs.getString("activatedByUsername"); + final String activatedByFirstname = rs.getString("activatedByFirstname"); + final String activatedByLastname = rs.getString("activatedByLastname"); + + final LocalDate closedOnDate = JdbcSupport.getLocalDate(rs, "closedOnDate"); + final String closedByUsername = rs.getString("closedByUsername"); + final String closedByFirstname = rs.getString("closedByFirstname"); + final String closedByLastname = rs.getString("closedByLastname"); + final Integer subStatusEnum = JdbcSupport.getInteger(rs, "subStatusEnum"); + final SavingsAccountSubStatusEnumData subStatus = SavingsEnumerations.subStatus(subStatusEnum); + + final LocalDate lastActiveTransactionDate = JdbcSupport.getLocalDate(rs, "lastActiveTransactionDate"); + + final SavingsAccountApplicationTimelineData timeline = new SavingsAccountApplicationTimelineData(submittedOnDate, + submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, rejectedByFirstname, + rejectedByLastname, withdrawnOnDate, withdrawnByUsername, withdrawnByFirstname, withdrawnByLastname, approvedOnDate, + approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, activatedByUsername, activatedByFirstname, + activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, closedByLastname); + + return new SavingsSummaryCustom(id, displayName, accountNo, externalId, productId, productName, shortProductName, status, + currency, accountBalance, accountTypeData, timeline, depositTypeData, subStatus, lastActiveTransactionDate); + } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GroupSavingsIndividualMonitoringWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GroupSavingsIndividualMonitoringWritePlatformService.java index 2fbe48466..3dbe63da1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GroupSavingsIndividualMonitoringWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GroupSavingsIndividualMonitoringWritePlatformService.java @@ -23,8 +23,7 @@ import java.math.BigDecimal; import org.apache.fineract.portfolio.group.domain.Group; import org.apache.fineract.portfolio.savings.domain.GroupSavingsIndividualMonitoring; -public interface GroupSavingsIndividualMonitoringWritePlatformService -{ +public interface GroupSavingsIndividualMonitoringWritePlatformService { void setIsAcceptingChild(GroupSavingsIndividualMonitoring gsimAccount); @@ -32,6 +31,6 @@ public interface GroupSavingsIndividualMonitoringWritePlatformService void incrementChildAccountCount(GroupSavingsIndividualMonitoring gsimAccount); - GroupSavingsIndividualMonitoring addGSIMAccountInfo(String accountNumber, Group group, BigDecimal parentDeposit, Long childAccountsCount, - Boolean isAcceptingChild, Integer loanStatus, BigDecimal applicationId); + GroupSavingsIndividualMonitoring addGSIMAccountInfo(String accountNumber, Group group, BigDecimal parentDeposit, + Long childAccountsCount, Boolean isAcceptingChild, Integer loanStatus, BigDecimal applicationId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GroupSavingsIndividualMonitoringWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GroupSavingsIndividualMonitoringWritePlatformServiceImpl.java index 2b787abb4..29415d145 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GroupSavingsIndividualMonitoringWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/GroupSavingsIndividualMonitoringWritePlatformServiceImpl.java @@ -28,61 +28,51 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class GroupSavingsIndividualMonitoringWritePlatformServiceImpl implements GroupSavingsIndividualMonitoringWritePlatformService -{ +public class GroupSavingsIndividualMonitoringWritePlatformServiceImpl implements GroupSavingsIndividualMonitoringWritePlatformService { + private final PlatformSecurityContext context; - private final PlatformSecurityContext context; + private final GSIMRepositoy gsimAccountRepository; - private final GSIMRepositoy gsimAccountRepository; + private final LoanRepository loanRepository; - private final LoanRepository loanRepository; + @Autowired + public GroupSavingsIndividualMonitoringWritePlatformServiceImpl(final PlatformSecurityContext context, + final GSIMRepositoy gsimAccountRepository, final LoanRepository loanRepository) { + this.context = context; + this.gsimAccountRepository = gsimAccountRepository; + this.loanRepository = loanRepository; + } - @Autowired - public GroupSavingsIndividualMonitoringWritePlatformServiceImpl(final PlatformSecurityContext context,final GSIMRepositoy gsimAccountRepository, - final LoanRepository loanRepository) - { - this.context=context; - this.gsimAccountRepository=gsimAccountRepository; - this.loanRepository=loanRepository; - } + @Override + public GroupSavingsIndividualMonitoring addGSIMAccountInfo(String accountNumber, Group group, BigDecimal parentDeposit, + Long childAccountsCount, Boolean isAcceptingChild, Integer loanStatus, BigDecimal applicationId) { - @Override - public GroupSavingsIndividualMonitoring addGSIMAccountInfo(String accountNumber,Group group,BigDecimal parentDeposit,Long childAccountsCount, - Boolean isAcceptingChild,Integer loanStatus,BigDecimal applicationId) - { + GroupSavingsIndividualMonitoring glimAccountInfo = GroupSavingsIndividualMonitoring.getInstance(accountNumber, group, parentDeposit, + childAccountsCount, isAcceptingChild, loanStatus, applicationId); - GroupSavingsIndividualMonitoring glimAccountInfo=GroupSavingsIndividualMonitoring.getInstance(accountNumber,group,parentDeposit,childAccountsCount, - isAcceptingChild,loanStatus,applicationId); + return this.gsimAccountRepository.save(glimAccountInfo); - return this.gsimAccountRepository.save(glimAccountInfo ); + } - } + @Override + public void setIsAcceptingChild(GroupSavingsIndividualMonitoring glimAccount) { + glimAccount.setIsAcceptingChild(true); + gsimAccountRepository.save(glimAccount); + } - @Override - public void setIsAcceptingChild(GroupSavingsIndividualMonitoring glimAccount) - { - glimAccount.setIsAcceptingChild(true); - gsimAccountRepository.save(glimAccount); + @Override + public void resetIsAcceptingChild(GroupSavingsIndividualMonitoring glimAccount) { + glimAccount.setIsAcceptingChild(false); + gsimAccountRepository.save(glimAccount); - } + } - - @Override - public void resetIsAcceptingChild(GroupSavingsIndividualMonitoring glimAccount) - { - glimAccount.setIsAcceptingChild(false); - gsimAccountRepository.save(glimAccount); - - } - - - @Override - public void incrementChildAccountCount(GroupSavingsIndividualMonitoring glimAccount) - { - long count=glimAccount.getChildAccountsCount(); - glimAccount.setChildAccountsCount(count+1); - gsimAccountRepository.save(glimAccount); - } -} \ No newline at end of file + @Override + public void incrementChildAccountCount(GroupSavingsIndividualMonitoring glimAccount) { + long count = glimAccount.getChildAccountsCount(); + glimAccount.setChildAccountsCount(count + 1); + gsimAccountRepository.save(glimAccount); + } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/RecurringDepositProductWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/RecurringDepositProductWritePlatformService.java index 343caaea3..81a5a2914 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/RecurringDepositProductWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/RecurringDepositProductWritePlatformService.java @@ -28,4 +28,4 @@ public interface RecurringDepositProductWritePlatformService { CommandProcessingResult update(Long productId, JsonCommand command); CommandProcessingResult delete(Long productId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/RecurringDepositProductWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/RecurringDepositProductWritePlatformServiceJpaRepositoryImpl.java index 94d8a137b..85adc3294 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/RecurringDepositProductWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/RecurringDepositProductWritePlatformServiceJpaRepositoryImpl.java @@ -101,8 +101,8 @@ public class RecurringDepositProductWritePlatformServiceJpaRepositoryImpl implem } catch (final DataAccessException e) { handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -123,8 +123,8 @@ public class RecurringDepositProductWritePlatformServiceJpaRepositoryImpl implem final Map changes = product.update(command); if (changes.containsKey(chargesParamName)) { - final Set savingsProductCharges = this.depositProductAssembler.assembleListOfSavingsProductCharges(command, product - .currency().getCode()); + final Set savingsProductCharges = this.depositProductAssembler.assembleListOfSavingsProductCharges(command, + product.currency().getCode()); final boolean updated = product.update(savingsProductCharges); if (!updated) { changes.remove(chargesParamName); @@ -161,8 +161,8 @@ public class RecurringDepositProductWritePlatformServiceJpaRepositoryImpl implem } catch (final DataAccessException e) { handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -192,8 +192,8 @@ public class RecurringDepositProductWritePlatformServiceJpaRepositoryImpl implem if (realCause.getMessage().contains("sp_unq_name")) { final String name = command.stringValueOfParameterNamed("name"); - throw new PlatformDataIntegrityException("error.msg.product.savings.duplicate.name", "Recurring Deposit product with name `" - + name + "` already exists", "name", name); + throw new PlatformDataIntegrityException("error.msg.product.savings.duplicate.name", + "Recurring Deposit product with name `" + name + "` already exists", "name", name); } else if (realCause.getMessage().contains("sp_unq_short_name")) { final String shortName = command.stringValueOfParameterNamed("shortName"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountApplicationTransitionApiJsonValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountApplicationTransitionApiJsonValidator.java index ec84dc83c..ccdd96233 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountApplicationTransitionApiJsonValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountApplicationTransitionApiJsonValidator.java @@ -137,4 +137,4 @@ public final class SavingsAccountApplicationTransitionApiJsonValidator { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountChargeReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountChargeReadPlatformServiceImpl.java index 46170407b..2f6a2c486 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountChargeReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountChargeReadPlatformServiceImpl.java @@ -73,18 +73,12 @@ public class SavingsAccountChargeReadPlatformServiceImpl implements SavingsAccou private static final class SavingsAccountChargeMapper implements RowMapper { public String schema() { - return "sc.id as id, c.id as chargeId, sc.savings_account_id as accountId, c.name as name, " - + "sc.amount as amountDue, " - + "sc.amount_paid_derived as amountPaid, " - + "sc.amount_waived_derived as amountWaived, " - + "sc.amount_writtenoff_derived as amountWrittenOff, " - + "sc.amount_outstanding_derived as amountOutstanding, " + return "sc.id as id, c.id as chargeId, sc.savings_account_id as accountId, c.name as name, " + "sc.amount as amountDue, " + + "sc.amount_paid_derived as amountPaid, " + "sc.amount_waived_derived as amountWaived, " + + "sc.amount_writtenoff_derived as amountWrittenOff, " + "sc.amount_outstanding_derived as amountOutstanding, " + "sc.calculation_percentage as percentageOf, sc.calculation_on_amount as amountPercentageAppliedTo, " - + "sc.charge_time_enum as chargeTime, " - + "sc.is_penalty as penalty, " - + "sc.charge_due_date as dueAsOfDate, " - + "sc.fee_on_month as feeOnMonth, " - + "sc.fee_on_day as feeOnDay, sc.fee_interval as feeInterval, " + + "sc.charge_time_enum as chargeTime, " + "sc.is_penalty as penalty, " + "sc.charge_due_date as dueAsOfDate, " + + "sc.fee_on_month as feeOnMonth, " + "sc.fee_on_day as feeOnDay, sc.fee_interval as feeInterval, " + "sc.charge_calculation_enum as chargeCalculation, " + "sc.is_active as isActive, sc.inactivated_on_date as inactivationDate, " + "c.currency_code as currencyCode, oc.name as currencyName, " @@ -240,20 +234,21 @@ public class SavingsAccountChargeReadPlatformServiceImpl implements SavingsAccou @Override public Collection retrieveChargesWithAnnualFeeDue() { - final String sql = "select " + this.chargeDueMapper.schema() + " where sac.charge_due_date is not null and sac.charge_time_enum = ? " + final String sql = "select " + this.chargeDueMapper.schema() + + " where sac.charge_due_date is not null and sac.charge_time_enum = ? " + " and sac.charge_due_date <= NOW() and sa.status_enum = ? "; - return this.jdbcTemplate.query(sql, this.chargeDueMapper, new Object[] {ChargeTimeType.ANNUAL_FEE.getValue(), SavingsAccountStatusType.ACTIVE.getValue()}); + return this.jdbcTemplate.query(sql, this.chargeDueMapper, + new Object[] { ChargeTimeType.ANNUAL_FEE.getValue(), SavingsAccountStatusType.ACTIVE.getValue() }); } @Override public Collection retrieveChargesWithDue() { - final String sql = "select " - + this.chargeDueMapper.schema() + final String sql = "select " + this.chargeDueMapper.schema() + " where sac.charge_due_date is not null and sac.charge_due_date <= NOW() and sac.waived = 0 and sac.is_paid_derived=0 and sac.is_active=1 and sa.status_enum = ? " + " order by sac.charge_due_date "; - return this.jdbcTemplate.query(sql, this.chargeDueMapper, new Object[] {SavingsAccountStatusType.ACTIVE.getValue()}); + return this.jdbcTemplate.query(sql, this.chargeDueMapper, new Object[] { SavingsAccountStatusType.ACTIVE.getValue() }); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountReadPlatformService.java index 433483d17..7cf7ed6d9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountReadPlatformService.java @@ -35,7 +35,8 @@ public interface SavingsAccountReadPlatformService { Collection retrieveActiveForLookup(Long clientId, DepositAccountType depositAccountType); - public Collection retrieveActiveForLookup(final Long clientId, DepositAccountType depositAccountType, String currencyCode) ; + public Collection retrieveActiveForLookup(final Long clientId, DepositAccountType depositAccountType, + String currencyCode); SavingsAccountData retrieveOne(Long savingsId); @@ -57,8 +58,10 @@ public interface SavingsAccountReadPlatformService { List retrieveSavingsIdsPendingDormant(LocalDate tenantLocalDate); List retrieveSavingsIdsPendingEscheat(LocalDate tenantLocalDate); - boolean isAccountBelongsToClient(final Long clientId, final Long accountId, final DepositAccountType depositAccountType, final String currencyCode) ; + + boolean isAccountBelongsToClient(final Long clientId, final Long accountId, final DepositAccountType depositAccountType, + final String currencyCode); String retrieveAccountNumberByAccountId(Long accountId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java index ee0ad474b..3fc762e9d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java @@ -152,7 +152,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead } @Override - public Collection retrieveActiveForLookup(final Long clientId, DepositAccountType depositAccountType, String currencyCode) { + public Collection retrieveActiveForLookup(final Long clientId, DepositAccountType depositAccountType, + String currencyCode) { final StringBuilder sqlBuilder = new StringBuilder("select " + this.savingAccountMapper.schema()); sqlBuilder.append(" where sa.client_id = ? and sa.status_enum = 300 and sa.deposit_type_enum = ? and sa.currency_code = ? "); @@ -177,7 +178,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final Object[] objectArray = new Object[2]; objectArray[0] = hierarchySearchString; int arrayPos = 1; - if(searchParameters!=null) { + if (searchParameters != null) { String sqlQueryCriteria = searchParameters.getSqlSearch(); if (StringUtils.isNotBlank(sqlQueryCriteria)) { sqlQueryCriteria = sqlQueryCriteria.replaceAll("accountNo", "sa.account_no"); @@ -190,9 +191,9 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead objectArray[arrayPos] = searchParameters.getExternalId(); arrayPos = arrayPos + 1; } - if(searchParameters.getOfficeId()!=null){ + if (searchParameters.getOfficeId() != null) { sqlBuilder.append("and c.office_id =?"); - objectArray[arrayPos]=searchParameters.getOfficeId(); + objectArray[arrayPos] = searchParameters.getOfficeId(); arrayPos = arrayPos + 1; } if (searchParameters.isOrderByRequested()) { @@ -268,8 +269,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead sqlBuilder.append("cbu.username as closedByUsername,"); sqlBuilder.append("cbu.firstname as closedByFirstname, cbu.lastname as closedByLastname,"); - sqlBuilder - .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); + sqlBuilder.append( + "sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); @@ -281,17 +282,21 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead sqlBuilder.append("sa.min_required_opening_balance as minRequiredOpeningBalance, "); sqlBuilder.append("sa.lockin_period_frequency as lockinPeriodFrequency,"); sqlBuilder.append("sa.lockin_period_frequency_enum as lockinPeriodFrequencyType, "); - // sqlBuilder.append("sa.withdrawal_fee_amount as withdrawalFeeAmount,"); - // sqlBuilder.append("sa.withdrawal_fee_type_enum as withdrawalFeeTypeEnum, "); + // sqlBuilder.append("sa.withdrawal_fee_amount as + // withdrawalFeeAmount,"); + // sqlBuilder.append("sa.withdrawal_fee_type_enum as + // withdrawalFeeTypeEnum, "); sqlBuilder.append("sa.withdrawal_fee_for_transfer as withdrawalFeeForTransfers, "); sqlBuilder.append("sa.allow_overdraft as allowOverdraft, "); sqlBuilder.append("sa.overdraft_limit as overdraftLimit, "); sqlBuilder.append("sa.nominal_annual_interest_rate_overdraft as nominalAnnualInterestRateOverdraft, "); sqlBuilder.append("sa.min_overdraft_for_interest_calculation as minOverdraftForInterestCalculation, "); // sqlBuilder.append("sa.annual_fee_amount as annualFeeAmount,"); - // sqlBuilder.append("sa.annual_fee_on_month as annualFeeOnMonth, "); + // sqlBuilder.append("sa.annual_fee_on_month as annualFeeOnMonth, + // "); // sqlBuilder.append("sa.annual_fee_on_day as annualFeeOnDay, "); - // sqlBuilder.append("sa.annual_fee_next_due_date as annualFeeNextDueDate, "); + // sqlBuilder.append("sa.annual_fee_next_due_date as + // annualFeeNextDueDate, "); sqlBuilder.append("sa.total_deposits_derived as totalDeposits, "); sqlBuilder.append("sa.total_withdrawals_derived as totalWithdrawals, "); sqlBuilder.append("sa.total_withdrawal_fees_derived as totalWithdrawalFees, "); @@ -377,15 +382,15 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead Integer daysToEscheat = null; LocalDate localTenantDate = DateUtils.getLocalDateOfTenant(); - if(isDormancyTrackingActive && statusEnum.equals(SavingsAccountStatusType.ACTIVE.getValue())){ - if(subStatusEnum < SavingsAccountSubStatusEnum.ESCHEAT.getValue()){ - daysToEscheat = Days.daysBetween(localTenantDate,lastActiveTransactionDate.plusDays(numDaysToEscheat)).getDays(); + if (isDormancyTrackingActive && statusEnum.equals(SavingsAccountStatusType.ACTIVE.getValue())) { + if (subStatusEnum < SavingsAccountSubStatusEnum.ESCHEAT.getValue()) { + daysToEscheat = Days.daysBetween(localTenantDate, lastActiveTransactionDate.plusDays(numDaysToEscheat)).getDays(); } - if(subStatusEnum < SavingsAccountSubStatusEnum.DORMANT.getValue()){ - daysToDormancy = Days.daysBetween(localTenantDate,lastActiveTransactionDate.plusDays(numDaysToDormancy)).getDays(); + if (subStatusEnum < SavingsAccountSubStatusEnum.DORMANT.getValue()) { + daysToDormancy = Days.daysBetween(localTenantDate, lastActiveTransactionDate.plusDays(numDaysToDormancy)).getDays(); } - if(subStatusEnum < SavingsAccountSubStatusEnum.INACTIVE.getValue()){ - daysToInactive = Days.daysBetween(localTenantDate,lastActiveTransactionDate.plusDays(numDaysToInactive)).getDays(); + if (subStatusEnum < SavingsAccountSubStatusEnum.INACTIVE.getValue()) { + daysToInactive = Days.daysBetween(localTenantDate, lastActiveTransactionDate.plusDays(numDaysToInactive)).getDays(); } } @@ -420,11 +425,10 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final String closedByLastname = rs.getString("closedByLastname"); final SavingsAccountApplicationTimelineData timeline = new SavingsAccountApplicationTimelineData(submittedOnDate, - submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, - rejectedByFirstname, rejectedByLastname, withdrawnOnDate, withdrawnByUsername, withdrawnByFirstname, - withdrawnByLastname, approvedOnDate, approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, - activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, - closedByLastname); + submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, rejectedByFirstname, + rejectedByLastname, withdrawnOnDate, withdrawnByUsername, withdrawnByFirstname, withdrawnByLastname, approvedOnDate, + approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, activatedByUsername, activatedByFirstname, + activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, closedByLastname); final String currencyCode = rs.getString("currencyCode"); final String currencyName = rs.getString("currencyName"); @@ -432,24 +436,22 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final BigDecimal nominalAnnualInterestRate = rs.getBigDecimal("nominalAnnualInterestRate"); - final EnumOptionData interestCompoundingPeriodType = SavingsEnumerations - .compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, - "interestCompoundingPeriodType"))); + final EnumOptionData interestCompoundingPeriodType = SavingsEnumerations.compoundingInterestPeriodType( + SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, "interestCompoundingPeriodType"))); - final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType - .fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType"))); + final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType( + SavingsPostingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType"))); - final EnumOptionData interestCalculationType = SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType - .fromInt(JdbcSupport.getInteger(rs, "interestCalculationType"))); + final EnumOptionData interestCalculationType = SavingsEnumerations + .interestCalculationType(SavingsInterestCalculationType.fromInt(JdbcSupport.getInteger(rs, "interestCalculationType"))); - final EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations - .interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs, - "interestCalculationDaysInYearType"))); + final EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations.interestCalculationDaysInYearType( + SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs, "interestCalculationDaysInYearType"))); final BigDecimal minRequiredOpeningBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "minRequiredOpeningBalance"); @@ -532,14 +534,15 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead BigDecimal interestNotPosted = BigDecimal.ZERO; LocalDate lastInterestCalculationDate = null; - if(totalInterestEarned != null){ + if (totalInterestEarned != null) { interestNotPosted = totalInterestEarned.subtract(totalInterestPosted).add(totalOverdraftInterestDerived); lastInterestCalculationDate = JdbcSupport.getLocalDate(rs, "lastInterestCalculationDate"); } final SavingsAccountSummaryData summary = new SavingsAccountSummaryData(currency, totalDeposits, totalWithdrawals, totalWithdrawalFees, totalAnnualFees, totalInterestEarned, totalInterestPosted, accountBalance, totalFeeCharge, - totalPenaltyCharge, totalOverdraftInterestDerived, totalWithholdTax, interestNotPosted, lastInterestCalculationDate, availableBalance); + totalPenaltyCharge, totalOverdraftInterestDerived, totalWithholdTax, interestNotPosted, lastInterestCalculationDate, + availableBalance); final boolean withHoldTax = rs.getBoolean("withHoldTax"); final Long taxGroupId = JdbcSupport.getLong(rs, "taxGroupId"); @@ -550,12 +553,12 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead } return SavingsAccountData.instance(id, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId, - productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, - nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, - interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, - summary, allowOverdraft, overdraftLimit, minRequiredBalance, enforceMinRequiredBalance, - minBalanceForInterestCalculation, onHoldFunds, nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, - taxGroupData, lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat, onHoldAmount); + productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, nominalAnnualInterestRate, + interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, + allowOverdraft, overdraftLimit, minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, + onHoldFunds, nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroupData, + lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat, onHoldAmount); } } @@ -762,8 +765,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final String sql = "select " + this.transactionsMapper.schema() + " where sa.id = ? and sa.deposit_type_enum = ? and tr.id= ?"; - return this.jdbcTemplate.queryForObject(sql, this.transactionsMapper, new Object[] { savingsId, depositAccountType.getValue(), - transactionId }); + return this.jdbcTemplate.queryForObject(sql, this.transactionsMapper, + new Object[] { savingsId, depositAccountType.getValue(), transactionId }); } /* @@ -788,7 +791,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead sqlBuilder.append("tr.transaction_date as transactionDate, tr.amount as transactionAmount,"); sqlBuilder.append("tr.created_date as submittedOnDate,"); sqlBuilder.append(" au.username as submittedByUsername, "); - sqlBuilder.append(" nt.note as transactionNote, ") ; + sqlBuilder.append(" nt.note as transactionNote, "); sqlBuilder.append("tr.running_balance_derived as runningBalance, tr.is_reversed as reversed,"); sqlBuilder.append("fromtran.id as fromTransferId, fromtran.is_reversed as fromTransferReversed,"); sqlBuilder.append("fromtran.transaction_date as fromTransferDate, fromtran.amount as fromTransferAmount,"); @@ -799,8 +802,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead sqlBuilder.append("sa.id as savingsId, sa.account_no as accountNo,"); sqlBuilder.append("pd.payment_type_id as paymentType,pd.account_number as accountNumber,pd.check_number as checkNumber, "); sqlBuilder.append("pd.receipt_number as receiptNumber, pd.bank_number as bankNumber,pd.routing_code as routingCode, "); - sqlBuilder - .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); + sqlBuilder.append( + "sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); sqlBuilder.append("pt.value as paymentTypeName, "); @@ -813,7 +816,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead sqlBuilder.append("left join m_payment_detail pd on tr.payment_detail_id = pd.id "); sqlBuilder.append("left join m_payment_type pt on pd.payment_type_id = pt.id "); sqlBuilder.append(" left join m_appuser au on au.id=tr.appuser_id "); - sqlBuilder.append(" left join m_note nt ON nt.savings_account_transaction_id=tr.id ") ; + sqlBuilder.append(" left join m_note nt ON nt.savings_account_transaction_id=tr.id "); this.schemaSql = sqlBuilder.toString(); } @@ -860,8 +863,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); AccountTransferData transfer = null; final Long fromTransferId = JdbcSupport.getLong(rs, "fromTransferId"); @@ -880,15 +883,14 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final boolean toTransferReversed = rs.getBoolean("toTransferReversed"); final String toTransferDescription = rs.getString("toTransferDescription"); - - transfer = AccountTransferData.transferBasicDetails(toTransferId, currency, toTransferAmount, toTransferDate, toTransferDescription, toTransferReversed); } final String submittedByUsername = rs.getString("submittedByUsername"); - final String note = rs.getString("transactionNote") ; + final String note = rs.getString("transactionNote"); return SavingsAccountTransactionData.create(id, transactionType, paymentDetailData, savingsId, accountNo, date, currency, - amount, outstandingChargeAmount, runningBalance, reversed, transfer, submittedOnDate, postInterestAsOn, submittedByUsername, note); + amount, outstandingChargeAmount, runningBalance, reversed, transfer, submittedOnDate, postInterestAsOn, + submittedByUsername, note); } } @@ -899,8 +901,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead public SavingsAccountTransactionTemplateMapper() { final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("sa.id as id, sa.account_no as accountNo, "); - sqlBuilder - .append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); + sqlBuilder.append( + "sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, sa.currency_multiplesof as inMultiplesOf, "); sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); sqlBuilder.append("sa.min_required_opening_balance as minRequiredOpeningBalance "); @@ -926,8 +928,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); return SavingsAccountTransactionData.template(savingsId, accountNo, DateUtils.getLocalDateOfTenant(), currency); } @@ -946,8 +948,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead 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, sp.currency_multiplesof as inMultiplesOf, "); + sqlBuilder.append( + "sp.currency_code as currencyCode, sp.currency_digits as currencyDigits, sp.currency_multiplesof as inMultiplesOf, "); sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); sqlBuilder.append("sp.nominal_annual_interest_rate as nominalAnnualIterestRate, "); @@ -958,8 +960,10 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead 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("sp.withdrawal_fee_amount as withdrawalFeeAmount,"); - // sqlBuilder.append("sp.withdrawal_fee_type_enum as withdrawalFeeTypeEnum, "); + // sqlBuilder.append("sp.withdrawal_fee_amount as + // withdrawalFeeAmount,"); + // sqlBuilder.append("sp.withdrawal_fee_type_enum as + // withdrawalFeeTypeEnum, "); sqlBuilder.append("sp.withdrawal_fee_for_transfer as withdrawalFeeForTransfers, "); sqlBuilder.append("sp.min_balance_for_interest_calculation as minBalanceForInterestCalculation, "); sqlBuilder.append("sp.allow_overdraft as allowOverdraft, "); @@ -970,7 +974,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead sqlBuilder.append("tg.id as taxGroupId, tg.name as taxGroupName, "); // sqlBuilder.append("sp.annual_fee_amount as annualFeeAmount,"); - // sqlBuilder.append("sp.annual_fee_on_month as annualFeeOnMonth, "); + // sqlBuilder.append("sp.annual_fee_on_month as annualFeeOnMonth, + // "); // sqlBuilder.append("sp.annual_fee_on_day as annualFeeOnDay "); sqlBuilder.append("sp.min_required_balance as minRequiredBalance, "); sqlBuilder.append("sp.enforce_min_required_balance as enforceMinRequiredBalance "); @@ -997,24 +1002,22 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final BigDecimal nominalAnnualIterestRate = rs.getBigDecimal("nominalAnnualIterestRate"); - final EnumOptionData interestCompoundingPeriodType = SavingsEnumerations - .compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, - "interestCompoundingPeriodType"))); + final EnumOptionData interestCompoundingPeriodType = SavingsEnumerations.compoundingInterestPeriodType( + SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, "interestCompoundingPeriodType"))); - final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType - .fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType"))); + final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType( + SavingsPostingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType"))); - final EnumOptionData interestCalculationType = SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType - .fromInt(JdbcSupport.getInteger(rs, "interestCalculationType"))); + final EnumOptionData interestCalculationType = SavingsEnumerations + .interestCalculationType(SavingsInterestCalculationType.fromInt(JdbcSupport.getInteger(rs, "interestCalculationType"))); - final EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations - .interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs, - "interestCalculationDaysInYearType"))); + final EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations.interestCalculationDaysInYearType( + SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs, "interestCalculationDaysInYearType"))); final BigDecimal minRequiredOpeningBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "minRequiredOpeningBalance"); @@ -1091,7 +1094,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead // final LocalDate annualFeeNextDueDate = null; final SavingsAccountSummaryData summary = null; final BigDecimal onHoldFunds = null; - final BigDecimal savingsAmountOnHold = null; + final BigDecimal savingsAmountOnHold = null; final SavingsAccountSubStatusEnumData subStatus = null; final LocalDate lastActiveTransactionDate = null; @@ -1103,12 +1106,13 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final SavingsAccountApplicationTimelineData timeline = SavingsAccountApplicationTimelineData.templateDefault(); final EnumOptionData depositType = null; return SavingsAccountData.instance(null, null, depositType, null, groupId, groupName, clientId, clientName, productId, - productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, - nominalAnnualIterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, - interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, - summary, allowOverdraft, overdraftLimit, minRequiredBalance, enforceMinRequiredBalance, - minBalanceForInterestCalculation, onHoldFunds, nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, - taxGroupData, lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat, savingsAmountOnHold); + productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, nominalAnnualIterestRate, + interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, + minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, + allowOverdraft, overdraftLimit, minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, + onHoldFunds, nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroupData, + lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat, + savingsAmountOnHold); } } @@ -1130,8 +1134,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead } @Override - public List retrieveSavingsIdsPendingInactive( - LocalDate tenantLocalDate) { + public List retrieveSavingsIdsPendingInactive(LocalDate tenantLocalDate) { List ret = null; StringBuilder sql = new StringBuilder("select sa.id "); sql.append(" from m_savings_account as sa "); @@ -1145,7 +1148,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead sql.append(" and sat.savings_account_id = sa.id)) >= sp.days_to_inactive "); try { - ret = this.jdbcTemplate.queryForList(sql.toString(), Long.class, new Object[] {formatter.print(tenantLocalDate)}); + ret = this.jdbcTemplate.queryForList(sql.toString(), Long.class, new Object[] { formatter.print(tenantLocalDate) }); } catch (EmptyResultDataAccessException e) { // ignore empty result scenario } catch (DataAccessException e) { @@ -1156,8 +1159,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead } @Override - public List retrieveSavingsIdsPendingDormant( - LocalDate tenantLocalDate) { + public List retrieveSavingsIdsPendingDormant(LocalDate tenantLocalDate) { List ret = null; StringBuilder sql = new StringBuilder("select sa.id "); sql.append(" from m_savings_account as sa "); @@ -1171,7 +1173,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead sql.append(" and sat.savings_account_id = sa.id)) >= sp.days_to_dormancy "); try { - ret = this.jdbcTemplate.queryForList(sql.toString(), Long.class, new Object[] {formatter.print(tenantLocalDate)}); + ret = this.jdbcTemplate.queryForList(sql.toString(), Long.class, new Object[] { formatter.print(tenantLocalDate) }); } catch (EmptyResultDataAccessException e) { // ignore empty result scenario } catch (DataAccessException e) { @@ -1182,8 +1184,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead } @Override - public List retrieveSavingsIdsPendingEscheat( - LocalDate tenantLocalDate) { + public List retrieveSavingsIdsPendingEscheat(LocalDate tenantLocalDate) { List ret = null; StringBuilder sql = new StringBuilder("select sa.id "); sql.append(" from m_savings_account as sa "); @@ -1197,7 +1198,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead sql.append(" and sat.savings_account_id = sa.id)) >= sp.days_to_escheat "); try { - ret = this.jdbcTemplate.queryForList(sql.toString(), Long.class, new Object[] {formatter.print(tenantLocalDate)}); + ret = this.jdbcTemplate.queryForList(sql.toString(), Long.class, new Object[] { formatter.print(tenantLocalDate) }); } catch (EmptyResultDataAccessException e) { // ignore empty result scenario } catch (DataAccessException e) { @@ -1211,8 +1212,9 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead public boolean isAccountBelongsToClient(final Long clientId, final Long accountId, final DepositAccountType depositAccountType, final String currencyCode) { try { - final StringBuilder buff = new StringBuilder("select count(*) from m_savings_account sa ") ; - buff.append(" where sa.id = ? and sa.client_id = ? and sa.deposit_type_enum = ? and sa.currency_code = ? and sa.status_enum = 300"); + final StringBuilder buff = new StringBuilder("select count(*) from m_savings_account sa "); + buff.append( + " where sa.id = ? and sa.client_id = ? and sa.deposit_type_enum = ? and sa.currency_code = ? and sa.status_enum = 300"); return this.jdbcTemplate.queryForObject(buff.toString(), new Object[] { accountId, clientId, depositAccountType.getValue(), currencyCode }, Integer.class) > 0; } catch (final EmptyResultDataAccessException e) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountWritePlatformService.java index 74ac3153f..343a38815 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountWritePlatformService.java @@ -75,7 +75,6 @@ public interface SavingsAccountWritePlatformService { void processPostActiveActions(SavingsAccount account, DateTimeFormatter fmt, Set existingTransactionIds, Set existingReversedTransactionIds); - CommandProcessingResult modifyWithHoldTax(Long savingsAccountId, JsonCommand command); void setSubStatusInactive(Long savingsId); @@ -109,4 +108,4 @@ public interface SavingsAccountWritePlatformService { CommandProcessingResult gsimDeposit(Long gsimId, JsonCommand command); CommandProcessingResult bulkGSIMClose(Long gsimId, JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index cfb3bbd45..18ada75dc --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java @@ -202,32 +202,33 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi this.appuserRepository = appuserRepository; this.standingInstructionRepository = standingInstructionRepository; this.businessEventNotifierService = businessEventNotifierService; - this.gsimRepository=gsimRepository; + this.gsimRepository = gsimRepository; } private final static Logger LOG = LoggerFactory.getLogger(SavingsAccountWritePlatformServiceJpaRepositoryImpl.class); + @Transactional @Override public CommandProcessingResult gsimActivate(final Long gsimId, final JsonCommand command) { - Long parentSavingId = gsimId; - GroupSavingsIndividualMonitoring parentSavings = gsimRepository.findById(parentSavingId).get(); - List childSavings = this.savingAccountRepositoryWrapper.findByGsimId(gsimId); + Long parentSavingId = gsimId; + GroupSavingsIndividualMonitoring parentSavings = gsimRepository.findById(parentSavingId).get(); + List childSavings = this.savingAccountRepositoryWrapper.findByGsimId(gsimId); - CommandProcessingResult result = null; - int count = 0; - for (SavingsAccount account : childSavings) { - result = activate(account.getId(), command); - if (result != null) { - count++; - if (count == parentSavings.getChildAccountsCount()) { - parentSavings.setSavingsStatus(SavingsAccountStatusType.ACTIVE.getValue()); - gsimRepository.save(parentSavings); - } - } - } - return result; - } + CommandProcessingResult result = null; + int count = 0; + for (SavingsAccount account : childSavings) { + result = activate(account.getId(), command); + if (result != null) { + count++; + if (count == parentSavings.getChildAccountsCount()) { + parentSavings.setSavingsStatus(SavingsAccountStatusType.ACTIVE.getValue()); + gsimRepository.save(parentSavings); + } + } + } + return result; + } @Transactional @Override @@ -301,22 +302,22 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi @Override public CommandProcessingResult gsimDeposit(final Long gsimId, final JsonCommand command) { - Long parentSavingId = gsimId; - // GroupSavingsIndividualMonitoringparentSavings=gsimRepository.findById(parentSavingId).get(); - List childSavings = this.savingAccountRepositoryWrapper.findByGsimId(gsimId); + Long parentSavingId = gsimId; + // GroupSavingsIndividualMonitoringparentSavings=gsimRepository.findById(parentSavingId).get(); + List childSavings = this.savingAccountRepositoryWrapper.findByGsimId(gsimId); - JsonArray savingsArray = command.arrayOfParameterNamed("savingsArray"); + JsonArray savingsArray = command.arrayOfParameterNamed("savingsArray"); - JsonArray childAccounts = command.arrayOfParameterNamed("childAccounts"); - int count = 0; + JsonArray childAccounts = command.arrayOfParameterNamed("childAccounts"); + int count = 0; - CommandProcessingResult result = null; - for (JsonElement element : savingsArray) { + CommandProcessingResult result = null; + for (JsonElement element : savingsArray) { - result = deposit(element.getAsJsonObject().get("childAccountId").getAsLong(), - JsonCommand.fromExistingCommand(command, element)); - } - return result; + result = deposit(element.getAsJsonObject().get("childAccountId").getAsLong(), + JsonCommand.fromExistingCommand(command, element)); + } + return result; } @Transactional @@ -329,8 +330,8 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi boolean isGsim = false; if (this.savingAccountRepositoryWrapper.findOneWithNotFoundDetection(savingsId).getGsim() != null) { - isGsim = true; - LOG.info("is gsim"); + isGsim = true; + LOG.info("is gsim"); } final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId); @@ -361,12 +362,12 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi gsimRepository.save(gsim); LOG.info("balance after making deposit : {} ", gsimRepository.findById(account.getGsim().getId()).get().getParentDeposit()); - } + } final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { final Note note = Note.savingsTransactionNote(account, deposit, noteText); - this.noteRepository.save(note) ; + this.noteRepository.save(note); } return new CommandProcessingResultBuilder() // @@ -423,12 +424,12 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi gsim.setParentDeposit(currentBalance); gsimRepository.save(gsim); - } + } final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { final Note note = Note.savingsTransactionNote(account, withdrawal, noteText); - this.noteRepository.save(note) ; + this.noteRepository.save(note); } return new CommandProcessingResultBuilder() // @@ -455,8 +456,7 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi fmt.withZone(DateUtils.getDateTimeZoneOfTenant()); while (todaysDate.isAfter(savingsAccountCharge.getDueLocalDate())) { - this.payCharge(savingsAccountCharge, savingsAccountCharge.getDueLocalDate(), savingsAccountCharge.amount(), - fmt, user); + this.payCharge(savingsAccountCharge, savingsAccountCharge.getDueLocalDate(), savingsAccountCharge.amount(), fmt, user); } return new CommandProcessingResultBuilder() // @@ -508,13 +508,16 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi if (transactionDate == null) { - throw new PostInterestAsOnDateException(PostInterestAsOnExceptionType.VALID_DATE); } - if (transactionDate.isBefore(account.accountSubmittedOrActivationDate())) { throw new PostInterestAsOnDateException( - PostInterestAsOnExceptionType.ACTIVATION_DATE); } + throw new PostInterestAsOnDateException(PostInterestAsOnExceptionType.VALID_DATE); + } + if (transactionDate.isBefore(account.accountSubmittedOrActivationDate())) { + throw new PostInterestAsOnDateException(PostInterestAsOnExceptionType.ACTIVATION_DATE); + } List savingTransactions = account.getTransactions(); for (SavingsAccountTransaction savingTransaction : savingTransactions) { - if (transactionDate.toDate().before(savingTransaction - .getDateOf())) { throw new PostInterestAsOnDateException(PostInterestAsOnExceptionType.LAST_TRANSACTION_DATE); } + if (transactionDate.toDate().before(savingTransaction.getDateOf())) { + throw new PostInterestAsOnDateException(PostInterestAsOnExceptionType.LAST_TRANSACTION_DATE); + } } LocalDate today = DateUtils.getLocalDateOfTenant(); @@ -586,15 +589,17 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi .findOneByIdAndSavingsAccountId(transactionId, savingsId); if (savingsAccountTransaction == null) { throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId); } - if (!allowAccountTransferModification && this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, - PortfolioAccountType.SAVINGS)) { throw new PlatformServiceUnavailableException( - "error.msg.saving.account.transfer.transaction.update.not.allowed", - "Savings account transaction:" + transactionId + " update not allowed as it involves in account transfer", - transactionId); } + if (!allowAccountTransferModification + && this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)) { + throw new PlatformServiceUnavailableException("error.msg.saving.account.transfer.transaction.update.not.allowed", + "Savings account transaction:" + transactionId + " update not allowed as it involves in account transfer", + transactionId); + } - if (!account - .allowModify()) { throw new PlatformServiceUnavailableException("error.msg.saving.account.transaction.update.not.allowed", - "Savings account transaction:" + transactionId + " update not allowed for this savings type", transactionId); } + if (!account.allowModify()) { + throw new PlatformServiceUnavailableException("error.msg.saving.account.transaction.update.not.allowed", + "Savings account transaction:" + transactionId + " update not allowed for this savings type", transactionId); + } final LocalDate today = DateUtils.getLocalDateOfTenant(); final MathContext mc = new MathContext(15, MoneyHelper.getRoundingMode()); @@ -656,13 +661,15 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi if (savingsAccountTransaction == null) { throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId); } if (!(savingsAccountTransaction.isDeposit() || savingsAccountTransaction.isWithdrawal()) - || savingsAccountTransaction.isReversed()) { throw new TransactionUpdateNotAllowedException(savingsId, transactionId); } + || savingsAccountTransaction.isReversed()) { + throw new TransactionUpdateNotAllowedException(savingsId, transactionId); + } - if (this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, - PortfolioAccountType.SAVINGS)) { throw new PlatformServiceUnavailableException( - "error.msg.saving.account.transfer.transaction.update.not.allowed", - "Savings account transaction:" + transactionId + " update not allowed as it involves in account transfer", - transactionId); } + if (this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)) { + throw new PlatformServiceUnavailableException("error.msg.saving.account.transfer.transaction.update.not.allowed", + "Savings account transaction:" + transactionId + " update not allowed as it involves in account transfer", + transactionId); + } this.savingsAccountTransactionDataValidator.validate(command); @@ -672,9 +679,10 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi if (account.isNotActive()) { throwValidationForActiveStatus(SavingsApiConstants.adjustTransactionAction); } - if (!account - .allowModify()) { throw new PlatformServiceUnavailableException("error.msg.saving.account.transaction.update.not.allowed", - "Savings account transaction:" + transactionId + " update not allowed for this savings type", transactionId); } + if (!account.allowModify()) { + throw new PlatformServiceUnavailableException("error.msg.saving.account.transaction.update.not.allowed", + "Savings account transaction:" + transactionId + " update not allowed for this savings type", transactionId); + } final Set existingTransactionIds = new HashSet<>(); final Set existingReversedTransactionIds = new HashSet<>(); updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); @@ -760,24 +768,24 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi @Override public CommandProcessingResult bulkGSIMClose(final Long gsimId, final JsonCommand command) { - final Long parentSavingId = gsimId; - GroupSavingsIndividualMonitoring parentSavings = gsimRepository.findById(parentSavingId).get(); - List childSavings = this.savingAccountRepositoryWrapper.findByGsimId(gsimId); + final Long parentSavingId = gsimId; + GroupSavingsIndividualMonitoring parentSavings = gsimRepository.findById(parentSavingId).get(); + List childSavings = this.savingAccountRepositoryWrapper.findByGsimId(gsimId); - CommandProcessingResult result = null; - int count = 0; - for (SavingsAccount account : childSavings) { - result = close(account.getId(), command); + CommandProcessingResult result = null; + int count = 0; + for (SavingsAccount account : childSavings) { + result = close(account.getId(), command); - if (result != null) { - count++; - if (count == parentSavings.getChildAccountsCount()) { - parentSavings.setSavingsStatus(SavingsAccountStatusType.CLOSED.getValue()); - gsimRepository.save(parentSavings); - } - } - } - return result; + if (result != null) { + count++; + if (count == parentSavings.getChildAccountsCount()) { + parentSavings.setSavingsStatus(SavingsAccountStatusType.CLOSED.getValue()); + gsimRepository.save(parentSavings); + } + } + } + return result; } @Override @@ -1377,8 +1385,9 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi savingsForUpdate.office().getHierarchy()); actualChanges.put("toSavingsOfficerId", toSavingsOfficer.getId()); } - if (!savingsForUpdate.hasSavingsOfficer( - fromSavingsOfficer)) { throw new SavingsOfficerAssignmentException(savingsAccountId, fromSavingsOfficerId); } + if (!savingsForUpdate.hasSavingsOfficer(fromSavingsOfficer)) { + throw new SavingsOfficerAssignmentException(savingsAccountId, fromSavingsOfficerId); + } savingsForUpdate.reassignSavingsOfficer(toSavingsOfficer, dateOfSavingsOfficerAssignment); @@ -1656,12 +1665,10 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi private void validateTransactionsForTransfer(final SavingsAccount savingsAccount, final LocalDate transferDate) { for (SavingsAccountTransaction transaction : savingsAccount.getTransactions()) { - if ((transaction.getTransactionLocalDate().isEqual(transferDate) - && transaction.getTransactionLocalDate().isAfter(transferDate)) + if ((transaction.getTransactionLocalDate().isEqual(transferDate) && transaction.getTransactionLocalDate().isAfter(transferDate)) || transaction.getTransactionLocalDate().isAfter(transferDate)) { throw new GeneralPlatformDomainRuleException(TransferApiConstants.transferClientSavingsException, - TransferApiConstants.transferClientSavingsException, new LocalDate(transaction.createdDate()), - transferDate); + TransferApiConstants.transferClientSavingsException, new LocalDate(transaction.createdDate()), transferDate); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsApplicationProcessWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsApplicationProcessWritePlatformService.java index 959a2fe0c..955d1e219 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsApplicationProcessWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsApplicationProcessWritePlatformService.java @@ -49,4 +49,4 @@ public interface SavingsApplicationProcessWritePlatformService { CommandProcessingResult undoGSIMApplicationApproval(Long gsimId, JsonCommand command); CommandProcessingResult modifyGSIMApplication(Long gsimId, JsonCommand command); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java index ba7802dc5..080b57dec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java @@ -132,8 +132,8 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl final SavingsAccountWritePlatformService savingsAccountWritePlatformService, final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository, final BusinessEventNotifierService businessEventNotifierService, - final EntityDatatableChecksWritePlatformService entityDatatableChecksWritePlatformService, - final GSIMRepositoy gsimRepository, final GroupRepositoryWrapper groupRepositoryWrapper, + final EntityDatatableChecksWritePlatformService entityDatatableChecksWritePlatformService, final GSIMRepositoy gsimRepository, + final GroupRepositoryWrapper groupRepositoryWrapper, final GroupSavingsIndividualMonitoringWritePlatformService gsimWritePlatformService) { this.context = context; this.savingAccountRepository = savingAccountRepository; @@ -151,7 +151,7 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl this.savingsAccountDomainService = savingsAccountDomainService; this.accountNumberFormatRepository = accountNumberFormatRepository; this.savingsAccountWritePlatformService = savingsAccountWritePlatformService; - this.businessEventNotifierService = businessEventNotifierService ; + this.businessEventNotifierService = businessEventNotifierService; this.entityDatatableChecksWritePlatformService = entityDatatableChecksWritePlatformService; this.gsimRepository = gsimRepository; this.groupRepositoryWrapper = groupRepositoryWrapper; @@ -169,15 +169,15 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl 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); + throw new PlatformDataIntegrityException(errorCodeBuilder.toString(), + "Savings account with accountNo " + accountNo + " already exists", "accountNo", accountNo); } else if (realCause.getMessage().contains("sa_externalid_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); + throw new PlatformDataIntegrityException(errorCodeBuilder.toString(), + "Savings account with externalId " + externalId + " already exists", "externalId", externalId); } errorCodeBuilder.append(".unknown.data.integrity.issue"); @@ -189,21 +189,21 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl @Override public CommandProcessingResult submitGSIMApplication(final JsonCommand command) { - CommandProcessingResult result = null; + CommandProcessingResult result = null; - JsonArray gsimApplications = command.arrayOfParameterNamed("clientArray"); + JsonArray gsimApplications = command.arrayOfParameterNamed("clientArray"); - final Object lock = new Object(); - synchronized (lock){ - for (JsonElement gsimApplication : gsimApplications) { - // result=submitApplication(JsonCommand.fromExistingCommand(command, - // gsimApplication)); - result = submitApplication(JsonCommand.fromExistingCommand(command, gsimApplication, + final Object lock = new Object(); + synchronized (lock) { + for (JsonElement gsimApplication : gsimApplications) { + // result=submitApplication(JsonCommand.fromExistingCommand(command, + // gsimApplication)); + result = submitApplication(JsonCommand.fromExistingCommand(command, gsimApplication, gsimApplication.getAsJsonObject().get("clientId").getAsLong())); - } - } + } + } - return result; + return result; } @Transactional @@ -220,92 +220,89 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl BigDecimal applicationId = BigDecimal.ZERO; Boolean isLastChildApplication = false; - //gsim + // gsim if (account.isAccountNumberRequiresAutoGeneration()) { - final AccountNumberFormat accountNumberFormat = this.accountNumberFormatRepository - .findByAccountType(EntityAccountType.SAVINGS); - // if application is of GSIM type - if (account.getAccountTypes() == 5) { - final Long groupId = command.longValueOfParameterNamed("groupId"); - // GSIM specific parameters - if (command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("applicationId") != null) { - applicationId = command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("applicationId"); - } + final AccountNumberFormat accountNumberFormat = this.accountNumberFormatRepository + .findByAccountType(EntityAccountType.SAVINGS); + // if application is of GSIM type + if (account.getAccountTypes() == 5) { + final Long groupId = command.longValueOfParameterNamed("groupId"); + // GSIM specific parameters + if (command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("applicationId") != null) { + applicationId = command.bigDecimalValueOfParameterNamedDefaultToNullIfZero("applicationId"); + } - if (command.booleanObjectValueOfParameterNamed("lastApplication") != null) { - isLastChildApplication = command.booleanPrimitiveValueOfParameterNamed("lastApplication"); - } + if (command.booleanObjectValueOfParameterNamed("lastApplication") != null) { + isLastChildApplication = command.booleanPrimitiveValueOfParameterNamed("lastApplication"); + } - Group group = this.groupRepositoryWrapper.findOneWithNotFoundDetection(groupId); + Group group = this.groupRepositoryWrapper.findOneWithNotFoundDetection(groupId); - if (command.booleanObjectValueOfParameterNamed("isParentAccount") != null) - { - // empty table check - if (gsimRepository.count() != 0) { - // Parent-Not an empty table + if (command.booleanObjectValueOfParameterNamed("isParentAccount") != null) { + // empty table check + if (gsimRepository.count() != 0) { + // Parent-Not an empty table - accountNumber = this.accountNumberGenerator.generate(account, accountNumberFormat); - account.updateAccountNo(accountNumber + "1"); - gsimAccount = gsimWritePlatformService.addGSIMAccountInfo(accountNumber, group, BigDecimal.ZERO, - Long.valueOf(1), true, - SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue(),applicationId); - account.setGsim(gsimAccount); - this.savingAccountRepository.save(account); + accountNumber = this.accountNumberGenerator.generate(account, accountNumberFormat); + account.updateAccountNo(accountNumber + "1"); + gsimAccount = gsimWritePlatformService.addGSIMAccountInfo(accountNumber, group, BigDecimal.ZERO, + Long.valueOf(1), true, SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue(), + applicationId); + account.setGsim(gsimAccount); + this.savingAccountRepository.save(account); - } else { - // Parent-empty table - accountNumber = this.accountNumberGenerator.generate(account, accountNumberFormat); - account.updateAccountNo(accountNumber + "1"); - gsimWritePlatformService.addGSIMAccountInfo(accountNumber, group, BigDecimal.ZERO, - Long.valueOf(1), true, - SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue(),applicationId); - account.setGsim(gsimRepository.findOneByAccountNumber(accountNumber)); - this.savingAccountRepository.save(account); - } - } else { - if (gsimRepository.count() != 0) { - // Child-Not an empty table check - gsimAccount = gsimRepository.findOneByIsAcceptingChildAndApplicationId(true,applicationId); - accountNumber = gsimAccount.getAccountNumber() - + (gsimAccount.getChildAccountsCount() + 1); - account.updateAccountNo(accountNumber); - this.gsimWritePlatformService.incrementChildAccountCount(gsimAccount); - account.setGsim(gsimAccount); - this.savingAccountRepository.save(account); + } else { + // Parent-empty table + accountNumber = this.accountNumberGenerator.generate(account, accountNumberFormat); + account.updateAccountNo(accountNumber + "1"); + gsimWritePlatformService.addGSIMAccountInfo(accountNumber, group, BigDecimal.ZERO, Long.valueOf(1), true, + SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue(), applicationId); + account.setGsim(gsimRepository.findOneByAccountNumber(accountNumber)); + this.savingAccountRepository.save(account); + } + } else { + if (gsimRepository.count() != 0) { + // Child-Not an empty table check + gsimAccount = gsimRepository.findOneByIsAcceptingChildAndApplicationId(true, applicationId); + accountNumber = gsimAccount.getAccountNumber() + (gsimAccount.getChildAccountsCount() + 1); + account.updateAccountNo(accountNumber); + this.gsimWritePlatformService.incrementChildAccountCount(gsimAccount); + account.setGsim(gsimAccount); + this.savingAccountRepository.save(account); - } else { - // Child-empty table - // if the gsim info is empty set the current account as parent - accountNumber = this.accountNumberGenerator.generate(account, accountNumberFormat); - account.updateAccountNo(accountNumber + "1"); - gsimWritePlatformService.addGSIMAccountInfo(accountNumber, group, BigDecimal.ZERO, - Long.valueOf(1), true, - SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue(),applicationId); - account.setGsim(gsimAccount); - this.savingAccountRepository.save(account); - } - //reset isAcceptingChild when processing last application of GSIM - if (isLastChildApplication) { - this.gsimWritePlatformService.resetIsAcceptingChild( - gsimRepository.findOneByIsAcceptingChildAndApplicationId(true, applicationId)); - } - } - } else // for applications other than GSIM - { - generateAccountNumber(account); - } + } else { + // Child-empty table + // if the gsim info is empty set the current account + // as parent + accountNumber = this.accountNumberGenerator.generate(account, accountNumberFormat); + account.updateAccountNo(accountNumber + "1"); + gsimWritePlatformService.addGSIMAccountInfo(accountNumber, group, BigDecimal.ZERO, Long.valueOf(1), true, + SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue(), applicationId); + account.setGsim(gsimAccount); + this.savingAccountRepository.save(account); + } + // reset isAcceptingChild when processing last + // application of GSIM + if (isLastChildApplication) { + this.gsimWritePlatformService + .resetIsAcceptingChild(gsimRepository.findOneByIsAcceptingChildAndApplicationId(true, applicationId)); + } + } + } else // for applications other than GSIM + { + generateAccountNumber(account); + } } // end of gsim final Long savingsId = account.getId(); - if(command.parameterExists(SavingsApiConstants.datatables)){ + if (command.parameterExists(SavingsApiConstants.datatables)) { this.entityDatatableChecksWritePlatformService.saveDatatables(StatusEnum.CREATE.getCode().longValue(), EntityTables.SAVING.getName(), savingsId, account.productId(), command.arrayOfParameterNamed(SavingsApiConstants.datatables)); } - this.entityDatatableChecksWritePlatformService.runTheCheckForProduct(savingsId, - EntityTables.SAVING.getName(), StatusEnum.CREATE.getCode().longValue(), - EntityTables.SAVING.getForeignKeyColumnNameOnDatatable(), account.productId()); + this.entityDatatableChecksWritePlatformService.runTheCheckForProduct(savingsId, EntityTables.SAVING.getName(), + StatusEnum.CREATE.getCode().longValue(), EntityTables.SAVING.getForeignKeyColumnNameOnDatatable(), account.productId()); this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.SAVINGS_CREATE, constructEntityMap(BusinessEntity.SAVING, account)); @@ -317,13 +314,12 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl .withClientId(account.clientId()) // .withGroupId(account.groupId()) // .withSavingsId(savingsId) // - .withGsimId(gsimAccount==null ? 0 : gsimAccount.getId()) - .build(); + .withGsimId(gsimAccount == null ? 0 : gsimAccount.getId()).build(); } catch (final DataAccessException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -342,16 +338,16 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl @Override public CommandProcessingResult modifyGSIMApplication(final Long gsimId, final JsonCommand command) { - final Long parentSavingId = gsimId; - List childSavings = this.savingAccountRepository.findByGsimId(parentSavingId); + final Long parentSavingId = gsimId; + List childSavings = this.savingAccountRepository.findByGsimId(parentSavingId); - CommandProcessingResult result = null; + CommandProcessingResult result = null; - for (SavingsAccount account : childSavings) { - result = modifyApplication(account.getId(), command); - } + for (SavingsAccount account : childSavings) { + result = modifyApplication(account.getId(), command); + } - return result; + return result; } @Transactional @@ -385,8 +381,7 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl if (changes.containsKey(SavingsApiConstants.groupIdParamName)) { final Long groupId = command.longValueOfParameterNamed(SavingsApiConstants.groupIdParamName); if (groupId != null) { - final Group group = this.groupRepository.findById(groupId) - .orElseThrow(() -> new GroupNotFoundException(groupId)); + final Group group = this.groupRepository.findById(groupId).orElseThrow(() -> new GroupNotFoundException(groupId)); if (group.isNotActive()) { if (group.isCenter()) { throw new CenterNotActiveException(groupId); } throw new GroupNotActiveException(groupId); @@ -440,8 +435,8 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } catch (final DataAccessException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return new CommandProcessingResult(Long.valueOf(-1)); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -483,26 +478,26 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl @Override public CommandProcessingResult approveGSIMApplication(final Long gsimId, final JsonCommand command) { - // GroupLoanIndividualMonitoringAccount - // glimAccount=glimRepository.findOne(loanId); - Long parentSavingId = gsimId; - GroupSavingsIndividualMonitoring parentSavings = gsimRepository.findById(parentSavingId).get(); - List childSavings = this.savingAccountRepository.findByGsimId(gsimId); - CommandProcessingResult result = null; - int count = 0; - for (SavingsAccount account : childSavings) { + // GroupLoanIndividualMonitoringAccount + // glimAccount=glimRepository.findOne(loanId); + Long parentSavingId = gsimId; + GroupSavingsIndividualMonitoring parentSavings = gsimRepository.findById(parentSavingId).get(); + List childSavings = this.savingAccountRepository.findByGsimId(gsimId); + CommandProcessingResult result = null; + int count = 0; + for (SavingsAccount account : childSavings) { - result = approveApplication(account.getId(), command); + result = approveApplication(account.getId(), command); - if (result != null) { - count++; - if (count == parentSavings.getChildAccountsCount()) { - parentSavings.setSavingsStatus(SavingsAccountStatusType.APPROVED.getValue()); - gsimRepository.save(parentSavings); - } - } - } - return result; + if (result != null) { + count++; + if (count == parentSavings.getChildAccountsCount()) { + parentSavings.setSavingsStatus(SavingsAccountStatusType.APPROVED.getValue()); + gsimRepository.save(parentSavings); + } + } + } + return result; } @Transactional @@ -517,10 +512,9 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl checkClientOrGroupActive(savingsAccount); entityDatatableChecksWritePlatformService.runTheCheckForProduct(savingsId, EntityTables.SAVING.getName(), - StatusEnum.APPROVE.getCode().longValue(),EntityTables.SAVING.getForeignKeyColumnNameOnDatatable(), + StatusEnum.APPROVE.getCode().longValue(), EntityTables.SAVING.getForeignKeyColumnNameOnDatatable(), savingsAccount.productId()); - final Map changes = savingsAccount.approveApplication(currentUser, command, DateUtils.getLocalDateOfTenant()); if (!changes.isEmpty()) { this.savingAccountRepository.save(savingsAccount); @@ -550,26 +544,26 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl @Transactional @Override public CommandProcessingResult undoGSIMApplicationApproval(final Long gsimId, final JsonCommand command) { - final Long parentSavingId = gsimId; - GroupSavingsIndividualMonitoring parentSavings = gsimRepository.findById(parentSavingId).get(); - List childSavings = this.savingAccountRepository.findByGsimId(gsimId); + final Long parentSavingId = gsimId; + GroupSavingsIndividualMonitoring parentSavings = gsimRepository.findById(parentSavingId).get(); + List childSavings = this.savingAccountRepository.findByGsimId(gsimId); - CommandProcessingResult result = null; - int count = 0; - for (SavingsAccount account : childSavings) { - result = undoApplicationApproval(account.getId(), command); + CommandProcessingResult result = null; + int count = 0; + for (SavingsAccount account : childSavings) { + result = undoApplicationApproval(account.getId(), command); - if (result != null) { - count++; - if (count == parentSavings.getChildAccountsCount()) { - parentSavings.setSavingsStatus(SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue()); - gsimRepository.save(parentSavings); - } - } + if (result != null) { + count++; + if (count == parentSavings.getChildAccountsCount()) { + parentSavings.setSavingsStatus(SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue()); + gsimRepository.save(parentSavings); + } + } - } + } - return result; + return result; } @Transactional @@ -610,24 +604,24 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl @Override public CommandProcessingResult rejectGSIMApplication(final Long gsimId, final JsonCommand command) { - final Long parentSavingId = gsimId; - GroupSavingsIndividualMonitoring parentSavings = gsimRepository.findById(parentSavingId).get(); - List childSavings = this.savingAccountRepository.findByGsimId(gsimId); + final Long parentSavingId = gsimId; + GroupSavingsIndividualMonitoring parentSavings = gsimRepository.findById(parentSavingId).get(); + List childSavings = this.savingAccountRepository.findByGsimId(gsimId); - CommandProcessingResult result = null; - int count = 0; - for (SavingsAccount account : childSavings) { - result = rejectApplication(account.getId(), command); + CommandProcessingResult result = null; + int count = 0; + for (SavingsAccount account : childSavings) { + result = rejectApplication(account.getId(), command); - if (result != null) { - count++; - if (count == parentSavings.getChildAccountsCount()) { - parentSavings.setSavingsStatus(SavingsAccountStatusType.REJECTED.getValue()); - gsimRepository.save(parentSavings); - } - } - } - return result; + if (result != null) { + count++; + if (count == parentSavings.getChildAccountsCount()) { + parentSavings.setSavingsStatus(SavingsAccountStatusType.REJECTED.getValue()); + gsimRepository.save(parentSavings); + } + } + } + return result; } @Transactional @@ -642,7 +636,7 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl checkClientOrGroupActive(savingsAccount); entityDatatableChecksWritePlatformService.runTheCheckForProduct(savingsId, EntityTables.SAVING.getName(), - StatusEnum.REJECTED.getCode().longValue(),EntityTables.SAVING.getForeignKeyColumnNameOnDatatable(), + StatusEnum.REJECTED.getCode().longValue(), EntityTables.SAVING.getForeignKeyColumnNameOnDatatable(), savingsAccount.productId()); final Map changes = savingsAccount.rejectApplication(currentUser, command, DateUtils.getLocalDateOfTenant()); @@ -680,7 +674,7 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl checkClientOrGroupActive(savingsAccount); entityDatatableChecksWritePlatformService.runTheCheckForProduct(savingsId, EntityTables.SAVING.getName(), - StatusEnum.WITHDRAWN.getCode().longValue(),EntityTables.SAVING.getForeignKeyColumnNameOnDatatable(), + StatusEnum.WITHDRAWN.getCode().longValue(), EntityTables.SAVING.getForeignKeyColumnNameOnDatatable(), savingsAccount.productId()); final Map changes = savingsAccount.applicantWithdrawsFromApplication(currentUser, command, @@ -753,7 +747,6 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl .build(); } - private Map constructEntityMap(final BusinessEntity entityEvent, Object entity) { Map map = new HashMap<>(1); map.put(entityEvent, entity); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsDropdownReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsDropdownReadPlatformService.java index 4c7f0b5d9..63188ec2f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsDropdownReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsDropdownReadPlatformService.java @@ -34,4 +34,4 @@ public interface SavingsDropdownReadPlatformService { Collection retrieveInterestCalculationDaysInYearTypeOptions(); Collection retrievewithdrawalFeeTypeOptions(); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java index b6249f47b..6a3cee384 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java @@ -38,7 +38,7 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe final List allowedOptions = Arrays.asList( // SavingsEnumerations.withdrawalFeeType(SavingsWithdrawalFeesType.FLAT), // SavingsEnumerations.withdrawalFeeType(SavingsWithdrawalFeesType.PERCENT_OF_AMOUNT) // - ); + ); return allowedOptions; } @@ -50,7 +50,7 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe SavingsEnumerations.lockinPeriodFrequencyType(SavingsPeriodFrequencyType.WEEKS), // SavingsEnumerations.lockinPeriodFrequencyType(SavingsPeriodFrequencyType.MONTHS), // SavingsEnumerations.lockinPeriodFrequencyType(SavingsPeriodFrequencyType.YEARS) // - ); + ); return allowedLockinPeriodFrequencyTypeOptions; } @@ -71,7 +71,7 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe // // // SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.NO_COMPOUNDING_SIMPLE_INTEREST) // // - ); + ); return allowedOptions; } @@ -83,7 +83,7 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType.QUATERLY), // SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType.BIANNUAL), // SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType.ANNUAL) // - ); + ); return allowedOptions; } @@ -93,7 +93,7 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe final List allowedOptions = Arrays.asList( // SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType.DAILY_BALANCE), // SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType.AVERAGE_DAILY_BALANCE) // - ); + ); return allowedOptions; } @@ -103,8 +103,8 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe final List allowedOptions = Arrays.asList( // SavingsEnumerations.interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.DAYS_360), // SavingsEnumerations.interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.DAYS_365) // - ); + ); return allowedOptions; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsEnumerations.java index ed604d4a6..d827e4180 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsEnumerations.java @@ -94,20 +94,20 @@ public class SavingsEnumerations { case INVALID: break; case DAYS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.DAYS.getCode(), "Days"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.DAYS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.DAYS.getCode(), "Days"); break; case WEEKS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.WEEKS.getCode(), "Weeks"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.WEEKS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.WEEKS.getCode(), "Weeks"); break; case MONTHS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.MONTHS.getCode(), "Months"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.MONTHS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.MONTHS.getCode(), "Months"); break; case YEARS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.YEARS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.YEARS.getCode(), "Years"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.YEARS.getCode(), "Years"); break; } return optionData; @@ -119,8 +119,8 @@ public class SavingsEnumerations { public static SavingsAccountTransactionEnumData transactionType(final SavingsAccountTransactionType type) { - SavingsAccountTransactionEnumData optionData = new SavingsAccountTransactionEnumData(SavingsAccountTransactionType.INVALID - .getValue().longValue(), SavingsAccountTransactionType.INVALID.getCode(), "Invalid"); + SavingsAccountTransactionEnumData optionData = new SavingsAccountTransactionEnumData( + SavingsAccountTransactionType.INVALID.getValue().longValue(), SavingsAccountTransactionType.INVALID.getCode(), "Invalid"); switch (type) { case INVALID: @@ -186,19 +186,19 @@ public class SavingsEnumerations { case DIVIDEND_PAYOUT: optionData = new SavingsAccountTransactionEnumData(SavingsAccountTransactionType.DIVIDEND_PAYOUT.getValue().longValue(), SavingsAccountTransactionType.DIVIDEND_PAYOUT.getCode(), "Dividend Payout"); - break; + break; case ESCHEAT: optionData = new SavingsAccountTransactionEnumData(SavingsAccountTransactionType.ESCHEAT.getValue().longValue(), SavingsAccountTransactionType.ESCHEAT.getCode(), "Escheat"); - break; + break; case AMOUNT_HOLD: optionData = new SavingsAccountTransactionEnumData(SavingsAccountTransactionType.AMOUNT_HOLD.getValue().longValue(), SavingsAccountTransactionType.AMOUNT_HOLD.getCode(), "Amount on hold"); - break; + break; case AMOUNT_RELEASE: optionData = new SavingsAccountTransactionEnumData(SavingsAccountTransactionType.AMOUNT_RELEASE.getValue().longValue(), SavingsAccountTransactionType.AMOUNT_RELEASE.getCode(), "Release Amount"); - break; + break; } return optionData; } @@ -231,8 +231,9 @@ public class SavingsEnumerations { isWithdrawnByApplicant, isActive, isClosed, isPrematureClosed, isTransferInProgress, isTransferOnHold, matured); break; case SUBMITTED_AND_PENDING_APPROVAL: - optionData = new SavingsAccountStatusEnumData(SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue() - .longValue(), SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getCode(), "Submitted and pending approval", + optionData = new SavingsAccountStatusEnumData( + SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue().longValue(), + SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getCode(), "Submitted and pending approval", submittedAndPendingApproval, isApproved, isRejected, isWithdrawnByApplicant, isActive, isClosed, isPrematureClosed, isTransferInProgress, isTransferOnHold, matured); break; @@ -270,14 +271,15 @@ public class SavingsEnumerations { break; case TRANSFER_ON_HOLD: optionData = new SavingsAccountStatusEnumData(SavingsAccountStatusType.TRANSFER_ON_HOLD.getValue().longValue(), - SavingsAccountStatusType.TRANSFER_ON_HOLD.getCode(), "Transfer on hold", submittedAndPendingApproval, - isApproved, isRejected, isWithdrawnByApplicant, isActive, isClosed, isPrematureClosed, isTransferInProgress, - isTransferOnHold, matured); + SavingsAccountStatusType.TRANSFER_ON_HOLD.getCode(), "Transfer on hold", submittedAndPendingApproval, isApproved, + isRejected, isWithdrawnByApplicant, isActive, isClosed, isPrematureClosed, isTransferInProgress, isTransferOnHold, + matured); break; case PRE_MATURE_CLOSURE: optionData = new SavingsAccountStatusEnumData(SavingsAccountStatusType.PRE_MATURE_CLOSURE.getValue().longValue(), SavingsAccountStatusType.PRE_MATURE_CLOSURE.getCode(), "Premature Closed", submittedAndPendingApproval, isApproved, - isRejected, isWithdrawnByApplicant, isActive, isClosed, isPrematureClosed, isTransferInProgress, isTransferOnHold, matured); + isRejected, isWithdrawnByApplicant, isActive, isClosed, isPrematureClosed, isTransferInProgress, isTransferOnHold, + matured); break; case MATURED: optionData = new SavingsAccountStatusEnumData(SavingsAccountStatusType.MATURED.getValue().longValue(), @@ -304,33 +306,40 @@ public class SavingsEnumerations { final boolean blockCredit = type.isSubStatusCreditBlocked(); final boolean blockDebit = type.isSubStatusDebitBlocked(); - SavingsAccountSubStatusEnumData optionData = new SavingsAccountSubStatusEnumData(SavingsAccountSubStatusEnum.NONE.getValue().longValue(), - SavingsAccountSubStatusEnum.NONE.getCode(), "None", true, inactive, dormant, escheat, block, blockCredit, blockDebit); + SavingsAccountSubStatusEnumData optionData = new SavingsAccountSubStatusEnumData( + SavingsAccountSubStatusEnum.NONE.getValue().longValue(), SavingsAccountSubStatusEnum.NONE.getCode(), "None", true, inactive, + dormant, escheat, block, blockCredit, blockDebit); switch (type) { case INACTIVE: optionData = new SavingsAccountSubStatusEnumData(SavingsAccountSubStatusEnum.INACTIVE.getValue().longValue(), - SavingsAccountSubStatusEnum.INACTIVE.getCode(), "Inactive", none, inactive, dormant, escheat, block, blockCredit, blockDebit); + SavingsAccountSubStatusEnum.INACTIVE.getCode(), "Inactive", none, inactive, dormant, escheat, block, blockCredit, + blockDebit); break; case DORMANT: optionData = new SavingsAccountSubStatusEnumData(SavingsAccountSubStatusEnum.DORMANT.getValue().longValue(), - SavingsAccountSubStatusEnum.DORMANT.getCode(), "Dormant", none, inactive, dormant, escheat, block, blockCredit, blockDebit); + SavingsAccountSubStatusEnum.DORMANT.getCode(), "Dormant", none, inactive, dormant, escheat, block, blockCredit, + blockDebit); break; case ESCHEAT: optionData = new SavingsAccountSubStatusEnumData(SavingsAccountSubStatusEnum.ESCHEAT.getValue().longValue(), - SavingsAccountSubStatusEnum.ESCHEAT.getCode(), "Escheat", none, inactive, dormant, escheat, block, blockCredit, blockDebit); + SavingsAccountSubStatusEnum.ESCHEAT.getCode(), "Escheat", none, inactive, dormant, escheat, block, blockCredit, + blockDebit); break; case BLOCK: optionData = new SavingsAccountSubStatusEnumData(SavingsAccountSubStatusEnum.BLOCK.getValue().longValue(), - SavingsAccountSubStatusEnum.BLOCK.getCode(), "Block", none, inactive, dormant, escheat, block, blockCredit, blockDebit); + SavingsAccountSubStatusEnum.BLOCK.getCode(), "Block", none, inactive, dormant, escheat, block, blockCredit, + blockDebit); break; case BLOCK_CREDIT: optionData = new SavingsAccountSubStatusEnumData(SavingsAccountSubStatusEnum.BLOCK_CREDIT.getValue().longValue(), - SavingsAccountSubStatusEnum.BLOCK_CREDIT.getCode(), "BlockCredit", none, inactive, dormant, escheat, block, blockCredit, blockDebit); + SavingsAccountSubStatusEnum.BLOCK_CREDIT.getCode(), "BlockCredit", none, inactive, dormant, escheat, block, + blockCredit, blockDebit); break; case BLOCK_DEBIT: optionData = new SavingsAccountSubStatusEnumData(SavingsAccountSubStatusEnum.BLOCK_DEBIT.getValue().longValue(), - SavingsAccountSubStatusEnum.BLOCK_DEBIT.getCode(), "BlockDebit", none, inactive, dormant, escheat, block, blockCredit, blockDebit); + SavingsAccountSubStatusEnum.BLOCK_DEBIT.getCode(), "BlockDebit", none, inactive, dormant, escheat, block, + blockCredit, blockDebit); break; default: break; @@ -352,20 +361,20 @@ public class SavingsEnumerations { case INVALID: break; case MONTHLY: - optionData = new EnumOptionData(SavingsPostingInterestPeriodType.MONTHLY.getValue().longValue(), codePrefix - + SavingsPostingInterestPeriodType.MONTHLY.getCode(), "Monthly"); + optionData = new EnumOptionData(SavingsPostingInterestPeriodType.MONTHLY.getValue().longValue(), + codePrefix + SavingsPostingInterestPeriodType.MONTHLY.getCode(), "Monthly"); break; case QUATERLY: - optionData = new EnumOptionData(SavingsPostingInterestPeriodType.QUATERLY.getValue().longValue(), codePrefix - + SavingsPostingInterestPeriodType.QUATERLY.getCode(), "Quarterly"); + optionData = new EnumOptionData(SavingsPostingInterestPeriodType.QUATERLY.getValue().longValue(), + codePrefix + SavingsPostingInterestPeriodType.QUATERLY.getCode(), "Quarterly"); break; case BIANNUAL: - optionData = new EnumOptionData(SavingsPostingInterestPeriodType.BIANNUAL.getValue().longValue(), codePrefix - + SavingsPostingInterestPeriodType.BIANNUAL.getCode(), "BiAnnual"); + optionData = new EnumOptionData(SavingsPostingInterestPeriodType.BIANNUAL.getValue().longValue(), + codePrefix + SavingsPostingInterestPeriodType.BIANNUAL.getCode(), "BiAnnual"); break; case ANNUAL: - optionData = new EnumOptionData(SavingsPostingInterestPeriodType.ANNUAL.getValue().longValue(), codePrefix - + SavingsPostingInterestPeriodType.ANNUAL.getCode(), "Annually"); + optionData = new EnumOptionData(SavingsPostingInterestPeriodType.ANNUAL.getValue().longValue(), + codePrefix + SavingsPostingInterestPeriodType.ANNUAL.getCode(), "Annually"); break; } @@ -386,8 +395,8 @@ public class SavingsEnumerations { case INVALID: break; case DAILY: - optionData = new EnumOptionData(SavingsCompoundingInterestPeriodType.DAILY.getValue().longValue(), codePrefix - + SavingsCompoundingInterestPeriodType.DAILY.getCode(), "Daily"); + optionData = new EnumOptionData(SavingsCompoundingInterestPeriodType.DAILY.getValue().longValue(), + codePrefix + SavingsCompoundingInterestPeriodType.DAILY.getCode(), "Daily"); break; // case WEEKLY: // optionData = new @@ -404,28 +413,28 @@ public class SavingsEnumerations { // "Bi-Weekly"); // break; case MONTHLY: - optionData = new EnumOptionData(SavingsCompoundingInterestPeriodType.MONTHLY.getValue().longValue(), codePrefix - + SavingsCompoundingInterestPeriodType.MONTHLY.getCode(), "Monthly"); + optionData = new EnumOptionData(SavingsCompoundingInterestPeriodType.MONTHLY.getValue().longValue(), + codePrefix + SavingsCompoundingInterestPeriodType.MONTHLY.getCode(), "Monthly"); break; case QUATERLY: - optionData = new EnumOptionData(SavingsCompoundingInterestPeriodType.QUATERLY.getValue().longValue(), codePrefix - + SavingsCompoundingInterestPeriodType.QUATERLY.getCode(), "Quarterly"); + optionData = new EnumOptionData(SavingsCompoundingInterestPeriodType.QUATERLY.getValue().longValue(), + codePrefix + SavingsCompoundingInterestPeriodType.QUATERLY.getCode(), "Quarterly"); break; case BI_ANNUAL: - optionData = new EnumOptionData(SavingsCompoundingInterestPeriodType.BI_ANNUAL.getValue().longValue(), codePrefix - + SavingsCompoundingInterestPeriodType.BI_ANNUAL.getCode(), "Semi-Annual"); + optionData = new EnumOptionData(SavingsCompoundingInterestPeriodType.BI_ANNUAL.getValue().longValue(), + codePrefix + SavingsCompoundingInterestPeriodType.BI_ANNUAL.getCode(), "Semi-Annual"); break; case ANNUAL: - optionData = new EnumOptionData(SavingsCompoundingInterestPeriodType.ANNUAL.getValue().longValue(), codePrefix - + SavingsCompoundingInterestPeriodType.ANNUAL.getCode(), "Annually"); + optionData = new EnumOptionData(SavingsCompoundingInterestPeriodType.ANNUAL.getValue().longValue(), + codePrefix + SavingsCompoundingInterestPeriodType.ANNUAL.getCode(), "Annually"); break; - // case NO_COMPOUNDING_SIMPLE_INTEREST: - // optionData = new - // EnumOptionData(SavingsCompoundingInterestPeriodType.NO_COMPOUNDING_SIMPLE_INTEREST.getValue().longValue(), - // codePrefix + - // SavingsCompoundingInterestPeriodType.NO_COMPOUNDING_SIMPLE_INTEREST.getCode(), - // "No Compounding - Simple Interest"); - // break; + // case NO_COMPOUNDING_SIMPLE_INTEREST: + // optionData = new + // EnumOptionData(SavingsCompoundingInterestPeriodType.NO_COMPOUNDING_SIMPLE_INTEREST.getValue().longValue(), + // codePrefix + + // SavingsCompoundingInterestPeriodType.NO_COMPOUNDING_SIMPLE_INTEREST.getCode(), + // "No Compounding - Simple Interest"); + // break; } return optionData; @@ -584,20 +593,20 @@ public class SavingsEnumerations { case INVALID: break; case DAYS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.DAYS.getCode(), "Days"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.DAYS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.DAYS.getCode(), "Days"); break; case WEEKS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.WEEKS.getCode(), "Weeks"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.WEEKS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.WEEKS.getCode(), "Weeks"); break; case MONTHS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.MONTHS.getCode(), "Months"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.MONTHS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.MONTHS.getCode(), "Months"); break; case YEARS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.YEARS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.YEARS.getCode(), "Years"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.YEARS.getCode(), "Years"); break; } return optionData; @@ -625,20 +634,20 @@ public class SavingsEnumerations { case INVALID: break; case DAYS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.DAYS.getCode(), "Days"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.DAYS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.DAYS.getCode(), "Days"); break; case WEEKS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.WEEKS.getCode(), "Weeks"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.WEEKS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.WEEKS.getCode(), "Weeks"); break; case MONTHS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.MONTHS.getCode(), "Months"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.MONTHS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.MONTHS.getCode(), "Months"); break; case YEARS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.YEARS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.YEARS.getCode(), "Years"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.YEARS.getCode(), "Years"); break; } return optionData; @@ -666,20 +675,20 @@ public class SavingsEnumerations { case INVALID: break; case DAYS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.DAYS.getCode(), "Days"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.DAYS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.DAYS.getCode(), "Days"); break; case WEEKS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.WEEKS.getCode(), "Weeks"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.WEEKS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.WEEKS.getCode(), "Weeks"); break; case MONTHS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.MONTHS.getCode(), "Months"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.MONTHS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.MONTHS.getCode(), "Months"); break; case YEARS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.YEARS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.YEARS.getCode(), "Years"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.YEARS.getCode(), "Years"); break; } return optionData; @@ -747,20 +756,20 @@ public class SavingsEnumerations { case INVALID: break; case DAYS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.DAYS.getCode(), "Days"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.DAYS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.DAYS.getCode(), "Days"); break; case WEEKS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.WEEKS.getCode(), "Weeks"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.WEEKS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.WEEKS.getCode(), "Weeks"); break; case MONTHS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.MONTHS.getCode(), "Months"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.MONTHS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.MONTHS.getCode(), "Months"); break; case YEARS: - optionData = new EnumOptionData(SavingsPeriodFrequencyType.YEARS.getValue().longValue(), codePrefix - + SavingsPeriodFrequencyType.YEARS.getCode(), "Years"); + optionData = new EnumOptionData(SavingsPeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + SavingsPeriodFrequencyType.YEARS.getCode(), "Years"); break; } return optionData; @@ -800,8 +809,8 @@ public class SavingsEnumerations { break; case REINVEST_PRINCIPAL_ONLY: optionData = new EnumOptionData(DepositAccountOnClosureType.REINVEST_PRINCIPAL_ONLY.getValue().longValue(), - DepositAccountOnClosureType.REINVEST_PRINCIPAL_ONLY.getCode(), "Re-Invest Principal Only"); - break; + DepositAccountOnClosureType.REINVEST_PRINCIPAL_ONLY.getCode(), "Re-Invest Principal Only"); + break; } return optionData; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java index c97cd347f..caf8b0d9b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java @@ -97,8 +97,8 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead try { this.context.authenticatedUser(); final String sql = "select " + this.savingsProductRowMapper.schema() + " where sp.id = ? and sp.deposit_type_enum = ?"; - return this.jdbcTemplate.queryForObject(sql, this.savingsProductRowMapper, new Object[] { savingProductId, - DepositAccountType.SAVINGS_DEPOSIT.getValue() }); + return this.jdbcTemplate.queryForObject(sql, this.savingsProductRowMapper, + new Object[] { savingProductId, DepositAccountType.SAVINGS_DEPOSIT.getValue() }); } catch (final EmptyResultDataAccessException e) { throw new SavingsProductNotFoundException(savingProductId); } @@ -111,8 +111,8 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead public SavingProductMapper() { final StringBuilder sqlBuilder = new StringBuilder(400); sqlBuilder.append("sp.id as id, sp.name as name, sp.short_name as shortName, sp.description as description, "); - sqlBuilder - .append("sp.currency_code as currencyCode, sp.currency_digits as currencyDigits, sp.currency_multiplesof as inMultiplesOf, "); + sqlBuilder.append( + "sp.currency_code as currencyCode, sp.currency_digits as currencyDigits, sp.currency_multiplesof as inMultiplesOf, "); sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, "); sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, "); sqlBuilder.append("sp.nominal_annual_interest_rate as nominalAnnualInterestRate, "); @@ -163,8 +163,8 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final BigDecimal nominalAnnualInterestRate = rs.getBigDecimal("nominalAnnualInterestRate"); final Integer compoundingInterestPeriodTypeValue = JdbcSupport.getInteger(rs, "compoundingInterestPeriodType"); @@ -265,15 +265,17 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead } else { sql += " where sp.allow_overdraft=? and sp.deposit_type_enum = ?"; } - return this.jdbcTemplate.query(sql, this.savingsProductLookupsRowMapper, new Object[] {isOverdraftType, DepositAccountType.SAVINGS_DEPOSIT.getValue() }); + return this.jdbcTemplate.query(sql, this.savingsProductLookupsRowMapper, + new Object[] { isOverdraftType, DepositAccountType.SAVINGS_DEPOSIT.getValue() }); } - if(inClauseAdded) { + if (inClauseAdded) { sql += " and sp.deposit_type_enum = ?"; - }else { - sql += " where sp.deposit_type_enum = ?"; + } else { + sql += " where sp.deposit_type_enum = ?"; } - return this.jdbcTemplate.query(sql, this.savingsProductLookupsRowMapper, new Object[] { DepositAccountType.SAVINGS_DEPOSIT.getValue() }); + return this.jdbcTemplate.query(sql, this.savingsProductLookupsRowMapper, + new Object[] { DepositAccountType.SAVINGS_DEPOSIT.getValue() }); } @@ -292,6 +294,6 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead sql += " and id in ( " + inClause + " ) "; } - return this.jdbcTemplate.query(sql, this.savingsProductRowMapper, new Object[] {currencyCode}); + return this.jdbcTemplate.query(sql, this.savingsProductRowMapper, new Object[] { currencyCode }); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductWritePlatformService.java index df41d4d0a..0617cc3be 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductWritePlatformService.java @@ -28,4 +28,4 @@ public interface SavingsProductWritePlatformService { CommandProcessingResult update(Long productId, JsonCommand command); CommandProcessingResult delete(Long productId); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java index 67d4277ae..f59f0dc1a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java @@ -90,13 +90,13 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi 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); + throw new PlatformDataIntegrityException("error.msg.product.savings.duplicate.name", + "Savings product with name `" + name + "` already exists", "name", name); } else if (realCause.getMessage().contains("sp_unq_short_name")) { final String shortName = command.stringValueOfParameterNamed("shortName"); - throw new PlatformDataIntegrityException("error.msg.product.savings.duplicate.short.name", "Savings product with short name `" - + shortName + "` already exists", "shortName", shortName); + throw new PlatformDataIntegrityException("error.msg.product.savings.duplicate.short.name", + "Savings product with short name `" + shortName + "` already exists", "shortName", shortName); } logAsErrorUnexpectedDataIntegrityException(dae); @@ -135,8 +135,8 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi } catch (final DataAccessException e) { handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } @@ -156,8 +156,8 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi final Map changes = product.update(command); if (changes.containsKey(chargesParamName)) { - final Set savingsProductCharges = this.savingsProductAssembler.assembleListOfSavingsProductCharges(command, product - .currency().getCode()); + final Set savingsProductCharges = this.savingsProductAssembler.assembleListOfSavingsProductCharges(command, + product.currency().getCode()); final boolean updated = product.update(savingsProductCharges); if (!updated) { changes.remove(chargesParamName); @@ -194,8 +194,8 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi } catch (final DataAccessException e) { handleDataIntegrityIssues(command, e.getMostSpecificCause(), e); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularService.java index d9ec4443a..a99ecd806 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularService.java @@ -20,7 +20,6 @@ package org.apache.fineract.portfolio.savings.service; import org.apache.fineract.infrastructure.jobs.exception.JobExecutionException; - public interface SavingsSchedularService { void postInterestForAccounts() throws JobExecutionException; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularServiceImpl.java index 67b7733ef..1c6368fee 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularServiceImpl.java @@ -50,7 +50,8 @@ public class SavingsSchedularServiceImpl implements SavingsSchedularService { @Autowired public SavingsSchedularServiceImpl(final SavingsAccountAssembler savingAccountAssembler, final SavingsAccountWritePlatformService savingsAccountWritePlatformService, - final SavingsAccountReadPlatformService savingAccountReadPlatformService, final SavingsAccountRepositoryWrapper savingsAccountRepository) { + final SavingsAccountReadPlatformService savingAccountReadPlatformService, + final SavingsAccountRepositoryWrapper savingsAccountRepository) { this.savingAccountAssembler = savingAccountAssembler; this.savingsAccountWritePlatformService = savingsAccountWritePlatformService; this.savingAccountReadPlatformService = savingAccountReadPlatformService; @@ -91,22 +92,22 @@ public class SavingsSchedularServiceImpl implements SavingsSchedularService { LocalDate tenantLocalDate = DateUtils.getLocalDateOfTenant(); List savingsPendingInactive = savingAccountReadPlatformService.retrieveSavingsIdsPendingInactive(tenantLocalDate); - if(null != savingsPendingInactive && savingsPendingInactive.size() > 0){ - for(Long savingsId : savingsPendingInactive){ + if (null != savingsPendingInactive && savingsPendingInactive.size() > 0) { + for (Long savingsId : savingsPendingInactive) { this.savingsAccountWritePlatformService.setSubStatusInactive(savingsId); } } List savingsPendingDormant = savingAccountReadPlatformService.retrieveSavingsIdsPendingDormant(tenantLocalDate); - if(null != savingsPendingDormant && savingsPendingDormant.size() > 0){ - for(Long savingsId : savingsPendingDormant){ + if (null != savingsPendingDormant && savingsPendingDormant.size() > 0) { + for (Long savingsId : savingsPendingDormant) { this.savingsAccountWritePlatformService.setSubStatusDormant(savingsId); } } List savingsPendingEscheat = savingAccountReadPlatformService.retrieveSavingsIdsPendingEscheat(tenantLocalDate); - if(null != savingsPendingEscheat && savingsPendingEscheat.size() > 0){ - for(Long savingsId : savingsPendingEscheat){ + if (null != savingsPendingEscheat && savingsPendingEscheat.size() > 0) { + for (Long savingsId : savingsPendingEscheat) { this.savingsAccountWritePlatformService.escheat(savingsId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/SearchConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/SearchConstants.java index 65e79fd30..ebfcdfc38 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/SearchConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/SearchConstants.java @@ -24,8 +24,10 @@ import java.util.Set; public class SearchConstants { public static enum SearchResponseParameters { - ENTITY_ID("entityId"), ENTITY_ACCOUNT_NO("entityAccountNo"), ENTITY_EXTERNAL_ID("entityExternalId"), ENTITY_NAME("entityName"), ENTITY_TYPE( - "entityType"), PARENT_ID("parentId"), PARENT_NAME("parentName"),ENTITY_MOBILE_NO("entityMobileNo"), ENTITY_STATUS("entityStatus"); + + ENTITY_ID("entityId"), ENTITY_ACCOUNT_NO("entityAccountNo"), ENTITY_EXTERNAL_ID("entityExternalId"), ENTITY_NAME( + "entityName"), ENTITY_TYPE("entityType"), PARENT_ID( + "parentId"), PARENT_NAME("parentName"), ENTITY_MOBILE_NO("entityMobileNo"), ENTITY_STATUS("entityStatus"); private final String value; @@ -55,7 +57,8 @@ public class SearchConstants { } public static enum SearchSupportedParameters { - QUERY("query"), RESOURCE("resource"),EXACTMATCH("exactMatch"); + + QUERY("query"), RESOURCE("resource"), EXACTMATCH("exactMatch"); private final String value; @@ -85,6 +88,7 @@ public class SearchConstants { } public static enum SearchSupportedResources { + CLIENTS("clients"), GROUPS("groups"), LOANS("loans"), SAVINGS("savings"), SHARES("shares"), CLIENTIDENTIFIERS("clientIdentifiers"); private final String value; @@ -115,6 +119,7 @@ public class SearchConstants { } public static enum SearchLoanDate { + APPROVAL_DATE("approvalDate"), CREATED_DATE("createdDate"), DISBURSAL_DATE("disbursalDate"); private final String value; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/api/SearchApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/api/SearchApiResource.java index d95dd6147..8ce2ab11b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/api/SearchApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/api/SearchApiResource.java @@ -56,10 +56,9 @@ import org.springframework.stereotype.Component; @Path("/search") @Component @Scope("singleton") -@Api(tags = {"Search API"}) +@Api(tags = { "Search API" }) @SwaggerDefinition(tags = { - @Tag(name = "Search API", description = "Search API allows to search scoped resources clients, loans and groups on specified fields.") -}) + @Tag(name = "Search API", description = "Search API allows to search scoped resources clients, loans and groups on specified fields.") }) public class SearchApiResource { private final Set searchResponseParameters = SearchResponseParameters.getAllValues(); @@ -85,8 +84,9 @@ public class SearchApiResource { @Path("/template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrive Adhoc Search query template", httpMethod = "GET", notes = "Mandatory Fields\n" + "\n" + "search?query=000000001\n") - @ApiResponses({@ApiResponse(code = 200, message = "", response = SearchApiResourceSwagger.GetSearchResponse.class)}) + @ApiOperation(value = "Retrive Adhoc Search query template", httpMethod = "GET", notes = "Mandatory Fields\n" + "\n" + + "search?query=000000001\n") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = SearchApiResourceSwagger.GetSearchResponse.class) }) public String retrieveAdHocSearchQueryTemplate(@Context final UriInfo uriInfo) { final AdHocSearchQueryData templateData = this.searchReadPlatformService.retrieveAdHocQueryTemplate(); @@ -98,12 +98,14 @@ public class SearchApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Search Resources", notes = "Example Requests:\n" + "\n" + "search?query=000000001\n" + "\n" + "\n" + "search?query=Petra&resource=clients,groups\n" + "\n" + "\n" + "search?query=Petra&resource=clients,groups&exactMatch=true") - @ApiResponses({@ApiResponse(code = 200, message = "", response = SearchApiResourceSwagger.GetSearchResponse.class)}) - public String searchData(@Context final UriInfo uriInfo, @QueryParam("query") @ApiParam(value = "query")final String query, - @QueryParam("resource") @ApiParam(value = "resource") final String resource ,@DefaultValue("false") @QueryParam("exactMatch") @ApiParam(value = "exactMatch") Boolean exactMatch) { + @ApiOperation(value = "Search Resources", notes = "Example Requests:\n" + "\n" + "search?query=000000001\n" + "\n" + "\n" + + "search?query=Petra&resource=clients,groups\n" + "\n" + "\n" + "search?query=Petra&resource=clients,groups&exactMatch=true") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = SearchApiResourceSwagger.GetSearchResponse.class) }) + public String searchData(@Context final UriInfo uriInfo, @QueryParam("query") @ApiParam(value = "query") final String query, + @QueryParam("resource") @ApiParam(value = "resource") final String resource, + @DefaultValue("false") @QueryParam("exactMatch") @ApiParam(value = "exactMatch") Boolean exactMatch) { - final SearchConditions searchConditions = new SearchConditions(query, resource,exactMatch); + final SearchConditions searchConditions = new SearchConditions(query, resource, exactMatch); final Collection searchResults = this.searchReadPlatformService.retriveMatchingData(searchConditions); @@ -115,13 +117,16 @@ public class SearchApiResource { @Path("/advance") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Adhoc query search", notes = "AdHocQuery search has more search options, it is a POST request, it uses request body to send search parameters\n" + "\n" + "\n" + "Mandatory fields:" + "entities" + "\n" + "\n" + "Optional fields:" + "loanStatus, loanProducts, offices, loanDateOption, loanFromDate, loanToDate, \n" + - "includeOutStandingAmountPercentage, outStandingAmountPercentageCondition, \n" + - "minOutStandingAmountPercentage and maxOutStandingAmountPercentage OR outStandingAmountPercentage, \n" + - "includeOutstandingAmount, outstandingAmountCondition, \n" + - "minOutstandingAmount and maxOutstandingAmount OR outstandingAmount" ) - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SearchApiResourceSwagger.PostAdhocQuerySearchRequest.class )}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = SearchApiResourceSwagger.PostAdhocQuerySearchResponse.class)}) + @ApiOperation(value = "Adhoc query search", notes = "AdHocQuery search has more search options, it is a POST request, it uses request body to send search parameters\n" + + "\n" + "\n" + "Mandatory fields:" + "entities" + "\n" + "\n" + "Optional fields:" + + "loanStatus, loanProducts, offices, loanDateOption, loanFromDate, loanToDate, \n" + + "includeOutStandingAmountPercentage, outStandingAmountPercentageCondition, \n" + + "minOutStandingAmountPercentage and maxOutStandingAmountPercentage OR outStandingAmountPercentage, \n" + + "includeOutstandingAmount, outstandingAmountCondition, \n" + + "minOutstandingAmount and maxOutstandingAmount OR outstandingAmount") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SearchApiResourceSwagger.PostAdhocQuerySearchRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = SearchApiResourceSwagger.PostAdhocQuerySearchResponse.class) }) public String advancedSearch(@Context final UriInfo uriInfo, final String json) { final AdHocQuerySearchConditions searchConditions = this.fromApiJsonDeserializer.retrieveSearchConditions(json); @@ -132,4 +137,4 @@ public class SearchApiResource { final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, searchResults); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/api/SearchApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/api/SearchApiResourceSwagger.java index 60b89130b..c0bd4b674 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/api/SearchApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/api/SearchApiResourceSwagger.java @@ -23,18 +23,18 @@ import io.swagger.annotations.ApiModelProperty; import org.apache.fineract.infrastructure.core.data.EnumOptionData; import org.joda.time.LocalDate; - - /** * Created by Kang Breder on 13/06/19. */ final class SearchApiResourceSwagger { + private SearchApiResourceSwagger() { } @ApiModel(value = "GetSearchResponse") public static final class GetSearchResponse { + private GetSearchResponse() { } @@ -58,11 +58,11 @@ final class SearchApiResourceSwagger { @ApiModel(value = "PostAdhocQuerySearchRequest") public static final class PostAdhocQuerySearchRequest { + private PostAdhocQuerySearchRequest() { } - @ApiModelProperty(example = "en") public String locale; @ApiModelProperty(example = "dd MMMM yyyy") @@ -91,6 +91,7 @@ final class SearchApiResourceSwagger { @ApiModel(value = "PostAdhocQuerySearchResponse") public static final class PostAdhocQuerySearchResponse { + private PostAdhocQuerySearchResponse() { } @@ -105,4 +106,3 @@ final class SearchApiResourceSwagger { public Long percentage; } } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/AdHocQueryDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/AdHocQueryDataValidator.java index 90df03fe6..a261a8120 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/AdHocQueryDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/AdHocQueryDataValidator.java @@ -43,34 +43,28 @@ import org.springframework.stereotype.Component; public class AdHocQueryDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set AD_HOC_SEARCH_QUERY_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(AdHocQuerySearchConstants.entitiesParamName, AdHocQuerySearchConstants.loanStatusParamName, - AdHocQuerySearchConstants.loanProductsParamName, AdHocQuerySearchConstants.officesParamName, - AdHocQuerySearchConstants.loanDateOptionParamName, AdHocQuerySearchConstants.loanFromDateParamName, - AdHocQuerySearchConstants.loanToDateParamName, - AdHocQuerySearchConstants.includeOutStandingAmountPercentageParamName, - AdHocQuerySearchConstants.outStandingAmountPercentageConditionParamName, - AdHocQuerySearchConstants.minOutStandingAmountPercentageParamName, - AdHocQuerySearchConstants.maxOutStandingAmountPercentageParamName, - AdHocQuerySearchConstants.outStandingAmountPercentageParamName, - AdHocQuerySearchConstants.includeOutstandingAmountParamName, - AdHocQuerySearchConstants.outstandingAmountConditionParamName, - AdHocQuerySearchConstants.minOutstandingAmountParamName, - AdHocQuerySearchConstants.maxOutstandingAmountParamName, - AdHocQuerySearchConstants.outstandingAmountParamName, AdHocQuerySearchConstants.localeParamName, - AdHocQuerySearchConstants.dateFormatParamName)); + private static final Set AD_HOC_SEARCH_QUERY_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList( + AdHocQuerySearchConstants.entitiesParamName, AdHocQuerySearchConstants.loanStatusParamName, + AdHocQuerySearchConstants.loanProductsParamName, AdHocQuerySearchConstants.officesParamName, + AdHocQuerySearchConstants.loanDateOptionParamName, AdHocQuerySearchConstants.loanFromDateParamName, + AdHocQuerySearchConstants.loanToDateParamName, AdHocQuerySearchConstants.includeOutStandingAmountPercentageParamName, + AdHocQuerySearchConstants.outStandingAmountPercentageConditionParamName, + AdHocQuerySearchConstants.minOutStandingAmountPercentageParamName, + AdHocQuerySearchConstants.maxOutStandingAmountPercentageParamName, + AdHocQuerySearchConstants.outStandingAmountPercentageParamName, AdHocQuerySearchConstants.includeOutstandingAmountParamName, + AdHocQuerySearchConstants.outstandingAmountConditionParamName, AdHocQuerySearchConstants.minOutstandingAmountParamName, + AdHocQuerySearchConstants.maxOutstandingAmountParamName, AdHocQuerySearchConstants.outstandingAmountParamName, + AdHocQuerySearchConstants.localeParamName, AdHocQuerySearchConstants.dateFormatParamName)); - private static final Set AD_HOC_SEARCH_QUERY_CONDITIONS = new HashSet<>( - Arrays.asList("between", "<=", ">=", "<", ">", "=")); + private static final Set AD_HOC_SEARCH_QUERY_CONDITIONS = new HashSet<>(Arrays.asList("between", "<=", ">=", "<", ">", "=")); private static final Object[] loanDateOptions = { AdHocQuerySearchConstants.approvalDateOption, - AdHocQuerySearchConstants.createDateOption, - AdHocQuerySearchConstants.disbursalDateOption }; + AdHocQuerySearchConstants.createDateOption, AdHocQuerySearchConstants.disbursalDateOption }; - private static final Object[] loanStatusOptions = {AdHocQuerySearchConstants.allLoanStatusOption, + private static final Object[] loanStatusOptions = { AdHocQuerySearchConstants.allLoanStatusOption, AdHocQuerySearchConstants.activeLoanStatusOption, AdHocQuerySearchConstants.overpaidLoanStatusOption, AdHocQuerySearchConstants.arrearsLoanStatusOption, AdHocQuerySearchConstants.closedLoanStatusOption, - AdHocQuerySearchConstants.writeoffLoanStatusOption}; + AdHocQuerySearchConstants.writeoffLoanStatusOption }; @Autowired public AdHocQueryDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -105,8 +99,8 @@ public class AdHocQueryDataValidator { } if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.loanProductsParamName, element)) { - final String[] loanProducts = this.fromApiJsonHelper - .extractArrayNamed(AdHocQuerySearchConstants.loanProductsParamName, element); + final String[] loanProducts = this.fromApiJsonHelper.extractArrayNamed(AdHocQuerySearchConstants.loanProductsParamName, + element); baseDataValidator.reset().parameter(AdHocQuerySearchConstants.loanProductsParamName).value(loanProducts).arrayNotEmpty(); } @@ -135,33 +129,32 @@ public class AdHocQueryDataValidator { } if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.includeOutStandingAmountPercentageParamName, element)) { - final boolean includeOutStandingAmountPercentage = this.fromApiJsonHelper.extractBooleanNamed( - AdHocQuerySearchConstants.includeOutStandingAmountPercentageParamName, element); + final boolean includeOutStandingAmountPercentage = this.fromApiJsonHelper + .extractBooleanNamed(AdHocQuerySearchConstants.includeOutStandingAmountPercentageParamName, element); baseDataValidator.reset().parameter(AdHocQuerySearchConstants.includeOutStandingAmountPercentageParamName) .value(includeOutStandingAmountPercentage).notNull(); } if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.outStandingAmountPercentageConditionParamName, element)) { - final String outStandingAmountPercentageCondition = this.fromApiJsonHelper.extractStringNamed( - AdHocQuerySearchConstants.outStandingAmountPercentageConditionParamName, element); + final String outStandingAmountPercentageCondition = this.fromApiJsonHelper + .extractStringNamed(AdHocQuerySearchConstants.outStandingAmountPercentageConditionParamName, element); baseDataValidator.reset().parameter(AdHocQuerySearchConstants.outStandingAmountPercentageConditionParamName) - .value(outStandingAmountPercentageCondition) - .isNotOneOfTheseValues(AD_HOC_SEARCH_QUERY_CONDITIONS); + .value(outStandingAmountPercentageCondition).isNotOneOfTheseValues(AD_HOC_SEARCH_QUERY_CONDITIONS); if (outStandingAmountPercentageCondition.equals("between")) { - final BigDecimal minOutStandingAmountPercentage = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.minOutStandingAmountPercentageParamName, element); + final BigDecimal minOutStandingAmountPercentage = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.minOutStandingAmountPercentageParamName, element); baseDataValidator.reset().parameter(AdHocQuerySearchConstants.minOutStandingAmountPercentageParamName) .value(minOutStandingAmountPercentage).notNull().notLessThanMin(BigDecimal.ZERO); - final BigDecimal maxOutStandingAmountPercentage = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.maxOutStandingAmountPercentageParamName, element); + final BigDecimal maxOutStandingAmountPercentage = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.maxOutStandingAmountPercentageParamName, element); baseDataValidator.reset().parameter(AdHocQuerySearchConstants.maxOutStandingAmountPercentageParamName) .value(maxOutStandingAmountPercentage).notNull().notLessThanMin(BigDecimal.ZERO); baseDataValidator.reset().comapareMinAndMaxOfTwoBigDecmimalNos(minOutStandingAmountPercentage, maxOutStandingAmountPercentage); } else { if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.outStandingAmountPercentageParamName, element)) { - final BigDecimal outStandingAmountPercentage = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.outStandingAmountPercentageParamName, element); + final BigDecimal outStandingAmountPercentage = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.outStandingAmountPercentageParamName, element); baseDataValidator.reset().parameter(AdHocQuerySearchConstants.outStandingAmountPercentageParamName) .value(outStandingAmountPercentage).notNull().notLessThanMin(BigDecimal.ZERO); } @@ -169,32 +162,32 @@ public class AdHocQueryDataValidator { } if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.includeOutstandingAmountParamName, element)) { - final Boolean includeOutstandingAmountParamName = this.fromApiJsonHelper.extractBooleanNamed( - AdHocQuerySearchConstants.includeOutstandingAmountParamName, element); + final Boolean includeOutstandingAmountParamName = this.fromApiJsonHelper + .extractBooleanNamed(AdHocQuerySearchConstants.includeOutstandingAmountParamName, element); baseDataValidator.reset().parameter(AdHocQuerySearchConstants.includeOutstandingAmountParamName) .value(includeOutstandingAmountParamName).notNull(); } if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.outstandingAmountConditionParamName, element)) { - final String outstandingAmountCondition = this.fromApiJsonHelper.extractStringNamed( - AdHocQuerySearchConstants.outstandingAmountConditionParamName, element); + final String outstandingAmountCondition = this.fromApiJsonHelper + .extractStringNamed(AdHocQuerySearchConstants.outstandingAmountConditionParamName, element); baseDataValidator.reset().parameter(AdHocQuerySearchConstants.outstandingAmountConditionParamName) .value(outstandingAmountCondition).isNotOneOfTheseValues(AD_HOC_SEARCH_QUERY_CONDITIONS); if (outstandingAmountCondition.equals("between")) { - final BigDecimal minOutstandingAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.minOutstandingAmountParamName, element); + final BigDecimal minOutstandingAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.minOutstandingAmountParamName, element); baseDataValidator.reset().parameter(AdHocQuerySearchConstants.minOutstandingAmountParamName).value(minOutstandingAmount) .notNull().notLessThanMin(BigDecimal.ZERO); - final BigDecimal maxOutstandingAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.maxOutstandingAmountParamName, element); + final BigDecimal maxOutstandingAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.maxOutstandingAmountParamName, element); baseDataValidator.reset().parameter(AdHocQuerySearchConstants.maxOutstandingAmountParamName).value(maxOutstandingAmount) .notNull().notLessThanMin(BigDecimal.ZERO); baseDataValidator.reset().comapareMinAndMaxOfTwoBigDecmimalNos(minOutstandingAmount, maxOutstandingAmount); } else { - final BigDecimal outstandingAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.outstandingAmountParamName, element); - baseDataValidator.reset().parameter(AdHocQuerySearchConstants.outstandingAmountParamName).value(outstandingAmount) - .notNull().notLessThanMin(BigDecimal.ZERO); + final BigDecimal outstandingAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.outstandingAmountParamName, element); + baseDataValidator.reset().parameter(AdHocQuerySearchConstants.outstandingAmountParamName).value(outstandingAmount).notNull() + .notLessThanMin(BigDecimal.ZERO); } } @@ -214,20 +207,19 @@ public class AdHocQueryDataValidator { List loanStatus = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.loanStatusParamName, element)) { - loanStatus = Arrays.asList( - this.fromApiJsonHelper.extractArrayNamed(AdHocQuerySearchConstants.loanStatusParamName, element)); + loanStatus = Arrays.asList(this.fromApiJsonHelper.extractArrayNamed(AdHocQuerySearchConstants.loanStatusParamName, element)); } List loanProducts = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.loanProductsParamName, element)) { - loanProducts = extractLongValuesList(Arrays.asList(this.fromApiJsonHelper.extractArrayNamed( - AdHocQuerySearchConstants.loanProductsParamName, element))); + loanProducts = extractLongValuesList( + Arrays.asList(this.fromApiJsonHelper.extractArrayNamed(AdHocQuerySearchConstants.loanProductsParamName, element))); } List offices = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.officesParamName, element)) { - offices = extractLongValuesList(Arrays.asList(this.fromApiJsonHelper.extractArrayNamed( - AdHocQuerySearchConstants.officesParamName, element))); + offices = extractLongValuesList( + Arrays.asList(this.fromApiJsonHelper.extractArrayNamed(AdHocQuerySearchConstants.officesParamName, element))); } String loanDateOption = null; @@ -248,64 +240,64 @@ public class AdHocQueryDataValidator { Boolean includeOutStandingAmountPercentage = false; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.includeOutStandingAmountPercentageParamName, element)) { - includeOutStandingAmountPercentage = this.fromApiJsonHelper.extractBooleanNamed( - AdHocQuerySearchConstants.includeOutStandingAmountPercentageParamName, element); + includeOutStandingAmountPercentage = this.fromApiJsonHelper + .extractBooleanNamed(AdHocQuerySearchConstants.includeOutStandingAmountPercentageParamName, element); } String outStandingAmountPercentageCondition = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.outStandingAmountPercentageConditionParamName, element)) { - outStandingAmountPercentageCondition = this.fromApiJsonHelper.extractStringNamed( - AdHocQuerySearchConstants.outStandingAmountPercentageConditionParamName, element); + outStandingAmountPercentageCondition = this.fromApiJsonHelper + .extractStringNamed(AdHocQuerySearchConstants.outStandingAmountPercentageConditionParamName, element); SQLInjectionValidator.validateSQLInput(outStandingAmountPercentageCondition); } BigDecimal minOutStandingAmountPercentage = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.minOutStandingAmountPercentageParamName, element)) { - minOutStandingAmountPercentage = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.minOutStandingAmountPercentageParamName, element); + minOutStandingAmountPercentage = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.minOutStandingAmountPercentageParamName, element); } BigDecimal maxOutStandingAmountPercentage = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.maxOutStandingAmountPercentageParamName, element)) { - maxOutStandingAmountPercentage = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.maxOutStandingAmountPercentageParamName, element); + maxOutStandingAmountPercentage = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.maxOutStandingAmountPercentageParamName, element); } BigDecimal outStandingAmountPercentage = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.outStandingAmountPercentageParamName, element)) { - outStandingAmountPercentage = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.outStandingAmountPercentageParamName, element); + outStandingAmountPercentage = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.outStandingAmountPercentageParamName, element); } Boolean includeOutstandingAmountParamName = false; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.includeOutstandingAmountParamName, element)) { - includeOutstandingAmountParamName = this.fromApiJsonHelper.extractBooleanNamed( - AdHocQuerySearchConstants.includeOutstandingAmountParamName, element); + includeOutstandingAmountParamName = this.fromApiJsonHelper + .extractBooleanNamed(AdHocQuerySearchConstants.includeOutstandingAmountParamName, element); } String outstandingAmountCondition = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.outstandingAmountConditionParamName, element)) { - outstandingAmountCondition = this.fromApiJsonHelper.extractStringNamed( - AdHocQuerySearchConstants.outstandingAmountConditionParamName, element); + outstandingAmountCondition = this.fromApiJsonHelper + .extractStringNamed(AdHocQuerySearchConstants.outstandingAmountConditionParamName, element); SQLInjectionValidator.validateSQLInput(outstandingAmountCondition); } BigDecimal minOutstandingAmount = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.minOutstandingAmountParamName, element)) { - minOutstandingAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.minOutstandingAmountParamName, element); + minOutstandingAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.minOutstandingAmountParamName, element); } BigDecimal maxOutstandingAmount = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.maxOutstandingAmountParamName, element)) { - maxOutstandingAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.maxOutstandingAmountParamName, element); + maxOutstandingAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.maxOutstandingAmountParamName, element); } BigDecimal outstandingAmount = null; if (this.fromApiJsonHelper.parameterExists(AdHocQuerySearchConstants.outstandingAmountParamName, element)) { - outstandingAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - AdHocQuerySearchConstants.outstandingAmountParamName, element); + outstandingAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(AdHocQuerySearchConstants.outstandingAmountParamName, element); } return AdHocQuerySearchConditions.instance(loanStatus, loanProducts, offices, loanDateOption, loanFromDate, loanToDate, diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/AdHocQuerySearchConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/AdHocQuerySearchConstants.java index 3d2ac0cc2..dac8ebaf2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/AdHocQuerySearchConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/AdHocQuerySearchConstants.java @@ -46,12 +46,12 @@ public interface AdHocQuerySearchConstants { public static final String createDateOption = "createdDate"; public static final String disbursalDateOption = "disbursalDate"; - public static final String allLoanStatusOption= "all"; - public static final String activeLoanStatusOption= "active"; - public static final String overpaidLoanStatusOption= "overpaid"; - public static final String arrearsLoanStatusOption= "arrears"; - public static final String closedLoanStatusOption= "closed"; - public static final String writeoffLoanStatusOption= "writeoff"; + public static final String allLoanStatusOption = "all"; + public static final String activeLoanStatusOption = "active"; + public static final String overpaidLoanStatusOption = "overpaid"; + public static final String arrearsLoanStatusOption = "arrears"; + public static final String closedLoanStatusOption = "closed"; + public static final String writeoffLoanStatusOption = "writeoff"; public static final Object[] entityTypeOptions = { "clients", "groups", "loans", "clientIdentifiers" }; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/SearchConditions.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/SearchConditions.java index dce4eb474..7176144fd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/SearchConditions.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/SearchConditions.java @@ -30,28 +30,29 @@ public class SearchConditions { private final Boolean savingSeach; private final Boolean shareSeach; private final Boolean clientIdentifierSearch; - private Boolean exactMatch; + private Boolean exactMatch; public SearchConditions(final String searchQueryParam, final String searchResource, Boolean exactMatch) { this.searchQuery = searchQueryParam; this.searchResource = searchResource; - this.exactMatch=exactMatch; - this.clientSearch = (null == searchResource || searchResource.toLowerCase().contains( - SearchSupportedResources.CLIENTS.name().toLowerCase())) ? true : false; - this.groupSearch = (null == searchResource || searchResource.toLowerCase().contains( - SearchSupportedResources.GROUPS.name().toLowerCase())) ? true : false; - this.loanSeach = (null == searchResource || searchResource.toLowerCase().contains( - SearchSupportedResources.LOANS.name().toLowerCase())) ? true : false; - this.savingSeach = (null == searchResource || searchResource.toLowerCase().contains( - SearchSupportedResources.SAVINGS.name().toLowerCase())) ? true : false; - this.shareSeach = (null == searchResource || searchResource.toLowerCase().contains( - SearchSupportedResources.SHARES.name().toLowerCase())) ? true : false; - this.clientIdentifierSearch = (null == searchResource || searchResource.toLowerCase().contains( - SearchSupportedResources.CLIENTIDENTIFIERS.name().toLowerCase())) ? true : false; + this.exactMatch = exactMatch; + this.clientSearch = (null == searchResource + || searchResource.toLowerCase().contains(SearchSupportedResources.CLIENTS.name().toLowerCase())) ? true : false; + this.groupSearch = (null == searchResource + || searchResource.toLowerCase().contains(SearchSupportedResources.GROUPS.name().toLowerCase())) ? true : false; + this.loanSeach = (null == searchResource + || searchResource.toLowerCase().contains(SearchSupportedResources.LOANS.name().toLowerCase())) ? true : false; + this.savingSeach = (null == searchResource + || searchResource.toLowerCase().contains(SearchSupportedResources.SAVINGS.name().toLowerCase())) ? true : false; + this.shareSeach = (null == searchResource + || searchResource.toLowerCase().contains(SearchSupportedResources.SHARES.name().toLowerCase())) ? true : false; + this.clientIdentifierSearch = (null == searchResource + || searchResource.toLowerCase().contains(SearchSupportedResources.CLIENTIDENTIFIERS.name().toLowerCase())) ? true : false; } public SearchConditions(final String searchQueryParam, final String searchResource, final Boolean clientSearch, - final Boolean groupSearch, final Boolean loanSeach, final Boolean savingSeach, final Boolean shareSeach, final Boolean clientIdentifierSearch, Boolean exactMatch) { + final Boolean groupSearch, final Boolean loanSeach, final Boolean savingSeach, final Boolean shareSeach, + final Boolean clientIdentifierSearch, Boolean exactMatch) { this.searchQuery = searchQueryParam; this.searchResource = searchResource; this.clientSearch = clientSearch; @@ -60,7 +61,7 @@ public class SearchConditions { this.savingSeach = savingSeach; this.shareSeach = shareSeach; this.clientIdentifierSearch = clientIdentifierSearch; - this.exactMatch=exactMatch; + this.exactMatch = exactMatch; } public String getSearchQuery() { @@ -70,9 +71,11 @@ public class SearchConditions { public String getSearchResource() { return this.searchResource; } + public Boolean getExactMatch() { return this.exactMatch; } + public Boolean isClientSearch() { return this.clientSearch; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/SearchData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/SearchData.java index 10305b894..9fb1f10f4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/SearchData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/data/SearchData.java @@ -34,7 +34,8 @@ public class SearchData { private final String parentType; public SearchData(final Long entityId, final String entityAccountNo, final String entityExternalId, final String entityName, - final String entityType, final Long parentId, final String parentName, final String parentType, final String entityMobileNo, final EnumOptionData entityStatus) { + final String entityType, final Long parentId, final String parentName, final String parentType, final String entityMobileNo, + final EnumOptionData entityStatus) { this.entityId = entityId; this.entityAccountNo = entityAccountNo; @@ -44,7 +45,7 @@ public class SearchData { this.parentId = parentId; this.parentName = parentName; this.parentType = parentType; - this.entityMobileNo=entityMobileNo; + this.entityMobileNo = entityMobileNo; this.entityStatus = entityStatus; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/service/SearchReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/service/SearchReadPlatformServiceImpl.java index c40c0edbc..76ca12428 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/service/SearchReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/search/service/SearchReadPlatformServiceImpl.java @@ -58,7 +58,8 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService @Autowired public SearchReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, - final LoanProductReadPlatformService loanProductReadPlatformService, final OfficeReadPlatformService officeReadPlatformService) { + final LoanProductReadPlatformService loanProductReadPlatformService, + final OfficeReadPlatformService officeReadPlatformService) { this.context = context; this.namedParameterjdbcTemplate = new NamedParameterJdbcTemplate(dataSource); this.loanProductReadPlatformService = loanProductReadPlatformService; @@ -74,11 +75,11 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService final MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("hierarchy", hierarchy + "%"); - if(searchConditions.getExactMatch()){ + if (searchConditions.getExactMatch()) { params.addValue("search", searchConditions.getSearchQuery()); - }else{ + } else { params.addValue("search", "%" + searchConditions.getSearchQuery() + "%"); - } + } return this.namedParameterjdbcTemplate.query(rm.searchSchema(searchConditions), params, rm); } @@ -95,7 +96,6 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService + " , IFNULL(c.id,g.id) as parentId, IFNULL(c.display_name,g.display_name) as parentName, null as entityMobileNo, l.loan_status_id as entityStatusEnum, IF(g.id is null, 'client', 'group') as parentType " + " from m_loan l left join m_client c on l.client_id = c.id left join m_group g ON l.group_id = g.id left join m_office o on o.id = c.office_id left join m_product_loan pl on pl.id=l.product_id where (o.hierarchy IS NULL OR o.hierarchy like :hierarchy) and (l.account_no like :search or l.external_id like :search)) "; - final String savingMatchSql = " (select 'SAVING' as entityType, s.id as entityId, sp.name as entityName, s.external_id as entityExternalId, s.account_no as entityAccountNo " + " , IFNULL(c.id,g.id) as parentId, IFNULL(c.display_name,g.display_name) as parentName, null as entityMobileNo, s.status_enum as entityStatusEnum, IF(g.id is null, 'client', 'group') as parentType " + " from m_savings_account s left join m_client c on s.client_id = c.id left join m_group g ON s.group_id = g.id left join m_office o on o.id = c.office_id left join m_savings_product sp on sp.id=s.product_id " @@ -139,8 +139,6 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService sql.append(groupMatchSql).append(union); } - - sql.replace(sql.lastIndexOf(union), sql.length(), ""); // remove last occurrence of "union all" string diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfAccountTransferApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfAccountTransferApiResource.java index 11dfd5eea..add89487f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfAccountTransferApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfAccountTransferApiResource.java @@ -61,130 +61,105 @@ import org.springframework.stereotype.Component; @Path("/self/accounttransfers") @Component @Scope("singleton") -@Api(tags = {"Self Account Transfer"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self Account transfer", description = "") -}) +@Api(tags = { "Self Account Transfer" }) +@SwaggerDefinition(tags = { @Tag(name = "Self Account transfer", description = "") }) public class SelfAccountTransferApiResource { - private final PlatformSecurityContext context; - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final AccountTransfersApiResource accountTransfersApiResource; - private final SelfAccountTransferReadService selfAccountTransferReadService; - private final ApiRequestParameterHelper apiRequestParameterHelper; - private final SelfAccountTransferDataValidator dataValidator; - private final SelfBeneficiariesTPTReadPlatformService tptBeneficiaryReadPlatformService; - private final ConfigurationDomainService configurationDomainService; - private final AccountTransfersReadPlatformService accountTransfersReadPlatformService; + private final PlatformSecurityContext context; + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final AccountTransfersApiResource accountTransfersApiResource; + private final SelfAccountTransferReadService selfAccountTransferReadService; + private final ApiRequestParameterHelper apiRequestParameterHelper; + private final SelfAccountTransferDataValidator dataValidator; + private final SelfBeneficiariesTPTReadPlatformService tptBeneficiaryReadPlatformService; + private final ConfigurationDomainService configurationDomainService; + private final AccountTransfersReadPlatformService accountTransfersReadPlatformService; - @Autowired - public SelfAccountTransferApiResource( - final PlatformSecurityContext context, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final AccountTransfersApiResource accountTransfersApiResource, - final SelfAccountTransferReadService selfAccountTransferReadService, - final ApiRequestParameterHelper apiRequestParameterHelper, - final SelfAccountTransferDataValidator dataValidator, - final SelfBeneficiariesTPTReadPlatformService tptBeneficiaryReadPlatformService, - final ConfigurationDomainService configurationDomainService, - final AccountTransfersReadPlatformService accountTransfersReadPlatformService) { - this.context = context; - this.toApiJsonSerializer = toApiJsonSerializer; - this.accountTransfersApiResource = accountTransfersApiResource; - this.selfAccountTransferReadService = selfAccountTransferReadService; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.dataValidator = dataValidator; - this.tptBeneficiaryReadPlatformService = tptBeneficiaryReadPlatformService; - this.configurationDomainService = configurationDomainService; - this.accountTransfersReadPlatformService = accountTransfersReadPlatformService; - } + @Autowired + public SelfAccountTransferApiResource(final PlatformSecurityContext context, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final AccountTransfersApiResource accountTransfersApiResource, + final SelfAccountTransferReadService selfAccountTransferReadService, final ApiRequestParameterHelper apiRequestParameterHelper, + final SelfAccountTransferDataValidator dataValidator, + final SelfBeneficiariesTPTReadPlatformService tptBeneficiaryReadPlatformService, + final ConfigurationDomainService configurationDomainService, + final AccountTransfersReadPlatformService accountTransfersReadPlatformService) { + this.context = context; + this.toApiJsonSerializer = toApiJsonSerializer; + this.accountTransfersApiResource = accountTransfersApiResource; + this.selfAccountTransferReadService = selfAccountTransferReadService; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.dataValidator = dataValidator; + this.tptBeneficiaryReadPlatformService = tptBeneficiaryReadPlatformService; + this.configurationDomainService = configurationDomainService; + this.accountTransfersReadPlatformService = accountTransfersReadPlatformService; + } - @GET - @Path("template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Account Transfer Template", httpMethod = "GET", notes = "Returns list of loan/savings accounts that can be used for account transfer\n" + - "\n" + "\n" + "Example Requests:\n" + "\n" + "self/accounttransfers/template\n") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SelfAccountTransferApiResourceSwagger.GetAccountTransferTemplateResponse.class)}) - public String template( - @DefaultValue("") @QueryParam("type") @ApiParam("type") final String type, - @Context final UriInfo uriInfo) { + @GET + @Path("template") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Retrieve Account Transfer Template", httpMethod = "GET", notes = "Returns list of loan/savings accounts that can be used for account transfer\n" + + "\n" + "\n" + "Example Requests:\n" + "\n" + "self/accounttransfers/template\n") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SelfAccountTransferApiResourceSwagger.GetAccountTransferTemplateResponse.class) }) + public String template(@DefaultValue("") @QueryParam("type") @ApiParam("type") final String type, @Context final UriInfo uriInfo) { - AppUser user = this.context.authenticatedUser(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - Collection selfTemplateData = this.selfAccountTransferReadService - .retrieveSelfAccountTemplateData(user); + AppUser user = this.context.authenticatedUser(); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + Collection selfTemplateData = this.selfAccountTransferReadService.retrieveSelfAccountTemplateData(user); - if (type.equals("tpt")) { - Collection tptTemplateData = this.tptBeneficiaryReadPlatformService - .retrieveTPTSelfAccountTemplateData(user); - return this.toApiJsonSerializer.serialize(settings, - new SelfAccountTransferData(selfTemplateData, - tptTemplateData)); - } + if (type.equals("tpt")) { + Collection tptTemplateData = this.tptBeneficiaryReadPlatformService + .retrieveTPTSelfAccountTemplateData(user); + return this.toApiJsonSerializer.serialize(settings, new SelfAccountTransferData(selfTemplateData, tptTemplateData)); + } - return this.toApiJsonSerializer - .serialize(settings, new SelfAccountTransferData( - selfTemplateData, selfTemplateData)); - } + return this.toApiJsonSerializer.serialize(settings, new SelfAccountTransferData(selfTemplateData, selfTemplateData)); + } - @POST - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create new Transfer", httpMethod = "POST", notes = "Ability to create new transfer of monetary funds from one account to another.\n" + - "\n" + "\n" + "Example Requests:\n" + "\n" + " self/accounttransfers/\n") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SelfAccountTransferApiResourceSwagger.PostNewTransferResponse.class)}) - public String create( - @DefaultValue("") @QueryParam("type") @ApiParam("type") final String type, - final String apiRequestBodyAsJson) { - Map params = this.dataValidator.validateCreate(type, - apiRequestBodyAsJson); - if (type.equals("tpt")) { - checkForLimits(params); - } - return this.accountTransfersApiResource.create(apiRequestBodyAsJson); - } + @POST + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Create new Transfer", httpMethod = "POST", notes = "Ability to create new transfer of monetary funds from one account to another.\n" + + "\n" + "\n" + "Example Requests:\n" + "\n" + " self/accounttransfers/\n") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SelfAccountTransferApiResourceSwagger.PostNewTransferResponse.class) }) + public String create(@DefaultValue("") @QueryParam("type") @ApiParam("type") final String type, final String apiRequestBodyAsJson) { + Map params = this.dataValidator.validateCreate(type, apiRequestBodyAsJson); + if (type.equals("tpt")) { + checkForLimits(params); + } + return this.accountTransfersApiResource.create(apiRequestBodyAsJson); + } - private void checkForLimits(Map params) { - SelfAccountTemplateData fromAccount = (SelfAccountTemplateData) params - .get("fromAccount"); - SelfAccountTemplateData toAccount = (SelfAccountTemplateData) params - .get("toAccount"); - LocalDate transactionDate = (LocalDate) params.get("transactionDate"); - BigDecimal transactionAmount = (BigDecimal) params - .get("transactionAmount"); + private void checkForLimits(Map params) { + SelfAccountTemplateData fromAccount = (SelfAccountTemplateData) params.get("fromAccount"); + SelfAccountTemplateData toAccount = (SelfAccountTemplateData) params.get("toAccount"); + LocalDate transactionDate = (LocalDate) params.get("transactionDate"); + BigDecimal transactionAmount = (BigDecimal) params.get("transactionAmount"); - AppUser user = this.context.authenticatedUser(); - Long transferLimit = this.tptBeneficiaryReadPlatformService - .getTransferLimit(user.getId(), toAccount.getAccountId(), - toAccount.getAccountType()); - if (transferLimit != null && transferLimit > 0) { - if (transactionAmount.compareTo(new BigDecimal(transferLimit)) > 0) { - throw new BeneficiaryTransferLimitExceededException(); - } - } + AppUser user = this.context.authenticatedUser(); + Long transferLimit = this.tptBeneficiaryReadPlatformService.getTransferLimit(user.getId(), toAccount.getAccountId(), + toAccount.getAccountType()); + if (transferLimit != null && transferLimit > 0) { + if (transactionAmount.compareTo(new BigDecimal(transferLimit)) > 0) { throw new BeneficiaryTransferLimitExceededException(); } + } - if (this.configurationDomainService.isDailyTPTLimitEnabled()) { - Long dailyTPTLimit = this.configurationDomainService - .getDailyTPTLimit(); - if (dailyTPTLimit != null && dailyTPTLimit > 0) { - BigDecimal dailyTPTLimitBD = new BigDecimal(dailyTPTLimit); - BigDecimal totTransactionAmount = this.accountTransfersReadPlatformService - .getTotalTransactionAmount(fromAccount.getAccountId(), - fromAccount.getAccountType(), transactionDate); - if (totTransactionAmount != null - && totTransactionAmount.compareTo(BigDecimal.ZERO) > 0) { - if (dailyTPTLimitBD.compareTo(totTransactionAmount) <= 0 - || dailyTPTLimitBD.compareTo(totTransactionAmount - .add(transactionAmount)) < 0) { - throw new DailyTPTTransactionAmountLimitExceededException( - fromAccount.getAccountId(), - fromAccount.getAccountType()); - } + if (this.configurationDomainService.isDailyTPTLimitEnabled()) { + Long dailyTPTLimit = this.configurationDomainService.getDailyTPTLimit(); + if (dailyTPTLimit != null && dailyTPTLimit > 0) { + BigDecimal dailyTPTLimitBD = new BigDecimal(dailyTPTLimit); + BigDecimal totTransactionAmount = this.accountTransfersReadPlatformService + .getTotalTransactionAmount(fromAccount.getAccountId(), fromAccount.getAccountType(), transactionDate); + if (totTransactionAmount != null && totTransactionAmount.compareTo(BigDecimal.ZERO) > 0) { + if (dailyTPTLimitBD.compareTo(totTransactionAmount) <= 0 + || dailyTPTLimitBD.compareTo(totTransactionAmount.add(transactionAmount)) < 0) { + throw new DailyTPTTransactionAmountLimitExceededException(fromAccount.getAccountId(), fromAccount.getAccountType()); + } + } + } + } } - } - } - } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfAccountTransferApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfAccountTransferApiResourceSwagger.java index aeb8b009b..d758ea633 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfAccountTransferApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfAccountTransferApiResourceSwagger.java @@ -27,18 +27,17 @@ import java.util.Set; */ final class SelfAccountTransferApiResourceSwagger { - private SelfAccountTransferApiResourceSwagger() { - } + private SelfAccountTransferApiResourceSwagger() {} @ApiModel(value = "GetAccountTransferTemplateResponse") public final static class GetAccountTransferTemplateResponse { - private GetAccountTransferTemplateResponse() { - } + + private GetAccountTransferTemplateResponse() {} final class GetAccountOptions { - private GetAccountOptions() { - } + + private GetAccountOptions() {} @ApiModelProperty(example = "2") public Integer id; @@ -51,8 +50,8 @@ final class SelfAccountTransferApiResourceSwagger { public Set accountTypeOptions; final class GetFromAccountOptions { - private GetFromAccountOptions() { - } + + private GetFromAccountOptions() {} @ApiModelProperty(example = "2") public Integer accountId; @@ -73,8 +72,8 @@ final class SelfAccountTransferApiResourceSwagger { public Set fromAccountTypeOptions; final class GetToAccountOptions { - private GetToAccountOptions() { - } + + private GetToAccountOptions() {} @ApiModelProperty(example = "2") public Integer accountId; @@ -97,8 +96,8 @@ final class SelfAccountTransferApiResourceSwagger { @ApiModel(value = "PostNewTransferRequest") public final static class PostNewTransferRequest { - private PostNewTransferRequest() { - } + + private PostNewTransferRequest() {} @ApiModelProperty(example = "1") public Integer fromOfficeId; @@ -131,12 +130,12 @@ final class SelfAccountTransferApiResourceSwagger { @ApiModel(value = "PostNewTransferResponse") public final static class PostNewTransferResponse { - private PostNewTransferResponse() { - } + + private PostNewTransferResponse() {} @ApiModelProperty(example = "1") public Integer savingsId; @ApiModelProperty(example = "1") public Integer resourceId; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiResource.java index 4a58229f7..c45e8078a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiResource.java @@ -62,10 +62,8 @@ import org.springframework.stereotype.Component; @Path("/self/beneficiaries/tpt") @Component @Scope("singleton") -@Api(tags = {"Self Third Party Transfer"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self Third Party Transfer", description = "") -}) +@Api(tags = { "Self Third Party Transfer" }) +@SwaggerDefinition(tags = { @Tag(name = "Self Third Party Transfer", description = "") }) public class SelfBeneficiariesTPTApiResource { private final PlatformSecurityContext context; @@ -75,19 +73,15 @@ public class SelfBeneficiariesTPTApiResource { private final SelfBeneficiariesTPTReadPlatformService readPlatformService; private static final Set RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList( SelfBeneficiariesTPTApiConstants.NAME_PARAM_NAME, SelfBeneficiariesTPTApiConstants.OFFICE_NAME_PARAM_NAME, - SelfBeneficiariesTPTApiConstants.ACCOUNT_NUMBER_PARAM_NAME, - SelfBeneficiariesTPTApiConstants.ACCOUNT_TYPE_PARAM_NAME, + SelfBeneficiariesTPTApiConstants.ACCOUNT_NUMBER_PARAM_NAME, SelfBeneficiariesTPTApiConstants.ACCOUNT_TYPE_PARAM_NAME, SelfBeneficiariesTPTApiConstants.TRANSFER_LIMIT_PARAM_NAME, SelfBeneficiariesTPTApiConstants.ID_PARAM_NAME, - SelfBeneficiariesTPTApiConstants.CLIENT_NAME_PARAM_NAME, - SelfBeneficiariesTPTApiConstants.ACCOUNT_TYPE_OPTIONS_PARAM_NAME)); + SelfBeneficiariesTPTApiConstants.CLIENT_NAME_PARAM_NAME, SelfBeneficiariesTPTApiConstants.ACCOUNT_TYPE_OPTIONS_PARAM_NAME)); @Autowired - public SelfBeneficiariesTPTApiResource( - final PlatformSecurityContext context, + public SelfBeneficiariesTPTApiResource(final PlatformSecurityContext context, final DefaultToApiJsonSerializer toApiJsonSerializer, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final ApiRequestParameterHelper apiRequestParameterHelper, - final SelfBeneficiariesTPTReadPlatformService readPlatformService) { + final ApiRequestParameterHelper apiRequestParameterHelper, final SelfBeneficiariesTPTReadPlatformService readPlatformService) { this.context = context; this.toApiJsonSerializer = toApiJsonSerializer; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; @@ -99,39 +93,41 @@ public class SelfBeneficiariesTPTApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Beneficiary Third Party Transfer Template", httpMethod = "GET", notes = "Returns Account Type enumerations. Self User is expected to know office name and account number to be able to add beneficiary.\n" + "\n" + "Example Requests:\n" + "\n" + "/self/beneficiaries/tpt/template") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfBeneficiariesTPTApiResourceSwagger.GetSelfBeneficiariesTPTTemplateResponse.class)}) + @ApiOperation(value = "Beneficiary Third Party Transfer Template", httpMethod = "GET", notes = "Returns Account Type enumerations. Self User is expected to know office name and account number to be able to add beneficiary.\n" + + "\n" + "Example Requests:\n" + "\n" + "/self/beneficiaries/tpt/template") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfBeneficiariesTPTApiResourceSwagger.GetSelfBeneficiariesTPTTemplateResponse.class) }) public String template(@Context final UriInfo uriInfo) { - final EnumOptionData loanAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.LOAN); - final EnumOptionData savingsAccountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.SAVINGS); + final EnumOptionData loanAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN); + final EnumOptionData savingsAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS); - final Collection accountTypeOptions = Arrays.asList( - savingsAccountType, loanAccountType); + final Collection accountTypeOptions = Arrays.asList(savingsAccountType, loanAccountType); - SelfBeneficiariesTPTData templateData = new SelfBeneficiariesTPTData( - accountTypeOptions); + SelfBeneficiariesTPTData templateData = new SelfBeneficiariesTPTData(accountTypeOptions); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, templateData, RESPONSE_DATA_PARAMETERS); } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Add TPT Beneficiary", httpMethod = "POST", notes = "Api to add third party beneficiary linked to current user.\n" + "\n" + "Parameter Definitions\n" + "\n" + "name : Nick name for beneficiary, should be unique for an self service user\n" + "\n" + "officeName : Office Name of beneficiary(not id)\n" + "\n" + "accountNumber : Account Number of beneficiary(not id)\n" + "\n" + "transferLimit : Each transfer initiated to this account will not exceed this amount\n" + "\n" + "Example Requests:\n" + "\n" + "/self/beneficiaries/tpt\n\n" + "Mandatory Fields: name, officeName, accountNumber, accountType\n\n" + "Optional Fields: transferLimit") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfBeneficiariesTPTApiResourceSwagger.PostSelfBeneficiariesTPTRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfBeneficiariesTPTApiResourceSwagger.PostSelfBeneficiariesTPTResponse.class)}) + @ApiOperation(value = "Add TPT Beneficiary", httpMethod = "POST", notes = "Api to add third party beneficiary linked to current user.\n" + + "\n" + "Parameter Definitions\n" + "\n" + "name : Nick name for beneficiary, should be unique for an self service user\n" + + "\n" + "officeName : Office Name of beneficiary(not id)\n" + "\n" + "accountNumber : Account Number of beneficiary(not id)\n" + + "\n" + "transferLimit : Each transfer initiated to this account will not exceed this amount\n" + "\n" + "Example Requests:\n" + + "\n" + "/self/beneficiaries/tpt\n\n" + "Mandatory Fields: name, officeName, accountNumber, accountType\n\n" + + "Optional Fields: transferLimit") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfBeneficiariesTPTApiResourceSwagger.PostSelfBeneficiariesTPTRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfBeneficiariesTPTApiResourceSwagger.PostSelfBeneficiariesTPTResponse.class) }) public String add(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .addSelfServiceBeneficiaryTPT().withJson(apiRequestBodyAsJson) + final CommandWrapper commandRequest = new CommandWrapperBuilder().addSelfServiceBeneficiaryTPT().withJson(apiRequestBodyAsJson) .build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } @@ -139,17 +135,18 @@ public class SelfBeneficiariesTPTApiResource { @Path("{beneficiaryId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Update TPT Beneficiary", httpMethod = "PUT", notes = "Api to update third party beneficiary linked to current user.\n" + "\n" + "Example Requests:\n" + "\n" + "/self/beneficiaries/tpt/{beneficiaryId}\n\n" + "Optional Fields: name, transferLimit") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfBeneficiariesTPTApiResourceSwagger.PutSelfBeneficiariesTPTBeneficiaryIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200,message = "OK", response = SelfBeneficiariesTPTApiResourceSwagger.PutSelfBeneficiariesTPTBeneficiaryIdResponse.class)}) + @ApiOperation(value = "Update TPT Beneficiary", httpMethod = "PUT", notes = "Api to update third party beneficiary linked to current user.\n" + + "\n" + "Example Requests:\n" + "\n" + "/self/beneficiaries/tpt/{beneficiaryId}\n\n" + "Optional Fields: name, transferLimit") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfBeneficiariesTPTApiResourceSwagger.PutSelfBeneficiariesTPTBeneficiaryIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfBeneficiariesTPTApiResourceSwagger.PutSelfBeneficiariesTPTBeneficiaryIdResponse.class) }) public String update(@PathParam("beneficiaryId") @ApiParam(value = "beneficiaryId") final Long beneficiaryId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .updateSelfServiceBeneficiaryTPT(beneficiaryId) + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateSelfServiceBeneficiaryTPT(beneficiaryId) .withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } @@ -157,34 +154,32 @@ public class SelfBeneficiariesTPTApiResource { @Path("{beneficiaryId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Delete TPT Beneficiary", httpMethod = "DELETE", notes = "Api to delete third party beneficiary linked to current user.\n" + "\n" + "Example Requests:\n" + "\n" + "/self/beneficiaries/tpt/{beneficiaryId}") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfBeneficiariesTPTApiResourceSwagger.DeleteSelfBeneficiariesTPTBeneficiaryIdResponse.class)}) - public String delete(@PathParam("beneficiaryId") final Long beneficiaryId, - @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Delete TPT Beneficiary", httpMethod = "DELETE", notes = "Api to delete third party beneficiary linked to current user.\n" + + "\n" + "Example Requests:\n" + "\n" + "/self/beneficiaries/tpt/{beneficiaryId}") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfBeneficiariesTPTApiResourceSwagger.DeleteSelfBeneficiariesTPTBeneficiaryIdResponse.class) }) + public String delete(@PathParam("beneficiaryId") final Long beneficiaryId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .deleteSelfServiceBeneficiaryTPT(beneficiaryId) + final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteSelfServiceBeneficiaryTPT(beneficiaryId) .withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Get All TPT Beneficiary", httpMethod = "GET", notes = "Api to get all third party beneficiary linked to current user.\n" + "\n" + "Example Requests:\n" + "\n" + "/self/beneficiaries/tpt") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfBeneficiariesTPTApiResourceSwagger.GetSelfBeneficiariesTPTResponse.class, responseContainer = "List")}) + @ApiOperation(value = "Get All TPT Beneficiary", httpMethod = "GET", notes = "Api to get all third party beneficiary linked to current user.\n" + + "\n" + "Example Requests:\n" + "\n" + "/self/beneficiaries/tpt") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfBeneficiariesTPTApiResourceSwagger.GetSelfBeneficiariesTPTResponse.class, responseContainer = "List") }) public String retrieveAll(@Context final UriInfo uriInfo) { - this.context.authenticatedUser().validateHasReadPermission( - SelfBeneficiariesTPTApiConstants.BENEFICIARY_ENTITY_NAME); + this.context.authenticatedUser().validateHasReadPermission(SelfBeneficiariesTPTApiConstants.BENEFICIARY_ENTITY_NAME); - final Collection beneficiaries = this.readPlatformService - .retrieveAll(); + final Collection beneficiaries = this.readPlatformService.retrieveAll(); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, beneficiaries, RESPONSE_DATA_PARAMETERS); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiResourceSwagger.java index 6697bca64..0668d39a4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/api/SelfBeneficiariesTPTApiResourceSwagger.java @@ -26,17 +26,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/22/17. */ final class SelfBeneficiariesTPTApiResourceSwagger { - private SelfBeneficiariesTPTApiResourceSwagger() { - } + + private SelfBeneficiariesTPTApiResourceSwagger() {} @ApiModel(value = "GetSelfBeneficiariesTPTTemplateResponse") public final static class GetSelfBeneficiariesTPTTemplateResponse { - private GetSelfBeneficiariesTPTTemplateResponse() { - } + + private GetSelfBeneficiariesTPTTemplateResponse() {} final class GetSelfBeneficiariesAccountOptions { - private GetSelfBeneficiariesAccountOptions() { - } + + private GetSelfBeneficiariesAccountOptions() {} @ApiModelProperty(example = "2") public Integer id; @@ -51,8 +51,8 @@ final class SelfBeneficiariesTPTApiResourceSwagger { @ApiModel(value = "PostSelfBeneficiariesTPTRequest") public final static class PostSelfBeneficiariesTPTRequest { - private PostSelfBeneficiariesTPTRequest() { - } + + private PostSelfBeneficiariesTPTRequest() {} @ApiModelProperty(example = "en_GB") public String locale; @@ -70,8 +70,8 @@ final class SelfBeneficiariesTPTApiResourceSwagger { @ApiModel(value = "PostSelfBeneficiariesTPTResponse") public final static class PostSelfBeneficiariesTPTResponse { - private PostSelfBeneficiariesTPTResponse() { - } + + private PostSelfBeneficiariesTPTResponse() {} @ApiModelProperty(example = "5") public Integer resourceId; @@ -79,8 +79,8 @@ final class SelfBeneficiariesTPTApiResourceSwagger { @ApiModel(value = "PutSelfBeneficiariesTPTBeneficiaryIdRequest") public final static class PutSelfBeneficiariesTPTBeneficiaryIdRequest { - private PutSelfBeneficiariesTPTBeneficiaryIdRequest() { - } + + private PutSelfBeneficiariesTPTBeneficiaryIdRequest() {} @ApiModelProperty(example = "beneficiary nick name") public String name; @@ -90,12 +90,12 @@ final class SelfBeneficiariesTPTApiResourceSwagger { @ApiModel(value = "PutSelfBeneficiariesTPTBeneficiaryIdResponse") public final static class PutSelfBeneficiariesTPTBeneficiaryIdResponse { - private PutSelfBeneficiariesTPTBeneficiaryIdResponse() { - } + + private PutSelfBeneficiariesTPTBeneficiaryIdResponse() {} final class PutSelfBeneficiariesChanges { - private PutSelfBeneficiariesChanges() { - } + + private PutSelfBeneficiariesChanges() {} @ApiModelProperty(example = "1000") public Integer transferLimit; @@ -110,8 +110,8 @@ final class SelfBeneficiariesTPTApiResourceSwagger { @ApiModel(value = "DeleteSelfBeneficiariesTPTBeneficiaryIdResponse") public final static class DeleteSelfBeneficiariesTPTBeneficiaryIdResponse { - private DeleteSelfBeneficiariesTPTBeneficiaryIdResponse() { - } + + private DeleteSelfBeneficiariesTPTBeneficiaryIdResponse() {} @ApiModelProperty(example = "5") public Integer resourceId; @@ -119,9 +119,8 @@ final class SelfBeneficiariesTPTApiResourceSwagger { @ApiModel(value = "GetSelfBeneficiariesTPTResponse") public final static class GetSelfBeneficiariesTPTResponse { - private GetSelfBeneficiariesTPTResponse() { - } + private GetSelfBeneficiariesTPTResponse() {} @ApiModelProperty(example = "1") public Integer id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTemplateData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTemplateData.java index d5a58ccd1..bcf8cbbed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTemplateData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTemplateData.java @@ -25,8 +25,7 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; import org.apache.fineract.portfolio.account.service.AccountTransferEnumerations; @SuppressWarnings("unused") -public class SelfAccountTemplateData implements - Comparable { +public class SelfAccountTemplateData implements Comparable { private final Long accountId; private final String accountNo; @@ -36,10 +35,8 @@ public class SelfAccountTemplateData implements private final Long officeId; private final String officeName; - public SelfAccountTemplateData(final Long accountId, - final String accountNo, final Integer accountType, - final Long clientId, final String clientName, final Long officeId, - final String officeName) { + public SelfAccountTemplateData(final Long accountId, final String accountNo, final Integer accountType, final Long clientId, + final String clientName, final Long officeId, final String officeName) { this.accountId = accountId; this.accountNo = accountNo; this.accountType = AccountTransferEnumerations.accountType(accountType); @@ -49,8 +46,7 @@ public class SelfAccountTemplateData implements this.officeName = officeName; } - public SelfAccountTemplateData(final Long accountId, - final Integer accountType, final Long clientId, final Long officeId) { + public SelfAccountTemplateData(final Long accountId, final Integer accountType, final Long clientId, final Long officeId) { this.accountId = accountId; this.accountNo = null; this.accountType = AccountTransferEnumerations.accountType(accountType); @@ -62,9 +58,7 @@ public class SelfAccountTemplateData implements @Override public int compareTo(final SelfAccountTemplateData obj) { - if (obj == null) { - return -1; - } + if (obj == null) { return -1; } return new CompareToBuilder() // .append(this.accountId, obj.accountId) // .append(this.accountType.getValue(), obj.accountType.getValue()) // @@ -75,15 +69,9 @@ public class SelfAccountTemplateData implements @Override public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (!(obj instanceof SelfAccountTemplateData)) { - return false; - } + if (obj == null) { return false; } + if (obj == this) { return true; } + if (!(obj instanceof SelfAccountTemplateData)) { return false; } final SelfAccountTemplateData rhs = (SelfAccountTemplateData) obj; return new EqualsBuilder() // .append(this.accountId, rhs.accountId) // @@ -111,5 +99,4 @@ public class SelfAccountTemplateData implements return this.accountType.getId().intValue(); } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTransferData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTransferData.java index 2ab56e0b6..696e97490 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTransferData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTransferData.java @@ -26,8 +26,7 @@ public class SelfAccountTransferData { private final Collection fromAccountOptions; private final Collection toAccountOptions; - public SelfAccountTransferData( - final Collection fromAccountOptions, + public SelfAccountTransferData(final Collection fromAccountOptions, Collection toAccountOptions) { this.fromAccountOptions = fromAccountOptions; this.toAccountOptions = toAccountOptions; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTransferDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTransferDataValidator.java index 0ac4568c1..d57eea317 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTransferDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfAccountTransferDataValidator.java @@ -61,78 +61,53 @@ public class SelfAccountTransferDataValidator { private final FromJsonHelper fromApiJsonHelper; @Autowired - public SelfAccountTransferDataValidator( - final PlatformSecurityContext context, + public SelfAccountTransferDataValidator(final PlatformSecurityContext context, final SelfAccountTransferReadService selfAccountTransferReadService, - final SelfBeneficiariesTPTReadPlatformService tptBeneficiaryReadPlatformService, - final FromJsonHelper fromApiJsonHelper) { + final SelfBeneficiariesTPTReadPlatformService tptBeneficiaryReadPlatformService, final FromJsonHelper fromApiJsonHelper) { this.context = context; this.selfAccountTransferReadService = selfAccountTransferReadService; this.tptBeneficiaryReadPlatformService = tptBeneficiaryReadPlatformService; this.fromApiJsonHelper = fromApiJsonHelper; } - public Map validateCreate(String type, String apiRequestBodyAsJson) { - if (StringUtils.isBlank(apiRequestBodyAsJson)) { - throw new InvalidJsonException(); - } + public Map validateCreate(String type, String apiRequestBodyAsJson) { + if (StringUtils.isBlank(apiRequestBodyAsJson)) { throw new InvalidJsonException(); } - JsonElement element = this.fromApiJsonHelper - .parse(apiRequestBodyAsJson); + JsonElement element = this.fromApiJsonHelper.parse(apiRequestBodyAsJson); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( - dataValidationErrors).resource(ACCOUNT_TRANSFER_RESOURCE_NAME); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(ACCOUNT_TRANSFER_RESOURCE_NAME); - final Long fromOfficeId = this.fromApiJsonHelper.extractLongNamed( - fromOfficeIdParamName, element); - baseDataValidator.reset().parameter(fromOfficeIdParamName) - .value(fromOfficeId).notNull().integerGreaterThanZero(); + final Long fromOfficeId = this.fromApiJsonHelper.extractLongNamed(fromOfficeIdParamName, element); + baseDataValidator.reset().parameter(fromOfficeIdParamName).value(fromOfficeId).notNull().integerGreaterThanZero(); - final Long fromClientId = this.fromApiJsonHelper.extractLongNamed( - fromClientIdParamName, element); - baseDataValidator.reset().parameter(fromClientIdParamName) - .value(fromClientId).notNull().integerGreaterThanZero(); + final Long fromClientId = this.fromApiJsonHelper.extractLongNamed(fromClientIdParamName, element); + baseDataValidator.reset().parameter(fromClientIdParamName).value(fromClientId).notNull().integerGreaterThanZero(); - final Long fromAccountId = this.fromApiJsonHelper.extractLongNamed( - fromAccountIdParamName, element); - baseDataValidator.reset().parameter(fromAccountIdParamName) - .value(fromAccountId).notNull().integerGreaterThanZero(); + final Long fromAccountId = this.fromApiJsonHelper.extractLongNamed(fromAccountIdParamName, element); + baseDataValidator.reset().parameter(fromAccountIdParamName).value(fromAccountId).notNull().integerGreaterThanZero(); - final Integer fromAccountType = this.fromApiJsonHelper - .extractIntegerSansLocaleNamed(fromAccountTypeParamName, - element); - baseDataValidator.reset().parameter(fromAccountTypeParamName) - .value(fromAccountType).notNull() + final Integer fromAccountType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(fromAccountTypeParamName, element); + baseDataValidator.reset().parameter(fromAccountTypeParamName).value(fromAccountType).notNull() .isOneOfTheseValues(Integer.valueOf(1), Integer.valueOf(2)); - final Long toOfficeId = this.fromApiJsonHelper.extractLongNamed( - toOfficeIdParamName, element); - baseDataValidator.reset().parameter(toOfficeIdParamName) - .value(toOfficeId).notNull().integerGreaterThanZero(); + final Long toOfficeId = this.fromApiJsonHelper.extractLongNamed(toOfficeIdParamName, element); + baseDataValidator.reset().parameter(toOfficeIdParamName).value(toOfficeId).notNull().integerGreaterThanZero(); - final Long toClientId = this.fromApiJsonHelper.extractLongNamed( - toClientIdParamName, element); - baseDataValidator.reset().parameter(toClientIdParamName) - .value(toClientId).notNull().integerGreaterThanZero(); + final Long toClientId = this.fromApiJsonHelper.extractLongNamed(toClientIdParamName, element); + baseDataValidator.reset().parameter(toClientIdParamName).value(toClientId).notNull().integerGreaterThanZero(); - final Long toAccountId = this.fromApiJsonHelper.extractLongNamed( - toAccountIdParamName, element); - baseDataValidator.reset().parameter(toAccountIdParamName) - .value(toAccountId).notNull().integerGreaterThanZero(); + final Long toAccountId = this.fromApiJsonHelper.extractLongNamed(toAccountIdParamName, element); + baseDataValidator.reset().parameter(toAccountIdParamName).value(toAccountId).notNull().integerGreaterThanZero(); - final Integer toAccountType = this.fromApiJsonHelper - .extractIntegerSansLocaleNamed(toAccountTypeParamName, element); - baseDataValidator.reset().parameter(toAccountTypeParamName) - .value(toAccountType).notNull() - .isOneOfTheseValues(Integer.valueOf(1), Integer.valueOf(2)); + final Integer toAccountType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(toAccountTypeParamName, element); + baseDataValidator.reset().parameter(toAccountTypeParamName).value(toAccountType).notNull().isOneOfTheseValues(Integer.valueOf(1), + Integer.valueOf(2)); - if (fromAccountType != null && fromAccountType == 1 - && toAccountType != null && toAccountType == 1) { - baseDataValidator - .reset() - .failWithCode("loan.to.loan.transfer.not.allowed", - "Cannot transfer from Loan account to another Loan account."); + if (fromAccountType != null && fromAccountType == 1 && toAccountType != null && toAccountType == 1) { + baseDataValidator.reset().failWithCode("loan.to.loan.transfer.not.allowed", + "Cannot transfer from Loan account to another Loan account."); } final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(transferDateParamName, element); @@ -147,10 +122,8 @@ public class SelfAccountTransferDataValidator { throwExceptionIfValidationWarningsExist(dataValidationErrors); - SelfAccountTemplateData fromAccount = new SelfAccountTemplateData( - fromAccountId, fromAccountType, fromClientId, fromOfficeId); - SelfAccountTemplateData toAccount = new SelfAccountTemplateData( - toAccountId, toAccountType, toClientId, toOfficeId); + SelfAccountTemplateData fromAccount = new SelfAccountTemplateData(fromAccountId, fromAccountType, fromClientId, fromOfficeId); + SelfAccountTemplateData toAccount = new SelfAccountTemplateData(toAccountId, toAccountType, toClientId, toOfficeId); validateUserAccounts(fromAccount, toAccount, baseDataValidator, type); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -165,18 +138,14 @@ public class SelfAccountTransferDataValidator { } - private void validateUserAccounts( - final SelfAccountTemplateData fromAccount, - final SelfAccountTemplateData toAccount, + private void validateUserAccounts(final SelfAccountTemplateData fromAccount, final SelfAccountTemplateData toAccount, final DataValidatorBuilder baseDataValidator, final String type) { AppUser user = this.context.authenticatedUser(); - Collection validFromAccounts = this.selfAccountTransferReadService - .retrieveSelfAccountTemplateData(user); + Collection validFromAccounts = this.selfAccountTransferReadService.retrieveSelfAccountTemplateData(user); Collection validToAccounts = validFromAccounts; if (type.equals("tpt")) { - validToAccounts = this.tptBeneficiaryReadPlatformService - .retrieveTPTSelfAccountTemplateData(user); + validToAccounts = this.tptBeneficiaryReadPlatformService.retrieveTPTSelfAccountTemplateData(user); } boolean validFromAccount = false; @@ -196,31 +165,22 @@ public class SelfAccountTransferDataValidator { } if (!validFromAccount) { - baseDataValidator - .reset() - .failWithCode("invalid.from.account.details", - "Source account details doesn't match with valid user account details."); + baseDataValidator.reset().failWithCode("invalid.from.account.details", + "Source account details doesn't match with valid user account details."); } if (!validToAccount) { - baseDataValidator - .reset() - .failWithCode("invalid.to.account.details", - "Destination account details doesn't match with valid user account details."); + baseDataValidator.reset().failWithCode("invalid.to.account.details", + "Destination account details doesn't match with valid user account details."); } if (fromAccount.equals(toAccount)) { - baseDataValidator.reset().failWithCode( - "same.from.to.account.details", - "Source and Destination account details are same."); + baseDataValidator.reset().failWithCode("same.from.to.account.details", "Source and Destination account details are same."); } } - private void throwExceptionIfValidationWarningsExist( - final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfBeneficiariesTPTData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfBeneficiariesTPTData.java index d83572360..7159149ac 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfBeneficiariesTPTData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfBeneficiariesTPTData.java @@ -22,6 +22,7 @@ import java.util.Collection; import org.apache.fineract.infrastructure.core.data.EnumOptionData; public class SelfBeneficiariesTPTData { + @SuppressWarnings("unused") private final Long id; @SuppressWarnings("unused") @@ -39,8 +40,7 @@ public class SelfBeneficiariesTPTData { @SuppressWarnings("unused") private final Collection accountTypeOptions; - public SelfBeneficiariesTPTData( - final Collection accountTypeOptions) { + public SelfBeneficiariesTPTData(final Collection accountTypeOptions) { this.accountTypeOptions = accountTypeOptions; this.id = null; this.name = null; @@ -51,10 +51,8 @@ public class SelfBeneficiariesTPTData { this.transferLimit = null; } - public SelfBeneficiariesTPTData(final Long id, final String name, - final String officeName, final String clientName, - final EnumOptionData accountType, final String accountNumber, - final Long transferLimit) { + public SelfBeneficiariesTPTData(final Long id, final String name, final String officeName, final String clientName, + final EnumOptionData accountType, final String accountNumber, final Long transferLimit) { this.accountTypeOptions = null; this.id = id; this.name = name; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfBeneficiariesTPTDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfBeneficiariesTPTDataValidator.java index 961ba9d2d..908224140 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfBeneficiariesTPTDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/data/SelfBeneficiariesTPTDataValidator.java @@ -50,66 +50,43 @@ import org.springframework.stereotype.Component; public class SelfBeneficiariesTPTDataValidator { private final FromJsonHelper fromApiJsonHelper; - private static final Set CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(SelfBeneficiariesTPTApiConstants.LOCALE, NAME_PARAM_NAME, OFFICE_NAME_PARAM_NAME, - ACCOUNT_NUMBER_PARAM_NAME, ACCOUNT_TYPE_PARAM_NAME, TRANSFER_LIMIT_PARAM_NAME)); + private static final Set CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(SelfBeneficiariesTPTApiConstants.LOCALE, + NAME_PARAM_NAME, OFFICE_NAME_PARAM_NAME, ACCOUNT_NUMBER_PARAM_NAME, ACCOUNT_TYPE_PARAM_NAME, TRANSFER_LIMIT_PARAM_NAME)); private static final Set UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>( Arrays.asList(NAME_PARAM_NAME, TRANSFER_LIMIT_PARAM_NAME)); - @Autowired - public SelfBeneficiariesTPTDataValidator( - final FromJsonHelper fromApiJsonHelper) { + public SelfBeneficiariesTPTDataValidator(final FromJsonHelper fromApiJsonHelper) { this.fromApiJsonHelper = fromApiJsonHelper; } public HashMap validateForCreate(String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - CREATE_REQUEST_DATA_PARAMETERS); + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, CREATE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( - dataValidationErrors).resource(RESOURCE_NAME); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(RESOURCE_NAME); final JsonElement element = this.fromApiJsonHelper.parse(json); - final String name = this.fromApiJsonHelper.extractStringNamed( - NAME_PARAM_NAME, element); - baseDataValidator.reset().parameter(NAME_PARAM_NAME).value(name) - .notBlank().notExceedingLengthOf(50); + final String name = this.fromApiJsonHelper.extractStringNamed(NAME_PARAM_NAME, element); + baseDataValidator.reset().parameter(NAME_PARAM_NAME).value(name).notBlank().notExceedingLengthOf(50); - final String officeName = this.fromApiJsonHelper.extractStringNamed( - OFFICE_NAME_PARAM_NAME, element); - baseDataValidator.reset().parameter(OFFICE_NAME_PARAM_NAME) - .value(officeName).notBlank() - .notExceedingLengthOf(50); + final String officeName = this.fromApiJsonHelper.extractStringNamed(OFFICE_NAME_PARAM_NAME, element); + baseDataValidator.reset().parameter(OFFICE_NAME_PARAM_NAME).value(officeName).notBlank().notExceedingLengthOf(50); - final String accountNo = this.fromApiJsonHelper.extractStringNamed( - ACCOUNT_NUMBER_PARAM_NAME, element); - baseDataValidator.reset().parameter(ACCOUNT_NUMBER_PARAM_NAME) - .value(accountNo).notBlank().notExceedingLengthOf(20); + final String accountNo = this.fromApiJsonHelper.extractStringNamed(ACCOUNT_NUMBER_PARAM_NAME, element); + baseDataValidator.reset().parameter(ACCOUNT_NUMBER_PARAM_NAME).value(accountNo).notBlank().notExceedingLengthOf(20); - final Integer accountType = this.fromApiJsonHelper.extractIntegerNamed( - ACCOUNT_TYPE_PARAM_NAME, element, this.fromApiJsonHelper - .extractLocaleParameter(element.getAsJsonObject())); - baseDataValidator - .reset() - .parameter(ACCOUNT_TYPE_PARAM_NAME) - .value(accountType) - .notNull() - .isOneOfTheseValues(PortfolioAccountType.LOAN.getValue(), - PortfolioAccountType.SAVINGS.getValue()); + final Integer accountType = this.fromApiJsonHelper.extractIntegerNamed(ACCOUNT_TYPE_PARAM_NAME, element, + this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject())); + baseDataValidator.reset().parameter(ACCOUNT_TYPE_PARAM_NAME).value(accountType).notNull() + .isOneOfTheseValues(PortfolioAccountType.LOAN.getValue(), PortfolioAccountType.SAVINGS.getValue()); - final Long transferLimit = this.fromApiJsonHelper.extractLongNamed( - TRANSFER_LIMIT_PARAM_NAME, element); - baseDataValidator.reset().parameter(TRANSFER_LIMIT_PARAM_NAME) - .value(transferLimit).ignoreIfNull().longGreaterThanZero(); + final Long transferLimit = this.fromApiJsonHelper.extractLongNamed(TRANSFER_LIMIT_PARAM_NAME, element); + baseDataValidator.reset().parameter(TRANSFER_LIMIT_PARAM_NAME).value(transferLimit).ignoreIfNull().longGreaterThanZero(); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -124,36 +101,26 @@ public class SelfBeneficiariesTPTDataValidator { } public HashMap validateForUpdate(String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - UPDATE_REQUEST_DATA_PARAMETERS); + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, UPDATE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( - dataValidationErrors).resource(RESOURCE_NAME); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(RESOURCE_NAME); final JsonElement element = this.fromApiJsonHelper.parse(json); HashMap ret = new HashMap<>(); if (this.fromApiJsonHelper.parameterExists(NAME_PARAM_NAME, element)) { - final String name = this.fromApiJsonHelper.extractStringNamed( - NAME_PARAM_NAME, element); - baseDataValidator.reset().parameter(NAME_PARAM_NAME).value(name) - .notBlank().notExceedingLengthOf(50); + final String name = this.fromApiJsonHelper.extractStringNamed(NAME_PARAM_NAME, element); + baseDataValidator.reset().parameter(NAME_PARAM_NAME).value(name).notBlank().notExceedingLengthOf(50); ret.put(NAME_PARAM_NAME, name); } - if (this.fromApiJsonHelper.parameterExists(TRANSFER_LIMIT_PARAM_NAME, - element)) { - final Long transferLimit = this.fromApiJsonHelper.extractLongNamed( - TRANSFER_LIMIT_PARAM_NAME, element); - baseDataValidator.reset().parameter(TRANSFER_LIMIT_PARAM_NAME) - .value(transferLimit).ignoreIfNull().longGreaterThanZero(); + if (this.fromApiJsonHelper.parameterExists(TRANSFER_LIMIT_PARAM_NAME, element)) { + final Long transferLimit = this.fromApiJsonHelper.extractLongNamed(TRANSFER_LIMIT_PARAM_NAME, element); + baseDataValidator.reset().parameter(TRANSFER_LIMIT_PARAM_NAME).value(transferLimit).ignoreIfNull().longGreaterThanZero(); ret.put(TRANSFER_LIMIT_PARAM_NAME, transferLimit); } @@ -162,11 +129,8 @@ public class SelfBeneficiariesTPTDataValidator { return ret; } - private void throwExceptionIfValidationWarningsExist( - final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/domain/SelfBeneficiariesTPT.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/domain/SelfBeneficiariesTPT.java index ea9b7c5b7..030c3ec64 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/domain/SelfBeneficiariesTPT.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/domain/SelfBeneficiariesTPT.java @@ -30,8 +30,8 @@ import javax.persistence.UniqueConstraint; import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Entity -@Table(name = "m_selfservice_beneficiaries_tpt", uniqueConstraints = { @UniqueConstraint(columnNames = { - "name", "app_user_id", "is_active" }, name = "name") }) +@Table(name = "m_selfservice_beneficiaries_tpt", uniqueConstraints = { + @UniqueConstraint(columnNames = { "name", "app_user_id", "is_active" }, name = "name") }) public class SelfBeneficiariesTPT extends AbstractPersistableCustom { @Column(name = "app_user_id", nullable = false) @@ -62,8 +62,7 @@ public class SelfBeneficiariesTPT extends AbstractPersistableCustom { // } - public SelfBeneficiariesTPT(Long appUserId, String name, Long officeId, - Long clientId, Long accountId, Integer accountType, + public SelfBeneficiariesTPT(Long appUserId, String name, Long officeId, Long clientId, Long accountId, Integer accountType, Long transferLimit) { this.appUserId = appUserId; this.name = name; @@ -124,7 +123,7 @@ public class SelfBeneficiariesTPT extends AbstractPersistableCustom { this.name = newName; changes.put(NAME_PARAM_NAME, newName); } - if ((this.transferLimit !=null && !this.transferLimit.equals(newTransferLimit)) + if ((this.transferLimit != null && !this.transferLimit.equals(newTransferLimit)) || (this.transferLimit == null && newTransferLimit != null)) { this.transferLimit = newTransferLimit; changes.put(TRANSFER_LIMIT_PARAM_NAME, newTransferLimit); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/domain/SelfBeneficiariesTPTRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/domain/SelfBeneficiariesTPTRepository.java index 35b7d144a..f09394a60 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/domain/SelfBeneficiariesTPTRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/domain/SelfBeneficiariesTPTRepository.java @@ -21,8 +21,7 @@ package org.apache.fineract.portfolio.self.account.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface SelfBeneficiariesTPTRepository extends - JpaRepository, - JpaSpecificationExecutor { +public interface SelfBeneficiariesTPTRepository + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/BeneficiaryTransferLimitExceededException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/BeneficiaryTransferLimitExceededException.java index 5fd0db1c4..9857a0386 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/BeneficiaryTransferLimitExceededException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/BeneficiaryTransferLimitExceededException.java @@ -23,8 +23,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class BeneficiaryTransferLimitExceededException extends AbstractPlatformDomainRuleException { public BeneficiaryTransferLimitExceededException() { - super("error.msg.beneficiary.transfer.amount.limit.for.beneficiary.exceeded", - "Transfer amount limit for beneficiary exceeded"); + super("error.msg.beneficiary.transfer.amount.limit.for.beneficiary.exceeded", "Transfer amount limit for beneficiary exceeded"); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/DailyTPTTransactionAmountLimitExceededException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/DailyTPTTransactionAmountLimitExceededException.java index a2ece00a1..eb045f886 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/DailyTPTTransactionAmountLimitExceededException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/DailyTPTTransactionAmountLimitExceededException.java @@ -22,10 +22,9 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class DailyTPTTransactionAmountLimitExceededException extends AbstractPlatformDomainRuleException { - public DailyTPTTransactionAmountLimitExceededException(Long accountId, - Integer accountType) { - super("error.msg.beneficiary.daily.tpt.transfer.limit.for.fromaccountid."+accountId+".fromaccounttype."+accountType+".exceeded", - "Daily third party transfer limit for the source account excceeded"); + public DailyTPTTransactionAmountLimitExceededException(Long accountId, Integer accountType) { + super("error.msg.beneficiary.daily.tpt.transfer.limit.for.fromaccountid." + accountId + ".fromaccounttype." + accountType + + ".exceeded", "Daily third party transfer limit for the source account excceeded"); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/InvalidAccountInformationException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/InvalidAccountInformationException.java index 3f3274d40..e1a29d3cf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/InvalidAccountInformationException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/InvalidAccountInformationException.java @@ -20,13 +20,10 @@ package org.apache.fineract.portfolio.self.account.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; -public class InvalidAccountInformationException extends - AbstractPlatformDomainRuleException { - public InvalidAccountInformationException(final String officeName, - final String accountNumber, final String accountType) { - super("error.msg.beneficiary.invalid.account.details.with.officeName." - + officeName + ".accountNumber." + accountNumber - + ".accountType." + accountType, - "Invalid Office Name, Account Number, Account Type combination"); +public class InvalidAccountInformationException extends AbstractPlatformDomainRuleException { + + public InvalidAccountInformationException(final String officeName, final String accountNumber, final String accountType) { + super("error.msg.beneficiary.invalid.account.details.with.officeName." + officeName + ".accountNumber." + accountNumber + + ".accountType." + accountType, "Invalid Office Name, Account Number, Account Type combination"); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/InvalidBeneficiaryException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/InvalidBeneficiaryException.java index 00900ddce..df1b2e0e8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/InvalidBeneficiaryException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/exception/InvalidBeneficiaryException.java @@ -20,10 +20,9 @@ package org.apache.fineract.portfolio.self.account.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; -public class InvalidBeneficiaryException extends - AbstractPlatformDomainRuleException { +public class InvalidBeneficiaryException extends AbstractPlatformDomainRuleException { + public InvalidBeneficiaryException(final Long beneficiaryId) { - super("error.msg.beneficiary.invalid.beneficiary.id." + beneficiaryId, - "Beneficiary ID doesn't belong to the User"); + super("error.msg.beneficiary.invalid.beneficiary.id." + beneficiaryId, "Beneficiary ID doesn't belong to the User"); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/AddSelfBeneficiariesTPTCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/AddSelfBeneficiariesTPTCommandHandler.java index 6bb2c0ec0..d698e889f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/AddSelfBeneficiariesTPTCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/AddSelfBeneficiariesTPTCommandHandler.java @@ -28,13 +28,12 @@ import org.springframework.stereotype.Service; @Service @CommandType(entity = "SSBENEFICIARYTPT", action = "CREATE") -public class AddSelfBeneficiariesTPTCommandHandler implements - NewCommandSourceHandler { +public class AddSelfBeneficiariesTPTCommandHandler implements NewCommandSourceHandler { + private final SelfBeneficiariesTPTWritePlatformService writePlatformService; @Autowired - public AddSelfBeneficiariesTPTCommandHandler( - final SelfBeneficiariesTPTWritePlatformService writePlatformService) { + public AddSelfBeneficiariesTPTCommandHandler(final SelfBeneficiariesTPTWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/DeleteSelfBeneficiariesTPTCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/DeleteSelfBeneficiariesTPTCommandHandler.java index 187bf2f53..69d819fbe 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/DeleteSelfBeneficiariesTPTCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/DeleteSelfBeneficiariesTPTCommandHandler.java @@ -28,13 +28,12 @@ import org.springframework.stereotype.Service; @Service @CommandType(entity = "SSBENEFICIARYTPT", action = "DELETE") -public class DeleteSelfBeneficiariesTPTCommandHandler implements - NewCommandSourceHandler { +public class DeleteSelfBeneficiariesTPTCommandHandler implements NewCommandSourceHandler { + private final SelfBeneficiariesTPTWritePlatformService writePlatformService; @Autowired - public DeleteSelfBeneficiariesTPTCommandHandler( - final SelfBeneficiariesTPTWritePlatformService writePlatformService) { + public DeleteSelfBeneficiariesTPTCommandHandler(final SelfBeneficiariesTPTWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/UpdateSelfBeneficiariesTPTCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/UpdateSelfBeneficiariesTPTCommandHandler.java index 4ed9feda5..19ede1450 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/UpdateSelfBeneficiariesTPTCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/handler/UpdateSelfBeneficiariesTPTCommandHandler.java @@ -28,13 +28,12 @@ import org.springframework.stereotype.Service; @Service @CommandType(entity = "SSBENEFICIARYTPT", action = "UPDATE") -public class UpdateSelfBeneficiariesTPTCommandHandler implements - NewCommandSourceHandler { +public class UpdateSelfBeneficiariesTPTCommandHandler implements NewCommandSourceHandler { + private final SelfBeneficiariesTPTWritePlatformService writePlatformService; @Autowired - public UpdateSelfBeneficiariesTPTCommandHandler( - final SelfBeneficiariesTPTWritePlatformService writePlatformService) { + public UpdateSelfBeneficiariesTPTCommandHandler(final SelfBeneficiariesTPTWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfAccountTransferReadService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfAccountTransferReadService.java index f4f1b7450..ff2cbd0ec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfAccountTransferReadService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfAccountTransferReadService.java @@ -24,7 +24,6 @@ import org.apache.fineract.useradministration.domain.AppUser; public interface SelfAccountTransferReadService { - Collection retrieveSelfAccountTemplateData( - AppUser user); + Collection retrieveSelfAccountTemplateData(AppUser user); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfAccountTransferReadServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfAccountTransferReadServiceImpl.java index 94d8dbc79..fe4bb9cf6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfAccountTransferReadServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfAccountTransferReadServiceImpl.java @@ -30,8 +30,7 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class SelfAccountTransferReadServiceImpl implements - SelfAccountTransferReadService { +public class SelfAccountTransferReadServiceImpl implements SelfAccountTransferReadService { private final JdbcTemplate jdbcTemplate; @@ -41,50 +40,27 @@ public class SelfAccountTransferReadServiceImpl implements } @Override - public Collection retrieveSelfAccountTemplateData( - AppUser user) { + public Collection retrieveSelfAccountTemplateData(AppUser user) { SelfAccountTemplateMapper mapper = new SelfAccountTemplateMapper(); - StringBuilder sql = new StringBuilder() - .append("select s.id as accountId, ") - .append("s.account_no as accountNo, ") - .append("2 as accountType, ") - .append("c.id as clientId, ") - .append("c.display_name as clientName, ") - .append("o.id as officeId, ") - .append("o.name as officeName ") - .append("from m_appuser as u ") + StringBuilder sql = new StringBuilder().append("select s.id as accountId, ").append("s.account_no as accountNo, ") + .append("2 as accountType, ").append("c.id as clientId, ").append("c.display_name as clientName, ") + .append("o.id as officeId, ").append("o.name as officeName ").append("from m_appuser as u ") .append("inner join m_selfservice_user_client_mapping as map on u.id = map.appuser_id ") - .append("inner join m_client as c on map.client_id = c.id ") - .append("inner join m_office as o on c.office_id = o.id ") - .append("inner join m_savings_account as s on s.client_id = c.id ") - .append("where u.id = ? ") - .append("and s.status_enum = 300 ") - .append("union ") - .append("select l.id as accountId, ") - .append("l.account_no as accountNo, ") - .append("1 as accountType, ") - .append("c.id as clientId, ") - .append("c.display_name as clientName, ") - .append("o.id as officeId, ") - .append("o.name as officeName ") - .append("from m_appuser as u ") - .append("inner join m_selfservice_user_client_mapping as map on u.id = map.appuser_id ") - .append("inner join m_client as c on map.client_id = c.id ") - .append("inner join m_office as o on c.office_id = o.id ") - .append("inner join m_loan as l on l.client_id = c.id ") - .append("where u.id = ? ") - .append("and l.loan_status_id = 300 "); - return this.jdbcTemplate.query(sql.toString(), mapper, new Object[] { - user.getId(), user.getId() }); + .append("inner join m_client as c on map.client_id = c.id ").append("inner join m_office as o on c.office_id = o.id ") + .append("inner join m_savings_account as s on s.client_id = c.id ").append("where u.id = ? ") + .append("and s.status_enum = 300 ").append("union ").append("select l.id as accountId, ") + .append("l.account_no as accountNo, ").append("1 as accountType, ").append("c.id as clientId, ") + .append("c.display_name as clientName, ").append("o.id as officeId, ").append("o.name as officeName ") + .append("from m_appuser as u ").append("inner join m_selfservice_user_client_mapping as map on u.id = map.appuser_id ") + .append("inner join m_client as c on map.client_id = c.id ").append("inner join m_office as o on c.office_id = o.id ") + .append("inner join m_loan as l on l.client_id = c.id ").append("where u.id = ? ").append("and l.loan_status_id = 300 "); + return this.jdbcTemplate.query(sql.toString(), mapper, new Object[] { user.getId(), user.getId() }); } - private final class SelfAccountTemplateMapper implements - RowMapper { + private final class SelfAccountTemplateMapper implements RowMapper { @Override - public SelfAccountTemplateData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public SelfAccountTemplateData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long accountId = rs.getLong("accountId"); final String accountNo = rs.getString("accountNo"); final Integer accountType = rs.getInt("accountType"); @@ -93,8 +69,7 @@ public class SelfAccountTransferReadServiceImpl implements final Long officeId = rs.getLong("officeId"); final String officeName = rs.getString("officeName"); - return new SelfAccountTemplateData(accountId, accountNo, - accountType, clientId, clientName, officeId, officeName); + return new SelfAccountTemplateData(accountId, accountNo, accountType, clientId, clientName, officeId, officeName); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTReadPlatformService.java index bdc2ef33a..3ed5e8cb7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTReadPlatformService.java @@ -27,8 +27,7 @@ public interface SelfBeneficiariesTPTReadPlatformService { Collection retrieveAll(); - Collection retrieveTPTSelfAccountTemplateData( - AppUser user); + Collection retrieveTPTSelfAccountTemplateData(AppUser user); Long getTransferLimit(Long id, Long accountId, Integer accountType); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTReadPlatformServiceImpl.java index e1c8678d1..2dd1a1278 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTReadPlatformServiceImpl.java @@ -35,8 +35,7 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class SelfBeneficiariesTPTReadPlatformServiceImpl implements - SelfBeneficiariesTPTReadPlatformService { +public class SelfBeneficiariesTPTReadPlatformServiceImpl implements SelfBeneficiariesTPTReadPlatformService { private final PlatformSecurityContext context; private final JdbcTemplate jdbcTemplate; @@ -44,9 +43,7 @@ public class SelfBeneficiariesTPTReadPlatformServiceImpl implements private final AccountTemplateMapper accountTemplateMapper; @Autowired - public SelfBeneficiariesTPTReadPlatformServiceImpl( - final PlatformSecurityContext context, - final RoutingDataSource dataSource) { + public SelfBeneficiariesTPTReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); this.mapper = new BeneficiaryMapper(); @@ -56,26 +53,21 @@ public class SelfBeneficiariesTPTReadPlatformServiceImpl implements @Override public Collection retrieveAll() { AppUser user = this.context.authenticatedUser(); - return this.jdbcTemplate.query(this.mapper.schema(), this.mapper, - new Object[] { user.getId(), user.getId() }); + return this.jdbcTemplate.query(this.mapper.schema(), this.mapper, new Object[] { user.getId(), user.getId() }); } @Override - public Collection retrieveTPTSelfAccountTemplateData( - AppUser user) { - return this.jdbcTemplate.query(this.accountTemplateMapper.schema(), - this.accountTemplateMapper, + public Collection retrieveTPTSelfAccountTemplateData(AppUser user) { + return this.jdbcTemplate.query(this.accountTemplateMapper.schema(), this.accountTemplateMapper, new Object[] { user.getId(), user.getId() }); } - private static final class BeneficiaryMapper implements - RowMapper { + private static final class BeneficiaryMapper implements RowMapper { private final String schemaSql; public BeneficiaryMapper() { - final StringBuilder sqlBuilder = new StringBuilder( - "(select b.id as id, "); + final StringBuilder sqlBuilder = new StringBuilder("(select b.id as id, "); sqlBuilder.append(" b.name as name, "); sqlBuilder.append(" o.name as officeName, "); sqlBuilder.append(" c.display_name as clientName, "); @@ -83,12 +75,9 @@ public class SelfBeneficiariesTPTReadPlatformServiceImpl implements sqlBuilder.append(" s.account_no as accountNumber, "); sqlBuilder.append(" b.transfer_limit as transferLimit "); sqlBuilder.append(" from m_selfservice_beneficiaries_tpt as b "); - sqlBuilder - .append(" inner join m_office as o on b.office_id = o.id "); - sqlBuilder - .append(" inner join m_client as c on b.client_id = c.id "); - sqlBuilder - .append(" inner join m_savings_account as s on b.account_id = s.id "); + sqlBuilder.append(" inner join m_office as o on b.office_id = o.id "); + sqlBuilder.append(" inner join m_client as c on b.client_id = c.id "); + sqlBuilder.append(" inner join m_savings_account as s on b.account_id = s.id "); sqlBuilder.append(" where b.is_active = 1 "); sqlBuilder.append(" and b.account_type = 2 "); sqlBuilder.append(" and b.app_user_id = ?) "); @@ -101,12 +90,9 @@ public class SelfBeneficiariesTPTReadPlatformServiceImpl implements sqlBuilder.append(" l.account_no as accountNumber, "); sqlBuilder.append(" b.transfer_limit as transferLimit "); sqlBuilder.append(" from m_selfservice_beneficiaries_tpt as b "); - sqlBuilder - .append(" inner join m_office as o on b.office_id = o.id "); - sqlBuilder - .append(" inner join m_client as c on b.client_id = c.id "); - sqlBuilder - .append(" inner join m_loan as l on b.account_id = l.id "); + sqlBuilder.append(" inner join m_office as o on b.office_id = o.id "); + sqlBuilder.append(" inner join m_client as c on b.client_id = c.id "); + sqlBuilder.append(" inner join m_loan as l on b.account_id = l.id "); sqlBuilder.append(" where b.is_active = 1 "); sqlBuilder.append(" and b.account_type = 1 "); sqlBuilder.append(" and b.app_user_id = ?) "); @@ -119,33 +105,27 @@ public class SelfBeneficiariesTPTReadPlatformServiceImpl implements } @Override - public SelfBeneficiariesTPTData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public SelfBeneficiariesTPTData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); final String name = rs.getString("name"); final String officeName = rs.getString("officeName"); final String clientName = rs.getString("clientName"); final Integer accountTypeId = rs.getInt("accountType"); - final EnumOptionData accountType = AccountTransferEnumerations - .accountType(PortfolioAccountType.fromInt(accountTypeId)); + final EnumOptionData accountType = AccountTransferEnumerations.accountType(PortfolioAccountType.fromInt(accountTypeId)); final String accountNumber = rs.getString("accountNumber"); final Long transferLimit = rs.getLong("transferLimit"); - return new SelfBeneficiariesTPTData(id, name, officeName, - clientName, accountType, accountNumber, transferLimit); + return new SelfBeneficiariesTPTData(id, name, officeName, clientName, accountType, accountNumber, transferLimit); } } - private static final class AccountTemplateMapper implements - RowMapper { + private static final class AccountTemplateMapper implements RowMapper { private final String schemaSql; public AccountTemplateMapper() { - final StringBuilder sqlBuilder = new StringBuilder( - "(select o.name as officeName, "); + final StringBuilder sqlBuilder = new StringBuilder("(select o.name as officeName, "); sqlBuilder.append(" o.id as officeId, "); sqlBuilder.append(" c.display_name as clientName, "); sqlBuilder.append(" c.id as clientId, "); @@ -153,12 +133,9 @@ public class SelfBeneficiariesTPTReadPlatformServiceImpl implements sqlBuilder.append(" s.account_no as accountNumber, "); sqlBuilder.append(" s.id as accountId "); sqlBuilder.append(" from m_selfservice_beneficiaries_tpt as b "); - sqlBuilder - .append(" inner join m_office as o on b.office_id = o.id "); - sqlBuilder - .append(" inner join m_client as c on b.client_id = c.id "); - sqlBuilder - .append(" inner join m_savings_account as s on b.account_id = s.id "); + sqlBuilder.append(" inner join m_office as o on b.office_id = o.id "); + sqlBuilder.append(" inner join m_client as c on b.client_id = c.id "); + sqlBuilder.append(" inner join m_savings_account as s on b.account_id = s.id "); sqlBuilder.append(" where b.is_active = 1 "); sqlBuilder.append(" and b.account_type = 2 "); sqlBuilder.append(" and b.app_user_id = ?) "); @@ -171,12 +148,9 @@ public class SelfBeneficiariesTPTReadPlatformServiceImpl implements sqlBuilder.append(" l.account_no as accountNumber, "); sqlBuilder.append(" l.id as accountId "); sqlBuilder.append(" from m_selfservice_beneficiaries_tpt as b "); - sqlBuilder - .append(" inner join m_office as o on b.office_id = o.id "); - sqlBuilder - .append(" inner join m_client as c on b.client_id = c.id "); - sqlBuilder - .append(" inner join m_loan as l on b.account_id = l.id "); + sqlBuilder.append(" inner join m_office as o on b.office_id = o.id "); + sqlBuilder.append(" inner join m_client as c on b.client_id = c.id "); + sqlBuilder.append(" inner join m_loan as l on b.account_id = l.id "); sqlBuilder.append(" where b.is_active = 1 "); sqlBuilder.append(" and b.account_type = 1 "); sqlBuilder.append(" and b.app_user_id = ?) "); @@ -189,9 +163,7 @@ public class SelfBeneficiariesTPTReadPlatformServiceImpl implements } @Override - public SelfAccountTemplateData mapRow(final ResultSet rs, - @SuppressWarnings("unused") final int rowNum) - throws SQLException { + public SelfAccountTemplateData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final String officeName = rs.getString("officeName"); final Long officeId = rs.getLong("officeId"); @@ -201,8 +173,7 @@ public class SelfBeneficiariesTPTReadPlatformServiceImpl implements final String accountNumber = rs.getString("accountNumber"); final Long accountId = rs.getLong("accountId"); - return new SelfAccountTemplateData(accountId, accountNumber, - accountTypeId, clientId, clientName, officeId, officeName); + return new SelfAccountTemplateData(accountId, accountNumber, accountTypeId, clientId, clientName, officeId, officeName); } } @@ -215,7 +186,6 @@ public class SelfBeneficiariesTPTReadPlatformServiceImpl implements sqlBuilder.append(" and b.account_type = ? "); sqlBuilder.append(" and b.is_active = 1; "); - return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), - new Object[]{appUserId, accountId, accountType}, Long.class); + return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), new Object[] { appUserId, accountId, accountType }, Long.class); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTWritePlatformServiceImpl.java index 2deebfeef..46f4e550d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/account/service/SelfBeneficiariesTPTWritePlatformServiceImpl.java @@ -50,8 +50,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -public class SelfBeneficiariesTPTWritePlatformServiceImpl implements - SelfBeneficiariesTPTWritePlatformService { +public class SelfBeneficiariesTPTWritePlatformServiceImpl implements SelfBeneficiariesTPTWritePlatformService { private final Logger LOG; private final PlatformSecurityContext context; @@ -61,26 +60,21 @@ public class SelfBeneficiariesTPTWritePlatformServiceImpl implements private final SavingsAccountRepositoryWrapper savingRepositoryWrapper; @Autowired - public SelfBeneficiariesTPTWritePlatformServiceImpl( - final PlatformSecurityContext context, - final SelfBeneficiariesTPTRepository repository, - final SelfBeneficiariesTPTDataValidator validator, - final LoanRepositoryWrapper loanRepositoryWrapper, - final SavingsAccountRepositoryWrapper savingRepositoryWrapper) { + public SelfBeneficiariesTPTWritePlatformServiceImpl(final PlatformSecurityContext context, + final SelfBeneficiariesTPTRepository repository, final SelfBeneficiariesTPTDataValidator validator, + final LoanRepositoryWrapper loanRepositoryWrapper, final SavingsAccountRepositoryWrapper savingRepositoryWrapper) { this.context = context; this.repository = repository; this.validator = validator; this.loanRepositoryWrapper = loanRepositoryWrapper; this.savingRepositoryWrapper = savingRepositoryWrapper; - this.LOG = LoggerFactory - .getLogger(SelfBeneficiariesTPTWritePlatformServiceImpl.class); + this.LOG = LoggerFactory.getLogger(SelfBeneficiariesTPTWritePlatformServiceImpl.class); } @Transactional @Override public CommandProcessingResult add(JsonCommand command) { - HashMap params = this.validator - .validateForCreate(command.json()); + HashMap params = this.validator.validateForCreate(command.json()); String name = (String) params.get(NAME_PARAM_NAME); Integer accountType = (Integer) params.get(ACCOUNT_TYPE_PARAM_NAME); @@ -95,8 +89,7 @@ public class SelfBeneficiariesTPTWritePlatformServiceImpl implements boolean validAccountDetails = true; if (accountType.equals(PortfolioAccountType.LOAN.getValue())) { Loan loan = this.loanRepositoryWrapper.findNonClosedLoanByAccountNumber(accountNumber); - if (loan != null && loan.getClientId() != null - && loan.getOffice().getName().equals(officeName)) { + if (loan != null && loan.getClientId() != null && loan.getOffice().getName().equals(officeName)) { accountId = loan.getId(); officeId = loan.getOfficeId(); clientId = loan.getClientId(); @@ -104,12 +97,8 @@ public class SelfBeneficiariesTPTWritePlatformServiceImpl implements validAccountDetails = false; } } else { - SavingsAccount savings = this.savingRepositoryWrapper - .findNonClosedAccountByAccountNumber(accountNumber); - if (savings != null - && savings.getClient() != null - && savings.getClient().getOffice().getName() - .equals(officeName)) { + SavingsAccount savings = this.savingRepositoryWrapper.findNonClosedAccountByAccountNumber(accountNumber); + if (savings != null && savings.getClient() != null && savings.getClient().getOffice().getName().equals(officeName)) { accountId = savings.getId(); clientId = savings.getClient().getId(); officeId = savings.getClient().getOffice().getId(); @@ -121,36 +110,30 @@ public class SelfBeneficiariesTPTWritePlatformServiceImpl implements if (validAccountDetails) { try { AppUser user = this.context.authenticatedUser(); - SelfBeneficiariesTPT beneficiary = new SelfBeneficiariesTPT( - user.getId(), name, officeId, clientId, accountId, - accountType, transferLimit); + SelfBeneficiariesTPT beneficiary = new SelfBeneficiariesTPT(user.getId(), name, officeId, clientId, accountId, accountType, + transferLimit); this.repository.save(beneficiary); - return new CommandProcessingResultBuilder().withEntityId( - beneficiary.getId()).build(); + return new CommandProcessingResultBuilder().withEntityId(beneficiary.getId()).build(); } catch (DataAccessException dae) { handleDataIntegrityIssues(command, dae); } } - throw new InvalidAccountInformationException(officeName, accountNumber, - PortfolioAccountType.fromInt(accountType).getCode()); + throw new InvalidAccountInformationException(officeName, accountNumber, PortfolioAccountType.fromInt(accountType).getCode()); } @Transactional @Override public CommandProcessingResult update(JsonCommand command) { - HashMap params = this.validator - .validateForUpdate(command.json()); + HashMap params = this.validator.validateForUpdate(command.json()); AppUser user = this.context.authenticatedUser(); Long beneficiaryId = command.entityId(); SelfBeneficiariesTPT beneficiary = this.repository.findById(beneficiaryId).orElse(null); - if (beneficiary != null - && beneficiary.getAppUserId().equals(user.getId())) { + if (beneficiary != null && beneficiary.getAppUserId().equals(user.getId())) { String name = (String) params.get(NAME_PARAM_NAME); Long transferLimit = (Long) params.get(TRANSFER_LIMIT_PARAM_NAME); - Map changes = beneficiary.update(name, - transferLimit); + Map changes = beneficiary.update(name, transferLimit); if (!changes.isEmpty()) { try { this.repository.save(beneficiary); @@ -173,8 +156,7 @@ public class SelfBeneficiariesTPTWritePlatformServiceImpl implements AppUser user = this.context.authenticatedUser(); Long beneficiaryId = command.entityId(); SelfBeneficiariesTPT beneficiary = this.repository.findById(beneficiaryId).orElse(null); - if (beneficiary != null - && beneficiary.getAppUserId().equals(user.getId())) { + if (beneficiary != null && beneficiary.getAppUserId().equals(user.getId())) { beneficiary.setActive(false); this.repository.save(beneficiary); @@ -186,23 +168,18 @@ public class SelfBeneficiariesTPTWritePlatformServiceImpl implements throw new InvalidBeneficiaryException(beneficiaryId); } - private void handleDataIntegrityIssues(final JsonCommand command, - final DataAccessException dae) { + private void handleDataIntegrityIssues(final JsonCommand command, final DataAccessException dae) { final Throwable realCause = dae.getMostSpecificCause(); if (realCause.getMessage().contains("name")) { - final String name = command - .stringValueOfParameterNamed(NAME_PARAM_NAME); - throw new PlatformDataIntegrityException( - "error.msg.beneficiary.duplicate.name", - "Beneficiary with name `" + name + "` already exists", - NAME_PARAM_NAME, name); + final String name = command.stringValueOfParameterNamed(NAME_PARAM_NAME); + throw new PlatformDataIntegrityException("error.msg.beneficiary.duplicate.name", + "Beneficiary with name `" + name + "` already exists", NAME_PARAM_NAME, name); } this.LOG.error("Error occured.", dae); - throw new PlatformDataIntegrityException( - "error.msg.beneficiary.unknown.data.integrity.issue", + throw new PlatformDataIntegrityException("error.msg.beneficiary.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/api/SelfClientsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/api/SelfClientsApiResource.java index 3491481bb..c9895427e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/api/SelfClientsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/api/SelfClientsApiResource.java @@ -60,10 +60,8 @@ import org.springframework.stereotype.Component; @Path("/self/clients") @Component @Scope("singleton") -@Api(tags = {"Self Client"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self Client", description = "") -}) +@Api(tags = { "Self Client" }) +@SwaggerDefinition(tags = { @Tag(name = "Self Client", description = "") }) public class SelfClientsApiResource { private final PlatformSecurityContext context; @@ -75,14 +73,10 @@ public class SelfClientsApiResource { private final SelfClientDataValidator dataValidator; @Autowired - public SelfClientsApiResource( - final PlatformSecurityContext context, - final ClientsApiResource clientApiResource, - final ImagesApiResource imagesApiResource, - final ClientChargesApiResource clientChargesApiResource, + public SelfClientsApiResource(final PlatformSecurityContext context, final ClientsApiResource clientApiResource, + final ImagesApiResource imagesApiResource, final ClientChargesApiResource clientChargesApiResource, final ClientTransactionsApiResource clientTransactionsApiResource, - final AppuserClientMapperReadService appUserClientMapperReadService, - final SelfClientDataValidator dataValidator) { + final AppuserClientMapperReadService appUserClientMapperReadService, final SelfClientDataValidator dataValidator) { this.context = context; this.clientApiResource = clientApiResource; this.imagesApiResource = imagesApiResource; @@ -95,8 +89,10 @@ public class SelfClientsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Clients associated to the user", httpMethod = "GET", notes = "The list capability of clients can support pagination and sorting.\n\n" + "Example Requests:\n" + "\n" + "self/clients\n" + "\n" + "self/clients?fields=displayName,officeName\n" + "\n" + "self/clients?offset=10&limit=50\n" + "\n" + "self/clients?orderBy=displayName&sortOrder=DESC") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsResponse.class)}) + @ApiOperation(value = "List Clients associated to the user", httpMethod = "GET", notes = "The list capability of clients can support pagination and sorting.\n\n" + + "Example Requests:\n" + "\n" + "self/clients\n" + "\n" + "self/clients?fields=displayName,officeName\n" + "\n" + + "self/clients?offset=10&limit=50\n" + "\n" + "self/clients?orderBy=displayName&sortOrder=DESC") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsResponse.class) }) public String retrieveAll(@Context final UriInfo uriInfo, @QueryParam("displayName") @ApiParam(value = "displayName") final String displayName, @QueryParam("firstName") @ApiParam(value = "firstName") final String firstname, @@ -111,8 +107,7 @@ public class SelfClientsApiResource { final String externalId = null; final String hierarchy = null; final Boolean orphansOnly = null; - return this.clientApiResource.retrieveAll(uriInfo, sqlSearch, officeId, - externalId, displayName, firstname, lastname, hierarchy, + return this.clientApiResource.retrieveAll(uriInfo, sqlSearch, officeId, externalId, displayName, firstname, lastname, hierarchy, offset, limit, orderBy, sortOrder, orphansOnly, true); } @@ -120,43 +115,44 @@ public class SelfClientsApiResource { @Path("{clientId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Client", httpMethod = "GET", notes = "Retrieves a Client\n\n" + "Example Requests:\n" + "\n" + "self/clients/1\n" + "\n" + "self/clients/1?fields=id,displayName,officeName") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdResponse.class)}) - public String retrieveOne(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Client", httpMethod = "GET", notes = "Retrieves a Client\n\n" + "Example Requests:\n" + "\n" + + "self/clients/1\n" + "\n" + "self/clients/1?fields=id,displayName,officeName") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdResponse.class) }) + public String retrieveOne(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @Context final UriInfo uriInfo) { this.dataValidator.validateRetrieveOne(uriInfo); validateAppuserClientsMapping(clientId); final boolean staffInSelectedOfficeOnly = false; - return this.clientApiResource.retrieveOne(clientId, uriInfo, - staffInSelectedOfficeOnly); + return this.clientApiResource.retrieveOne(clientId, uriInfo, staffInSelectedOfficeOnly); } @GET @Path("{clientId}/accounts") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve client accounts overview", httpMethod = "GET", notes = "An example of how a loan portfolio summary can be provided. This is requested in a specific use case of the community application.\n" + "It is quite reasonable to add resources like this to simplify User Interface development.\n" + "\n" + "Example Requests:\n" + "\n" + "self/clients/1/accounts\n" + "\n" + "\n" + "self/clients/1/accounts?fields=loanAccounts,savingsAccounts") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdAccountsResponse.class)}) - public String retrieveAssociatedAccounts( - @PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @ApiOperation(value = "Retrieve client accounts overview", httpMethod = "GET", notes = "An example of how a loan portfolio summary can be provided. This is requested in a specific use case of the community application.\n" + + "It is quite reasonable to add resources like this to simplify User Interface development.\n" + "\n" + "Example Requests:\n" + + "\n" + "self/clients/1/accounts\n" + "\n" + "\n" + "self/clients/1/accounts?fields=loanAccounts,savingsAccounts") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdAccountsResponse.class) }) + public String retrieveAssociatedAccounts(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @Context final UriInfo uriInfo) { validateAppuserClientsMapping(clientId); - return this.clientApiResource.retrieveAssociatedAccounts(clientId, - uriInfo); + return this.clientApiResource.retrieveAssociatedAccounts(clientId, uriInfo); } @GET @Path("{clientId}/images") - @Consumes({ MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, - MediaType.APPLICATION_JSON }) + @Consumes({ MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces({ MediaType.TEXT_PLAIN }) - @ApiOperation(value = "Retrieve Client Image", httpMethod = "GET", notes = "Optional arguments are identical to those of Get Image associated with an Entity (Binary file)\n" + "\n" + "Example Requests:\n" + "\n" + "self/clients/1/images") - @ApiResponses({@ApiResponse(code = 200, message = "OK")}) + @ApiOperation(value = "Retrieve Client Image", httpMethod = "GET", notes = "Optional arguments are identical to those of Get Image associated with an Entity (Binary file)\n" + + "\n" + "Example Requests:\n" + "\n" + "self/clients/1/images") + @ApiResponses({ @ApiResponse(code = 200, message = "OK") }) public Response retrieveImage(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @QueryParam("maxWidth") @ApiParam(example = "maxWidth") final Integer maxWidth, @QueryParam("maxHeight") @ApiParam(example = "maxHeight") final Integer maxHeight, @@ -164,105 +160,97 @@ public class SelfClientsApiResource { validateAppuserClientsMapping(clientId); - return this.imagesApiResource.retrieveImage("clients", clientId, - maxWidth, maxHeight, output); + return this.imagesApiResource.retrieveImage("clients", clientId, maxWidth, maxHeight, output); } @GET @Path("{clientId}/charges") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Client Charges", httpMethod = "GET", notes = "The list capability of client charges supports pagination.\n\n" + "Example Requests:\n" + "\n" + "self/clients/1/charges\n\n" + "self/clients/1/charges?offset=0&limit=5") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdChargesResponse.class)}) - public String retrieveAllClientCharges( - @PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @ApiOperation(value = "List Client Charges", httpMethod = "GET", notes = "The list capability of client charges supports pagination.\n\n" + + "Example Requests:\n" + "\n" + "self/clients/1/charges\n\n" + "self/clients/1/charges?offset=0&limit=5") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdChargesResponse.class) }) + public String retrieveAllClientCharges(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, @DefaultValue(ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ALL) @QueryParam(ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS) @ApiParam(value = "chargeStatus") final String chargeStatus, - @QueryParam("pendingPayment") @ApiParam(value = "pendingPayment") final Boolean pendingPayment, - @Context final UriInfo uriInfo, + @QueryParam("pendingPayment") @ApiParam(value = "pendingPayment") final Boolean pendingPayment, @Context final UriInfo uriInfo, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset) { validateAppuserClientsMapping(clientId); - return this.clientChargesApiResource.retrieveAllClientCharges(clientId, - chargeStatus, pendingPayment, uriInfo, limit, offset); + return this.clientChargesApiResource.retrieveAllClientCharges(clientId, chargeStatus, pendingPayment, uriInfo, limit, offset); } @GET @Path("{clientId}/charges/{chargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Client Charge", httpMethod = "GET", notes = "Retrieves a Client Charge\n\n" + "Example Requests:\n" + "\n" + "self/clients/1/charges/1\n" + "\n" + "\n" + "self/clients/1/charges/1?fields=name,id") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdChargesChargeIdResponse.class)}) - public String retrieveClientCharge( - @PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, - @PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Client Charge", httpMethod = "GET", notes = "Retrieves a Client Charge\n\n" + "Example Requests:\n" + + "\n" + "self/clients/1/charges/1\n" + "\n" + "\n" + "self/clients/1/charges/1?fields=name,id") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdChargesChargeIdResponse.class) }) + public String retrieveClientCharge(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @PathParam("chargeId") @ApiParam(value = "chargeId") final Long chargeId, @Context final UriInfo uriInfo) { this.dataValidator.validateClientCharges(uriInfo); validateAppuserClientsMapping(clientId); - return this.clientChargesApiResource.retrieveClientCharge(clientId, - chargeId, uriInfo); + return this.clientChargesApiResource.retrieveClientCharge(clientId, chargeId, uriInfo); } @GET @Path("{clientId}/transactions") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Client Transactions", httpMethod = "GET", notes = "The list capability of client transaction can support pagination.\n\n" + "Example Requests:\n" + "\n" + "self/clients/189/transactions\n\n" + "self/clients/189/transactions?offset=10&limit=50") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdTransactionsResponse.class)}) - public String retrieveAllClientTransactions( - @PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, - @Context final UriInfo uriInfo, - @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, + @ApiOperation(value = "List Client Transactions", httpMethod = "GET", notes = "The list capability of client transaction can support pagination.\n\n" + + "Example Requests:\n" + "\n" + "self/clients/189/transactions\n\n" + "self/clients/189/transactions?offset=10&limit=50") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdTransactionsResponse.class) }) + public String retrieveAllClientTransactions(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @Context final UriInfo uriInfo, @QueryParam("offset") @ApiParam(value = "offset") final Integer offset, @QueryParam("limit") @ApiParam(value = "limit") final Integer limit) { validateAppuserClientsMapping(clientId); - return this.clientTransactionsApiResource - .retrieveAllClientTransactions(clientId, uriInfo, offset, limit); + return this.clientTransactionsApiResource.retrieveAllClientTransactions(clientId, uriInfo, offset, limit); } @GET @Path("{clientId}/transactions/{transactionId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Client Transaction", httpMethod = "GET", notes = "Retrieves a Client Transaction" + "Example Requests:\n" + "\n" + "self/clients/1/transactions/1\n" + "\n" + "\n" + "self/clients/1/transactions/1?fields=id,officeName") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdTransactionsTransactionIdResponse.class)}) - public String retrieveClientTransaction( - @PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, - @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Client Transaction", httpMethod = "GET", notes = "Retrieves a Client Transaction" + + "Example Requests:\n" + "\n" + "self/clients/1/transactions/1\n" + "\n" + "\n" + + "self/clients/1/transactions/1?fields=id,officeName") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfClientsApiResourceSwagger.GetSelfClientsClientIdTransactionsTransactionIdResponse.class) }) + public String retrieveClientTransaction(@PathParam("clientId") @ApiParam(value = "clientId") final Long clientId, + @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, @Context final UriInfo uriInfo) { validateAppuserClientsMapping(clientId); - return this.clientTransactionsApiResource.retrieveClientTransaction( - clientId, transactionId, uriInfo); + return this.clientTransactionsApiResource.retrieveClientTransaction(clientId, transactionId, uriInfo); } private void validateAppuserClientsMapping(final Long clientId) { AppUser user = this.context.authenticatedUser(); - final boolean mappedClientId = this.appUserClientMapperReadService - .isClientMappedToUser(clientId, user.getId()); - if (!mappedClientId) { - throw new ClientNotFoundException(clientId); - } + final boolean mappedClientId = this.appUserClientMapperReadService.isClientMappedToUser(clientId, user.getId()); + if (!mappedClientId) { throw new ClientNotFoundException(clientId); } } @POST @Path("{clientId}/images") @Consumes({ MediaType.MULTIPART_FORM_DATA }) @Produces({ MediaType.APPLICATION_JSON }) - public String addNewClientImage(@PathParam("clientId") final Long clientId, - @HeaderParam("Content-Length") final Long fileSize, @FormDataParam("file") final InputStream inputStream, - @FormDataParam("file") final FormDataContentDisposition fileDetails, + public String addNewClientImage(@PathParam("clientId") final Long clientId, @HeaderParam("Content-Length") final Long fileSize, + @FormDataParam("file") final InputStream inputStream, @FormDataParam("file") final FormDataContentDisposition fileDetails, @FormDataParam("file") final FormDataBodyPart bodyPart) { validateAppuserClientsMapping(clientId); - return this.imagesApiResource.addNewClientImage(ClientApiConstants.clientEntityName, clientId, fileSize, - inputStream, fileDetails, bodyPart); + return this.imagesApiResource.addNewClientImage(ClientApiConstants.clientEntityName, clientId, fileSize, inputStream, fileDetails, + bodyPart); } @@ -270,8 +258,8 @@ public class SelfClientsApiResource { @Path("{clientId}/images") @Consumes({ MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String addNewClientImage(@PathParam("entity") final String entityName, - @PathParam("clientId") final Long clientId, final String jsonRequestBody) { + public String addNewClientImage(@PathParam("entity") final String entityName, @PathParam("clientId") final Long clientId, + final String jsonRequestBody) { validateAppuserClientsMapping(clientId); return this.imagesApiResource.addNewClientImage(ClientApiConstants.clientEntityName, clientId, jsonRequestBody); @@ -299,4 +287,4 @@ public class SelfClientsApiResource { return this.clientApiResource.retrieveObligeeDetails(clientId, uriInfo); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/api/SelfClientsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/api/SelfClientsApiResourceSwagger.java index 116ba320d..e7fdb3eb8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/api/SelfClientsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/api/SelfClientsApiResourceSwagger.java @@ -29,21 +29,21 @@ import java.util.Set; */ final class SelfClientsApiResourceSwagger { - private SelfClientsApiResourceSwagger() { - } + + private SelfClientsApiResourceSwagger() {} @ApiModel(value = "GetSelfClientsResponse") public final static class GetSelfClientsResponse { - private GetSelfClientsResponse() { - } + + private GetSelfClientsResponse() {} final class GetSelfClientsPageItems { - private GetSelfClientsPageItems() { - } + + private GetSelfClientsPageItems() {} final class GetSelfClientsStatus { - private GetSelfClientsStatus() { - } + + private GetSelfClientsStatus() {} @ApiModelProperty(example = "300") public Integer id; @@ -79,12 +79,12 @@ final class SelfClientsApiResourceSwagger { @ApiModel(value = "GetSelfClientsClientIdResponse") public final static class GetSelfClientsClientIdResponse { - private GetSelfClientsClientIdResponse() { - } + + private GetSelfClientsClientIdResponse() {} final class GetSelfClientsTimeline { - private GetSelfClientsTimeline() { - } + + private GetSelfClientsTimeline() {} @ApiModelProperty(example = "[2013, 1, 1]") public LocalDate submittedOnDate; @@ -135,16 +135,16 @@ final class SelfClientsApiResourceSwagger { @ApiModel(value = "GetSelfClientsClientIdAccountsResponse") public final static class GetSelfClientsClientIdAccountsResponse { - private GetSelfClientsClientIdAccountsResponse() { - } + + private GetSelfClientsClientIdAccountsResponse() {} final class GetSelfClientsLoanAccounts { - private GetSelfClientsLoanAccounts() { - } + + private GetSelfClientsLoanAccounts() {} final class GetSelfClientsLoanAccountsStatus { - private GetSelfClientsLoanAccountsStatus() { - } + + private GetSelfClientsLoanAccountsStatus() {} @ApiModelProperty(example = "300") public Integer id; @@ -171,8 +171,8 @@ final class SelfClientsApiResourceSwagger { } final class GetSelfClientsLoanAccountsType { - private GetSelfClientsLoanAccountsType() { - } + + private GetSelfClientsLoanAccountsType() {} @ApiModelProperty(example = "1") public Integer id; @@ -199,12 +199,12 @@ final class SelfClientsApiResourceSwagger { } final class GetSelfClientsSavingsAccounts { - private GetSelfClientsSavingsAccounts() { - } + + private GetSelfClientsSavingsAccounts() {} final class GetSelfClientsSavingsAccountsCurrency { - private GetSelfClientsSavingsAccountsCurrency() { - } + + private GetSelfClientsSavingsAccountsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -221,8 +221,8 @@ final class SelfClientsApiResourceSwagger { } final class GetSelfClientsSavingsAccountsStatus { - private GetSelfClientsSavingsAccountsStatus() { - } + + private GetSelfClientsSavingsAccountsStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -262,16 +262,16 @@ final class SelfClientsApiResourceSwagger { @ApiModel(value = "GetSelfClientsClientIdChargesResponse") public final static class GetSelfClientsClientIdChargesResponse { - private GetSelfClientsClientIdChargesResponse() { - } + + private GetSelfClientsClientIdChargesResponse() {} final class GetSelfClientsChargesPageItems { - private GetSelfClientsChargesPageItems() { - } + + private GetSelfClientsChargesPageItems() {} final class GetSelfClientsChargeTimeType { - private GetSelfClientsChargeTimeType() { - } + + private GetSelfClientsChargeTimeType() {} @ApiModelProperty(example = "2") public Integer id; @@ -282,8 +282,8 @@ final class SelfClientsApiResourceSwagger { } final class GetSelfClientsChargeCalculationType { - private GetSelfClientsChargeCalculationType() { - } + + private GetSelfClientsChargeCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -333,8 +333,8 @@ final class SelfClientsApiResourceSwagger { @ApiModel(value = "GetSelfClientsClientIdChargesChargeIdResponse") public final static class GetSelfClientsClientIdChargesChargeIdResponse { - private GetSelfClientsClientIdChargesChargeIdResponse() { - } + + private GetSelfClientsClientIdChargesChargeIdResponse() {} @ApiModelProperty(example = "3") public Integer id; @@ -371,16 +371,16 @@ final class SelfClientsApiResourceSwagger { @ApiModel(value = "GetSelfClientsClientIdTransactionsResponse") public final static class GetSelfClientsClientIdTransactionsResponse { - private GetSelfClientsClientIdTransactionsResponse() { - } + + private GetSelfClientsClientIdTransactionsResponse() {} final class GetSelfClientsClientIdTransactionsPageItems { - private GetSelfClientsClientIdTransactionsPageItems() { - } + + private GetSelfClientsClientIdTransactionsPageItems() {} final class GetSelfClientsClientIdTransactionsType { - private GetSelfClientsClientIdTransactionsType() { - } + + private GetSelfClientsClientIdTransactionsType() {} @ApiModelProperty(example = "1") public Integer id; @@ -415,8 +415,8 @@ final class SelfClientsApiResourceSwagger { @ApiModel(value = "GetSelfClientsClientIdTransactionsTransactionIdResponse") public final static class GetSelfClientsClientIdTransactionsTransactionIdResponse { - private GetSelfClientsClientIdTransactionsTransactionIdResponse() { - } + + private GetSelfClientsClientIdTransactionsTransactionIdResponse() {} @ApiModelProperty(example = "1") public Integer id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/data/SelfClientDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/data/SelfClientDataValidator.java index c379d0f6f..6749d89fb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/data/SelfClientDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/data/SelfClientDataValidator.java @@ -31,18 +31,14 @@ import org.springframework.stereotype.Component; @Component public class SelfClientDataValidator { - private static final Set allowedChargesAssociationParameters = new HashSet<>( - Arrays.asList("transactions")); + private static final Set allowedChargesAssociationParameters = new HashSet<>(Arrays.asList("transactions")); public void validateClientCharges(final UriInfo uriInfo) { List unsupportedParams = new ArrayList<>(); - Set associationParameters = ApiParameterHelper - .extractAssociationsForResponseIfProvided(uriInfo - .getQueryParameters()); + Set associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); if (!associationParameters.isEmpty()) { - associationParameters - .removeAll(allowedChargesAssociationParameters); + associationParameters.removeAll(allowedChargesAssociationParameters); if (!associationParameters.isEmpty()) { unsupportedParams.addAll(associationParameters); } @@ -52,23 +48,18 @@ public class SelfClientDataValidator { unsupportedParams.add("exclude"); } - if (unsupportedParams.size() > 0) { - throw new UnsupportedParameterException(unsupportedParams); - } + if (unsupportedParams.size() > 0) { throw new UnsupportedParameterException(unsupportedParams); } } public void validateRetrieveOne(final UriInfo uriInfo) { List unsupportedParams = new ArrayList<>(); - final boolean templateRequest = ApiParameterHelper.template(uriInfo - .getQueryParameters()); + final boolean templateRequest = ApiParameterHelper.template(uriInfo.getQueryParameters()); if (templateRequest) { unsupportedParams.add("template"); } - if (unsupportedParams.size() > 0) { - throw new UnsupportedParameterException(unsupportedParams); - } + if (unsupportedParams.size() > 0) { throw new UnsupportedParameterException(unsupportedParams); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/service/AppuserClientMapperReadServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/service/AppuserClientMapperReadServiceImpl.java index 37c9b7edf..3e21a21fc 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/service/AppuserClientMapperReadServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/client/service/AppuserClientMapperReadServiceImpl.java @@ -27,8 +27,7 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @Service -public class AppuserClientMapperReadServiceImpl implements - AppuserClientMapperReadService { +public class AppuserClientMapperReadServiceImpl implements AppuserClientMapperReadService { private final JdbcTemplate jdbcTemplate; private final PlatformSecurityContext context; @@ -41,11 +40,10 @@ public class AppuserClientMapperReadServiceImpl implements @Override public Boolean isClientMappedToUser(Long clientId, Long appUserId) { - return this.jdbcTemplate - .queryForObject( - "select case when (count(*) > 0) then true else false end " - + " from m_selfservice_user_client_mapping where client_id = ? and appuser_id = ?", - new Object[] { clientId, appUserId }, Boolean.class); + return this.jdbcTemplate.queryForObject( + "select case when (count(*) > 0) then true else false end " + + " from m_selfservice_user_client_mapping where client_id = ? and appuser_id = ?", + new Object[] { clientId, appUserId }, Boolean.class); } @Override @@ -53,9 +51,7 @@ public class AppuserClientMapperReadServiceImpl implements AppUser user = this.context.authenticatedUser(); if (clientId != null) { final boolean mappedClientId = isClientMappedToUser(clientId, user.getId()); - if (!mappedClientId) { - throw new ClientNotFoundException(clientId); - } + if (!mappedClientId) { throw new ClientNotFoundException(clientId); } } else { throw new ClientNotFoundException(clientId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/api/SelfLoansApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/api/SelfLoansApiResource.java index 5e225f85f..014eae373 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/api/SelfLoansApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/api/SelfLoansApiResource.java @@ -61,10 +61,8 @@ import org.springframework.stereotype.Component; @Path("/self/loans") @Component @Scope("singleton") -@Api(tags = {"Self Loans"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self Loans", description = "") -}) +@Api(tags = { "Self Loans" }) +@SwaggerDefinition(tags = { @Tag(name = "Self Loans", description = "") }) public class SelfLoansApiResource { private final PlatformSecurityContext context; @@ -77,13 +75,11 @@ public class SelfLoansApiResource { private final GuarantorsApiResource guarantorsApiResource; @Autowired - public SelfLoansApiResource(final PlatformSecurityContext context, - final LoansApiResource loansApiResource, - final LoanTransactionsApiResource loanTransactionsApiResource, - final LoanChargesApiResource loanChargesApiResource, + public SelfLoansApiResource(final PlatformSecurityContext context, final LoansApiResource loansApiResource, + final LoanTransactionsApiResource loanTransactionsApiResource, final LoanChargesApiResource loanChargesApiResource, final AppuserLoansMapperReadService appuserLoansMapperReadService, - final AppuserClientMapperReadService appUserClientMapperReadService, - final SelfLoansDataValidator dataValidator, final GuarantorsApiResource guarantorsApiResource) { + final AppuserClientMapperReadService appUserClientMapperReadService, final SelfLoansDataValidator dataValidator, + final GuarantorsApiResource guarantorsApiResource) { this.context = context; this.loansApiResource = loansApiResource; this.loanTransactionsApiResource = loanTransactionsApiResource; @@ -98,63 +94,64 @@ public class SelfLoansApiResource { @Path("{loanId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Loan", httpMethod = "GET", notes = "Retrieves a Loan\n\n" + "Example Requests:\n" + "\n" + "self/loans/1\n" + "\n" + "\n" + "self/loans/1?fields=id,principal,annualInterestRate\n" + "\n" + "\n" + "self/loans/1?fields=id,principal,annualInterestRate&associations=repaymentSchedule,transactions") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.GetSelfLoansLoanIdResponse.class)}) - public String retrieveLoan(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve a Loan", httpMethod = "GET", notes = "Retrieves a Loan\n\n" + "Example Requests:\n" + "\n" + + "self/loans/1\n" + "\n" + "\n" + "self/loans/1?fields=id,principal,annualInterestRate\n" + "\n" + "\n" + + "self/loans/1?fields=id,principal,annualInterestRate&associations=repaymentSchedule,transactions") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.GetSelfLoansLoanIdResponse.class) }) + public String retrieveLoan(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @Context final UriInfo uriInfo) { this.dataValidator.validateRetrieveLoan(uriInfo); validateAppuserLoanMapping(loanId); final boolean staffInSelectedOfficeOnly = false; - return this.loansApiResource.retrieveLoan(loanId, - staffInSelectedOfficeOnly, uriInfo); + return this.loansApiResource.retrieveLoan(loanId, staffInSelectedOfficeOnly, uriInfo); } @GET @Path("{loanId}/transactions/{transactionId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Loan Transaction Details", httpMethod = "GET", notes = "Retrieves a Loan Transaction Details" + "Example Request:\n" + "\n" + "self/loans/5/transactions/3") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.GetSelfLoansLoanIdTransactionsTransactionIdResponse.class)}) + @ApiOperation(value = "Retrieve a Loan Transaction Details", httpMethod = "GET", notes = "Retrieves a Loan Transaction Details" + + "Example Request:\n" + "\n" + "self/loans/5/transactions/3") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.GetSelfLoansLoanIdTransactionsTransactionIdResponse.class) }) public String retrieveTransaction(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, - @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, - @Context final UriInfo uriInfo) { + @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, @Context final UriInfo uriInfo) { this.dataValidator.validateRetrieveTransaction(uriInfo); validateAppuserLoanMapping(loanId); - return this.loanTransactionsApiResource.retrieveTransaction(loanId, - transactionId, uriInfo); + return this.loanTransactionsApiResource.retrieveTransaction(loanId, transactionId, uriInfo); } @GET @Path("{loanId}/charges") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Loan Charges", httpMethod = "GET", notes = "Lists loan Charges\n\n" + "Example Requests:\n" + "\n" + "self/loans/1/charges\n" + "\n" + "\n" + "self/loans/1/charges?fields=name,amountOrPercentage") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.GetSelfLoansLoanIdChargesResponse.class, responseContainer = "List")}) - public String retrieveAllLoanCharges( - @PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @ApiOperation(value = "List Loan Charges", httpMethod = "GET", notes = "Lists loan Charges\n\n" + "Example Requests:\n" + "\n" + + "self/loans/1/charges\n" + "\n" + "\n" + "self/loans/1/charges?fields=name,amountOrPercentage") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.GetSelfLoansLoanIdChargesResponse.class, responseContainer = "List") }) + public String retrieveAllLoanCharges(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @Context final UriInfo uriInfo) { validateAppuserLoanMapping(loanId); - return this.loanChargesApiResource.retrieveAllLoanCharges(loanId, - uriInfo); + return this.loanChargesApiResource.retrieveAllLoanCharges(loanId, uriInfo); } @GET @Path("{loanId}/charges/{chargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Loan Charge", httpMethod = "GET", notes = "Retrieves a Loan Charge\n\n" + "Example Requests:\n" + "\n" + "self/loans/1/charges/1\n" + "\n" + "\n" + "self/loans/1/charges/1?fields=name,amountOrPercentage") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.GetSelfLoansLoanIdChargesResponse.class)}) + @ApiOperation(value = "Retrieve a Loan Charge", httpMethod = "GET", notes = "Retrieves a Loan Charge\n\n" + "Example Requests:\n" + "\n" + + "self/loans/1/charges/1\n" + "\n" + "\n" + "self/loans/1/charges/1?fields=name,amountOrPercentage") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.GetSelfLoansLoanIdChargesResponse.class) }) public String retrieveLoanCharge(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, - @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId, - @Context final UriInfo uriInfo) { + @PathParam("chargeId") @ApiParam(value = "chargeId") final Long loanChargeId, @Context final UriInfo uriInfo) { validateAppuserLoanMapping(loanId); @@ -165,48 +162,59 @@ public class SelfLoansApiResource { @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Loan Details Template", httpMethod = "GET", notes = "Retrieves Loan Details Template\n\n" + "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:\n" + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Requests:\n" + "\n" + "self/loans/template?templateType=individual&clientId=1\n" + "\n" + "\n" + "self/loans/template?templateType=individual&clientId=1&productId=1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.GetSelfLoansTemplateResponse.class)}) + @ApiOperation(value = "Retrieve Loan Details Template", httpMethod = "GET", notes = "Retrieves Loan Details Template\n\n" + + "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:\n" + + "\n" + "Field Defaults\n" + "Allowed Value Lists\n\n" + "Example Requests:\n" + "\n" + + "self/loans/template?templateType=individual&clientId=1\n" + "\n" + "\n" + + "self/loans/template?templateType=individual&clientId=1&productId=1") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.GetSelfLoansTemplateResponse.class) }) public String template(@QueryParam("clientId") @ApiParam(value = "clientId") final Long clientId, @QueryParam("productId") @ApiParam(value = "productId") final Long productId, - @QueryParam("templateType") @ApiParam(value = "templateType") final String templateType, - @Context final UriInfo uriInfo) { + @QueryParam("templateType") @ApiParam(value = "templateType") final String templateType, @Context final UriInfo uriInfo) { - if(clientId != null){ + if (clientId != null) { validateAppuserClientsMapping(clientId); } if (templateType == null) { final String errorMsg = "Loan template type must be provided"; throw new LoanTemplateTypeRequiredException(errorMsg); - } else if (!(templateType.equalsIgnoreCase("individual") - || templateType.equalsIgnoreCase("collateral"))){ + } else if (!(templateType.equalsIgnoreCase("individual") || templateType.equalsIgnoreCase("collateral"))) { final String errorMsg = "Loan template type '" + templateType + "' is not supported"; throw new NotSupportedLoanTemplateTypeException(errorMsg, templateType); } final Long groupId = null; final boolean staffInSelectedOfficeOnly = false; final boolean onlyActive = true; - return this.loansApiResource.template(clientId, groupId, productId, - templateType, staffInSelectedOfficeOnly, onlyActive, uriInfo); + return this.loansApiResource.template(clientId, groupId, productId, templateType, staffInSelectedOfficeOnly, onlyActive, uriInfo); } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Calculate Loan Repayment Schedule | Submit a new Loan Application", httpMethod = "POST", notes = "Calculate Loan Repayment Schedule:\n\n" + "Calculates Loan Repayment Schedule\n\n" + "Mandatory Fields: productId, principal, loanTermFrequency, loanTermFrequencyType, numberOfRepayments, repaymentEvery, repaymentFrequencyType, interestRatePerPeriod, amortizationType, interestType, interestCalculationPeriodType, expectedDisbursementDate, transactionProcessingStrategyId\n\n" + "Submit a new Loan Application:\n\n" + "Mandatory Fields: clientId, productId, principal, loanTermFrequency, loanTermFrequencyType, loanType, numberOfRepayments, repaymentEvery, repaymentFrequencyType, interestRatePerPeriod, amortizationType, interestType, interestCalculationPeriodType, transactionProcessingStrategyId, expectedDisbursementDate, submittedOnDate, loanType\n\n" + "Additional Mandatory Fields if interest recalculation is enabled for product and Rest frequency not same as repayment period: recalculationRestFrequencyDate\n\n" + "Additional Mandatory Fields if interest recalculation with interest/fee compounding is enabled for product and compounding frequency not same as repayment period: recalculationCompoundingFrequencyDate\n\n" + "Additional Mandatory Field if Entity-Datatable Check is enabled for the entity of type loan: datatables\n\n" + "Optional Fields: graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, linkAccountId, allowPartialPeriodInterestCalcualtion, fixedEmiAmount, maxOutstandingLoanBalance, disbursementData, graceOnArrearsAgeing, createStandingInstructionAtDisbursement (requires linkedAccountId if set to true)\n\n" + "Showing request/response for 'Submit a new Loan Application'") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfLoansApiResourceSwagger.PostSelfLoansRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.PostSelfLoansResponse.class)}) - public String calculateLoanScheduleOrSubmitLoanApplication(@QueryParam("command") @ApiParam(value = "command") final String commandParam, - @Context final UriInfo uriInfo, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiOperation(value = "Calculate Loan Repayment Schedule | Submit a new Loan Application", httpMethod = "POST", notes = "Calculate Loan Repayment Schedule:\n\n" + + "Calculates Loan Repayment Schedule\n\n" + + "Mandatory Fields: productId, principal, loanTermFrequency, loanTermFrequencyType, numberOfRepayments, repaymentEvery, repaymentFrequencyType, interestRatePerPeriod, amortizationType, interestType, interestCalculationPeriodType, expectedDisbursementDate, transactionProcessingStrategyId\n\n" + + "Submit a new Loan Application:\n\n" + + "Mandatory Fields: clientId, productId, principal, loanTermFrequency, loanTermFrequencyType, loanType, numberOfRepayments, repaymentEvery, repaymentFrequencyType, interestRatePerPeriod, amortizationType, interestType, interestCalculationPeriodType, transactionProcessingStrategyId, expectedDisbursementDate, submittedOnDate, loanType\n\n" + + "Additional Mandatory Fields if interest recalculation is enabled for product and Rest frequency not same as repayment period: recalculationRestFrequencyDate\n\n" + + "Additional Mandatory Fields if interest recalculation with interest/fee compounding is enabled for product and compounding frequency not same as repayment period: recalculationCompoundingFrequencyDate\n\n" + + "Additional Mandatory Field if Entity-Datatable Check is enabled for the entity of type loan: datatables\n\n" + + "Optional Fields: graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, linkAccountId, allowPartialPeriodInterestCalcualtion, fixedEmiAmount, maxOutstandingLoanBalance, disbursementData, graceOnArrearsAgeing, createStandingInstructionAtDisbursement (requires linkedAccountId if set to true)\n\n" + + "Showing request/response for 'Submit a new Loan Application'") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfLoansApiResourceSwagger.PostSelfLoansRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.PostSelfLoansResponse.class) }) + public String calculateLoanScheduleOrSubmitLoanApplication( + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { HashMap attr = this.dataValidator.validateLoanApplication(apiRequestBodyAsJson); final Long clientId = (Long) attr.get("clientId"); validateAppuserClientsMapping(clientId); - return this.loansApiResource.calculateLoanScheduleOrSubmitLoanApplication(commandParam, - uriInfo, apiRequestBodyAsJson); + return this.loansApiResource.calculateLoanScheduleOrSubmitLoanApplication(commandParam, uriInfo, apiRequestBodyAsJson); } @PUT @@ -214,14 +222,16 @@ public class SelfLoansApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update a Loan Application", httpMethod = "PUT", notes = "Loan application can only be modified when in 'Submitted and pending approval' state. Once the application is approved, the details cannot be changed using this method.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfLoansApiResourceSwagger.PutSelfLoansLoanIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.PutSelfLoansLoanIdResponse.class)}) - public String modifyLoanApplication(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfLoansApiResourceSwagger.PutSelfLoansLoanIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.PutSelfLoansLoanIdResponse.class) }) + public String modifyLoanApplication(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { HashMap attr = this.dataValidator.validateModifyLoanApplication(apiRequestBodyAsJson); validateAppuserLoanMapping(loanId); final Long clientId = (Long) attr.get("clientId"); - if(clientId != null){ + if (clientId != null) { validateAppuserClientsMapping(clientId); } @@ -232,34 +242,29 @@ public class SelfLoansApiResource { @Path("{loanId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Applicant Withdraws from Loan Application", httpMethod = "POST", notes = "Applicant Withdraws from Loan Application\n\n" + "Mandatory Fields: withdrawnOnDate") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfLoansApiResourceSwagger.PostSelfLoansLoanIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200,message = "OK", response = SelfLoansApiResourceSwagger.PostSelfLoansLoanIdResponse.class)}) - public String stateTransitions(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, @QueryParam("command") @ApiParam(value = "command") final String commandParam, + @ApiOperation(value = "Applicant Withdraws from Loan Application", httpMethod = "POST", notes = "Applicant Withdraws from Loan Application\n\n" + + "Mandatory Fields: withdrawnOnDate") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfLoansApiResourceSwagger.PostSelfLoansLoanIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = SelfLoansApiResourceSwagger.PostSelfLoansLoanIdResponse.class) }) + public String stateTransitions(@PathParam("loanId") @ApiParam(value = "loanId") final Long loanId, + @QueryParam("command") @ApiParam(value = "command") final String commandParam, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { - if (!is(commandParam, "withdrawnByApplicant")) { - throw new UnrecognizedQueryParamException("command", commandParam); - } + if (!is(commandParam, "withdrawnByApplicant")) { throw new UnrecognizedQueryParamException("command", commandParam); } validateAppuserLoanMapping(loanId); return this.loansApiResource.stateTransitions(loanId, commandParam, apiRequestBodyAsJson); } private void validateAppuserLoanMapping(final Long loanId) { AppUser user = this.context.authenticatedUser(); - final boolean isLoanMappedToUser = this.appuserLoansMapperReadService - .isLoanMappedToUser(loanId, user.getId()); - if (!isLoanMappedToUser) { - throw new LoanNotFoundException(loanId); - } + final boolean isLoanMappedToUser = this.appuserLoansMapperReadService.isLoanMappedToUser(loanId, user.getId()); + if (!isLoanMappedToUser) { throw new LoanNotFoundException(loanId); } } private void validateAppuserClientsMapping(final Long clientId) { AppUser user = this.context.authenticatedUser(); - final boolean mappedClientId = this.appUserClientMapperReadService - .isClientMappedToUser(clientId, user.getId()); - if (!mappedClientId) { - throw new ClientNotFoundException(clientId); - } + final boolean mappedClientId = this.appUserClientMapperReadService.isClientMappedToUser(clientId, user.getId()); + if (!mappedClientId) { throw new ClientNotFoundException(clientId); } } private boolean is(final String commandParam, final String commandValue) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/api/SelfLoansApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/api/SelfLoansApiResourceSwagger.java index d11d74c23..ae821ff14 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/api/SelfLoansApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/api/SelfLoansApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/19/17. */ final class SelfLoansApiResourceSwagger { - private SelfLoansApiResourceSwagger() { - } + + private SelfLoansApiResourceSwagger() {} @ApiModel(value = "GetSelfLoansLoanIdResponse") public final static class GetSelfLoansLoanIdResponse { - private GetSelfLoansLoanIdResponse() { - } + + private GetSelfLoansLoanIdResponse() {} final class GetLoansLoanIdStatus { - private GetLoansLoanIdStatus() { - } + + private GetLoansLoanIdStatus() {} @ApiModelProperty(example = "300") public Integer id; @@ -64,8 +64,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdLoanType { - private GetLoansLoanIdLoanType() { - } + + private GetLoansLoanIdLoanType() {} @ApiModelProperty(example = "1") public Integer id; @@ -76,8 +76,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdCurrency { - private GetLoansLoanIdCurrency() { - } + + private GetLoansLoanIdCurrency() {} @ApiModelProperty(example = "UGX") public String code; @@ -94,8 +94,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdTermPeriodFrequencyType { - private GetLoansLoanIdTermPeriodFrequencyType() { - } + + private GetLoansLoanIdTermPeriodFrequencyType() {} @ApiModelProperty(example = "2") public Integer id; @@ -106,8 +106,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdRepaymentFrequencyType { - private GetLoansLoanIdRepaymentFrequencyType() { - } + + private GetLoansLoanIdRepaymentFrequencyType() {} @ApiModelProperty(example = "2") public Integer id; @@ -118,8 +118,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdInterestRateFrequencyType { - private GetLoansLoanIdInterestRateFrequencyType() { - } + + private GetLoansLoanIdInterestRateFrequencyType() {} @ApiModelProperty(example = "3") public Integer id; @@ -130,8 +130,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdAmortizationType { - private GetLoansLoanIdAmortizationType() { - } + + private GetLoansLoanIdAmortizationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -142,8 +142,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdInterestType { - private GetLoansLoanIdInterestType() { - } + + private GetLoansLoanIdInterestType() {} @ApiModelProperty(example = "1") public Integer id; @@ -154,8 +154,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdInterestCalculationPeriodType { - private GetLoansLoanIdInterestCalculationPeriodType() { - } + + private GetLoansLoanIdInterestCalculationPeriodType() {} @ApiModelProperty(example = "1") public Integer id; @@ -166,8 +166,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdTimeline { - private GetLoansLoanIdTimeline() { - } + + private GetLoansLoanIdTimeline() {} @ApiModelProperty(example = "[2012, 4, 3]") public LocalDate submittedOnDate; @@ -200,17 +200,17 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdSummary { - private GetLoansLoanIdSummary() { - } + + private GetLoansLoanIdSummary() {} final class GetLoansLoanIdEmiVariations { - private GetLoansLoanIdEmiVariations() { - } + + private GetLoansLoanIdEmiVariations() {} } final class GetLoansLoanIdLinkedAccount { - private GetLoansLoanIdLinkedAccount() { - } + + private GetLoansLoanIdLinkedAccount() {} @ApiModelProperty(example = "1") public Integer id; @@ -219,8 +219,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdDisbursementDetails { - private GetLoansLoanIdDisbursementDetails() { - } + + private GetLoansLoanIdDisbursementDetails() {} @ApiModelProperty(example = "71") public Integer id; @@ -233,12 +233,12 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdOverdueCharges { - private GetLoansLoanIdOverdueCharges() { - } + + private GetLoansLoanIdOverdueCharges() {} final class GetLoansLoanIdChargeTimeType { - private GetLoansLoanIdChargeTimeType() { - } + + private GetLoansLoanIdChargeTimeType() {} @ApiModelProperty(example = "9") public Integer id; @@ -249,8 +249,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdChargeCalculationType { - private GetLoansLoanIdChargeCalculationType() { - } + + private GetLoansLoanIdChargeCalculationType() {} @ApiModelProperty(example = "2") public Integer id; @@ -261,8 +261,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdChargePaymentMode { - private GetLoansLoanIdChargePaymentMode() { - } + + private GetLoansLoanIdChargePaymentMode() {} @ApiModelProperty(example = "0") public Integer id; @@ -273,8 +273,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoansLoanIdFeeFrequency { - private GetLoansLoanIdFeeFrequency() { - } + + private GetLoansLoanIdFeeFrequency() {} @ApiModelProperty(example = "1") public Integer id; @@ -285,8 +285,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoanCurrency { - private GetLoanCurrency() { - } + + private GetLoanCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -303,8 +303,8 @@ final class SelfLoansApiResourceSwagger { } final class GetLoanChargeTemplateChargeAppliesTo { - private GetLoanChargeTemplateChargeAppliesTo() { - } + + private GetLoanChargeTemplateChargeAppliesTo() {} @ApiModelProperty(example = "1 ") public Integer id; @@ -470,12 +470,12 @@ final class SelfLoansApiResourceSwagger { @ApiModel(value = "GetSelfLoansLoanIdTransactionsTransactionIdResponse") public final static class GetSelfLoansLoanIdTransactionsTransactionIdResponse { - private GetSelfLoansLoanIdTransactionsTransactionIdResponse() { - } + + private GetSelfLoansLoanIdTransactionsTransactionIdResponse() {} final class GetSelfLoansLoanIdTransactionsType { - private GetSelfLoansLoanIdTransactionsType() { - } + + private GetSelfLoansLoanIdTransactionsType() {} @ApiModelProperty(example = "2") public Integer id; @@ -517,12 +517,12 @@ final class SelfLoansApiResourceSwagger { @ApiModel(value = "GetSelfLoansLoanIdChargesResponse") public final static class GetSelfLoansLoanIdChargesResponse { - private GetSelfLoansLoanIdChargesResponse() { - } + + private GetSelfLoansLoanIdChargesResponse() {} final class GetSelfLoansChargeTimeType { - private GetSelfLoansChargeTimeType() { - } + + private GetSelfLoansChargeTimeType() {} @ApiModelProperty(example = "1") public Integer id; @@ -533,8 +533,8 @@ final class SelfLoansApiResourceSwagger { } final class GetSelfLoansChargeCalculationType { - private GetSelfLoansChargeCalculationType() { - } + + private GetSelfLoansChargeCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -575,20 +575,20 @@ final class SelfLoansApiResourceSwagger { @ApiModel(value = "GetSelfLoansTemplateResponse") public final static class GetSelfLoansTemplateResponse { - private GetSelfLoansTemplateResponse() { - } + + private GetSelfLoansTemplateResponse() {} final class GetSelfLoansTimeline { - private GetSelfLoansTimeline() { - } + + private GetSelfLoansTimeline() {} @ApiModelProperty(example = "[2013, 3, 8]") public LocalDate expectedDisbursementDate; } final class GetSelfLoansProductOptions { - private GetSelfLoansProductOptions() { - } + + private GetSelfLoansProductOptions() {} @ApiModelProperty(example = "1") public Integer id; @@ -608,12 +608,12 @@ final class SelfLoansApiResourceSwagger { @ApiModel(value = "PostSelfLoansRequest") public final static class PostSelfLoansRequest { - private PostSelfLoansRequest() { - } + + private PostSelfLoansRequest() {} final class PostSelfLoansDisbursementData { - private PostSelfLoansDisbursementData() { - } + + private PostSelfLoansDisbursementData() {} @ApiModelProperty(example = "01 November 2013") public String expectedDisbursementDate; @@ -624,12 +624,12 @@ final class SelfLoansApiResourceSwagger { } final class PostSelfLoansDatatables { - private PostSelfLoansDatatables() { - } + + private PostSelfLoansDatatables() {} final class PostSelfLoansData { - private PostSelfLoansData() { - } + + private PostSelfLoansData() {} @ApiModelProperty(example = "en") public String locale; @@ -692,8 +692,8 @@ final class SelfLoansApiResourceSwagger { @ApiModel(value = "PostSelfLoansResponse") public final static class PostSelfLoansResponse { - private PostSelfLoansResponse() { - } + + private PostSelfLoansResponse() {} @ApiModelProperty(example = "1") public Integer officeId; @@ -707,8 +707,8 @@ final class SelfLoansApiResourceSwagger { @ApiModel(value = "PutSelfLoansLoanIdRequest") public final static class PutSelfLoansLoanIdRequest { - private PutSelfLoansLoanIdRequest() { - } + + private PutSelfLoansLoanIdRequest() {} @ApiModelProperty(example = "en") public String locale; @@ -744,12 +744,12 @@ final class SelfLoansApiResourceSwagger { @ApiModel(value = "PutSelfLoansLoanIdResponse") public final static class PutSelfLoansLoanIdResponse { - private PutSelfLoansLoanIdResponse() { - } + + private PutSelfLoansLoanIdResponse() {} final class PutSelfLoansChanges { - private PutSelfLoansChanges() { - } + + private PutSelfLoansChanges() {} @ApiModelProperty(example = "5000") public Long principal; @@ -770,8 +770,8 @@ final class SelfLoansApiResourceSwagger { @ApiModel(value = "PostSelfLoansLoanIdRequest") public final static class PostSelfLoansLoanIdRequest { - private PostSelfLoansLoanIdRequest() { - } + + private PostSelfLoansLoanIdRequest() {} @ApiModelProperty(example = "en") public String locale; @@ -785,16 +785,16 @@ final class SelfLoansApiResourceSwagger { @ApiModel(value = "PostSelfLoansLoanIdResponse") public final static class PostSelfLoansLoanIdResponse { - private PostSelfLoansLoanIdResponse() { - } + + private PostSelfLoansLoanIdResponse() {} final class PostSelfLoansLoanIdChanges { - private PostSelfLoansLoanIdChanges() { - } + + private PostSelfLoansLoanIdChanges() {} final class PostSelfLoansLoanIdStatus { - private PostSelfLoansLoanIdStatus() { - } + + private PostSelfLoansLoanIdStatus() {} @ApiModelProperty(example = "400") public Integer id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/data/SelfLoansDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/data/SelfLoansDataValidator.java index e460bae62..204fe1aff 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/data/SelfLoansDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/data/SelfLoansDataValidator.java @@ -39,48 +39,44 @@ import org.springframework.stereotype.Component; @Component public class SelfLoansDataValidator { - private static final Set allowedAssociationParameters = new HashSet<>( - Arrays.asList("repaymentSchedule", "futureSchedule", - "originalSchedule", "transactions", "charges", - "guarantors", "collateral", "linkedAccount", - "multiDisburseDetails")); - private final FromJsonHelper fromApiJsonHelper; - @Autowired - public SelfLoansDataValidator(final FromJsonHelper fromApiJsonHelper){ - this.fromApiJsonHelper = fromApiJsonHelper; - } + private static final Set allowedAssociationParameters = new HashSet<>(Arrays.asList("repaymentSchedule", "futureSchedule", + "originalSchedule", "transactions", "charges", "guarantors", "collateral", "linkedAccount", "multiDisburseDetails")); + private final FromJsonHelper fromApiJsonHelper; - public void validateRetrieveLoan(final UriInfo uriInfo) { - List unsupportedParams = new ArrayList<>(); + @Autowired + public SelfLoansDataValidator(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } - Set associationParameters = ApiParameterHelper - .extractAssociationsForResponseIfProvided(uriInfo - .getQueryParameters()); - if (!associationParameters.isEmpty()) { - associationParameters.removeAll(allowedAssociationParameters); - if (!associationParameters.isEmpty()) { - unsupportedParams.addAll(associationParameters); - } - } + public void validateRetrieveLoan(final UriInfo uriInfo) { + List unsupportedParams = new ArrayList<>(); - if (uriInfo.getQueryParameters().getFirst("exclude") != null) { - unsupportedParams.add("exclude"); - } + Set associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); + if (!associationParameters.isEmpty()) { + associationParameters.removeAll(allowedAssociationParameters); + if (!associationParameters.isEmpty()) { + unsupportedParams.addAll(associationParameters); + } + } - throwExceptionIfReqd(unsupportedParams); - } + if (uriInfo.getQueryParameters().getFirst("exclude") != null) { + unsupportedParams.add("exclude"); + } - public void validateRetrieveTransaction(UriInfo uriInfo) { - List unsupportedParams = new ArrayList<>(); + throwExceptionIfReqd(unsupportedParams); + } - validateTemplate(uriInfo, unsupportedParams); + public void validateRetrieveTransaction(UriInfo uriInfo) { + List unsupportedParams = new ArrayList<>(); - throwExceptionIfReqd(unsupportedParams); + validateTemplate(uriInfo, unsupportedParams); - } + throwExceptionIfReqd(unsupportedParams); - public HashMap validateLoanApplication(final String json){ + } + + public HashMap validateLoanApplication(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final List dataValidationErrors = new ArrayList<>(); @@ -102,23 +98,23 @@ public class SelfLoansDataValidator { retAttr.put("clientId", Long.parseLong(clientId)); return retAttr; - } + } - public HashMap validateModifyLoanApplication(final String json) { + public HashMap validateModifyLoanApplication(final String json) { final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan"); final JsonElement element = this.fromApiJsonHelper.parse(json); final String loanTypeParameterName = "loanType"; - if(this.fromApiJsonHelper.parameterExists(loanTypeParameterName, element)){ + if (this.fromApiJsonHelper.parameterExists(loanTypeParameterName, element)) { final String loanTypeStr = this.fromApiJsonHelper.extractStringNamed(loanTypeParameterName, element); baseDataValidator.reset().parameter(loanTypeParameterName).value(loanTypeStr).notNull().isOneOfTheseStringValues("individual"); } final String clientIdParameterName = "clientId"; String clientId = null; - if(this.fromApiJsonHelper.parameterExists(clientIdParameterName, element)){ + if (this.fromApiJsonHelper.parameterExists(clientIdParameterName, element)) { clientId = this.fromApiJsonHelper.extractStringNamed(clientIdParameterName, element); baseDataValidator.reset().parameter(clientIdParameterName).value(clientId).notNull().longGreaterThanZero(); } @@ -126,25 +122,21 @@ public class SelfLoansDataValidator { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } HashMap retAttr = new HashMap<>(); - if(clientId != null){ + if (clientId != null) { retAttr.put("clientId", Long.parseLong(clientId)); } return retAttr; - } + } - private void throwExceptionIfReqd(List unsupportedParams) { - if (unsupportedParams.size() > 0) { - throw new UnsupportedParameterException(unsupportedParams); - } - } + private void throwExceptionIfReqd(List unsupportedParams) { + if (unsupportedParams.size() > 0) { throw new UnsupportedParameterException(unsupportedParams); } + } - private void validateTemplate(final UriInfo uriInfo, - List unsupportedParams) { - final boolean templateRequest = ApiParameterHelper.template(uriInfo - .getQueryParameters()); - if (templateRequest) { - unsupportedParams.add("template"); - } - } + private void validateTemplate(final UriInfo uriInfo, List unsupportedParams) { + final boolean templateRequest = ApiParameterHelper.template(uriInfo.getQueryParameters()); + if (templateRequest) { + unsupportedParams.add("template"); + } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/service/AppuserLoansMapperReadServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/service/AppuserLoansMapperReadServiceImpl.java index 60cb4a591..40fec6d77 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/service/AppuserLoansMapperReadServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/loanaccount/service/AppuserLoansMapperReadServiceImpl.java @@ -24,8 +24,7 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @Service -public class AppuserLoansMapperReadServiceImpl implements - AppuserLoansMapperReadService { +public class AppuserLoansMapperReadServiceImpl implements AppuserLoansMapperReadService { private final JdbcTemplate jdbcTemplate; @@ -36,13 +35,10 @@ public class AppuserLoansMapperReadServiceImpl implements @Override public Boolean isLoanMappedToUser(Long loanId, Long appUserId) { - return this.jdbcTemplate - .queryForObject( - "select case when (count(*) > 0) then true else false end " - + " from m_selfservice_user_client_mapping as m " - + " left join m_loan as l on l.client_id = m.client_id " - + " where l.id = ? and m.appuser_id = ? ", - new Object[] { loanId, appUserId }, Boolean.class); + return this.jdbcTemplate.queryForObject( + "select case when (count(*) > 0) then true else false end " + " from m_selfservice_user_client_mapping as m " + + " left join m_loan as l on l.client_id = m.client_id " + " where l.id = ? and m.appuser_id = ? ", + new Object[] { loanId, appUserId }, Boolean.class); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiResource.java index c995270ee..f2b084fe9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiResource.java @@ -50,64 +50,64 @@ import org.springframework.stereotype.Component; @Path("/self/pockets") @Component @Scope("singleton") -@Api(tags = {"Pocket"}) -@SwaggerDefinition(tags = { - @Tag(name = "Pocket", description = "") -}) +@Api(tags = { "Pocket" }) +@SwaggerDefinition(tags = { @Tag(name = "Pocket", description = "") }) public class PocketApiResource { - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - @SuppressWarnings("rawtypes") - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService; - @SuppressWarnings("rawtypes") - @Autowired - public PocketApiResource(PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService) { - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - this.toApiJsonSerializer = toApiJsonSerializer; - this.pocketAccountMappingReadPlatformService = pocketAccountMappingReadPlatformService; - } + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + @SuppressWarnings("rawtypes") + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService; - @POST - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Link/delink accounts to/from pocket", httpMethod = "POST", notes = "Pockets behave as favourites. An user can link his/her Loan, Savings and Share accounts to pocket for faster access. In a similar way linked accounts can be delinked from the pocket.\n\n" + "Example Requests:\n" + "\n" + "self/pockets?command=linkAccounts\n" + "\n" + "self/pockets?command=delinkAccounts") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = PocketApiResourceSwagger.PostLinkDelinkAccountsToFromPocketResponse.class)}) - public String handleCommands(@QueryParam("command") @ApiParam(value = "command") final String commandParam, @Context final UriInfo uriInfo, - final String apiRequestBodyAsJson) { + @SuppressWarnings("rawtypes") + @Autowired + public PocketApiResource(PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final DefaultToApiJsonSerializer toApiJsonSerializer, + final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService) { + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.pocketAccountMappingReadPlatformService = pocketAccountMappingReadPlatformService; + } - final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); + @POST + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Link/delink accounts to/from pocket", httpMethod = "POST", notes = "Pockets behave as favourites. An user can link his/her Loan, Savings and Share accounts to pocket for faster access. In a similar way linked accounts can be delinked from the pocket.\n\n" + + "Example Requests:\n" + "\n" + "self/pockets?command=linkAccounts\n" + "\n" + "self/pockets?command=delinkAccounts") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = PocketApiResourceSwagger.PostLinkDelinkAccountsToFromPocketResponse.class) }) + public String handleCommands(@QueryParam("command") @ApiParam(value = "command") final String commandParam, + @Context final UriInfo uriInfo, final String apiRequestBodyAsJson) { - CommandProcessingResult result = null; + final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); - if (is(commandParam, PocketApiConstants.linkAccountsToPocketCommandParam)) { - final CommandWrapper commandRequest = builder.linkAccountsToPocket().build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } else if (is(commandParam, PocketApiConstants.delinkAccountsFromPocketCommandParam)) { - final CommandWrapper commandRequest = builder.delinkAccountsFromPocket().build(); - result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - } + CommandProcessingResult result = null; - if (result == null) { - throw new UnrecognizedQueryParamException("command", commandParam); - } + if (is(commandParam, PocketApiConstants.linkAccountsToPocketCommandParam)) { + final CommandWrapper commandRequest = builder.linkAccountsToPocket().build(); + result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + } else if (is(commandParam, PocketApiConstants.delinkAccountsFromPocketCommandParam)) { + final CommandWrapper commandRequest = builder.delinkAccountsFromPocket().build(); + result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + } - return this.toApiJsonSerializer.serialize(result); - } + if (result == null) { throw new UnrecognizedQueryParamException("command", commandParam); } - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve accounts linked to pocket", httpMethod = "GET", notes = "All linked loan\n\n" + "Example Requests:\n" + "\n" + "\n" + "self/pockets") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = PocketApiResourceSwagger.GetAccountsLinkedToPocketResponse.class)}) - public String retrieveAll() { - return this.toApiJsonSerializer.serialize(this.pocketAccountMappingReadPlatformService.retrieveAll()); - } + return this.toApiJsonSerializer.serialize(result); + } - private boolean is(final String commandParam, final String commandValue) { - return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); - } + @GET + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Retrieve accounts linked to pocket", httpMethod = "GET", notes = "All linked loan\n\n" + "Example Requests:\n" + + "\n" + "\n" + "self/pockets") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = PocketApiResourceSwagger.GetAccountsLinkedToPocketResponse.class) }) + public String retrieveAll() { + return this.toApiJsonSerializer.serialize(this.pocketAccountMappingReadPlatformService.retrieveAll()); + } + + private boolean is(final String commandParam, final String commandValue) { + return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiResourceSwagger.java index 16cb45f5c..fb7b93600 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/api/PocketApiResourceSwagger.java @@ -27,41 +27,44 @@ import java.util.Set; */ final class PocketApiResourceSwagger { - private PocketApiResourceSwagger() { - } + + private PocketApiResourceSwagger() {} @ApiModel(value = "PostLinkDelinkAccountsToFromPocketRequest") public final static class PostLinkDelinkAccountsToFromPocketRequest { - private PostLinkDelinkAccountsToFromPocketRequest() { - } + + private PostLinkDelinkAccountsToFromPocketRequest() {} + final class GetPocketAccountDetail { - private GetPocketAccountDetail() { - } + + private GetPocketAccountDetail() {} @ApiModelProperty(example = "11") public Integer accountId; @ApiModelProperty(example = "LOAN") public String accountType; } + public Set accountDetail; } @ApiModel(value = "PostLinkDelinkAccountsToFromPocketResponse") public final static class PostLinkDelinkAccountsToFromPocketResponse { - private PostLinkDelinkAccountsToFromPocketResponse() { - } + + private PostLinkDelinkAccountsToFromPocketResponse() {} + @ApiModelProperty(example = "6") public Integer resourceId; } @ApiModel(value = "GetAccountsLinkedToPocketResponse") public final static class GetAccountsLinkedToPocketResponse { - private GetAccountsLinkedToPocketResponse() { - } + + private GetAccountsLinkedToPocketResponse() {} final class GetPocketLoanAccounts { - private GetPocketLoanAccounts() { - } + + private GetPocketLoanAccounts() {} @ApiModelProperty(example = "6") public Integer pocketId; @@ -76,8 +79,8 @@ final class PocketApiResourceSwagger { } final class GetPocketSavingAccounts { - private GetPocketSavingAccounts() { - } + + private GetPocketSavingAccounts() {} @ApiModelProperty(example = "6") public Integer pocketId; @@ -92,8 +95,8 @@ final class PocketApiResourceSwagger { } final class GetPocketShareAccounts { - private GetPocketShareAccounts() { - } + + private GetPocketShareAccounts() {} } @@ -102,4 +105,3 @@ final class PocketApiResourceSwagger { public Set shareAccounts; } } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/data/PocketAccountMappingData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/data/PocketAccountMappingData.java index 62d4c8e0b..84aac9839 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/data/PocketAccountMappingData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/data/PocketAccountMappingData.java @@ -29,13 +29,15 @@ public class PocketAccountMappingData { private final Collection savingsAccounts; private final Collection shareAccounts; - private PocketAccountMappingData(final Collection loanAccounts, Collection savingsAccounts, final Collection shareAccounts ) { + private PocketAccountMappingData(final Collection loanAccounts, Collection savingsAccounts, + final Collection shareAccounts) { this.loanAccounts = loanAccounts; this.savingsAccounts = savingsAccounts; this.shareAccounts = shareAccounts; } - public static PocketAccountMappingData instance(final Collection loanAccounts, final Collection savingsAccounts, final Collection shareAccounts) { + public static PocketAccountMappingData instance(final Collection loanAccounts, + final Collection savingsAccounts, final Collection shareAccounts) { return new PocketAccountMappingData(loanAccounts, savingsAccounts, shareAccounts); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/data/PocketDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/data/PocketDataValidator.java index 8311f2ebd..c94f06ed6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/data/PocketDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/data/PocketDataValidator.java @@ -42,9 +42,9 @@ import org.springframework.stereotype.Service; @Service public class PocketDataValidator { - private final Set linkingAccountsSupportedParameters = new HashSet<>( - Arrays.asList(PocketApiConstants.accountIdParamName, PocketApiConstants.accountTypeParamName, - PocketApiConstants.accountsDetail)); + + private final Set linkingAccountsSupportedParameters = new HashSet<>(Arrays.asList(PocketApiConstants.accountIdParamName, + PocketApiConstants.accountTypeParamName, PocketApiConstants.accountsDetail)); private final Set delinkingAccountsSupportedParameters = new HashSet<>( Arrays.asList(PocketApiConstants.pocketAccountMappingList)); @@ -57,12 +57,9 @@ public class PocketDataValidator { } public void validateForLinkingAccounts(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.linkingAccountsSupportedParameters); final List dataValidationErrors = new ArrayList<>(); @@ -71,22 +68,18 @@ public class PocketDataValidator { final JsonElement element = this.fromApiJsonHelper.parse(json); - JsonArray accountsDetail = this.fromApiJsonHelper.extractJsonArrayNamed(PocketApiConstants.accountsDetail, - element); - baseDataValidator.reset().parameter(PocketApiConstants.accountsDetail).value(accountsDetail).notNull() - .jsonArrayNotEmpty(); + JsonArray accountsDetail = this.fromApiJsonHelper.extractJsonArrayNamed(PocketApiConstants.accountsDetail, element); + baseDataValidator.reset().parameter(PocketApiConstants.accountsDetail).value(accountsDetail).notNull().jsonArrayNotEmpty(); final List valueList = Arrays.asList(EntityAccountType.LOAN.name().toLowerCase(), EntityAccountType.SAVINGS.name().toLowerCase(), EntityAccountType.SHARES.name().toLowerCase()); for (JsonElement accountDetails : accountsDetail) { - final Long accountId = this.fromApiJsonHelper.extractLongNamed(PocketApiConstants.accountIdParamName, - accountDetails); + final Long accountId = this.fromApiJsonHelper.extractLongNamed(PocketApiConstants.accountIdParamName, accountDetails); baseDataValidator.reset().parameter(PocketApiConstants.accountIdParamName).value(accountId).notBlank(); - final String accountType = this.fromApiJsonHelper - .extractStringNamed(PocketApiConstants.accountTypeParamName, accountDetails); + final String accountType = this.fromApiJsonHelper.extractStringNamed(PocketApiConstants.accountTypeParamName, accountDetails); baseDataValidator.reset().parameter(PocketApiConstants.accountTypeParamName).value(accountType).notBlank() .isOneOfTheseStringValues(valueList); @@ -97,14 +90,10 @@ public class PocketDataValidator { } public void validateForDeLinkingAccounts(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() { - }.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - this.delinkingAccountsSupportedParameters); + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.delinkingAccountsSupportedParameters); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -112,10 +101,10 @@ public class PocketDataValidator { final JsonElement element = this.fromApiJsonHelper.parse(json); - JsonArray pocketAccountMappingList = this.fromApiJsonHelper - .extractJsonArrayNamed(PocketApiConstants.pocketAccountMappingList, element); - baseDataValidator.reset().parameter(PocketApiConstants.pocketAccountMappingList).value(pocketAccountMappingList) - .notNull().jsonArrayNotEmpty(); + JsonArray pocketAccountMappingList = this.fromApiJsonHelper.extractJsonArrayNamed(PocketApiConstants.pocketAccountMappingList, + element); + baseDataValidator.reset().parameter(PocketApiConstants.pocketAccountMappingList).value(pocketAccountMappingList).notNull() + .jsonArrayNotEmpty(); for (JsonElement pocketAccountMapping : pocketAccountMappingList) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/Pocket.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/Pocket.java index 9ceabfc72..b39100ffd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/Pocket.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/Pocket.java @@ -27,8 +27,7 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @SuppressWarnings("serial") @Entity -@Table(name = "m_pocket", uniqueConstraints = { - @UniqueConstraint(columnNames = { "app_user_id" }, name = "unique_app_user") }) +@Table(name = "m_pocket", uniqueConstraints = { @UniqueConstraint(columnNames = { "app_user_id" }, name = "unique_app_user") }) public class Pocket extends AbstractPersistableCustom { @Column(name = "app_user_id", length = 20, nullable = false) @@ -42,8 +41,7 @@ public class Pocket extends AbstractPersistableCustom { this.appUserId = appUserId; } - protected Pocket() { - } + protected Pocket() {} private Pocket(final Long appUserId) { this.appUserId = appUserId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMapping.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMapping.java index c18a53584..8d884399a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMapping.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMapping.java @@ -41,11 +41,9 @@ public class PocketAccountMapping extends AbstractPersistableCustom { @Column(name = "account_number", nullable = false) private String accountNumber; - protected PocketAccountMapping() { - } + protected PocketAccountMapping() {} - private PocketAccountMapping(final Long pocketId, final Long accountId, final Integer accountType, - final String accountNumber) { + private PocketAccountMapping(final Long pocketId, final Long accountId, final Integer accountType, final String accountNumber) { this.pocketId = pocketId; this.accountId = accountId; this.accountType = accountType; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMappingRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMappingRepositoryWrapper.java index 9f1acb266..9137608f6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMappingRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketAccountMappingRepositoryWrapper.java @@ -48,11 +48,8 @@ public class PocketAccountMappingRepositoryWrapper { } public PocketAccountMapping findByIdAndPocketIdWithNotFoundException(final Long id, final Long pocketId) { - PocketAccountMapping pocketAccountMapping = this.pocketAccountMappingRepository.findByIdAndPocketId(id, - pocketId); - if (pocketAccountMapping == null) { - throw new MappingIdNotLinkedToPocketException(id); - } + PocketAccountMapping pocketAccountMapping = this.pocketAccountMappingRepository.findByIdAndPocketId(id, pocketId); + if (pocketAccountMapping == null) { throw new MappingIdNotLinkedToPocketException(id); } return pocketAccountMapping; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketRepository.java index 78ec69499..4fa85340b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketRepository.java @@ -24,7 +24,7 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface PocketRepository extends JpaRepository , JpaSpecificationExecutor{ +public interface PocketRepository extends JpaRepository, JpaSpecificationExecutor { @Query("select pocket.id from Pocket pocket where pocket.appUserId= :appUserId") Long findByAppUserId(@Param("appUserId") Long appUserId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketRepositoryWrapper.java index 90f0a415d..052d61354 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/domain/PocketRepositoryWrapper.java @@ -25,6 +25,7 @@ import org.springframework.stereotype.Service; @Service public class PocketRepositoryWrapper { + private final PocketRepository pocketRepository; @Autowired @@ -42,9 +43,7 @@ public class PocketRepositoryWrapper { public Long findByAppUserIdWithNotFoundDetection(final Long appUserId) { final Long pocketId = this.pocketRepository.findByAppUserId(appUserId); - if (pocketId == null) { - throw new PocketNotFoundException(); - } + if (pocketId == null) { throw new PocketNotFoundException(); } return pocketId; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/exception/MappingIdNotLinkedToPocketException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/exception/MappingIdNotLinkedToPocketException.java index 35a892658..5864c3287 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/exception/MappingIdNotLinkedToPocketException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/exception/MappingIdNotLinkedToPocketException.java @@ -25,7 +25,6 @@ import org.apache.fineract.portfolio.self.pockets.api.PocketApiConstants; public class MappingIdNotLinkedToPocketException extends AbstractPlatformDomainRuleException { public MappingIdNotLinkedToPocketException(final Long id) { - super(PocketApiConstants.mappingIdNotLinkedToPocketException, - PocketApiConstants.mappingIdNotLinkedToPocketErrorMessage, id); + super(PocketApiConstants.mappingIdNotLinkedToPocketException, PocketApiConstants.mappingIdNotLinkedToPocketErrorMessage, id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/handler/DelinkAccountsFromPocketCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/handler/DelinkAccountsFromPocketCommandHandler.java index 56f510696..8bf476254 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/handler/DelinkAccountsFromPocketCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/handler/DelinkAccountsFromPocketCommandHandler.java @@ -32,6 +32,7 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = PocketApiConstants.pocketEntityName, action = PocketApiConstants.delinkAccountsActionName) public class DelinkAccountsFromPocketCommandHandler implements NewCommandSourceHandler { + private final PocketWritePlatformService pocketWritePlatformService; @Autowired diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceFactory.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceFactory.java index a2ba54753..a3427e61b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceFactory.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceFactory.java @@ -30,18 +30,17 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class AccountEntityServiceFactory { - private Map accountEntityServiceHashMap = new HashMap<>(); + private Map accountEntityServiceHashMap = new HashMap<>(); - @Autowired - public AccountEntityServiceFactory(final Set accountEntityServices) { - for (AccountEntityService service : accountEntityServices) { - this.accountEntityServiceHashMap.put(service.getKey(), service); - } - } - - public AccountEntityService getAccountEntityService(final String key) { - return this.accountEntityServiceHashMap.get(key); + @Autowired + public AccountEntityServiceFactory(final Set accountEntityServices) { + for (AccountEntityService service : accountEntityServices) { + this.accountEntityServiceHashMap.put(service.getKey(), service); } + } + public AccountEntityService getAccountEntityService(final String key) { + return this.accountEntityServiceHashMap.get(key); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForLoanImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForLoanImpl.java index 116c159db..4fd7ff18e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForLoanImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForLoanImpl.java @@ -38,8 +38,7 @@ public class AccountEntityServiceForLoanImpl implements AccountEntityService { @Autowired public AccountEntityServiceForLoanImpl(final PlatformSecurityContext context, - final AppuserLoansMapperReadService appuserLoansMapperReadService, - final LoanReadPlatformService loanReadPlatformService) { + final AppuserLoansMapperReadService appuserLoansMapperReadService, final LoanReadPlatformService loanReadPlatformService) { this.context = context; this.appuserLoansMapperReadService = appuserLoansMapperReadService; @@ -54,8 +53,7 @@ public class AccountEntityServiceForLoanImpl implements AccountEntityService { @Override public void validateSelfUserAccountMapping(Long accountId) { - if (!this.appuserLoansMapperReadService.isLoanMappedToUser(accountId, - this.context.authenticatedUser().getId())) { + if (!this.appuserLoansMapperReadService.isLoanMappedToUser(accountId, this.context.authenticatedUser().getId())) { throw new LoanNotFoundException(accountId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForSavingsImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForSavingsImpl.java index 2abefeb01..b2dcad2b4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForSavingsImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForSavingsImpl.java @@ -55,8 +55,7 @@ public class AccountEntityServiceForSavingsImpl implements AccountEntityService @Override public void validateSelfUserAccountMapping(Long accountId) { - if (!this.appuserSavingsMapperReadService.isSavingsMappedToUser(accountId, - this.context.getAuthenticatedUserIfPresent().getId())) { + if (!this.appuserSavingsMapperReadService.isSavingsMappedToUser(accountId, this.context.getAuthenticatedUserIfPresent().getId())) { throw new SavingsAccountNotFoundException(accountId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForShareAccountsImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForShareAccountsImpl.java index ae334631a..ae155fdef 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForShareAccountsImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/AccountEntityServiceForShareAccountsImpl.java @@ -36,7 +36,6 @@ public class AccountEntityServiceForShareAccountsImpl implements AccountEntitySe private final AppUserShareAccountsMapperReadPlatformService appUserShareAccountsMapperReadPlatformService; private final ShareAccountReadPlatformService shareAccountReadPlatformService; - @Autowired public AccountEntityServiceForShareAccountsImpl(final PlatformSecurityContext context, final AppUserShareAccountsMapperReadPlatformService appUserShareAccountsMapperReadPlatformService, diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketAccountMappingReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketAccountMappingReadPlatformServiceImpl.java index a74297382..1475d24af 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketAccountMappingReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketAccountMappingReadPlatformServiceImpl.java @@ -41,8 +41,8 @@ public class PocketAccountMappingReadPlatformServiceImpl implements PocketAccoun private final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper; @Autowired - public PocketAccountMappingReadPlatformServiceImpl(final RoutingDataSource dataSource, - final PlatformSecurityContext context, final PocketRepositoryWrapper pocketRepositoryWrapper, + public PocketAccountMappingReadPlatformServiceImpl(final RoutingDataSource dataSource, final PlatformSecurityContext context, + final PocketRepositoryWrapper pocketRepositoryWrapper, final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.context = context; @@ -54,8 +54,7 @@ public class PocketAccountMappingReadPlatformServiceImpl implements PocketAccoun public PocketAccountMappingData retrieveAll() { final Long pocketId = this.pocketRepositoryWrapper.findByAppUserId(this.context.authenticatedUser().getId()); if (pocketId != null) { - Collection pocketAccountMappingList = this.pocketAccountMappingRepositoryWrapper - .findByPocketId(pocketId); + Collection pocketAccountMappingList = this.pocketAccountMappingRepositoryWrapper.findByPocketId(pocketId); if (pocketAccountMappingList != null && !pocketAccountMappingList.isEmpty()) { Collection loanAccounts = new ArrayList<>(); Collection savingsAccounts = new ArrayList<>(); @@ -80,8 +79,7 @@ public class PocketAccountMappingReadPlatformServiceImpl implements PocketAccoun public boolean validatePocketAndAccountMapping(Long pocketId, Long accountId, Integer accountType) { final String sql = "select count(id) from m_pocket_accounts_mapping mapping where pocket_id = ? and account_id = ? and account_type = ?"; try { - return this.jdbcTemplate.queryForObject(sql, new Object[] { pocketId, accountId, accountType }, - Boolean.class); + return this.jdbcTemplate.queryForObject(sql, new Object[] { pocketId, accountId, accountType }, Boolean.class); } catch (EmptyResultDataAccessException e) { return false; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketWritePlatformService.java index 63e61ec87..c720d6979 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketWritePlatformService.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.fineract.portfolio.self.pockets.service; import org.apache.fineract.infrastructure.core.api.JsonCommand; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketWritePlatformServiceImpl.java index b4de19a99..34c30cde5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/pockets/service/PocketWritePlatformServiceImpl.java @@ -51,9 +51,8 @@ public class PocketWritePlatformServiceImpl implements PocketWritePlatformServic private final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService; @Autowired - public PocketWritePlatformServiceImpl(final PlatformSecurityContext context, - PocketDataValidator pocketDataValidator, final AccountEntityServiceFactory accountEntityServiceFactory, - final PocketRepositoryWrapper pocketRepositoryWrapper, + public PocketWritePlatformServiceImpl(final PlatformSecurityContext context, PocketDataValidator pocketDataValidator, + final AccountEntityServiceFactory accountEntityServiceFactory, final PocketRepositoryWrapper pocketRepositoryWrapper, final PocketAccountMappingRepositoryWrapper pocketAccountMappingRepositoryWrapper, final PocketAccountMappingReadPlatformService pocketAccountMappingReadPlatformService) { this.context = context; @@ -86,12 +85,10 @@ public class PocketWritePlatformServiceImpl implements PocketWritePlatformServic final Long accountId = element.get(PocketApiConstants.accountIdParamName).getAsLong(); final String accountType = element.get(PocketApiConstants.accountTypeParamName).getAsString(); - final AccountEntityService accountEntityService = this.accountEntityServiceFactory - .getAccountEntityService(accountType); + final AccountEntityService accountEntityService = this.accountEntityServiceFactory.getAccountEntityService(accountType); accountEntityService.validateSelfUserAccountMapping(accountId); Integer accountTypeValue = EntityAccountType.valueOf(accountType).getValue(); - if (this.pocketAccountMappingReadPlatformService.validatePocketAndAccountMapping(pocketId, accountId, - accountTypeValue)) { + if (this.pocketAccountMappingReadPlatformService.validatePocketAndAccountMapping(pocketId, accountId, accountTypeValue)) { throw new PlatformDataIntegrityException(PocketApiConstants.duplicateMappingException, PocketApiConstants.duplicateMappingExceptionMessage, accountId, accountType); } @@ -111,8 +108,7 @@ public class PocketWritePlatformServiceImpl implements PocketWritePlatformServic this.pocketDataValidator.validateForDeLinkingAccounts(command.json()); JsonArray pocketAccountMappingList = command.arrayOfParameterNamed(PocketApiConstants.pocketAccountMappingList); - Long pocketId = this.pocketRepositoryWrapper - .findByAppUserIdWithNotFoundDetection(this.context.authenticatedUser().getId()); + Long pocketId = this.pocketRepositoryWrapper.findByAppUserIdWithNotFoundDetection(this.context.authenticatedUser().getId()); final List pocketAccounts = new ArrayList<>(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfLoanProductsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfLoanProductsApiResource.java index 51eae77fe..8d1ed8621 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfLoanProductsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfLoanProductsApiResource.java @@ -41,139 +41,92 @@ import org.springframework.stereotype.Component; @Path("/self/loanproducts") @Component @Scope("singleton") -@Api(tags = {"Self Loan Products"}) +@Api(tags = { "Self Loan Products" }) @SwaggerDefinition(tags = { - @Tag(name = "Self Loan Products", description = "A Loan product is a template that is used when creating a loan. Much of the template definition can be overridden during loan creation.\n" + "\n" + - "Field Descriptions\n" + - "name\n" + - "Name associated with loan product on system.\n" + - "shortName\n" + - "Short name associated with a loan product. \n" + - "An abbreviated version of the name, used in reports or menus where space is limited, such as Collection Sheets.\n" + - "description\n" + - "For providing helpful description of product offering.\n" + - "fundId\n" + - "For associating a loan product with a given fund by default.\n" + - "includeInBorrowerCycle\n" + - "It is a flag, Used to denote whether the loans should include in loan cycle counter or not.\n" + - "useBorrowerCycle\n" + - "It is a flag, Used to denote whether the loans should depend on \n" + - "borrower loan cycle counter or not.\n" + - "currencyCode\n" + - "A three letter ISO code of currency.\n" + - "digitsAfterDecimal\n" + - "Override the currency default value for digitsAfterDecimal.\n" + - "inMultiplesOf\n" + - "Override the default value for rounding currency to multiples of value provided.\n" + - "installmentAmountInMultiplesOf\n" + - "Override the default value for rounding instalment amount to multiples of value provided.\n" + - "principal\n" + - "The loan amount to be disbursed to through loan.\n" + - "numberOfRepayments\n" + - "Number of installments to repay.\n" + - "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + - "e.g. 10 (repayments) Every 12 Weeks\n" + - "repaymentEvery\n" + - "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + - "e.g. 10 (repayments) Every 12 Weeks\n" + - "repaymentFrequencyType\n" + - "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + - "e.g. 10 (repayments) Every 12 Weeks \n" + - "Example Values: 0=Days, 1=Weeks, 2=Months\n" + - "interestRatePerPeriod\n" + - "Interest Rate.\n" + - "Used like: interestRatePerPeriod % interestRateFrequencyType - interestType\n" + - "e.g. 12.0000% Per year - Declining Balance\n" + - "interestRateFrequencyType\n" + - "Used like: interestRatePerPeriod% interestRateFrequencyType - interestType\n" + - "e.g. 12.0000% Per year - Declining Balance \n" + - "Example Values: 2=Per month, 3=Per year\n" + - "amortizationType\n" + - "Example Values: 0=Equal principle payments, 1=Equal installments\n" + - "interestType\n" + - "Used like: interestRatePerPeriod% interestRateFrequencyType - interestType\n" + - "e.g. 12.0000% Per year - Declining Balance \n" + - "Example Values: 0=Declining Balance, 1=Flat\n" + - "interestCalculationPeriodType\n" + - "Example Values: 0=Daily, 1=Same as repayment period\n" + - "allowPartialPeriodInterestCalcualtion\n" + - "This value will be supported along with interestCalculationPeriodType as Same as repayment period to calculate interest for partial periods. Example: Interest charged from is 5th of April , Principal is 10000 and interest is 1% per month then the interest will be (10000 * 1%)* (25/30) , it calculates for the month first then calculates exact periods between start date and end date(can be a decimal)\n" + - "inArrearsTolerance\n" + - "The amount that can be 'waived' at end of all loan payments because it is too small to worry about.\n" + - "This is also the tolerance amount assessed when determining if a loan is in arrears.\n" + - "principalVariationsForBorrowerCycle,interestRateVariationsForBorrowerCycle,\n" + - "numberOfRepaymentVariationsForBorrowerCycle\n" + - "Variations for loan, based on borrower cycle number\n" + - "minimumDaysBetweenDisbursalAndFirstRepayment\n" + - "The minimum number of days allowed between a Loan disbursal and its first repayment.\n" + - "principalThresholdForLastInstalment\n" + - "Field represents percentage of current instalment principal amount for comparing against principal outstanding to add another repayment instalment. If the outstanding principal amount is less then calculated amount, remaining outstanding amount will be added to current instalment. Default value for multi disburse loan is 50% and non-multi disburse loan is 0%\n" + - "canDefineInstallmentAmount\n" + - "if provided as true, then fixed instalment amount can be provided from loan account.\n" + - "transactionProcessingStrategyId\n" + - "An enumeration that indicates the type of transaction processing strategy to be used. This relates to functionality that is also known as Payment Application Logic.\n" + - "A number of out of the box approaches exist, some are custom to specific MFIs, some are more general and indicate the order in which payments are processed.\n" + - "\n" + - "Refer to the Payment Application Logic / Transaction Processing Strategy section in the appendix for more detailed overview of each available payment application logic provided out of the box.\n" + - "\n" + - "List of current approaches:\n" + - "1 = Mifos style (Similar to Old Mifos)\n" + - "2 = Heavensfamily (Custom MFI approach)\n" + - "3 = Creocore (Custom MFI approach)\n" + - "4 = RBI (India)\n" + - "5 = Principal Interest Penalties Fees Order\n" + - "6 = Interest Principal Penalties Fees Order\n" + - "7 = Early Payment Strategy\n" + - "graceOnPrincipalPayment\n" + - "Optional: Integer - represents the number of repayment periods that grace should apply to the principal component of a repayment period.\n" + - "graceOnInterestPayment\n" + - "Optional: Integer - represents the number of repayment periods that grace should apply to the interest component of a repayment period. Interest is still calculated but offset to later repayment periods.\n" + - "graceOnInterestCharged\n" + - "Optional: Integer - represents the number of repayment periods that should be interest-free.\n" + - "graceOnArrearsAgeing\n" + - "Optional: Integer - Used in Arrears calculation to only take into account loans that are more than graceOnArrearsAgeing days overdue.\n" + - "overdueDaysForNPA\n" + - "Optional: Integer - represents the maximum number of days a Loan may be overdue before being classified as a NPA (non performing asset)\n" + - "accountMovesOutOfNPAOnlyOnArrearsCompletion\n" + - "Optional: Boolean - if provided as true, Loan Account moves out of NPA state only when all arrears are cleared\n" + - "accountingRule\n" + - "Specifies if accounting is enabled for the particular product and the type of the accounting rule to be used Example Values:1=NONE, 2=CASH_BASED, 3=ACCRUAL_PERIODIC, 4=ACCRUAL_UPFRONT\n" + - "isInterestRecalculationEnabled\n" + - "It is a flag, Used to denote whether interest recalculation is enabled or disabled for the particular product\n" + - "daysInYearType\n" + - "Specifies the number of days in a year. \n" + - "Example Values:1=ACTUAL(Actual number of days in year), 360=360 DAYS, 364=364 DAYS(52 WEEKS), 365=365 DAYS\n" + - "daysInMonthType\n" + - "Specifies the number of days in a month. \n" + - "Example Values:1=ACTUAL(Actual number of days in month), 30=30 DAYS\n" + - "interestRecalculationCompoundingMethod\n" + - "Specifies which amount portion should be added to principal for interest recalculation. \n" + - "Example Values:0=NONE(Only on principal), 1=INTEREST(Principal+Interest), 2=FEE(Principal+Fee), 3=FEE And INTEREST (Principal+Fee+Interest)\n" + - "rescheduleStrategyMethod\n" + - "Specifies what action should perform on loan repayment schedule for advance payments. \n" + - "Example Values:1=Reschedule next repayments, 2=Reduce number of installments, 3=Reduce EMI amount\n" + - "recalculationCompoundingFrequencyType\n" + - "Specifies effective date from which the compounding of interest or fee amounts will be considered in recalculation on late payment.\n" + - "Example Values:1=Same as repayment period, 2=Daily, 3=Weekly, 4=Monthly\n" + - "recalculationCompoundingFrequencyInterval\n" + - "Specifies compounding frequency interval for interest recalculation.\n" + - "recalculationCompoundingFrequencyDate\n" + - "Specifies compounding frequency start date for interest recalculation.\n" + - "recalculationRestFrequencyType\n" + - "Specifies effective date from which the late or advanced payment amounts will be considered in recalculation.\n" + - "Example Values:1=Same as repayment period, 2=Daily, 3=Weekly, 4=Monthly\n" + - "recalculationRestFrequencyInterval\n" + - "Specifies rest frequency interval for interest recalculation.\n" + - "recalculationRestFrequencyDate\n" + - "Specifies rest frequency start date for interest recalculation.\n" + - "preClosureInterestCalculationStrategy\n" + - "Specifies applicable days for interest calculation on pre closure of a loan.\n" + - "Example Values:1=Calculate till pre closure date, 2=Calculate till rest frequency date\n" + - "isArrearsBasedOnOriginalSchedule\n" + - "If Specified as true, arrears will be identified based on original schedule.\n" + - "allowAttributeOverrides\n" + - "Specifies if select attributes may be overridden for individual loan accounts.") -}) + @Tag(name = "Self Loan Products", description = "A Loan product is a template that is used when creating a loan. Much of the template definition can be overridden during loan creation.\n" + + "\n" + "Field Descriptions\n" + "name\n" + "Name associated with loan product on system.\n" + "shortName\n" + + "Short name associated with a loan product. \n" + + "An abbreviated version of the name, used in reports or menus where space is limited, such as Collection Sheets.\n" + + "description\n" + "For providing helpful description of product offering.\n" + "fundId\n" + + "For associating a loan product with a given fund by default.\n" + "includeInBorrowerCycle\n" + + "It is a flag, Used to denote whether the loans should include in loan cycle counter or not.\n" + "useBorrowerCycle\n" + + "It is a flag, Used to denote whether the loans should depend on \n" + "borrower loan cycle counter or not.\n" + + "currencyCode\n" + "A three letter ISO code of currency.\n" + "digitsAfterDecimal\n" + + "Override the currency default value for digitsAfterDecimal.\n" + "inMultiplesOf\n" + + "Override the default value for rounding currency to multiples of value provided.\n" + "installmentAmountInMultiplesOf\n" + + "Override the default value for rounding instalment amount to multiples of value provided.\n" + "principal\n" + + "The loan amount to be disbursed to through loan.\n" + "numberOfRepayments\n" + "Number of installments to repay.\n" + + "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + "e.g. 10 (repayments) Every 12 Weeks\n" + + "repaymentEvery\n" + "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + + "e.g. 10 (repayments) Every 12 Weeks\n" + "repaymentFrequencyType\n" + + "Used like: numberOfRepayments Every repaymentEvery repaymentFrequencyType\n" + "e.g. 10 (repayments) Every 12 Weeks \n" + + "Example Values: 0=Days, 1=Weeks, 2=Months\n" + "interestRatePerPeriod\n" + "Interest Rate.\n" + + "Used like: interestRatePerPeriod % interestRateFrequencyType - interestType\n" + + "e.g. 12.0000% Per year - Declining Balance\n" + "interestRateFrequencyType\n" + + "Used like: interestRatePerPeriod% interestRateFrequencyType - interestType\n" + + "e.g. 12.0000% Per year - Declining Balance \n" + "Example Values: 2=Per month, 3=Per year\n" + "amortizationType\n" + + "Example Values: 0=Equal principle payments, 1=Equal installments\n" + "interestType\n" + + "Used like: interestRatePerPeriod% interestRateFrequencyType - interestType\n" + + "e.g. 12.0000% Per year - Declining Balance \n" + "Example Values: 0=Declining Balance, 1=Flat\n" + + "interestCalculationPeriodType\n" + "Example Values: 0=Daily, 1=Same as repayment period\n" + + "allowPartialPeriodInterestCalcualtion\n" + + "This value will be supported along with interestCalculationPeriodType as Same as repayment period to calculate interest for partial periods. Example: Interest charged from is 5th of April , Principal is 10000 and interest is 1% per month then the interest will be (10000 * 1%)* (25/30) , it calculates for the month first then calculates exact periods between start date and end date(can be a decimal)\n" + + "inArrearsTolerance\n" + + "The amount that can be 'waived' at end of all loan payments because it is too small to worry about.\n" + + "This is also the tolerance amount assessed when determining if a loan is in arrears.\n" + + "principalVariationsForBorrowerCycle,interestRateVariationsForBorrowerCycle,\n" + + "numberOfRepaymentVariationsForBorrowerCycle\n" + "Variations for loan, based on borrower cycle number\n" + + "minimumDaysBetweenDisbursalAndFirstRepayment\n" + + "The minimum number of days allowed between a Loan disbursal and its first repayment.\n" + + "principalThresholdForLastInstalment\n" + + "Field represents percentage of current instalment principal amount for comparing against principal outstanding to add another repayment instalment. If the outstanding principal amount is less then calculated amount, remaining outstanding amount will be added to current instalment. Default value for multi disburse loan is 50% and non-multi disburse loan is 0%\n" + + "canDefineInstallmentAmount\n" + "if provided as true, then fixed instalment amount can be provided from loan account.\n" + + "transactionProcessingStrategyId\n" + + "An enumeration that indicates the type of transaction processing strategy to be used. This relates to functionality that is also known as Payment Application Logic.\n" + + "A number of out of the box approaches exist, some are custom to specific MFIs, some are more general and indicate the order in which payments are processed.\n" + + "\n" + + "Refer to the Payment Application Logic / Transaction Processing Strategy section in the appendix for more detailed overview of each available payment application logic provided out of the box.\n" + + "\n" + "List of current approaches:\n" + "1 = Mifos style (Similar to Old Mifos)\n" + + "2 = Heavensfamily (Custom MFI approach)\n" + "3 = Creocore (Custom MFI approach)\n" + "4 = RBI (India)\n" + + "5 = Principal Interest Penalties Fees Order\n" + "6 = Interest Principal Penalties Fees Order\n" + + "7 = Early Payment Strategy\n" + "graceOnPrincipalPayment\n" + + "Optional: Integer - represents the number of repayment periods that grace should apply to the principal component of a repayment period.\n" + + "graceOnInterestPayment\n" + + "Optional: Integer - represents the number of repayment periods that grace should apply to the interest component of a repayment period. Interest is still calculated but offset to later repayment periods.\n" + + "graceOnInterestCharged\n" + + "Optional: Integer - represents the number of repayment periods that should be interest-free.\n" + + "graceOnArrearsAgeing\n" + + "Optional: Integer - Used in Arrears calculation to only take into account loans that are more than graceOnArrearsAgeing days overdue.\n" + + "overdueDaysForNPA\n" + + "Optional: Integer - represents the maximum number of days a Loan may be overdue before being classified as a NPA (non performing asset)\n" + + "accountMovesOutOfNPAOnlyOnArrearsCompletion\n" + + "Optional: Boolean - if provided as true, Loan Account moves out of NPA state only when all arrears are cleared\n" + + "accountingRule\n" + + "Specifies if accounting is enabled for the particular product and the type of the accounting rule to be used Example Values:1=NONE, 2=CASH_BASED, 3=ACCRUAL_PERIODIC, 4=ACCRUAL_UPFRONT\n" + + "isInterestRecalculationEnabled\n" + + "It is a flag, Used to denote whether interest recalculation is enabled or disabled for the particular product\n" + + "daysInYearType\n" + "Specifies the number of days in a year. \n" + + "Example Values:1=ACTUAL(Actual number of days in year), 360=360 DAYS, 364=364 DAYS(52 WEEKS), 365=365 DAYS\n" + + "daysInMonthType\n" + "Specifies the number of days in a month. \n" + + "Example Values:1=ACTUAL(Actual number of days in month), 30=30 DAYS\n" + "interestRecalculationCompoundingMethod\n" + + "Specifies which amount portion should be added to principal for interest recalculation. \n" + + "Example Values:0=NONE(Only on principal), 1=INTEREST(Principal+Interest), 2=FEE(Principal+Fee), 3=FEE And INTEREST (Principal+Fee+Interest)\n" + + "rescheduleStrategyMethod\n" + "Specifies what action should perform on loan repayment schedule for advance payments. \n" + + "Example Values:1=Reschedule next repayments, 2=Reduce number of installments, 3=Reduce EMI amount\n" + + "recalculationCompoundingFrequencyType\n" + + "Specifies effective date from which the compounding of interest or fee amounts will be considered in recalculation on late payment.\n" + + "Example Values:1=Same as repayment period, 2=Daily, 3=Weekly, 4=Monthly\n" + + "recalculationCompoundingFrequencyInterval\n" + "Specifies compounding frequency interval for interest recalculation.\n" + + "recalculationCompoundingFrequencyDate\n" + "Specifies compounding frequency start date for interest recalculation.\n" + + "recalculationRestFrequencyType\n" + + "Specifies effective date from which the late or advanced payment amounts will be considered in recalculation.\n" + + "Example Values:1=Same as repayment period, 2=Daily, 3=Weekly, 4=Monthly\n" + "recalculationRestFrequencyInterval\n" + + "Specifies rest frequency interval for interest recalculation.\n" + "recalculationRestFrequencyDate\n" + + "Specifies rest frequency start date for interest recalculation.\n" + "preClosureInterestCalculationStrategy\n" + + "Specifies applicable days for interest calculation on pre closure of a loan.\n" + + "Example Values:1=Calculate till pre closure date, 2=Calculate till rest frequency date\n" + + "isArrearsBasedOnOriginalSchedule\n" + "If Specified as true, arrears will be identified based on original schedule.\n" + + "allowAttributeOverrides\n" + "Specifies if select attributes may be overridden for individual loan accounts.") }) public class SelfLoanProductsApiResource { private final LoanProductsApiResource loanProductsApiResource; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfSavingsProductsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfSavingsProductsApiResource.java index e1968da2b..6d6c6ed12 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfSavingsProductsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfSavingsProductsApiResource.java @@ -54,8 +54,7 @@ public class SelfSavingsProductsApiResource { @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveAll(@QueryParam(SavingsApiConstants.clientIdParamName) final Long clientId, - @Context final UriInfo uriInfo) { + public String retrieveAll(@QueryParam(SavingsApiConstants.clientIdParamName) final Long clientId, @Context final UriInfo uriInfo) { this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); return this.savingsProductsApiResource.retrieveAll(uriInfo); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfShareProductsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfShareProductsApiResource.java index 0c89fe321..78013fef6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfShareProductsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/products/api/SelfShareProductsApiResource.java @@ -56,8 +56,7 @@ public class SelfShareProductsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveProduct(@QueryParam(ShareAccountApiConstants.clientid_paramname) final Long clientId, - @PathParam("productId") final Long productId, @PathParam("type") final String productType, - @Context final UriInfo uriInfo) { + @PathParam("productId") final Long productId, @PathParam("type") final String productType, @Context final UriInfo uriInfo) { this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); return this.productsApiResource.retrieveProduct(productId, ShareAccountApiConstants.shareEntityType, uriInfo); @@ -67,11 +66,9 @@ public class SelfShareProductsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAllProducts(@QueryParam(ShareAccountApiConstants.clientid_paramname) final Long clientId, - @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, - @Context final UriInfo uriInfo) { + @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, @Context final UriInfo uriInfo) { this.appUserClientMapperReadService.validateAppuserClientsMapping(clientId); - return this.productsApiResource.retrieveAllProducts(ShareAccountApiConstants.shareEntityType, offset, limit, - uriInfo); + return this.productsApiResource.retrieveAllProducts(ShareAccountApiConstants.shareEntityType, offset, limit, uriInfo); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/SelfServiceApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/SelfServiceApiConstants.java index 7a2542f1b..3b5c4d6ff 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/SelfServiceApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/SelfServiceApiConstants.java @@ -38,14 +38,12 @@ public class SelfServiceApiConstants { public static final String mobileModeParamName = "mobile"; public static final String requestIdParamName = "requestId"; public static final String createRequestSuccessMessage = "Self service request created."; - public static final Set REGISTRATION_REQUEST_DATA_PARAMETERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(usernameParamName, accountNumberParamName, - passwordParamName, firstNameParamName, mobileNumberParamName, lastNameParamName, emailParamName, - authenticationModeParamName))); - public static final Set CREATE_USER_REQUEST_DATA_PARAMETERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(requestIdParamName, - authenticationTokenParamName))); - public static final Object[] SUPPORTED_AUTHENTICATION_MODE_PARAMETERS = new Object[] {emailModeParamName, mobileModeParamName}; + public static final Set REGISTRATION_REQUEST_DATA_PARAMETERS = Collections + .unmodifiableSet(new HashSet<>(Arrays.asList(usernameParamName, accountNumberParamName, passwordParamName, firstNameParamName, + mobileNumberParamName, lastNameParamName, emailParamName, authenticationModeParamName))); + public static final Set CREATE_USER_REQUEST_DATA_PARAMETERS = Collections + .unmodifiableSet(new HashSet<>(Arrays.asList(requestIdParamName, authenticationTokenParamName))); + public static final Object[] SUPPORTED_AUTHENTICATION_MODE_PARAMETERS = new Object[] { emailModeParamName, mobileModeParamName }; public static final String SELF_SERVICE_USER_ROLE = "Self Service User"; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/api/SelfServiceRegistrationApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/api/SelfServiceRegistrationApiResource.java index 1cf01e984..9ce4e1074 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/api/SelfServiceRegistrationApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/api/SelfServiceRegistrationApiResource.java @@ -38,18 +38,15 @@ import org.springframework.stereotype.Component; @Path("/self/registration") @Component @Scope("singleton") -@Api(tags = {"Self Service Registration"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self Service Registration", description = "") -}) +@Api(tags = { "Self Service Registration" }) +@SwaggerDefinition(tags = { @Tag(name = "Self Service Registration", description = "") }) public class SelfServiceRegistrationApiResource { private final SelfServiceRegistrationWritePlatformService selfServiceRegistrationWritePlatformService; private final DefaultToApiJsonSerializer toApiJsonSerializer; @Autowired - public SelfServiceRegistrationApiResource( - final SelfServiceRegistrationWritePlatformService selfServiceRegistrationWritePlatformService, + public SelfServiceRegistrationApiResource(final SelfServiceRegistrationWritePlatformService selfServiceRegistrationWritePlatformService, final DefaultToApiJsonSerializer toApiJsonSerializer) { this.selfServiceRegistrationWritePlatformService = selfServiceRegistrationWritePlatformService; this.toApiJsonSerializer = toApiJsonSerializer; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/domain/SelfServiceRegistrationRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/domain/SelfServiceRegistrationRepository.java index 2f9348232..45693c825 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/domain/SelfServiceRegistrationRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/domain/SelfServiceRegistrationRepository.java @@ -23,8 +23,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface SelfServiceRegistrationRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface SelfServiceRegistrationRepository + extends JpaRepository, JpaSpecificationExecutor { public static final String FIND_BY_REQUEST_AND_AUTHENTICATION_TOKEN = "select request from SelfServiceRegistration request where request.id = :id and " + "request.authenticationToken = :authenticationToken"; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/exception/SelfServiceRegistrationNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/exception/SelfServiceRegistrationNotFoundException.java index 888a827e9..4f07e68da 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/exception/SelfServiceRegistrationNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/exception/SelfServiceRegistrationNotFoundException.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc public class SelfServiceRegistrationNotFoundException extends AbstractPlatformResourceNotFoundException { public SelfServiceRegistrationNotFoundException(Long requestId, String authenticationToken) { - super("error.msg.self.service.registration.not.found", "Self service registration not found with request id : " + requestId - + " and authentication token :" + authenticationToken); + super("error.msg.self.service.registration.not.found", + "Self service registration not found with request id : " + requestId + " and authentication token :" + authenticationToken); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/service/SelfServiceRegistrationWritePlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/service/SelfServiceRegistrationWritePlatformServiceImpl.java index 2ce143c0b..2f451bd69 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/service/SelfServiceRegistrationWritePlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/registration/service/SelfServiceRegistrationWritePlatformServiceImpl.java @@ -94,7 +94,7 @@ public class SelfServiceRegistrationWritePlatformServiceImpl implements SelfServ final UserDomainService userDomainService, final GmailBackedPlatformEmailService gmailBackedPlatformEmailService, final SmsMessageRepository smsMessageRepository, SmsMessageScheduledJobService smsMessageScheduledJobService, final SmsCampaignDropdownReadPlatformService smsCampaignDropdownReadPlatformService, - final AppUserReadPlatformService appUserReadPlatformService,final RoleRepository roleRepository) { + final AppUserReadPlatformService appUserReadPlatformService, final RoleRepository roleRepository) { this.selfServiceRegistrationRepository = selfServiceRegistrationRepository; this.fromApiJsonHelper = fromApiJsonHelper; this.selfServiceRegistrationReadPlatformService = selfServiceRegistrationReadPlatformService; @@ -190,8 +190,10 @@ public class SelfServiceRegistrationWritePlatformServiceImpl implements SelfServ private void sendAuthorizationMessage(SelfServiceRegistration selfServiceRegistration) { Collection smsProviders = this.smsCampaignDropdownReadPlatformService.retrieveSmsProviders(); - if (smsProviders.isEmpty()) { throw new PlatformDataIntegrityException("error.msg.mobile.service.provider.not.available", - "Mobile service provider not available."); } + if (smsProviders.isEmpty()) { + throw new PlatformDataIntegrityException("error.msg.mobile.service.provider.not.available", + "Mobile service provider not available."); + } Long providerId = new ArrayList<>(smsProviders).get(0).getId(); final String message = "Hi " + selfServiceRegistration.getFirstName() + "," + "\n" + "To create user, please use following details \n" + "Request Id : " + selfServiceRegistration.getId() @@ -218,8 +220,8 @@ public class SelfServiceRegistrationWritePlatformServiceImpl implements SelfServ this.gmailBackedPlatformEmailService.sendDefinedEmail(emailDetail); } - private void throwExceptionIfValidationError(final List dataValidationErrors, String accountNumber, - String firstName, String lastName, String mobileNumber, boolean isEmailAuthenticationMode) { + private void throwExceptionIfValidationError(final List dataValidationErrors, String accountNumber, String firstName, + String lastName, String mobileNumber, boolean isEmailAuthenticationMode) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } boolean isClientExist = this.selfServiceRegistrationReadPlatformService.isClientExist(accountNumber, firstName, lastName, mobileNumber, isEmailAuthenticationMode); @@ -254,8 +256,8 @@ public class SelfServiceRegistrationWritePlatformServiceImpl implements SelfServ if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - SelfServiceRegistration selfServiceRegistration = this.selfServiceRegistrationRepository.getRequestByIdAndAuthenticationToken( - id, authenticationToken); + SelfServiceRegistration selfServiceRegistration = this.selfServiceRegistrationRepository + .getRequestByIdAndAuthenticationToken(id, authenticationToken); if (selfServiceRegistration == null) { throw new SelfServiceRegistrationNotFoundException(id, authenticationToken); } username = selfServiceRegistration.getUsername(); Client client = selfServiceRegistration.getClient(); @@ -265,9 +267,9 @@ public class SelfServiceRegistrationWritePlatformServiceImpl implements SelfServ authorities.add(new SimpleGrantedAuthority("DUMMY_ROLE_NOT_USED_OR_PERSISTED_TO_AVOID_EXCEPTION")); final Set allRoles = new HashSet<>(); Role role = this.roleRepository.getRoleByName(SelfServiceApiConstants.SELF_SERVICE_USER_ROLE); - if(role != null){ + if (role != null) { allRoles.add(role); - }else{ + } else { throw new RoleNotFoundException(SelfServiceApiConstants.SELF_SERVICE_USER_ROLE); } List clients = new ArrayList<>(Arrays.asList(client)); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/runreport/SelfRunReportApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/runreport/SelfRunReportApiResource.java index b0037bede..0ec3fa7d4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/runreport/SelfRunReportApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/runreport/SelfRunReportApiResource.java @@ -43,19 +43,17 @@ import org.springframework.stereotype.Component; @Path("/self/runreports") @Component @Scope("singleton") -@Api(tags = {"Self Run Report "}) +@Api(tags = { "Self Run Report " }) @SwaggerDefinition(tags = { - @Tag(name = "Self Run Report", description = "This resource allows you to run and receive output from pre-defined Apache Fineract reports.\n" + - "\n" + - "The default output is a JSON formatted \"Generic Resultset\". The Generic Resultset contains Column Heading as well as Data information. However, you can export to CSV format by simply adding \"&exportCSV=true\" to the end of your URL.\n" + - "\n" + - "If Pentaho reports have been pre-defined, they can also be run through this resource. Pentaho reports can return HTML, PDF or CSV formats.\n" + - "\n" + - "The Apache Fineract reference application uses a JQuery plugin called stretchyreporting which, itself, uses this reports resource to provide a pretty flexible reporting User Interface (UI).\n" + - "\n" + - "ARGUMENTS\n" + - "R_'parameter names' ... optional, No defaults The number and names of the parameters depend on the specific report and how it has been configured. R_officeId is an example parameter name.Note: the prefix R_ stands for ReportinggenericResultSetoptional, defaults to true If 'true' an optimised JSON format is returned suitable for tabular display of data. If 'false' a simple JSON format is returned. parameterType optional, The only valid value is 'true'. If any other value is provided the argument will be ignored Determines whether the request looks in the list of reports or the list of parameters for its data. Doesn't apply to Pentaho reports.exportCSV optional, The only valid value is 'true'. If any other value is provided the argument will be ignored Output will be delivered as a CSV file instead of JSON. Doesn't apply to Pentaho reports.output-type optional, Defaults to HTML. Valid Values are HTML, XLS, XSLX, CSV and PDF for html, Excel, Excel 2007+, CSV and PDF formats respectively.Only applies to Pentaho reports.locale optional Any valid locale Ex: en_US, en_IN, fr_FR etcOnly applies to Pentaho reports.") -}) + @Tag(name = "Self Run Report", description = "This resource allows you to run and receive output from pre-defined Apache Fineract reports.\n" + + "\n" + + "The default output is a JSON formatted \"Generic Resultset\". The Generic Resultset contains Column Heading as well as Data information. However, you can export to CSV format by simply adding \"&exportCSV=true\" to the end of your URL.\n" + + "\n" + + "If Pentaho reports have been pre-defined, they can also be run through this resource. Pentaho reports can return HTML, PDF or CSV formats.\n" + + "\n" + + "The Apache Fineract reference application uses a JQuery plugin called stretchyreporting which, itself, uses this reports resource to provide a pretty flexible reporting User Interface (UI).\n" + + "\n" + "ARGUMENTS\n" + + "R_'parameter names' ... optional, No defaults The number and names of the parameters depend on the specific report and how it has been configured. R_officeId is an example parameter name.Note: the prefix R_ stands for ReportinggenericResultSetoptional, defaults to true If 'true' an optimised JSON format is returned suitable for tabular display of data. If 'false' a simple JSON format is returned. parameterType optional, The only valid value is 'true'. If any other value is provided the argument will be ignored Determines whether the request looks in the list of reports or the list of parameters for its data. Doesn't apply to Pentaho reports.exportCSV optional, The only valid value is 'true'. If any other value is provided the argument will be ignored Output will be delivered as a CSV file instead of JSON. Doesn't apply to Pentaho reports.output-type optional, Defaults to HTML. Valid Values are HTML, XLS, XSLX, CSV and PDF for html, Excel, Excel 2007+, CSV and PDF formats respectively.Only applies to Pentaho reports.locale optional Any valid locale Ex: en_US, en_IN, fr_FR etcOnly applies to Pentaho reports.") }) public class SelfRunReportApiResource { private final PlatformSecurityContext context; @@ -71,10 +69,12 @@ public class SelfRunReportApiResource { @Path("{reportName}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON, "text/csv", "application/vnd.ms-excel", "application/pdf", "text/html" }) - @ApiOperation(value = "Running A Report", httpMethod = "GET", notes = "" + "Example Requests:\n" + "\n" + "\n" + "self/runreports/Client%20Details?R_officeId=1" + "\n" + "\n" + "\n" + - "self/runreports/Client%20Details?R_officeId=1&exportCSV=true") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfRunReportApiResourceSwagger.GetRunReportResponse.class)}) - public Response runReport(@PathParam("reportName") @ApiParam(value = "reportName") final String reportName, @Context final UriInfo uriInfo) { + @ApiOperation(value = "Running A Report", httpMethod = "GET", notes = "" + "Example Requests:\n" + "\n" + "\n" + + "self/runreports/Client%20Details?R_officeId=1" + "\n" + "\n" + "\n" + + "self/runreports/Client%20Details?R_officeId=1&exportCSV=true") + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = SelfRunReportApiResourceSwagger.GetRunReportResponse.class) }) + public Response runReport(@PathParam("reportName") @ApiParam(value = "reportName") final String reportName, + @Context final UriInfo uriInfo) { this.context.authenticatedUser(); final boolean isSelfServiceUserReport = true; return this.runreportsApiResource.runReport(reportName, uriInfo, isSelfServiceUserReport); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/runreport/SelfRunReportApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/runreport/SelfRunReportApiResourceSwagger.java index b8d47dc16..f81d5b405 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/runreport/SelfRunReportApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/runreport/SelfRunReportApiResourceSwagger.java @@ -22,21 +22,23 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Set; - /** * Created by Kang Breder on 07/08/19. */ final class SelfRunReportApiResourceSwagger { - private SelfRunReportApiResourceSwagger() { - } + + private SelfRunReportApiResourceSwagger() {} + @ApiModel(value = "GetRunReportResponse") public final static class GetRunReportResponse { - private GetRunReportResponse() { - } + + private GetRunReportResponse() {} + final class GetRunReportColumnHeaders { - private GetRunReportColumnHeaders() { - } + + private GetRunReportColumnHeaders() {} + @ApiModelProperty(example = "Office/Branch") public String columnName; @ApiModelProperty(example = "VARCHAR") @@ -49,15 +51,17 @@ final class SelfRunReportApiResourceSwagger { public String columnValues; } - final class GetPocketData { - private GetPocketData() { - } - @ApiModelProperty(example = "[\"Head Office\", \"000000001\", \"John Doe\" \"2017-03-04\", \"786YYH7\"") - public String row; - } + final class GetPocketData { + + private GetPocketData() {} + + @ApiModelProperty(example = "[\"Head Office\", \"000000001\", \"John Doe\" \"2017-03-04\", \"786YYH7\"") + public String row; + } + public Set columnHeaders; public Set data; - } } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/api/SelfSavingsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/api/SelfSavingsApiResource.java index ec583af4f..b55a105ea 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/api/SelfSavingsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/api/SelfSavingsApiResource.java @@ -56,10 +56,8 @@ import org.springframework.stereotype.Component; @Path("/self/savingsaccounts") @Component @Scope("singleton") -@Api(tags = {"Self Savings Account"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self Savings Account", description = "") -}) +@Api(tags = { "Self Savings Account" }) +@SwaggerDefinition(tags = { @Tag(name = "Self Savings Account", description = "") }) public class SelfSavingsApiResource { private final PlatformSecurityContext context; @@ -71,13 +69,10 @@ public class SelfSavingsApiResource { private final AppuserClientMapperReadService appUserClientMapperReadService; @Autowired - public SelfSavingsApiResource( - final PlatformSecurityContext context, - final SavingsAccountsApiResource savingsAccountsApiResource, + public SelfSavingsApiResource(final PlatformSecurityContext context, final SavingsAccountsApiResource savingsAccountsApiResource, final SavingsAccountChargesApiResource savingsAccountChargesApiResource, final SavingsAccountTransactionsApiResource savingsAccountTransactionsApiResource, - final AppuserSavingsMapperReadService appuserSavingsMapperReadService, - final SelfSavingsDataValidator dataValidator, + final AppuserSavingsMapperReadService appuserSavingsMapperReadService, final SelfSavingsDataValidator dataValidator, final AppuserClientMapperReadService appUserClientMapperReadService) { this.context = context; this.savingsAccountsApiResource = savingsAccountsApiResource; @@ -92,10 +87,11 @@ public class SelfSavingsApiResource { @Path("{accountId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a savings account", httpMethod = "GET", notes = "Retrieves a savings account\n\n" + "Example Requests :\n" + "\n" + "self/savingsaccounts/1\n" + "\n" + "\n" + "self/savingsaccounts/1?associations=transactions") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfSavingsApiResourceSwagger.GetSelfSavingsAccountsResponse.class)}) - public String retrieveSavings( - @PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @ApiOperation(value = "Retrieve a savings account", httpMethod = "GET", notes = "Retrieves a savings account\n\n" + + "Example Requests :\n" + "\n" + "self/savingsaccounts/1\n" + "\n" + "\n" + "self/savingsaccounts/1?associations=transactions") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfSavingsApiResourceSwagger.GetSelfSavingsAccountsResponse.class) }) + public String retrieveSavings(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, @Context final UriInfo uriInfo) { @@ -104,92 +100,87 @@ public class SelfSavingsApiResource { validateAppuserSavingsAccountMapping(accountId); final boolean staffInSelectedOfficeOnly = false; - return this.savingsAccountsApiResource.retrieveOne(accountId, - staffInSelectedOfficeOnly, chargeStatus, uriInfo); + return this.savingsAccountsApiResource.retrieveOne(accountId, staffInSelectedOfficeOnly, chargeStatus, uriInfo); } @GET @Path("{accountId}/transactions/{transactionId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Savings Account Transaction", httpMethod = "GET", notes = "Retrieves Savings Account Transaction\n\n" + "Example Requests:\n" + "\n" + "self/savingsaccounts/1/transactions/1") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfSavingsApiResourceSwagger.GetSelfSavingsAccountsAccountIdTransactionsTransactionIdResponse.class)}) - public String retrieveSavingsTransaction( - @PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, - @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, - @Context final UriInfo uriInfo) { + @ApiOperation(value = "Retrieve Savings Account Transaction", httpMethod = "GET", notes = "Retrieves Savings Account Transaction\n\n" + + "Example Requests:\n" + "\n" + "self/savingsaccounts/1/transactions/1") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfSavingsApiResourceSwagger.GetSelfSavingsAccountsAccountIdTransactionsTransactionIdResponse.class) }) + public String retrieveSavingsTransaction(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @PathParam("transactionId") @ApiParam(value = "transactionId") final Long transactionId, @Context final UriInfo uriInfo) { this.dataValidator.validateRetrieveSavingsTransaction(uriInfo); validateAppuserSavingsAccountMapping(accountId); - return this.savingsAccountTransactionsApiResource.retrieveOne( - accountId, transactionId, uriInfo); + return this.savingsAccountTransactionsApiResource.retrieveOne(accountId, transactionId, uriInfo); } @GET @Path("{accountId}/charges") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "List Savings Charges", httpMethod = "GET", notes = "Lists Savings Charges\n\n" + "Example Requests:\n" + "\n" + "self/savingsaccounts/1/charges\n" + "\n" + "self/savingsaccounts/1/charges?chargeStatus=inactive\n" + "\n" + "self/savingsaccounts/1/charges?fields=name,amountOrPercentage") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfSavingsApiResourceSwagger.GetSelfSavingsAccountsAccountIdChargesResponse.class, responseContainer = "List")}) - public String retrieveAllSavingsAccountCharges( - @PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @ApiOperation(value = "List Savings Charges", httpMethod = "GET", notes = "Lists Savings Charges\n\n" + "Example Requests:\n" + "\n" + + "self/savingsaccounts/1/charges\n" + "\n" + "self/savingsaccounts/1/charges?chargeStatus=inactive\n" + "\n" + + "self/savingsaccounts/1/charges?fields=name,amountOrPercentage") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfSavingsApiResourceSwagger.GetSelfSavingsAccountsAccountIdChargesResponse.class, responseContainer = "List") }) + public String retrieveAllSavingsAccountCharges(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @DefaultValue("all") @QueryParam("chargeStatus") @ApiParam(value = "chargeStatus") final String chargeStatus, @Context final UriInfo uriInfo) { validateAppuserSavingsAccountMapping(accountId); - return this.savingsAccountChargesApiResource - .retrieveAllSavingsAccountCharges(accountId, chargeStatus, - uriInfo); + return this.savingsAccountChargesApiResource.retrieveAllSavingsAccountCharges(accountId, chargeStatus, uriInfo); } @GET @Path("{accountId}/charges/{savingsAccountChargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a Savings account Charge", httpMethod = "GET", notes = "Retrieves a Savings account Charge\n\n" + "Example Requests:\n" + "\n" + "self/savingsaccounts/1/charges/5\n" + "\n" + "\n" + "self/savingsaccounts/1/charges/5?fields=name,amountOrPercentage") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfSavingsApiResourceSwagger.GetSelfSavingsAccountsAccountIdChargesSavingsAccountChargeIdResponse.class)}) - public String retrieveSavingsAccountCharge( - @PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, + @ApiOperation(value = "Retrieve a Savings account Charge", httpMethod = "GET", notes = "Retrieves a Savings account Charge\n\n" + + "Example Requests:\n" + "\n" + "self/savingsaccounts/1/charges/5\n" + "\n" + "\n" + + "self/savingsaccounts/1/charges/5?fields=name,amountOrPercentage") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfSavingsApiResourceSwagger.GetSelfSavingsAccountsAccountIdChargesSavingsAccountChargeIdResponse.class) }) + public String retrieveSavingsAccountCharge(@PathParam("accountId") @ApiParam(value = "accountId") final Long accountId, @PathParam("savingsAccountChargeId") @ApiParam(value = "savingsAccountChargeId") final Long savingsAccountChargeId, @Context final UriInfo uriInfo) { validateAppuserSavingsAccountMapping(accountId); - return this.savingsAccountChargesApiResource - .retrieveSavingsAccountCharge(accountId, - savingsAccountChargeId, uriInfo); + return this.savingsAccountChargesApiResource.retrieveSavingsAccountCharge(accountId, savingsAccountChargeId, uriInfo); } private void validateAppuserSavingsAccountMapping(final Long accountId) { AppUser user = this.context.authenticatedUser(); - final boolean isMappedSavings = this.appuserSavingsMapperReadService - .isSavingsMappedToUser(accountId, user.getId()); - if (!isMappedSavings) { - throw new SavingsAccountNotFoundException(accountId); - } + final boolean isMappedSavings = this.appuserSavingsMapperReadService.isSavingsMappedToUser(accountId, user.getId()); + if (!isMappedSavings) { throw new SavingsAccountNotFoundException(accountId); } } @GET @Path("template") @Produces({ MediaType.APPLICATION_JSON }) - public String template(@QueryParam("clientId") final Long clientId, @QueryParam("productId") final Long productId, @Context final UriInfo uriInfo) { + public String template(@QueryParam("clientId") final Long clientId, @QueryParam("productId") final Long productId, + @Context final UriInfo uriInfo) { validateAppuserClientsMapping(clientId); Long groupId = null; boolean staffInSelectedOfficeOnly = false; - return this.savingsAccountsApiResource.template(clientId, groupId, productId, staffInSelectedOfficeOnly, - uriInfo); + return this.savingsAccountsApiResource.template(clientId, groupId, productId, staffInSelectedOfficeOnly, uriInfo); } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String submitSavingsAccountApplication(@QueryParam("command") final String commandParam, - @Context final UriInfo uriInfo, final String apiRequestBodyAsJson) { + public String submitSavingsAccountApplication(@QueryParam("command") final String commandParam, @Context final UriInfo uriInfo, + final String apiRequestBodyAsJson) { HashMap parameterMap = this.dataValidator.validateSavingsApplication(apiRequestBodyAsJson); final Long clientId = (Long) parameterMap.get(SelfSavingsAccountConstants.clientIdParameterName); @@ -212,9 +203,7 @@ public class SelfSavingsApiResource { private void validateAppuserClientsMapping(final Long clientId) { AppUser user = this.context.authenticatedUser(); final boolean mappedClientId = this.appUserClientMapperReadService.isClientMappedToUser(clientId, user.getId()); - if (!mappedClientId) { - throw new ClientNotFoundException(clientId); - } + if (!mappedClientId) { throw new ClientNotFoundException(clientId); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/api/SelfSavingsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/api/SelfSavingsApiResourceSwagger.java index 1e844b4c3..451aa559f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/api/SelfSavingsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/api/SelfSavingsApiResourceSwagger.java @@ -26,17 +26,17 @@ import java.time.LocalDate; * Created by Chirag Gupta on 12/25/17. */ final class SelfSavingsApiResourceSwagger { - private SelfSavingsApiResourceSwagger() { - } + + private SelfSavingsApiResourceSwagger() {} @ApiModel(value = "GetSelfSavingsAccountsResponse") public final static class GetSelfSavingsAccountsResponse { - private GetSelfSavingsAccountsResponse() { - } + + private GetSelfSavingsAccountsResponse() {} final class GetSelfSavingsStatus { - private GetSelfSavingsStatus() { - } + + private GetSelfSavingsStatus() {} @ApiModelProperty(example = "100") public Integer id; @@ -60,16 +60,16 @@ final class SelfSavingsApiResourceSwagger { } final class GetSelfSavingsTimeline { - private GetSelfSavingsTimeline() { - } + + private GetSelfSavingsTimeline() {} @ApiModelProperty(example = "[2013, 3, 1]") public LocalDate submittedOnDate; } final class GetSelfSavingsCurrency { - private GetSelfSavingsCurrency() { - } + + private GetSelfSavingsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -86,8 +86,8 @@ final class SelfSavingsApiResourceSwagger { } final class GetSelfSavingsInterestCompoundingPeriodType { - private GetSelfSavingsInterestCompoundingPeriodType() { - } + + private GetSelfSavingsInterestCompoundingPeriodType() {} @ApiModelProperty(example = "1") public Integer id; @@ -98,8 +98,8 @@ final class SelfSavingsApiResourceSwagger { } final class GetSelfSavingsInterestPostingPeriodType { - private GetSelfSavingsInterestPostingPeriodType() { - } + + private GetSelfSavingsInterestPostingPeriodType() {} @ApiModelProperty(example = "4") public Integer id; @@ -110,8 +110,8 @@ final class SelfSavingsApiResourceSwagger { } final class GetSelfSavingsInterestCalculationType { - private GetSelfSavingsInterestCalculationType() { - } + + private GetSelfSavingsInterestCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -122,8 +122,8 @@ final class SelfSavingsApiResourceSwagger { } final class GetSelfSavingsInterestCalculationDaysInYearType { - private GetSelfSavingsInterestCalculationDaysInYearType() { - } + + private GetSelfSavingsInterestCalculationDaysInYearType() {} @ApiModelProperty(example = "365") public Integer id; @@ -134,8 +134,8 @@ final class SelfSavingsApiResourceSwagger { } final class GetSelfSavingsSummary { - private GetSelfSavingsSummary() { - } + + private GetSelfSavingsSummary() {} public GetSelfSavingsCurrency currency; @ApiModelProperty(example = "0") @@ -170,12 +170,12 @@ final class SelfSavingsApiResourceSwagger { @ApiModel(value = "GetSelfSavingsAccountsAccountIdTransactionsTransactionIdResponse") public final static class GetSelfSavingsAccountsAccountIdTransactionsTransactionIdResponse { - private GetSelfSavingsAccountsAccountIdTransactionsTransactionIdResponse() { - } + + private GetSelfSavingsAccountsAccountIdTransactionsTransactionIdResponse() {} final class GetSelfSavingsTransactionType { - private GetSelfSavingsTransactionType() { - } + + private GetSelfSavingsTransactionType() {} @ApiModelProperty(example = "2") public Integer id; @@ -194,8 +194,8 @@ final class SelfSavingsApiResourceSwagger { } final class GetSelfSavingsTransactionCurrency { - private GetSelfSavingsTransactionCurrency() { - } + + private GetSelfSavingsTransactionCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -214,12 +214,12 @@ final class SelfSavingsApiResourceSwagger { } final class GetSelfSavingsPaymentDetailData { - private GetSelfSavingsPaymentDetailData() { - } + + private GetSelfSavingsPaymentDetailData() {} final class GetSelfSavingsPaymentType { - private GetSelfSavingsPaymentType() { - } + + private GetSelfSavingsPaymentType() {} @ApiModelProperty(example = "11") public Integer id; @@ -263,12 +263,12 @@ final class SelfSavingsApiResourceSwagger { @ApiModel(value = "GetSelfSavingsAccountsAccountIdChargesResponse") public final static class GetSelfSavingsAccountsAccountIdChargesResponse { - private GetSelfSavingsAccountsAccountIdChargesResponse() { - } + + private GetSelfSavingsAccountsAccountIdChargesResponse() {} final class GetSelfSavingsChargeTimeType { - private GetSelfSavingsChargeTimeType() { - } + + private GetSelfSavingsChargeTimeType() {} @ApiModelProperty(example = "1") public Integer id; @@ -279,8 +279,8 @@ final class SelfSavingsApiResourceSwagger { } final class GetSelfSavingsChargeCalculationType { - private GetSelfSavingsChargeCalculationType() { - } + + private GetSelfSavingsChargeCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -323,8 +323,8 @@ final class SelfSavingsApiResourceSwagger { @ApiModel(value = "GetSelfSavingsAccountsAccountIdChargesSavingsAccountChargeIdResponse") public final static class GetSelfSavingsAccountsAccountIdChargesSavingsAccountChargeIdResponse { - private GetSelfSavingsAccountsAccountIdChargesSavingsAccountChargeIdResponse() { - } + + private GetSelfSavingsAccountsAccountIdChargesSavingsAccountChargeIdResponse() {} @ApiModelProperty(example = "1") public Integer id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/data/SelfSavingsDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/data/SelfSavingsDataValidator.java index ac0aeb272..28bd16265 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/data/SelfSavingsDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/data/SelfSavingsDataValidator.java @@ -41,82 +41,74 @@ import org.springframework.stereotype.Component; @Component public class SelfSavingsDataValidator { - private final FromJsonHelper fromApiJsonHelper; + private final FromJsonHelper fromApiJsonHelper; - @Autowired - public SelfSavingsDataValidator(final FromJsonHelper fromApiJsonHelper) { - this.fromApiJsonHelper = fromApiJsonHelper; - } + @Autowired + public SelfSavingsDataValidator(final FromJsonHelper fromApiJsonHelper) { + this.fromApiJsonHelper = fromApiJsonHelper; + } - private static final Set allowedAssociationParameters = new HashSet<>( - Arrays.asList(SavingsApiConstants.transactions, SavingsApiConstants.charges)); + private static final Set allowedAssociationParameters = new HashSet<>( + Arrays.asList(SavingsApiConstants.transactions, SavingsApiConstants.charges)); - public void validateRetrieveSavings(final UriInfo uriInfo) { - List unsupportedParams = new ArrayList<>(); + public void validateRetrieveSavings(final UriInfo uriInfo) { + List unsupportedParams = new ArrayList<>(); - validateTemplate(uriInfo, unsupportedParams); + validateTemplate(uriInfo, unsupportedParams); - Set associationParameters = ApiParameterHelper - .extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); - if (!associationParameters.isEmpty()) { - associationParameters.removeAll(allowedAssociationParameters); - if (!associationParameters.isEmpty()) { - unsupportedParams.addAll(associationParameters); - } - } + Set associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); + if (!associationParameters.isEmpty()) { + associationParameters.removeAll(allowedAssociationParameters); + if (!associationParameters.isEmpty()) { + unsupportedParams.addAll(associationParameters); + } + } - if (uriInfo.getQueryParameters().getFirst("exclude") != null) { - unsupportedParams.add("exclude"); - } + if (uriInfo.getQueryParameters().getFirst("exclude") != null) { + unsupportedParams.add("exclude"); + } - throwExceptionIfReqd(unsupportedParams); - } + throwExceptionIfReqd(unsupportedParams); + } - public void validateRetrieveSavingsTransaction(final UriInfo uriInfo) { - List unsupportedParams = new ArrayList<>(); + public void validateRetrieveSavingsTransaction(final UriInfo uriInfo) { + List unsupportedParams = new ArrayList<>(); - validateTemplate(uriInfo, unsupportedParams); + validateTemplate(uriInfo, unsupportedParams); - throwExceptionIfReqd(unsupportedParams); - } + throwExceptionIfReqd(unsupportedParams); + } - private void throwExceptionIfReqd(final List unsupportedParams) { - if (unsupportedParams.size() > 0) { - throw new UnsupportedParameterException(unsupportedParams); - } - } + private void throwExceptionIfReqd(final List unsupportedParams) { + if (unsupportedParams.size() > 0) { throw new UnsupportedParameterException(unsupportedParams); } + } - private void validateTemplate(final UriInfo uriInfo, List unsupportedParams) { - final boolean templateRequest = ApiParameterHelper.template(uriInfo.getQueryParameters()); - if (templateRequest) { - unsupportedParams.add("template"); - } - } + private void validateTemplate(final UriInfo uriInfo, List unsupportedParams) { + final boolean templateRequest = ApiParameterHelper.template(uriInfo.getQueryParameters()); + if (templateRequest) { + unsupportedParams.add("template"); + } + } - public HashMap validateSavingsApplication(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + public HashMap validateSavingsApplication(final String json) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final List dataValidationErrors = new ArrayList<>(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource(SelfSavingsAccountConstants.savingsAccountResource); + final List dataValidationErrors = new ArrayList<>(); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(SelfSavingsAccountConstants.savingsAccountResource); - final JsonElement element = this.fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final Long clientId = this.fromApiJsonHelper.extractLongNamed(SelfSavingsAccountConstants.clientIdParameterName, - element); - baseDataValidator.reset().parameter(SelfSavingsAccountConstants.clientIdParameterName).value(clientId).notNull() - .longGreaterThanZero(); + final Long clientId = this.fromApiJsonHelper.extractLongNamed(SelfSavingsAccountConstants.clientIdParameterName, element); + baseDataValidator.reset().parameter(SelfSavingsAccountConstants.clientIdParameterName).value(clientId).notNull() + .longGreaterThanZero(); - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - HashMap parameterMap = new HashMap<>(); - parameterMap.put(SelfSavingsAccountConstants.clientIdParameterName, clientId); + HashMap parameterMap = new HashMap<>(); + parameterMap.put(SelfSavingsAccountConstants.clientIdParameterName, clientId); - return parameterMap; + return parameterMap; - } -} \ No newline at end of file + } +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/service/AppuserSavingsMapperReadServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/service/AppuserSavingsMapperReadServiceImpl.java index 87ab0b258..b9455ef4d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/service/AppuserSavingsMapperReadServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/savings/service/AppuserSavingsMapperReadServiceImpl.java @@ -24,25 +24,20 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @Service -public class AppuserSavingsMapperReadServiceImpl implements - AppuserSavingsMapperReadService { +public class AppuserSavingsMapperReadServiceImpl implements AppuserSavingsMapperReadService { private final JdbcTemplate jdbcTemplate; @Autowired - public AppuserSavingsMapperReadServiceImpl( - final RoutingDataSource dataSource) { + public AppuserSavingsMapperReadServiceImpl(final RoutingDataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override public Boolean isSavingsMappedToUser(Long savingsId, Long appUserId) { - return this.jdbcTemplate - .queryForObject( - "select case when (count(*) > 0) then true else false end " - + " from m_selfservice_user_client_mapping as m " - + " left join m_savings_account as s on s.client_id = m.client_id " - + " where s.id = ? and m.appuser_id = ? ", - new Object[] { savingsId, appUserId }, Boolean.class); + return this.jdbcTemplate.queryForObject( + "select case when (count(*) > 0) then true else false end " + " from m_selfservice_user_client_mapping as m " + + " left join m_savings_account as s on s.client_id = m.client_id " + " where s.id = ? and m.appuser_id = ? ", + new Object[] { savingsId, appUserId }, Boolean.class); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfAuthenticationApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfAuthenticationApiResource.java index 53aa45f63..8b94a6204 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfAuthenticationApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfAuthenticationApiResource.java @@ -39,23 +39,23 @@ import org.springframework.stereotype.Component; @Profile("basicauth") @Path("/self/authentication") @SwaggerDefinition(tags = { - @Tag(name = "Self Authentication", description = "Authenticates the credentials provided and returns the set roles and permissions allowed") -}) + @Tag(name = "Self Authentication", description = "Authenticates the credentials provided and returns the set roles and permissions allowed") }) public class SelfAuthenticationApiResource { private final AuthenticationApiResource authenticationApiResource; @Autowired - public SelfAuthenticationApiResource( - final AuthenticationApiResource authenticationApiResource) { + public SelfAuthenticationApiResource(final AuthenticationApiResource authenticationApiResource) { this.authenticationApiResource = authenticationApiResource; } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Verify authentication", httpMethod = "POST", notes = "Authenticates the credentials provided and returns the set roles and permissions allowed.\n\n" + "Please visit this link for more info - https://demo.fineract.dev/fineract-provider/api-docs/apiLive.htm#selfbasicauth") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfAuthenticationApiResourceSwagger.PostSelfAuthenticationResponse.class)}) + @ApiOperation(value = "Verify authentication", httpMethod = "POST", notes = "Authenticates the credentials provided and returns the set roles and permissions allowed.\n\n" + + "Please visit this link for more info - https://demo.fineract.dev/fineract-provider/api-docs/apiLive.htm#selfbasicauth") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfAuthenticationApiResourceSwagger.PostSelfAuthenticationResponse.class) }) public String authenticate(final String apiRequestBodyAsJson) { return this.authenticationApiResource.authenticate(apiRequestBodyAsJson); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfAuthenticationApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfAuthenticationApiResourceSwagger.java index 5c3d7f70f..55623b2f8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfAuthenticationApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfAuthenticationApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/22/17. */ final class SelfAuthenticationApiResourceSwagger { - private SelfAuthenticationApiResourceSwagger() { - } + + private SelfAuthenticationApiResourceSwagger() {} @ApiModel(value = "PostSelfAuthenticationResponse") public final static class PostSelfAuthenticationResponse { - private PostSelfAuthenticationResponse() { - } + + private PostSelfAuthenticationResponse() {} final class GetSelfUserDetailsOrganisationalRole { - private GetSelfUserDetailsOrganisationalRole() { - } + + private GetSelfUserDetailsOrganisationalRole() {} @ApiModelProperty(example = "100") public Integer id; @@ -48,8 +48,8 @@ final class SelfAuthenticationApiResourceSwagger { } final class GetSelfUserDetailsRoles { - private GetSelfUserDetailsRoles() { - } + + private GetSelfUserDetailsRoles() {} @ApiModelProperty(example = "1") public Integer id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserApiResource.java index 7286e6225..bee36019d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserApiResource.java @@ -47,41 +47,37 @@ import org.springframework.stereotype.Component; @Path("/self/user") @Component -@Api(tags = {"Self User"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self User", description = "") -}) +@Api(tags = { "Self User" }) +@SwaggerDefinition(tags = { @Tag(name = "Self User", description = "") }) public class SelfUserApiResource { - private final UsersApiResource usersApiResource; - private final PlatformSecurityContext context; - private final FromJsonHelper fromApiJsonHelper; - private final Set supportedParameters = new HashSet<>(Arrays.asList("password", "repeatPassword")); + private final UsersApiResource usersApiResource; + private final PlatformSecurityContext context; + private final FromJsonHelper fromApiJsonHelper; + private final Set supportedParameters = new HashSet<>(Arrays.asList("password", "repeatPassword")); - @Autowired - public SelfUserApiResource(final UsersApiResource usersApiResource, - final PlatformSecurityContext context, - final FromJsonHelper fromApiJsonHelper){ + @Autowired + public SelfUserApiResource(final UsersApiResource usersApiResource, final PlatformSecurityContext context, + final FromJsonHelper fromApiJsonHelper) { - this.usersApiResource = usersApiResource; - this.context = context; - this.fromApiJsonHelper = fromApiJsonHelper; - } + this.usersApiResource = usersApiResource; + this.context = context; + this.fromApiJsonHelper = fromApiJsonHelper; + } - @PUT - @ApiOperation(value = "Update User", httpMethod = "PUT", notes = "This API can be used by Self Service user to update their own user information. Currently, \"password\" and \"repeatPassword\" are the only parameters accepted.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfUserApiResourceSwagger.PutSelfUserRequest.class)}) - @ApiResponses({@ApiResponse(code = 200,message = "OK", response = SelfUserApiResourceSwagger.PutSelfUserResponse.class)}) - public String update(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { - if (StringUtils.isBlank(apiRequestBodyAsJson)) { throw new InvalidJsonException(); } + @PUT + @ApiOperation(value = "Update User", httpMethod = "PUT", notes = "This API can be used by Self Service user to update their own user information. Currently, \"password\" and \"repeatPassword\" are the only parameters accepted.") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = SelfUserApiResourceSwagger.PutSelfUserRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = SelfUserApiResourceSwagger.PutSelfUserResponse.class) }) + public String update(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { + if (StringUtils.isBlank(apiRequestBodyAsJson)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, - apiRequestBodyAsJson, - this.supportedParameters); + final Type typeOfMap = new TypeToken>() {}.getType(); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, apiRequestBodyAsJson, this.supportedParameters); - final AppUser appUser = this.context.authenticatedUser(); - return this.usersApiResource.update(appUser.getId(), apiRequestBodyAsJson); - } + final AppUser appUser = this.context.authenticatedUser(); + return this.usersApiResource.update(appUser.getId(), apiRequestBodyAsJson); + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserApiResourceSwagger.java index 1a1891c8e..1460c88b9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserApiResourceSwagger.java @@ -25,13 +25,13 @@ import io.swagger.annotations.ApiModelProperty; * Created by Chirag Gupta on 12/20/17. */ final class SelfUserApiResourceSwagger { - private SelfUserApiResourceSwagger() { - } + + private SelfUserApiResourceSwagger() {} @ApiModel(value = "PutSelfUserRequest") public final static class PutSelfUserRequest { - private PutSelfUserRequest() { - } + + private PutSelfUserRequest() {} @ApiModelProperty(example = "Abcd1234") public String password; @@ -41,12 +41,12 @@ final class SelfUserApiResourceSwagger { @ApiModel(value = "PutSelfUserResponse") public final static class PutSelfUserResponse { - private PutSelfUserResponse() { - } + + private PutSelfUserResponse() {} final class PutSelfUserChanges { - private PutSelfUserChanges() { - } + + private PutSelfUserChanges() {} @ApiModelProperty(example = "6a72a630795be86fe926ce540fc45b6b922fe5ba130f185fe806a26b5e5efcdd") public String passwordEncoded; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserDetailsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserDetailsApiResource.java index c4dd6710a..8b81cd543 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserDetailsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserDetailsApiResource.java @@ -40,27 +40,24 @@ import org.springframework.stereotype.Component; @Component @Profile("oauth") @Scope("singleton") -@Api(tags = {"Self User Details"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self User Details", description = "") -}) +@Api(tags = { "Self User Details" }) +@SwaggerDefinition(tags = { @Tag(name = "Self User Details", description = "") }) public class SelfUserDetailsApiResource { private final UserDetailsApiResource userDetailsApiResource; @Autowired - public SelfUserDetailsApiResource( - final UserDetailsApiResource userDetailsApiResource) { + public SelfUserDetailsApiResource(final UserDetailsApiResource userDetailsApiResource) { this.userDetailsApiResource = userDetailsApiResource; } @GET @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Fetch authenticated user details", httpMethod = "GET", notes = "Checks the Authentication and returns the set roles and permissions allowed\n\n" + "For more info visit this link - https://demo.fineract.dev/fineract-provider/api-docs/apiLive.htm#selfoauth") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = SelfUserDetailsApiResourceSwagger.GetSelfUserDetailsResponse.class)}) - public String fetchAuthenticatedUserData( - @QueryParam("access_token") @ApiParam(value = "äccess_token") final String accessToken) { - return this.userDetailsApiResource - .fetchAuthenticatedUserData(accessToken); + @ApiOperation(value = "Fetch authenticated user details", httpMethod = "GET", notes = "Checks the Authentication and returns the set roles and permissions allowed\n\n" + + "For more info visit this link - https://demo.fineract.dev/fineract-provider/api-docs/apiLive.htm#selfoauth") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = SelfUserDetailsApiResourceSwagger.GetSelfUserDetailsResponse.class) }) + public String fetchAuthenticatedUserData(@QueryParam("access_token") @ApiParam(value = "äccess_token") final String accessToken) { + return this.userDetailsApiResource.fetchAuthenticatedUserData(accessToken); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserDetailsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserDetailsApiResourceSwagger.java index 8539f782f..8dd9c8c78 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserDetailsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfUserDetailsApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/20/17. */ final class SelfUserDetailsApiResourceSwagger { - private SelfUserDetailsApiResourceSwagger() { - } + + private SelfUserDetailsApiResourceSwagger() {} @ApiModel(value = "GetSelfUserDetailsResponse") public final static class GetSelfUserDetailsResponse { - private GetSelfUserDetailsResponse() { - } + + private GetSelfUserDetailsResponse() {} final class GetSelfUserDetailsOrganisationalRole { - private GetSelfUserDetailsOrganisationalRole() { - } + + private GetSelfUserDetailsOrganisationalRole() {} @ApiModelProperty(example = "100") public Integer id; @@ -48,8 +48,8 @@ final class SelfUserDetailsApiResourceSwagger { } final class GetSelfUserDetailsRoles { - private GetSelfUserDetailsRoles() { - } + + private GetSelfUserDetailsRoles() {} @ApiModelProperty(example = "1") public Integer id; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/api/SelfShareAccountsApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/api/SelfShareAccountsApiResource.java index a27c440e3..7561da257 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/api/SelfShareAccountsApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/api/SelfShareAccountsApiResource.java @@ -62,126 +62,123 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; - @Path("/self/shareaccounts") @Component @Scope("singleton") -@Api(tags = {"Self Share Accounts"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self Share Accounts", description = "") -}) +@Api(tags = { "Self Share Accounts" }) +@SwaggerDefinition(tags = { @Tag(name = "Self Share Accounts", description = "") }) public class SelfShareAccountsApiResource { - private final PlatformSecurityContext context; - private final AccountsApiResource accountsApiResource; - private final ShareAccountReadPlatformService readPlatformService; - private final ApiRequestParameterHelper apiRequestParameterHelper; + private final PlatformSecurityContext context; + private final AccountsApiResource accountsApiResource; + private final ShareAccountReadPlatformService readPlatformService; + private final ApiRequestParameterHelper apiRequestParameterHelper; - private final DefaultToApiJsonSerializer toApiJsonSerializer; - private final AppuserClientMapperReadService appuserClientMapperReadService; - private final SelfShareAccountsDataValidator selfShareAccountsDataValidator; - private final ProductReadPlatformService productReadPlatformService; - private final ChargeReadPlatformService chargeReadPlatformService; - private final AppUserShareAccountsMapperReadPlatformService appUserShareAccountsMapperReadPlatformService; + private final DefaultToApiJsonSerializer toApiJsonSerializer; + private final AppuserClientMapperReadService appuserClientMapperReadService; + private final SelfShareAccountsDataValidator selfShareAccountsDataValidator; + private final ProductReadPlatformService productReadPlatformService; + private final ChargeReadPlatformService chargeReadPlatformService; + private final AppUserShareAccountsMapperReadPlatformService appUserShareAccountsMapperReadPlatformService; - @Autowired - public SelfShareAccountsApiResource(final PlatformSecurityContext context, - final AccountsApiResource accountsApiResource, final ShareAccountReadPlatformService readPlatformService, - final DefaultToApiJsonSerializer toApiJsonSerializer, - final ApiRequestParameterHelper apiRequestParameterHelper, - final AppuserClientMapperReadService appuserClientMapperReadService, - final SelfShareAccountsDataValidator selfShareAccountsDataValidator, - final ProductReadPlatformService productReadPlatformService, - final ChargeReadPlatformService chargeReadPlatformService, - final AppUserShareAccountsMapperReadPlatformService appUserShareAccountsMapperReadPlatformService) { - this.context = context; - this.accountsApiResource = accountsApiResource; - this.readPlatformService = readPlatformService; - this.toApiJsonSerializer = toApiJsonSerializer; - this.apiRequestParameterHelper = apiRequestParameterHelper; - this.selfShareAccountsDataValidator = selfShareAccountsDataValidator; - this.appuserClientMapperReadService = appuserClientMapperReadService; - this.productReadPlatformService = productReadPlatformService; - this.chargeReadPlatformService = chargeReadPlatformService; - this.appUserShareAccountsMapperReadPlatformService = appUserShareAccountsMapperReadPlatformService; - } + @Autowired + public SelfShareAccountsApiResource(final PlatformSecurityContext context, final AccountsApiResource accountsApiResource, + final ShareAccountReadPlatformService readPlatformService, final DefaultToApiJsonSerializer toApiJsonSerializer, + final ApiRequestParameterHelper apiRequestParameterHelper, final AppuserClientMapperReadService appuserClientMapperReadService, + final SelfShareAccountsDataValidator selfShareAccountsDataValidator, + final ProductReadPlatformService productReadPlatformService, final ChargeReadPlatformService chargeReadPlatformService, + final AppUserShareAccountsMapperReadPlatformService appUserShareAccountsMapperReadPlatformService) { + this.context = context; + this.accountsApiResource = accountsApiResource; + this.readPlatformService = readPlatformService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.apiRequestParameterHelper = apiRequestParameterHelper; + this.selfShareAccountsDataValidator = selfShareAccountsDataValidator; + this.appuserClientMapperReadService = appuserClientMapperReadService; + this.productReadPlatformService = productReadPlatformService; + this.chargeReadPlatformService = chargeReadPlatformService; + this.appUserShareAccountsMapperReadPlatformService = appUserShareAccountsMapperReadPlatformService; + } - @GET - @Path("template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve Share Account Template", httpMethod = "GET", notes = "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:\n" + - "Field Defaults\n" + "\n"+ - "Allowed Value Lists\n" + "\n"+ "\n"+ "Arguments\n"+ "\n"+ "clientId:Integer mandatory\n"+ "productId:Integer optionalIf entered, productId, productName and selectedProduct fields are returned.\n"+ "Example Requests:\n" + "\n" + "self/shareaccounts/template?clientId=14\n" + "\n" + - "self/shareaccounts/template?clientId=14&productId=3\n") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SelfShareAccountsApiResourceSwagger.GetShareAccountsClientIdProductIdResponse.class)}) - public String template(@QueryParam("clientId") @ApiParam("clientId") final Long clientId, @QueryParam("productId") @ApiParam("productId") final Long productId, - @Context final UriInfo uriInfo) { + @GET + @Path("template") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Retrieve Share Account Template", httpMethod = "GET", notes = "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:\n" + + "Field Defaults\n" + "\n" + "Allowed Value Lists\n" + "\n" + "\n" + "Arguments\n" + "\n" + "clientId:Integer mandatory\n" + + "productId:Integer optionalIf entered, productId, productName and selectedProduct fields are returned.\n" + + "Example Requests:\n" + "\n" + "self/shareaccounts/template?clientId=14\n" + "\n" + + "self/shareaccounts/template?clientId=14&productId=3\n") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SelfShareAccountsApiResourceSwagger.GetShareAccountsClientIdProductIdResponse.class) }) + public String template(@QueryParam("clientId") @ApiParam("clientId") final Long clientId, + @QueryParam("productId") @ApiParam("productId") final Long productId, @Context final UriInfo uriInfo) { - validateAppuserClientsMapping(clientId); + validateAppuserClientsMapping(clientId); - Collection productOptions = new ArrayList(); - if (productId != null) { - final boolean includeTemplate = true; - productOptions.add(productReadPlatformService.retrieveOne(productId, includeTemplate)); - } else { - productOptions = productReadPlatformService.retrieveAllForLookup(); - } + Collection productOptions = new ArrayList(); + if (productId != null) { + final boolean includeTemplate = true; + productOptions.add(productReadPlatformService.retrieveOne(productId, includeTemplate)); + } else { + productOptions = productReadPlatformService.retrieveAllForLookup(); + } - String clientName = null; + String clientName = null; - final Collection chargeOptions = this.chargeReadPlatformService.retrieveSharesApplicableCharges(); - final ShareAccountData accountData = new ShareAccountData(clientId, clientName, productOptions, chargeOptions); + final Collection chargeOptions = this.chargeReadPlatformService.retrieveSharesApplicableCharges(); + final ShareAccountData accountData = new ShareAccountData(clientId, clientName, productOptions, chargeOptions); - return this.toApiJsonSerializer.serialize(accountData); + return this.toApiJsonSerializer.serialize(accountData); - } + } - @POST - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Submit new share application", httpMethod = "POST", notes = "Mandatory fields:\n" + "\n" + "clientId, productId, submittedDate, savingsAccountId, requestedShares, applicationDate\n" + "\n" + "\n" + "Optional Fields\n" + "\n" + "accountNo, externalId\n" + "\n" + "\n" + "Inherited from Product (if not provided)\n" + "\n" + "minimumActivePeriod, minimumActivePeriodFrequencyType, lockinPeriodFrequency, lockinPeriodFrequencyType.") - @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SelfShareAccountsApiResourceSwagger.PostNewShareApplicationResponse.class)}) - public String createAccount(final String apiRequestBodyAsJson) { - HashMap attr = this.selfShareAccountsDataValidator - .validateShareAccountApplication(apiRequestBodyAsJson); - final Long clientId = (Long) attr.get(ShareAccountApiConstants.clientid_paramname); - validateAppuserClientsMapping(clientId); - String accountType = ShareAccountApiConstants.shareEntityType; - return this.accountsApiResource.createAccount(accountType, apiRequestBodyAsJson); - } + @POST + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Submit new share application", httpMethod = "POST", notes = "Mandatory fields:\n" + "\n" + + "clientId, productId, submittedDate, savingsAccountId, requestedShares, applicationDate\n" + "\n" + "\n" + "Optional Fields\n" + + "\n" + "accountNo, externalId\n" + "\n" + "\n" + "Inherited from Product (if not provided)\n" + "\n" + + "minimumActivePeriod, minimumActivePeriodFrequencyType, lockinPeriodFrequency, lockinPeriodFrequencyType.") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SelfShareAccountsApiResourceSwagger.PostNewShareApplicationResponse.class) }) + public String createAccount(final String apiRequestBodyAsJson) { + HashMap attr = this.selfShareAccountsDataValidator.validateShareAccountApplication(apiRequestBodyAsJson); + final Long clientId = (Long) attr.get(ShareAccountApiConstants.clientid_paramname); + validateAppuserClientsMapping(clientId); + String accountType = ShareAccountApiConstants.shareEntityType; + return this.accountsApiResource.createAccount(accountType, apiRequestBodyAsJson); + } - @GET - @Path("{accountId}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Retrieve a share application/account", httpMethod = "GET", notes = "\n" + - "\n" + "\n" + "Example Requests:\n" + "\n" + "self/shareaccounts/12\n") - // TODO actually write SelfShareAccountsApiResourceSwagger.GetShareAccountResponse (it currently does not exist) - // @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer = "List", response = SelfShareAccountsApiResourceSwagger.GetShareAccountResponse.class)}) - public String retrieveShareAccount(@PathParam("accountId") final Long accountId, @Context final UriInfo uriInfo) { - validateAppuserShareAccountMapping(accountId); - final boolean includeTemplate = false; - AccountData accountData = this.readPlatformService.retrieveOne(accountId, includeTemplate); - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, accountData, readPlatformService.getResponseDataParams()); - } + @GET + @Path("{accountId}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation(value = "Retrieve a share application/account", httpMethod = "GET", notes = "\n" + "\n" + "\n" + "Example Requests:\n" + + "\n" + "self/shareaccounts/12\n") + // TODO actually write + // SelfShareAccountsApiResourceSwagger.GetShareAccountResponse (it currently + // does not exist) + // @ApiResponses({@ApiResponse(code = 200, message = "OK", responseContainer + // = "List", response = + // SelfShareAccountsApiResourceSwagger.GetShareAccountResponse.class)}) + public String retrieveShareAccount(@PathParam("accountId") final Long accountId, @Context final UriInfo uriInfo) { + validateAppuserShareAccountMapping(accountId); + final boolean includeTemplate = false; + AccountData accountData = this.readPlatformService.retrieveOne(accountId, includeTemplate); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, accountData, readPlatformService.getResponseDataParams()); + } - private void validateAppuserShareAccountMapping(final Long accountId) { - AppUser user = this.context.authenticatedUser(); - final boolean isMapped = this.appUserShareAccountsMapperReadPlatformService - .isShareAccountsMappedToUser(accountId, user.getId()); - if (!isMapped) { - throw new ShareAccountNotFoundException(accountId); - } - } + private void validateAppuserShareAccountMapping(final Long accountId) { + AppUser user = this.context.authenticatedUser(); + final boolean isMapped = this.appUserShareAccountsMapperReadPlatformService.isShareAccountsMappedToUser(accountId, user.getId()); + if (!isMapped) { throw new ShareAccountNotFoundException(accountId); } + } - private void validateAppuserClientsMapping(final Long clientId) { - AppUser user = this.context.authenticatedUser(); - final boolean mappedClientId = this.appuserClientMapperReadService.isClientMappedToUser(clientId, user.getId()); - if (!mappedClientId) { - throw new ClientNotFoundException(clientId); - } - } + private void validateAppuserClientsMapping(final Long clientId) { + AppUser user = this.context.authenticatedUser(); + final boolean mappedClientId = this.appuserClientMapperReadService.isClientMappedToUser(clientId, user.getId()); + if (!mappedClientId) { throw new ClientNotFoundException(clientId); } + } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/api/SelfShareAccountsApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/api/SelfShareAccountsApiResourceSwagger.java index 9761d9f70..e32cbed70 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/api/SelfShareAccountsApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/api/SelfShareAccountsApiResourceSwagger.java @@ -23,24 +23,24 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Set; - /** * Created by Kang Breder on 05/08/19. */ final class SelfShareAccountsApiResourceSwagger { - private SelfShareAccountsApiResourceSwagger(){ + + private SelfShareAccountsApiResourceSwagger() { } @ApiModel(value = "GetShareAccountsClientIdResponse") public final static class GetShareAccountsClientIdResponse { - private GetShareAccountsClientIdResponse() { - } + + private GetShareAccountsClientIdResponse() {} final class GetShareAccountsProductOptions { - private GetShareAccountsProductOptions() { - } + + private GetShareAccountsProductOptions() {} @ApiModelProperty(example = "3") public Integer id; @@ -53,12 +53,12 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsChargeOptions { - private GetShareAccountsChargeOptions() { - } + + private GetShareAccountsChargeOptions() {} final class GetShareAccountsCurrency { - private GetShareAccountsCurrency() { - } + + private GetShareAccountsCurrency() {} @ApiModelProperty(example = "USD") public String code; @@ -76,8 +76,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsChargeTimeType { - private GetShareAccountsChargeTimeType() { - } + + private GetShareAccountsChargeTimeType() {} @ApiModelProperty(example = "14") public Integer id; @@ -88,8 +88,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsChargeAppliesTo { - private GetShareAccountsChargeAppliesTo() { - } + + private GetShareAccountsChargeAppliesTo() {} @ApiModelProperty(example = "4") public Integer id; @@ -100,8 +100,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsChargeCalculationType { - private GetShareAccountsChargeCalculationType() { - } + + private GetShareAccountsChargeCalculationType() {} @ApiModelProperty(example = "1") public Integer id; @@ -112,8 +112,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsChargePaymentMode { - private GetShareAccountsChargePaymentMode() { - } + + private GetShareAccountsChargePaymentMode() {} @ApiModelProperty(example = "0") public Integer id; @@ -149,16 +149,16 @@ final class SelfShareAccountsApiResourceSwagger { @ApiModel(value = "GetShareAccountsClientIdProductIdResponse") public final static class GetShareAccountsClientIdProductIdResponse { - private GetShareAccountsClientIdProductIdResponse() { - } + + private GetShareAccountsClientIdProductIdResponse() {} final class GetClientIdProductIdProductOptions { - private GetClientIdProductIdProductOptions() { - } + + private GetClientIdProductIdProductOptions() {} final class GetShareAccountsClientIdProductIdLockPeriodTypeEnum { - private GetShareAccountsClientIdProductIdLockPeriodTypeEnum() { - } + + private GetShareAccountsClientIdProductIdLockPeriodTypeEnum() {} @ApiModelProperty(example = "0") public Integer id; @@ -170,8 +170,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsClientIdProductIdMinimumActivePeriodForDividendsTypeEnum { - private GetShareAccountsClientIdProductIdMinimumActivePeriodForDividendsTypeEnum() { - } + + private GetShareAccountsClientIdProductIdMinimumActivePeriodForDividendsTypeEnum() {} @ApiModelProperty(example = "0") public Integer id; @@ -183,8 +183,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsClientIdProductIdAccountingRule { - private GetShareAccountsClientIdProductIdAccountingRule() { - } + + private GetShareAccountsClientIdProductIdAccountingRule() {} @ApiModelProperty(example = "2") public Integer id; @@ -196,12 +196,12 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetClientIdProductIdAccountingMappings { - private GetClientIdProductIdAccountingMappings() { - } + + private GetClientIdProductIdAccountingMappings() {} final class GetShareAccountsShareReferenceId { - private GetShareAccountsShareReferenceId() { - } + + private GetShareAccountsShareReferenceId() {} @ApiModelProperty(example = "32") public Integer id; @@ -213,8 +213,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsIncomeFromFeeAccountId { - private GetShareAccountsIncomeFromFeeAccountId() { - } + + private GetShareAccountsIncomeFromFeeAccountId() {} @ApiModelProperty(example = "40") public Integer id; @@ -226,8 +226,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsShareEquityId { - private GetShareAccountsShareEquityId() { - } + + private GetShareAccountsShareEquityId() {} @ApiModelProperty(example = "56") public Integer id; @@ -239,8 +239,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsShareSuspenseId { - private GetShareAccountsShareSuspenseId() { - } + + private GetShareAccountsShareSuspenseId() {} @ApiModelProperty(example = "2") public Integer id; @@ -258,8 +258,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetClientIdProductIdMinimumActivePeriodFrequencyTypeOptions { - private GetClientIdProductIdMinimumActivePeriodFrequencyTypeOptions() { - } + + private GetClientIdProductIdMinimumActivePeriodFrequencyTypeOptions() {} @ApiModelProperty(example = "0") public Integer id; @@ -271,8 +271,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetClientIdProductIdLockinPeriodFrequencyTypeOptions { - private GetClientIdProductIdLockinPeriodFrequencyTypeOptions() { - } + + private GetClientIdProductIdLockinPeriodFrequencyTypeOptions() {} @ApiModelProperty(example = "0") public Integer id; @@ -284,16 +284,16 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetAccountingMappingOptions { - private GetAccountingMappingOptions() { - } + + private GetAccountingMappingOptions() {} final class GetAccountingMappingLiabilityAccountOptions { - private GetAccountingMappingLiabilityAccountOptions() { - } + + private GetAccountingMappingLiabilityAccountOptions() {} final class GetLiabilityAccountType { - private GetLiabilityAccountType() { - } + + private GetLiabilityAccountType() {} @ApiModelProperty(example = "2") public Integer id; @@ -305,8 +305,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetLiabilityAccountUsage { - private GetLiabilityAccountUsage() { - } + + private GetLiabilityAccountUsage() {} @ApiModelProperty(example = "1") public Integer id; @@ -318,8 +318,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetLiabilityAccountTagId { - private GetLiabilityAccountTagId() { - } + + private GetLiabilityAccountTagId() {} @ApiModelProperty(example = "0") public Integer id; @@ -351,12 +351,12 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetAccountingMappingAssetAccountOptions { - private GetAccountingMappingAssetAccountOptions() { - } + + private GetAccountingMappingAssetAccountOptions() {} final class GetAssetAccountType { - private GetAssetAccountType() { - } + + private GetAssetAccountType() {} @ApiModelProperty(example = "1") public Integer id; @@ -368,8 +368,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetAssetAccountUsage { - private GetAssetAccountUsage() { - } + + private GetAssetAccountUsage() {} @ApiModelProperty(example = "1") public Integer id; @@ -381,8 +381,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetAssetAccountTagId { - private GetAssetAccountTagId() { - } + + private GetAssetAccountTagId() {} @ApiModelProperty(example = "0") public Integer id; @@ -414,12 +414,12 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetAccountingMappingIncomeAccountOptions { - private GetAccountingMappingIncomeAccountOptions() { - } + + private GetAccountingMappingIncomeAccountOptions() {} final class GetIncomeAccountType { - private GetIncomeAccountType() { - } + + private GetIncomeAccountType() {} @ApiModelProperty(example = "4") public Integer id; @@ -431,8 +431,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetIncomeAccountUsage { - private GetIncomeAccountUsage() { - } + + private GetIncomeAccountUsage() {} @ApiModelProperty(example = "1") public Integer id; @@ -444,8 +444,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetIncomeAccountTagId { - private GetIncomeAccountTagId() { - } + + private GetIncomeAccountTagId() {} @ApiModelProperty(example = "0") public Integer id; @@ -476,12 +476,12 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountAccountingMappingEquityAccountOptions { - private GetShareAccountAccountingMappingEquityAccountOptions() { - } + + private GetShareAccountAccountingMappingEquityAccountOptions() {} final class GetShareAccountsEquityAccountType { - private GetShareAccountsEquityAccountType() { - } + + private GetShareAccountsEquityAccountType() {} @ApiModelProperty(example = "3") public Integer id; @@ -493,8 +493,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsEquityAccountUsage { - private GetShareAccountsEquityAccountUsage() { - } + + private GetShareAccountsEquityAccountUsage() {} @ApiModelProperty(example = "1") public Integer id; @@ -506,8 +506,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetShareAccountsEquityAccountTagId { - private GetShareAccountsEquityAccountTagId() { - } + + private GetShareAccountsEquityAccountTagId() {} @ApiModelProperty(example = "0") public Integer id; @@ -585,8 +585,8 @@ final class SelfShareAccountsApiResourceSwagger { } final class GetClientIdProductIdChargeOptions { - private GetClientIdProductIdChargeOptions() { - } + + private GetClientIdProductIdChargeOptions() {} public GetShareAccountsClientIdResponse.GetShareAccountsChargeOptions chargeOptions; } @@ -597,12 +597,12 @@ final class SelfShareAccountsApiResourceSwagger { @ApiModel(value = "PostNewShareApplicationRequest") public final static class PostNewShareApplicationRequest { - private PostNewShareApplicationRequest() { - } + + private PostNewShareApplicationRequest() {} final class GetShareAccountsCharges { - private GetShareAccountsCharges() { - } + + private GetShareAccountsCharges() {} @ApiModelProperty(example = "2") public Integer chargeId; @@ -633,8 +633,8 @@ final class SelfShareAccountsApiResourceSwagger { @ApiModel(value = "PostNewShareApplicationResponse") public final static class PostNewShareApplicationResponse { - private PostNewShareApplicationResponse() { - } + + private PostNewShareApplicationResponse() {} @ApiModelProperty(example = "12") public Integer resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/data/SelfShareAccountsDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/data/SelfShareAccountsDataValidator.java index 61d775074..c7661f14b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/data/SelfShareAccountsDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/data/SelfShareAccountsDataValidator.java @@ -44,9 +44,7 @@ public class SelfShareAccountsDataValidator { } public HashMap validateShareAccountApplication(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -54,14 +52,10 @@ public class SelfShareAccountsDataValidator { final JsonElement element = this.fromApiJsonHelper.parse(json); - final String clientId = this.fromApiJsonHelper.extractStringNamed(ShareAccountApiConstants.clientid_paramname, - element); - baseDataValidator.reset().parameter(ShareAccountApiConstants.clientid_paramname).value(clientId).notNull() - .longGreaterThanZero(); + final String clientId = this.fromApiJsonHelper.extractStringNamed(ShareAccountApiConstants.clientid_paramname, element); + baseDataValidator.reset().parameter(ShareAccountApiConstants.clientid_paramname).value(clientId).notNull().longGreaterThanZero(); - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } HashMap retAttr = new HashMap<>(); retAttr.put(ShareAccountApiConstants.clientid_paramname, Long.parseLong(clientId)); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/service/AppUserShareAccountsMapperReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/service/AppUserShareAccountsMapperReadPlatformServiceImpl.java index b1f1bff50..a20b2f03c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/service/AppUserShareAccountsMapperReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/shareaccounts/service/AppUserShareAccountsMapperReadPlatformServiceImpl.java @@ -25,27 +25,21 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @Service -public class AppUserShareAccountsMapperReadPlatformServiceImpl - implements AppUserShareAccountsMapperReadPlatformService { - +public class AppUserShareAccountsMapperReadPlatformServiceImpl implements AppUserShareAccountsMapperReadPlatformService { private final JdbcTemplate jdbcTemplate; @Autowired - public AppUserShareAccountsMapperReadPlatformServiceImpl( - final RoutingDataSource dataSource) { + public AppUserShareAccountsMapperReadPlatformServiceImpl(final RoutingDataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override public Boolean isShareAccountsMappedToUser(Long accountId, Long appUserId) { - return this.jdbcTemplate - .queryForObject( - "select case when (count(*) > 0) then true else false end " - + " from m_selfservice_user_client_mapping as m " - + " left join m_share_account as shares on shares.client_id = m.client_id " - + " where shares.id = ? and m.appuser_id = ? ", - new Object[] { accountId, appUserId }, Boolean.class); + return this.jdbcTemplate.queryForObject("select case when (count(*) > 0) then true else false end " + + " from m_selfservice_user_client_mapping as m " + + " left join m_share_account as shares on shares.client_id = m.client_id " + " where shares.id = ? and m.appuser_id = ? ", + new Object[] { accountId, appUserId }, Boolean.class); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/spm/api/SelfScorecardApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/spm/api/SelfScorecardApiResource.java index 69c714200..46b9cd8df 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/spm/api/SelfScorecardApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/spm/api/SelfScorecardApiResource.java @@ -44,10 +44,8 @@ import org.springframework.transaction.annotation.Transactional; @Path("/self/surveys/scorecards") @Component @Scope("singleton") -@Api(tags = {"Self Score Card"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self Score Card", description = "") -}) +@Api(tags = { "Self Score Card" }) +@SwaggerDefinition(tags = { @Tag(name = "Self Score Card", description = "") }) public class SelfScorecardApiResource { private final PlatformSecurityContext context; @@ -56,8 +54,7 @@ public class SelfScorecardApiResource { @Autowired public SelfScorecardApiResource(final PlatformSecurityContext securityContext, - final AppuserClientMapperReadService appuserClientMapperReadService, - final ScorecardApiResource scorecardApiResource) { + final AppuserClientMapperReadService appuserClientMapperReadService, final ScorecardApiResource scorecardApiResource) { this.context = securityContext; this.scorecardApiResource = scorecardApiResource; this.appuserClientMapperReadService = appuserClientMapperReadService; @@ -90,9 +87,7 @@ public class SelfScorecardApiResource { private void validateAppuserClientsMapping(final Long clientId) { AppUser user = this.context.authenticatedUser(); final boolean mappedClientId = this.appuserClientMapperReadService.isClientMappedToUser(clientId, user.getId()); - if (!mappedClientId) { - throw new ClientNotFoundException(clientId); - } + if (!mappedClientId) { throw new ClientNotFoundException(clientId); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/spm/api/SelfSpmApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/spm/api/SelfSpmApiResource.java index acd464958..8222ab2c2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/spm/api/SelfSpmApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/self/spm/api/SelfSpmApiResource.java @@ -39,10 +39,8 @@ import org.springframework.transaction.annotation.Transactional; @Path("/self/surveys") @Component @Scope("singleton") -@Api(tags = {"Self Spm"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self Spm", description = "") -}) +@Api(tags = { "Self Spm" }) +@SwaggerDefinition(tags = { @Tag(name = "Self Spm", description = "") }) public class SelfSpmApiResource { private final PlatformSecurityContext securityContext; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountApplicationTimelineData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountApplicationTimelineData.java index fafdcff6c..947562292 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountApplicationTimelineData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountApplicationTimelineData.java @@ -81,10 +81,10 @@ public class ShareAccountApplicationTimelineData implements Serializable { public ShareAccountApplicationTimelineData(final LocalDate submittedOnDate, final String submittedByUsername, final String submittedByFirstname, final String submittedByLastname, final LocalDate rejectedOnDate, final String rejectedByUsername, final String rejectedByFirstname, final String rejectedByLastname, - final LocalDate approvedOnDate, final String approvedByUsername, - final String approvedByFirstname, final String approvedByLastname, final LocalDate activatedOnDate, - final String activatedByUsername, final String activatedByFirstname, final String activatedByLastname, - final LocalDate closedOnDate, final String closedByUsername, final String closedByFirstname, final String closedByLastname) { + final LocalDate approvedOnDate, final String approvedByUsername, final String approvedByFirstname, + final String approvedByLastname, final LocalDate activatedOnDate, final String activatedByUsername, + final String activatedByFirstname, final String activatedByLastname, final LocalDate closedOnDate, + final String closedByUsername, final String closedByFirstname, final String closedByLastname) { this.submittedOnDate = submittedOnDate; this.submittedByUsername = submittedByUsername; this.submittedByFirstname = submittedByFirstname; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountChargeData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountChargeData.java index 0451a17f6..ae3c2f9c6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountChargeData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountChargeData.java @@ -82,12 +82,11 @@ public class ShareAccountChargeData implements Serializable { this.chargeOptions = null; } - - public ShareAccountChargeData(final Long id, final Long chargeId, final Long accountId, final String name, - final CurrencyData currency, final BigDecimal amount, final BigDecimal amountPaid, final BigDecimal amountWaived, - final BigDecimal amountWrittenOff, final BigDecimal amountOutstanding, final EnumOptionData chargeTimeType, - final EnumOptionData chargeCalculationType, final BigDecimal percentage, final BigDecimal amountPercentageAppliedTo, - final Collection chargeOptions, final Boolean isActive, final BigDecimal chargeamountorpercentage) { + public ShareAccountChargeData(final Long id, final Long chargeId, final Long accountId, final String name, final CurrencyData currency, + final BigDecimal amount, final BigDecimal amountPaid, final BigDecimal amountWaived, final BigDecimal amountWrittenOff, + final BigDecimal amountOutstanding, final EnumOptionData chargeTimeType, final EnumOptionData chargeCalculationType, + final BigDecimal percentage, final BigDecimal amountPercentageAppliedTo, final Collection chargeOptions, + final Boolean isActive, final BigDecimal chargeamountorpercentage) { this.id = id; this.chargeId = chargeId; this.accountId = accountId; @@ -107,7 +106,6 @@ public class ShareAccountChargeData implements Serializable { this.isActive = isActive; } - private BigDecimal getAmountOrPercentage() { return this.chargeCalculationType != null && this.chargeCalculationType.getId().intValue() > 1 ? this.percentage : this.amount; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountData.java index 809a6f9e9..8a5597cdf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountData.java @@ -46,7 +46,7 @@ public class ShareAccountData implements Serializable, AccountData { private String clientName; - private Long defaultShares ; + private Long defaultShares; private Long productId; @@ -78,9 +78,9 @@ public class ShareAccountData implements Serializable, AccountData { private Collection charges; - private Collection dividends ; + private Collection dividends; - //import fields + // import fields private Integer requestedShares; private LocalDate submittedDate; private Integer minimumActivePeriodFrequencyType; @@ -89,39 +89,39 @@ public class ShareAccountData implements Serializable, AccountData { private LocalDate applicationDate; private String locale; private transient Integer rowIndex; - private String dateFormat; + private String dateFormat; - public static ShareAccountData importInstance(Long clientId,Long productId,Integer requestedShares,String externalId, - LocalDate submittedOnDate , Integer minimumActivePeriodDays,Integer minimumActivePeriodFrequencyType, - Integer lockinPeriodFrequency,Integer lockinPeriodFrequencyType,LocalDate applicationDate, - Boolean allowDividendCalculationForInactiveClients, Collection charges, - Long defaultSavingsAccountId,Integer rowIndex,String locale, String dateFormat){ - return new ShareAccountData(clientId,productId,requestedShares,externalId,submittedOnDate,minimumActivePeriodDays, - minimumActivePeriodFrequencyType,lockinPeriodFrequency,lockinPeriodFrequencyType,applicationDate,allowDividendCalculationForInactiveClients,charges, - defaultSavingsAccountId,rowIndex,locale,dateFormat); + public static ShareAccountData importInstance(Long clientId, Long productId, Integer requestedShares, String externalId, + LocalDate submittedOnDate, Integer minimumActivePeriodDays, Integer minimumActivePeriodFrequencyType, + Integer lockinPeriodFrequency, Integer lockinPeriodFrequencyType, LocalDate applicationDate, + Boolean allowDividendCalculationForInactiveClients, Collection charges, Long defaultSavingsAccountId, + Integer rowIndex, String locale, String dateFormat) { + return new ShareAccountData(clientId, productId, requestedShares, externalId, submittedOnDate, minimumActivePeriodDays, + minimumActivePeriodFrequencyType, lockinPeriodFrequency, lockinPeriodFrequencyType, applicationDate, + allowDividendCalculationForInactiveClients, charges, defaultSavingsAccountId, rowIndex, locale, dateFormat); } - private ShareAccountData(Long clientId,Long productId,Integer requestedShares,String externalId, - LocalDate submittedDate , Integer minimumActivePeriod,Integer minimumActivePeriodFrequencyType, - Integer lockinPeriodFrequency,Integer lockinPeriodFrequencyType,LocalDate applicationDate, - Boolean allowDividendCalculationForInactiveClients, Collection charges, - Long savingsAccountId,Integer rowIndex,String locale, String dateFormat) { + + private ShareAccountData(Long clientId, Long productId, Integer requestedShares, String externalId, LocalDate submittedDate, + Integer minimumActivePeriod, Integer minimumActivePeriodFrequencyType, Integer lockinPeriodFrequency, + Integer lockinPeriodFrequencyType, LocalDate applicationDate, Boolean allowDividendCalculationForInactiveClients, + Collection charges, Long savingsAccountId, Integer rowIndex, String locale, String dateFormat) { this.clientId = clientId; this.productId = productId; - this.requestedShares=requestedShares; + this.requestedShares = requestedShares; this.externalId = externalId; - this.submittedDate=submittedDate; + this.submittedDate = submittedDate; this.minimumActivePeriod = minimumActivePeriod; - this.minimumActivePeriodFrequencyType=minimumActivePeriodFrequencyType; - this.lockinPeriodFrequency=lockinPeriodFrequency; - this.lockinPeriodFrequencyType=lockinPeriodFrequencyType; - this.applicationDate=applicationDate; + this.minimumActivePeriodFrequencyType = minimumActivePeriodFrequencyType; + this.lockinPeriodFrequency = lockinPeriodFrequency; + this.lockinPeriodFrequencyType = lockinPeriodFrequencyType; + this.applicationDate = applicationDate; this.allowDividendCalculationForInactiveClients = allowDividendCalculationForInactiveClients; - this.dateFormat= dateFormat; - this.locale=locale; + this.dateFormat = dateFormat; + this.locale = locale; this.charges = charges; this.savingsAccountId = savingsAccountId; - this.rowIndex=rowIndex; + this.rowIndex = rowIndex; this.clientName = null; this.savingsAccountNumber = null; this.defaultShares = null; @@ -157,11 +157,12 @@ public class ShareAccountData implements Serializable, AccountData { private Collection clientSavingsAccounts; public ShareAccountData(final Long id, final String accountNo, final String externalId, final Long savingsAccountId, - final String savingsAccountNumber, final Long clientId, final String clientName, final Long productId, - final String productName, final ShareAccountStatusEnumData status, final ShareAccountApplicationTimelineData timeline, - final CurrencyData currency, final ShareAccountSummaryData summaryData, final Collection charges, - final Collection purchasedSharesData, final Integer lockinPeriod, final EnumOptionData lockPeriodTypeEnum, - final Integer minimumActivePeriod, final EnumOptionData minimumActivePeriodTypeEnum, Boolean allowdividendsforinactiveclients) { + final String savingsAccountNumber, final Long clientId, final String clientName, final Long productId, final String productName, + final ShareAccountStatusEnumData status, final ShareAccountApplicationTimelineData timeline, final CurrencyData currency, + final ShareAccountSummaryData summaryData, final Collection charges, + final Collection purchasedSharesData, final Integer lockinPeriod, + final EnumOptionData lockPeriodTypeEnum, final Integer minimumActivePeriod, final EnumOptionData minimumActivePeriodTypeEnum, + Boolean allowdividendsforinactiveclients) { this.id = id; this.accountNo = accountNo; this.externalId = externalId; @@ -206,15 +207,15 @@ public class ShareAccountData implements Serializable, AccountData { this.minimumActivePeriodFrequencyTypeOptions = minimumActivePeriodFrequencyTypeOptions; this.lockinPeriodFrequencyTypeOptions = lockinPeriodFrequencyTypeOptions; this.clientSavingsAccounts = clientSavingsAccounts; - this.defaultShares = defaultShares ; + this.defaultShares = defaultShares; } private ShareAccountData(final Long id, final String accountNo, final String externalId, final Long savingsAccountId, - final String savingsAccountNumber, final Long clientId, final String clientName, final Long productId, - final String productName, final ShareAccountStatusEnumData status, final ShareAccountApplicationTimelineData timeline, - final CurrencyData currency, final ShareAccountSummaryData summaryData, final Collection charges, - final Collection purchasedSharesData, final Integer lockinPeriod, final EnumOptionData lockPeriodTypeEnum, - final Integer minimumActivePeriod, final EnumOptionData minimumActivePeriodTypeEnum, + final String savingsAccountNumber, final Long clientId, final String clientName, final Long productId, final String productName, + final ShareAccountStatusEnumData status, final ShareAccountApplicationTimelineData timeline, final CurrencyData currency, + final ShareAccountSummaryData summaryData, final Collection charges, + final Collection purchasedSharesData, final Integer lockinPeriod, + final EnumOptionData lockPeriodTypeEnum, final Integer minimumActivePeriod, final EnumOptionData minimumActivePeriodTypeEnum, final Boolean allowDividendCalculationForInactiveClients, final Collection productOptions, final Collection chargeOptions, final Collection clientSavingsAccounts, final Collection lockinPeriodFrequencyTypeOptions, @@ -257,7 +258,8 @@ public class ShareAccountData implements Serializable, AccountData { public static ShareAccountData template(ShareAccountData data, Collection productOptions, Collection chargeOptions, Collection clientSavingsAccounts, - Collection lockinPeriodFrequencyTypeOptions, Collection minimumActivePeriodFrequencyTypeOptions) { + Collection lockinPeriodFrequencyTypeOptions, + Collection minimumActivePeriodFrequencyTypeOptions) { return new ShareAccountData(data.id, data.accountNo, data.externalId, data.savingsAccountId, data.savingsAccountNumber, data.clientId, data.clientName, data.productId, data.productName, data.status, data.timeline, data.currency, data.summary, data.charges, data.purchasedShares, data.lockinPeriod, data.lockPeriodTypeEnum, data.minimumActivePeriod, @@ -292,9 +294,8 @@ public class ShareAccountData implements Serializable, AccountData { return new ShareAccountData(id, accountNo, externalId, savingsAccountId, savingsAccountNumber, clientId, clientName, productId, productName, status, timeline, currency, summaryData, charges, purchasedSharesData, lockinPeriod, lockPeriodTypeEnum, - minimumActivePeriod, minimumActivePeriodTypeEnum, allowDividendCalculationForInactiveClients, productOptions, - chargeOptions, clientSavingsAccounts, lockinPeriodFrequencyTypeOptions, minimumActivePeriodFrequencyTypeOption, - currenMarketPrice); + minimumActivePeriod, minimumActivePeriodTypeEnum, allowDividendCalculationForInactiveClients, productOptions, chargeOptions, + clientSavingsAccounts, lockinPeriodFrequencyTypeOptions, minimumActivePeriodFrequencyTypeOption, currenMarketPrice); } public Long getId() { @@ -310,6 +311,6 @@ public class ShareAccountData implements Serializable, AccountData { } public void setDividends(Collection dividends) { - this.dividends = dividends ; + this.dividends = dividends; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountDividendData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountDividendData.java index 288a0710f..4f455df68 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountDividendData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountDividendData.java @@ -27,7 +27,7 @@ import org.apache.fineract.infrastructure.core.data.EnumOptionData; public class ShareAccountDividendData implements Serializable { private final Long id; - private final Date postedDate ; + private final Date postedDate; private final ShareAccountData accountData; private final BigDecimal amount; private final EnumOptionData status; @@ -39,17 +39,17 @@ public class ShareAccountDividendData implements Serializable { this.amount = amount; this.status = null; this.savingsTransactionId = null; - this.postedDate = null ; + this.postedDate = null; } - public ShareAccountDividendData(final Long id, final ShareAccountData accountData, final BigDecimal amount, - final EnumOptionData status, final Long savingsTransactionId) { + public ShareAccountDividendData(final Long id, final ShareAccountData accountData, final BigDecimal amount, final EnumOptionData status, + final Long savingsTransactionId) { this.id = id; this.accountData = accountData; this.amount = amount; this.status = status; this.savingsTransactionId = savingsTransactionId; - this.postedDate = null ; + this.postedDate = null; } public ShareAccountDividendData(final Long id, final Date postedDate, final ShareAccountData accountData, final BigDecimal amount, @@ -59,6 +59,6 @@ public class ShareAccountDividendData implements Serializable { this.amount = amount; this.status = status; this.savingsTransactionId = savingsTransactionId; - this.postedDate = postedDate ; + this.postedDate = postedDate; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountStatusEnumData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountStatusEnumData.java index 1fecb62e8..43b55eba7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountStatusEnumData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountStatusEnumData.java @@ -51,4 +51,4 @@ public class ShareAccountStatusEnumData implements Serializable { public Long id() { return this.id; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountTransactionData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountTransactionData.java index 5785d3d68..ee9319bec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountTransactionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountTransactionData.java @@ -40,15 +40,15 @@ public class ShareAccountTransactionData implements Serializable { private final EnumOptionData type; - private final BigDecimal amount ; + private final BigDecimal amount; - private final BigDecimal chargeAmount ; + private final BigDecimal chargeAmount; - private final BigDecimal amountPaid ; + private final BigDecimal amountPaid; public ShareAccountTransactionData(final Long id, final Long accountId, final LocalDate purchasedDate, final Long numberOfShares, - final BigDecimal purchasedPrice, final EnumOptionData status, final EnumOptionData type, final BigDecimal amount, final BigDecimal chargeAmount, - final BigDecimal amountPaid) { + final BigDecimal purchasedPrice, final EnumOptionData status, final EnumOptionData type, final BigDecimal amount, + final BigDecimal chargeAmount, final BigDecimal amountPaid) { this.id = id; this.accountId = accountId; this.purchasedDate = purchasedDate; @@ -56,9 +56,9 @@ public class ShareAccountTransactionData implements Serializable { this.purchasedPrice = purchasedPrice; this.status = status; this.type = type; - this.amount = amount ; - this.chargeAmount = chargeAmount ; - this.amountPaid = amountPaid ; + this.amount = amount; + this.chargeAmount = chargeAmount; + this.amountPaid = amountPaid; } public LocalDate getPurchasedDate() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountTransactionEnumData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountTransactionEnumData.java index a41a80ec7..3d59c2c8b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountTransactionEnumData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/data/ShareAccountTransactionEnumData.java @@ -77,7 +77,6 @@ public class ShareAccountTransactionEnumData implements Serializable { return this.isRedeemed; } - public boolean isChargePayment() { return this.isChargePayment; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/PurchasedSharesStatusType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/PurchasedSharesStatusType.java index 8274e9d2b..3977d8a08 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/PurchasedSharesStatusType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/PurchasedSharesStatusType.java @@ -19,10 +19,10 @@ package org.apache.fineract.portfolio.shareaccounts.domain; public enum PurchasedSharesStatusType { + INVALID(0, "purchasedSharesStatusType.invalid"), APPLIED(100, "purchasedSharesStatusType.applied"), APPROVED(300, "purchasedSharesStatusType.approved"), REJECTED(400, "purchasedSharesStatusType.rejected"), PURCHASED(500, - "purchasedSharesType.purchased"), REDEEMED(600, "purchasedSharesType.redeemed"), - CHARGE_PAYMENT(700, "charge.payment"); + "purchasedSharesType.purchased"), REDEEMED(600, "purchasedSharesType.redeemed"), CHARGE_PAYMENT(700, "charge.payment"); private final Integer value; private final String code; @@ -53,7 +53,7 @@ public enum PurchasedSharesStatusType { break; case 700: enumeration = PurchasedSharesStatusType.CHARGE_PAYMENT; - break ; + break; } return enumeration; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccount.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccount.java index 5d358a383..443ea5dc9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccount.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccount.java @@ -130,7 +130,7 @@ public class ShareAccount extends AbstractPersistableCustom { @JoinColumn(name = "savings_account_id", nullable = true) private SavingsAccount savingsAccount; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "shareAccount", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "shareAccount", orphanRemoval = true, fetch = FetchType.EAGER) private Set shareAccountTransactions; @Column(name = "lockin_period_frequency") @@ -147,7 +147,7 @@ public class ShareAccount extends AbstractPersistableCustom { @Column(name = "minimum_active_period_frequency_enum", nullable = true) private PeriodFrequencyType minimumActivePeriodFrequencyType; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "shareAccount", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "shareAccount", orphanRemoval = true, fetch = FetchType.EAGER) private Set charges; @Transient @@ -256,18 +256,18 @@ public class ShareAccount extends AbstractPersistableCustom { public void addTransaction(final ShareAccountTransaction transaction) { transaction.setShareAccount(this); - if(transaction.isPendingForApprovalTransaction()) { - if(this.totalSharesPending == null) { - this.totalSharesPending = transaction.getTotalShares() ; - }else { - this.totalSharesPending += transaction.getTotalShares() ; + if (transaction.isPendingForApprovalTransaction()) { + if (this.totalSharesPending == null) { + this.totalSharesPending = transaction.getTotalShares(); + } else { + this.totalSharesPending += transaction.getTotalShares(); } - }else if(transaction.isPurchasTransaction()) { - if(this.totalSharesApproved == null) { - this.totalSharesApproved = transaction.getTotalShares() ; - }else { - this.totalSharesApproved += transaction.getTotalShares() ; + } else if (transaction.isPurchasTransaction()) { + if (this.totalSharesApproved == null) { + this.totalSharesApproved = transaction.getTotalShares(); + } else { + this.totalSharesApproved += transaction.getTotalShares(); } } @@ -276,7 +276,8 @@ public class ShareAccount extends AbstractPersistableCustom { public boolean setAllowDividendCalculationForInactiveClients(Boolean allowDividendCalculationForInactiveClients) { boolean returnValue = false; - if (this.allowDividendCalculationForInactiveClients == null || !this.allowDividendCalculationForInactiveClients.equals(allowDividendCalculationForInactiveClients)) { + if (this.allowDividendCalculationForInactiveClients == null + || !this.allowDividendCalculationForInactiveClients.equals(allowDividendCalculationForInactiveClients)) { this.allowDividendCalculationForInactiveClients = allowDividendCalculationForInactiveClients; returnValue = true; } @@ -294,7 +295,8 @@ public class ShareAccount extends AbstractPersistableCustom { public boolean setLockPeriodFrequencyEnum(final PeriodFrequencyType lockinPeriodFrequencyType) { boolean returnValue = false; - if (this.lockinPeriodFrequencyType == null || !this.lockinPeriodFrequencyType.getValue().equals(lockinPeriodFrequencyType.getValue())) { + if (this.lockinPeriodFrequencyType == null + || !this.lockinPeriodFrequencyType.getValue().equals(lockinPeriodFrequencyType.getValue())) { this.lockinPeriodFrequencyType = lockinPeriodFrequencyType; returnValue = true; } @@ -312,7 +314,8 @@ public class ShareAccount extends AbstractPersistableCustom { public boolean setminimumActivePeriodTypeEnum(final PeriodFrequencyType minimumActivePeriodForDividends) { boolean returnValue = false; - if (this.minimumActivePeriodFrequencyType == null || !this.minimumActivePeriodFrequencyType.getValue().equals(minimumActivePeriodForDividends.getValue())) { + if (this.minimumActivePeriodFrequencyType == null + || !this.minimumActivePeriodFrequencyType.getValue().equals(minimumActivePeriodForDividends.getValue())) { this.minimumActivePeriodFrequencyType = minimumActivePeriodForDividends; returnValue = true; } @@ -342,7 +345,7 @@ public class ShareAccount extends AbstractPersistableCustom { } public Client getClient() { - return this.client ; + return this.client; } public String getSavingsAccountNo() { @@ -368,8 +371,8 @@ public class ShareAccount extends AbstractPersistableCustom { } public void updateRequestedShares(ShareAccountTransaction purchased) { - for(ShareAccountTransaction transaction: this.shareAccountTransactions) { - if(!transaction.isChargeTransaction() && transaction.getId().equals(purchased.getId())) { + for (ShareAccountTransaction transaction : this.shareAccountTransactions) { + if (!transaction.isChargeTransaction() && transaction.getId().equals(purchased.getId())) { transaction.update(purchased.getPurchasedDate(), purchased.getTotalShares(), purchased.getPurchasePrice()); } } @@ -422,9 +425,9 @@ public class ShareAccount extends AbstractPersistableCustom { this.totalSharesApproved = null; Long tempTotalShares = Long.valueOf(0); for (ShareAccountTransaction transaction : this.shareAccountTransactions) { - if(transaction.isPurchasTransaction()) { + if (transaction.isPurchasTransaction()) { transaction.undoApprove(); - tempTotalShares += transaction.getTotalShares() ; + tempTotalShares += transaction.getTotalShares(); } } this.totalSharesPending = tempTotalShares; @@ -437,19 +440,20 @@ public class ShareAccount extends AbstractPersistableCustom { this.totalSharesPending = null; this.totalSharesApproved = null; for (ShareAccountTransaction transaction : this.shareAccountTransactions) { - if(transaction.isPendingForApprovalTransaction()) { + if (transaction.isPendingForApprovalTransaction()) { transaction.reject(); } } } public void close(final Date closedDate, final AppUser closedBy) { - this.closedDate = closedDate ; - this.closedBy = closedBy ; - this.status = ShareAccountStatusType.CLOSED.getValue() ; + this.closedDate = closedDate; + this.closedBy = closedBy; + this.status = ShareAccountStatusType.CLOSED.getValue(); this.totalSharesPending = null; this.totalSharesApproved = null; } + public String getAccountNumber() { return this.accountNumber; } @@ -498,7 +502,7 @@ public class ShareAccount extends AbstractPersistableCustom { } public Long getTotalApprovedShares() { - return this.totalSharesApproved ; + return this.totalSharesApproved; } public void removePendingShares(Long totalShares) { @@ -510,17 +514,16 @@ public class ShareAccount extends AbstractPersistableCustom { } public void setTotalPendingShares(final Long shares) { - this.totalSharesPending = shares ; + this.totalSharesPending = shares; } public ShareAccountTransaction getShareAccountTransaction(final ShareAccountTransaction transaction) { ShareAccountTransaction returnTrans = null; for (ShareAccountTransaction tran : this.shareAccountTransactions) { - if (tran.getPurchasedDate().equals(transaction.getPurchasedDate()) - && tran.getTotalShares().equals(transaction.getTotalShares()) - && tran.getPurchasePrice().compareTo(transaction.getPurchasePrice()) == 0 ? Boolean.TRUE:Boolean.FALSE - && tran.getTransactionStatus().equals(transaction.getTransactionStatus()) - && tran.getTransactionType().equals(transaction.getTransactionType())) { + if (tran.getPurchasedDate().equals(transaction.getPurchasedDate()) && tran.getTotalShares().equals(transaction.getTotalShares()) + && tran.getPurchasePrice().compareTo(transaction.getPurchasePrice()) == 0 ? Boolean.TRUE + : Boolean.FALSE && tran.getTransactionStatus().equals(transaction.getTransactionStatus()) + && tran.getTransactionType().equals(transaction.getTransactionType())) { returnTrans = tran; break; } @@ -528,45 +531,45 @@ public class ShareAccount extends AbstractPersistableCustom { return returnTrans; } - public Date getSubmittedDate(){ - return this.submittedDate ; + public Date getSubmittedDate() { + return this.submittedDate; } public Date getApprovedDate() { - return this.approvedDate ; + return this.approvedDate; } public void removeTransactions() { - for(ShareAccountTransaction transaction: this.shareAccountTransactions) { + for (ShareAccountTransaction transaction : this.shareAccountTransactions) { transaction.setActive(false); } - this.totalSharesApproved = Long.valueOf(0) ; - this.totalSharesPending = Long.valueOf(0) ; + this.totalSharesApproved = Long.valueOf(0); + this.totalSharesPending = Long.valueOf(0); } public void removeCharges() { - for(ShareAccountCharge charge: this.charges) { + for (ShareAccountCharge charge : this.charges) { charge.setActive(false); } } public void addCharges(Set charges) { - this.charges.addAll(charges) ; + this.charges.addAll(charges); } public Integer getLockinPeriodFrequency() { - return this.lockinPeriodFrequency ; + return this.lockinPeriodFrequency; } - public PeriodFrequencyType getLockinPeriodFrequencyType() { - return this.lockinPeriodFrequencyType ; + public PeriodFrequencyType getLockinPeriodFrequencyType() { + return this.lockinPeriodFrequencyType; } public Date getActivatedDate() { - return this.activatedDate ; + return this.activatedDate; } public Integer status() { - return this.status ; + return this.status; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountCharge.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountCharge.java index e26885e3a..0d7ada3d5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountCharge.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountCharge.java @@ -118,7 +118,7 @@ public class ShareAccountCharge extends AbstractPersistableCustom { } private void populateDerivedFields(final BigDecimal transactionAmount, final BigDecimal chargeAmount) { - this.amountOrPercentage = chargeAmount ; + this.amountOrPercentage = chargeAmount; if (this.chargeCalculation.equals(ChargeCalculationType.FLAT.getValue())) { this.percentage = null; this.amount = BigDecimal.ZERO; @@ -145,7 +145,7 @@ public class ShareAccountCharge extends AbstractPersistableCustom { } public void resetToOriginal(final MonetaryCurrency currency) { - this.amount = BigDecimal.ZERO ; + this.amount = BigDecimal.ZERO; this.amountPaid = BigDecimal.ZERO; this.amountWaived = BigDecimal.ZERO; this.amountWrittenOff = BigDecimal.ZERO; @@ -201,7 +201,7 @@ public class ShareAccountCharge extends AbstractPersistableCustom { } public void update(final BigDecimal transactionAmount, final BigDecimal amount) { - populateDerivedFields(transactionAmount, amount); + populateDerivedFields(transactionAmount, amount); } private boolean isGreaterThanZero(final BigDecimal value) { @@ -374,14 +374,14 @@ public class ShareAccountCharge extends AbstractPersistableCustom { public BigDecimal deriveChargeAmount(BigDecimal transactionAmount, final MonetaryCurrency currency) { BigDecimal toReturnAmount = amountOrPercentage; if (ChargeCalculationType.fromInt(this.chargeCalculation) == ChargeCalculationType.PERCENT_OF_AMOUNT) { - toReturnAmount = Money.of(currency, percentageOf(transactionAmount, this.percentage)).getAmount() ; + toReturnAmount = Money.of(currency, percentageOf(transactionAmount, this.percentage)).getAmount(); this.amountPercentageAppliedTo = transactionAmount; - this.amount = Money.of(currency, percentageOf(this.amountPercentageAppliedTo, this.percentage)).getAmount() ; + this.amount = Money.of(currency, percentageOf(this.amountPercentageAppliedTo, this.percentage)).getAmount(); this.amountPaid = null; this.amountOutstanding = calculateOutstanding(); this.amountWaived = null; this.amountWrittenOff = null; - }else { + } else { this.amount = this.amountOrPercentage; this.amountOutstanding = calculateOutstanding(); this.amountWaived = null; @@ -393,9 +393,9 @@ public class ShareAccountCharge extends AbstractPersistableCustom { public BigDecimal updateChargeDetailsForAdditionalSharesRequest(final BigDecimal transactionAmount, final MonetaryCurrency currency) { BigDecimal toReturnAmount = amountOrPercentage; if (ChargeCalculationType.fromInt(this.chargeCalculation) == ChargeCalculationType.PERCENT_OF_AMOUNT) { - toReturnAmount = Money.of(currency, percentageOf(transactionAmount, this.percentage)).getAmount() ; + toReturnAmount = Money.of(currency, percentageOf(transactionAmount, this.percentage)).getAmount(); this.amountPercentageAppliedTo = this.amountPercentageAppliedTo.add(transactionAmount); - this.amount = Money.of(currency, percentageOf(this.amountPercentageAppliedTo, this.percentage)).getAmount() ; + this.amount = Money.of(currency, percentageOf(this.amountPercentageAppliedTo, this.percentage)).getAmount(); this.amountOutstanding = calculateOutstanding(); this.amountWaived = null; this.amountWrittenOff = null; @@ -409,6 +409,6 @@ public class ShareAccountCharge extends AbstractPersistableCustom { } public void setActive(boolean active) { - this.active = active ; + this.active = active; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountChargePaidBy.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountChargePaidBy.java index b9be358c8..1ceffb4d4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountChargePaidBy.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountChargePaidBy.java @@ -26,10 +26,9 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; - @Entity @Table(name = "m_share_account_charge_paid_by") -public class ShareAccountChargePaidBy extends AbstractPersistableCustom{ +public class ShareAccountChargePaidBy extends AbstractPersistableCustom { @ManyToOne(optional = false) @JoinColumn(name = "share_transaction_id", referencedColumnName = "id", nullable = false) @@ -40,41 +39,41 @@ public class ShareAccountChargePaidBy extends AbstractPersistableCustom{ private ShareAccountCharge shareAccountCharge; @Column(name = "amount", scale = 6, precision = 19, nullable = false) - private BigDecimal amount ; + private BigDecimal amount; protected ShareAccountChargePaidBy() { } - public ShareAccountChargePaidBy(final ShareAccountTransaction shareAccountTransaction, - final ShareAccountCharge shareAccountCharge, final BigDecimal amount) { - this.shareAccountTransaction = shareAccountTransaction ; - this.shareAccountCharge = shareAccountCharge ; - this.amount = amount ; + public ShareAccountChargePaidBy(final ShareAccountTransaction shareAccountTransaction, final ShareAccountCharge shareAccountCharge, + final BigDecimal amount) { + this.shareAccountTransaction = shareAccountTransaction; + this.shareAccountCharge = shareAccountCharge; + this.amount = amount; } public ShareAccountCharge getCharge() { - return this.shareAccountCharge ; + return this.shareAccountCharge; } public BigDecimal getAmount() { - return this.amount ; + return this.amount; } public ShareAccountTransaction getShareAccountTransaction() { - return this.shareAccountTransaction ; + return this.shareAccountTransaction; } public Long getChargeId() { - return this.shareAccountCharge.getChargeId() ; + return this.shareAccountCharge.getChargeId(); } public Long getShareChargeId() { - return this.shareAccountCharge.getId() ; + return this.shareAccountCharge.getId(); } public void reset() { - this.shareAccountTransaction = null ; - this.shareAccountCharge = null ; + this.shareAccountTransaction = null; + this.shareAccountCharge = null; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountDividendRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountDividendRepository.java index 04ae892ae..5ea2af8c5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountDividendRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountDividendRepository.java @@ -21,7 +21,7 @@ package org.apache.fineract.portfolio.shareaccounts.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface ShareAccountDividendRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface ShareAccountDividendRepository + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountRepository.java index 285203b05..437046f2b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountRepository.java @@ -21,7 +21,6 @@ package org.apache.fineract.portfolio.shareaccounts.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - public interface ShareAccountRepository extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountRepositoryWrapper.java index cf5a16faf..59a0820e1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountRepositoryWrapper.java @@ -25,22 +25,22 @@ import org.springframework.stereotype.Service; @Service public class ShareAccountRepositoryWrapper { - private final ShareAccountRepository shareAccountRepository ; + private final ShareAccountRepository shareAccountRepository; @Autowired public ShareAccountRepositoryWrapper(final ShareAccountRepository shareAccountRepository) { - this.shareAccountRepository = shareAccountRepository ; + this.shareAccountRepository = shareAccountRepository; } public ShareAccount findOneWithNotFoundDetection(final Long accountId) { - return this.shareAccountRepository.findById(accountId) - .orElseThrow(() -> new ShareAccountNotFoundException(accountId)); + return this.shareAccountRepository.findById(accountId).orElseThrow(() -> new ShareAccountNotFoundException(accountId)); } + public void save(final ShareAccount shareAccount) { - this.shareAccountRepository.save(shareAccount) ; + this.shareAccountRepository.save(shareAccount); } public void saveAndFlush(final ShareAccount shareAccount) { - this.shareAccountRepository.saveAndFlush(shareAccount) ; + this.shareAccountRepository.saveAndFlush(shareAccount); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountStatusType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountStatusType.java index c276c8f93..cebb40a2a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountStatusType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountStatusType.java @@ -97,4 +97,4 @@ public enum ShareAccountStatusType { return this.value.equals(ShareAccountStatusType.CLOSED.getValue()) || isRejected(); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountTransaction.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountTransaction.java index 493e2668a..9943f803b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountTransaction.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/domain/ShareAccountTransaction.java @@ -53,24 +53,24 @@ public class ShareAccountTransaction extends AbstractPersistableCustom { private BigDecimal shareValue; @Column(name = "amount") - private BigDecimal amount ; + private BigDecimal amount; @Column(name = "amount_paid") - private BigDecimal amountPaid ; + private BigDecimal amountPaid; @Column(name = "charge_amount") - private BigDecimal chargeAmount ; + private BigDecimal chargeAmount; @Column(name = "status_enum", nullable = true) private Integer status; @Column(name = "type_enum", nullable = true) - private Integer type ; + private Integer type; @Column(name = "is_active", nullable = false) - private boolean active = true ; + private boolean active = true; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "shareAccountTransaction", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "shareAccountTransaction", orphanRemoval = true, fetch = FetchType.EAGER) private Set shareAccountChargesPaid = new HashSet<>(); protected ShareAccountTransaction() { @@ -86,40 +86,41 @@ public class ShareAccountTransaction extends AbstractPersistableCustom { this.totalShares = totalShares; this.shareValue = shareValue; this.status = PurchasedSharesStatusType.APPLIED.getValue(); - this.type = PurchasedSharesStatusType.PURCHASED.getValue() ; - this.amount = shareValue.multiply(BigDecimal.valueOf(totalShares)) ; - this.amountPaid = new BigDecimal(this.amount.doubleValue()) ; + this.type = PurchasedSharesStatusType.PURCHASED.getValue(); + this.amount = shareValue.multiply(BigDecimal.valueOf(totalShares)); + this.amountPaid = new BigDecimal(this.amount.doubleValue()); } - private ShareAccountTransaction(final Date transactionDate, final Long totalShares, final BigDecimal shareValue, - final Integer status, final Integer type, final BigDecimal amount, final BigDecimal chargeAmount, final BigDecimal amountPaid) { + private ShareAccountTransaction(final Date transactionDate, final Long totalShares, final BigDecimal shareValue, final Integer status, + final Integer type, final BigDecimal amount, final BigDecimal chargeAmount, final BigDecimal amountPaid) { this.transactionDate = transactionDate; this.totalShares = totalShares; this.shareValue = shareValue; - this.status = status ; - this.type = type ; - this.amount = amount ; - this.chargeAmount = chargeAmount ; - this.amountPaid = amountPaid ; + this.status = status; + this.type = type; + this.amount = amount; + this.chargeAmount = chargeAmount; + this.amountPaid = amountPaid; } - public static ShareAccountTransaction createRedeemTransaction(final Date transactionDate, final Long totalShares, final BigDecimal shareValue) { - final Integer status = PurchasedSharesStatusType.APPROVED.getValue() ; - final Integer type = PurchasedSharesStatusType.REDEEMED.getValue() ; - final BigDecimal amount = shareValue.multiply(BigDecimal.valueOf(totalShares)) ; - BigDecimal amountPaid = new BigDecimal(amount.doubleValue()) ; - return new ShareAccountTransaction(transactionDate, totalShares, shareValue, status, type, amount, null, amountPaid) ; + public static ShareAccountTransaction createRedeemTransaction(final Date transactionDate, final Long totalShares, + final BigDecimal shareValue) { + final Integer status = PurchasedSharesStatusType.APPROVED.getValue(); + final Integer type = PurchasedSharesStatusType.REDEEMED.getValue(); + final BigDecimal amount = shareValue.multiply(BigDecimal.valueOf(totalShares)); + BigDecimal amountPaid = new BigDecimal(amount.doubleValue()); + return new ShareAccountTransaction(transactionDate, totalShares, shareValue, status, type, amount, null, amountPaid); } public static ShareAccountTransaction createChargeTransaction(final Date transactionDate, final ShareAccountCharge charge) { - final Long totalShares = null ; - final BigDecimal unitPrice = null ; - final Integer status = PurchasedSharesStatusType.APPROVED.getValue() ; - final Integer type = PurchasedSharesStatusType.CHARGE_PAYMENT.getValue() ; - BigDecimal amount = charge.percentageOrAmount() ; - BigDecimal chargeAmount = null ; - BigDecimal amountPaid = null ; - return new ShareAccountTransaction(transactionDate, totalShares, unitPrice, status, type, amount, chargeAmount, amountPaid) ; + final Long totalShares = null; + final BigDecimal unitPrice = null; + final Integer status = PurchasedSharesStatusType.APPROVED.getValue(); + final Integer type = PurchasedSharesStatusType.CHARGE_PAYMENT.getValue(); + BigDecimal amount = charge.percentageOrAmount(); + BigDecimal chargeAmount = null; + BigDecimal amountPaid = null; + return new ShareAccountTransaction(transactionDate, totalShares, unitPrice, status, type, amount, chargeAmount, amountPaid); } public Date getPurchasedDate() { @@ -138,112 +139,119 @@ public class ShareAccountTransaction extends AbstractPersistableCustom { this.transactionDate = purchasedDate; this.totalShares = totalShares; this.shareValue = shareValue; - this.amount = shareValue.multiply(BigDecimal.valueOf(totalShares)) ; - this.chargeAmount = BigDecimal.ZERO ; + this.amount = shareValue.multiply(BigDecimal.valueOf(totalShares)); + this.chargeAmount = BigDecimal.ZERO; this.status = PurchasedSharesStatusType.APPLIED.getValue(); } public void approve() { - this.status = PurchasedSharesStatusType.APPROVED.getValue() ; + this.status = PurchasedSharesStatusType.APPROVED.getValue(); } public void undoApprove() { - this.status = PurchasedSharesStatusType.APPLIED.getValue() ; + this.status = PurchasedSharesStatusType.APPLIED.getValue(); } public void reject() { - this.status = PurchasedSharesStatusType.REJECTED.getValue() ; - if(this.chargeAmount != null) { - this.amount = this.amount.subtract(chargeAmount) ; - } + this.status = PurchasedSharesStatusType.REJECTED.getValue(); + if (this.chargeAmount != null) { + this.amount = this.amount.subtract(chargeAmount); + } } public boolean isPendingForApprovalTransaction() { - return this.status.equals(PurchasedSharesStatusType.APPLIED.getValue()) && this.type.equals(PurchasedSharesStatusType.PURCHASED.getValue()) ; + return this.status.equals(PurchasedSharesStatusType.APPLIED.getValue()) + && this.type.equals(PurchasedSharesStatusType.PURCHASED.getValue()); } public boolean isPurchasTransaction() { - return this.status.equals(PurchasedSharesStatusType.APPROVED.getValue()) && this.type.equals(PurchasedSharesStatusType.PURCHASED.getValue()) ; + return this.status.equals(PurchasedSharesStatusType.APPROVED.getValue()) + && this.type.equals(PurchasedSharesStatusType.PURCHASED.getValue()); } public boolean isRedeemTransaction() { - return this.status.equals(PurchasedSharesStatusType.APPROVED.getValue()) && this.type.equals(PurchasedSharesStatusType.REDEEMED.getValue()) ; + return this.status.equals(PurchasedSharesStatusType.APPROVED.getValue()) + && this.type.equals(PurchasedSharesStatusType.REDEEMED.getValue()); } public boolean isChargeTransaction() { - return this.status.equals(PurchasedSharesStatusType.APPROVED.getValue()) && this.type.equals(PurchasedSharesStatusType.CHARGE_PAYMENT.getValue()) ; + return this.status.equals(PurchasedSharesStatusType.APPROVED.getValue()) + && this.type.equals(PurchasedSharesStatusType.CHARGE_PAYMENT.getValue()); } public boolean isPurchaseRejectedTransaction() { - return this.status.equals(PurchasedSharesStatusType.REJECTED.getValue()) && this.type.equals(PurchasedSharesStatusType.PURCHASED.getValue()) ; + return this.status.equals(PurchasedSharesStatusType.REJECTED.getValue()) + && this.type.equals(PurchasedSharesStatusType.PURCHASED.getValue()); } public void addShareAccountChargePaidBy(final ShareAccountChargePaidBy chargePaidBy) { - this.shareAccountChargesPaid.add(chargePaidBy) ; + this.shareAccountChargesPaid.add(chargePaidBy); } public BigDecimal amount() { - return this.amount ; + return this.amount; } public BigDecimal chargeAmount() { - return this.chargeAmount ; + return this.chargeAmount; } public void updateChargeAmount(BigDecimal totalChargeAmount) { this.amount = this.amount.add(totalChargeAmount); - this.chargeAmount = totalChargeAmount ; + this.chargeAmount = totalChargeAmount; } public void deductChargesFromTotalAmount(BigDecimal totalChargeAmount) { this.amount = this.amount.subtract(totalChargeAmount); - this.chargeAmount = totalChargeAmount ; + this.chargeAmount = totalChargeAmount; } public Set getChargesPaidBy() { - return this.shareAccountChargesPaid ; + return this.shareAccountChargesPaid; } public Integer getTransactionStatus() { - return this.status ; + return this.status; } public Integer getTransactionType() { - return this.type ; + return this.type; } public void updateAmountPaid(final BigDecimal amountPaid) { - this.amountPaid = amountPaid ; + this.amountPaid = amountPaid; } public void addAmountPaid(final BigDecimal amountPaid) { - if(isRedeemTransaction()) { - this.amountPaid = this.amountPaid.subtract(amountPaid) ; - }else if(isPurchasTransaction() /*|| isPurchaseRejectedTransaction()*/) { - this.amountPaid = this.amountPaid.add(amountPaid) ; + if (isRedeemTransaction()) { + this.amountPaid = this.amountPaid.subtract(amountPaid); + } else if (isPurchasTransaction() /* + * || isPurchaseRejectedTransaction() + */) { + this.amountPaid = this.amountPaid.add(amountPaid); } } public void resetAmountPaid() { - this.amountPaid = BigDecimal.ZERO ; + this.amountPaid = BigDecimal.ZERO; } public void setActive(boolean active) { - this.active = active ; - if(!this.active) { - //this.shareAccountChargesPaid.clear(); + this.active = active; + if (!this.active) { + // this.shareAccountChargesPaid.clear(); } } public void updateTransactionDate(final Date transactionDate) { - this.transactionDate = transactionDate ; + this.transactionDate = transactionDate; } public boolean isActive() { - return this.active ; + return this.active; } public BigDecimal shareValue() { - return this.shareValue ; + return this.shareValue; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/exceptions/IssueableSharesExceededException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/exceptions/IssueableSharesExceededException.java index 72eb6fae1..af6e68a66 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/exceptions/IssueableSharesExceededException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/exceptions/IssueableSharesExceededException.java @@ -28,4 +28,4 @@ public class IssueableSharesExceededException extends AbstractPlatformResourceNo public IssueableSharesExceededException() { super("error.msg.shares.issuable.shares.exceeded", "Issueable Shares exceeded than product definition"); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ActivateShareAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ActivateShareAccountCommandHandler.java index 2f2feccad..2b5108da3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ActivateShareAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ActivateShareAccountCommandHandler.java @@ -29,15 +29,15 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "SHAREACCOUNT", action = "ACTIVATE") -public class ActivateShareAccountCommandHandler implements NewCommandSourceHandler{ +public class ActivateShareAccountCommandHandler implements NewCommandSourceHandler { - - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public ActivateShareAccountCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApplyAddtionalSharesCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApplyAddtionalSharesCommandHandler.java index 71aea7ad3..5aa43fed3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApplyAddtionalSharesCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApplyAddtionalSharesCommandHandler.java @@ -29,15 +29,15 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "SHAREACCOUNT", action = "APPLYADDITIONALSHARES") -public class ApplyAddtionalSharesCommandHandler implements NewCommandSourceHandler{ +public class ApplyAddtionalSharesCommandHandler implements NewCommandSourceHandler { - - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public ApplyAddtionalSharesCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApproveAddtionalSharesCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApproveAddtionalSharesCommandHandler.java index 3fbf2d453..bac050084 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApproveAddtionalSharesCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApproveAddtionalSharesCommandHandler.java @@ -29,15 +29,15 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "SHAREACCOUNT", action = "APPROVEADDITIONALSHARES") -public class ApproveAddtionalSharesCommandHandler implements NewCommandSourceHandler{ +public class ApproveAddtionalSharesCommandHandler implements NewCommandSourceHandler { - - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public ApproveAddtionalSharesCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApproveShareAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApproveShareAccountCommandHandler.java index d1d69f8c0..658d8622d 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApproveShareAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/ApproveShareAccountCommandHandler.java @@ -29,15 +29,15 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "SHAREACCOUNT", action = "APPROVE") -public class ApproveShareAccountCommandHandler implements NewCommandSourceHandler{ +public class ApproveShareAccountCommandHandler implements NewCommandSourceHandler { - - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public ApproveShareAccountCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/CloseShareAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/CloseShareAccountCommandHandler.java index 0ba2917dd..a20689f0e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/CloseShareAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/CloseShareAccountCommandHandler.java @@ -29,15 +29,15 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "SHAREACCOUNT", action = "CLOSE") -public class CloseShareAccountCommandHandler implements NewCommandSourceHandler{ +public class CloseShareAccountCommandHandler implements NewCommandSourceHandler { - - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public CloseShareAccountCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/CreateShareAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/CreateShareAccountCommandHandler.java index dd12a273e..1640037a7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/CreateShareAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/CreateShareAccountCommandHandler.java @@ -29,15 +29,15 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "SHAREACCOUNT", action = "CREATE") -public class CreateShareAccountCommandHandler implements NewCommandSourceHandler{ +public class CreateShareAccountCommandHandler implements NewCommandSourceHandler { - - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public CreateShareAccountCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RedeemSharesCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RedeemSharesCommandHandler.java index 44cab3938..06f6f7ade 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RedeemSharesCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RedeemSharesCommandHandler.java @@ -29,15 +29,15 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "SHAREACCOUNT", action = "REDEEMSHARES") -public class RedeemSharesCommandHandler implements NewCommandSourceHandler{ +public class RedeemSharesCommandHandler implements NewCommandSourceHandler { - - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public RedeemSharesCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RejectAddtionalSharesCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RejectAddtionalSharesCommandHandler.java index 577b301bd..0a46bec2c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RejectAddtionalSharesCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RejectAddtionalSharesCommandHandler.java @@ -29,15 +29,15 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "SHAREACCOUNT", action = "REJECTADDITIONALSHARES") -public class RejectAddtionalSharesCommandHandler implements NewCommandSourceHandler{ +public class RejectAddtionalSharesCommandHandler implements NewCommandSourceHandler { - - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public RejectAddtionalSharesCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RejectShareAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RejectShareAccountCommandHandler.java index 9ef4479a9..4f45cdb44 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RejectShareAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/RejectShareAccountCommandHandler.java @@ -29,15 +29,15 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "SHAREACCOUNT", action = "REJECT") -public class RejectShareAccountCommandHandler implements NewCommandSourceHandler{ +public class RejectShareAccountCommandHandler implements NewCommandSourceHandler { - - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public RejectShareAccountCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/UndoApproveShareAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/UndoApproveShareAccountCommandHandler.java index ef2b3a1b3..5cab49df1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/UndoApproveShareAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/UndoApproveShareAccountCommandHandler.java @@ -29,15 +29,15 @@ import org.springframework.transaction.annotation.Transactional; @Service @CommandType(entity = "SHAREACCOUNT", action = "UNDOAPPROVAL") -public class UndoApproveShareAccountCommandHandler implements NewCommandSourceHandler{ +public class UndoApproveShareAccountCommandHandler implements NewCommandSourceHandler { - - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public UndoApproveShareAccountCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } + @Transactional @Override public CommandProcessingResult processCommand(JsonCommand jsonCommand) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/UpdateShareAccountCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/UpdateShareAccountCommandHandler.java index b7e6993d2..9a5e5b042 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/UpdateShareAccountCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/handler/UpdateShareAccountCommandHandler.java @@ -31,11 +31,11 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "SHAREACCOUNT", action = "UPDATE") public class UpdateShareAccountCommandHandler implements NewCommandSourceHandler { - private final ShareAccountWritePlatformService shareAccountWritePlatformService ; + private final ShareAccountWritePlatformService shareAccountWritePlatformService; @Autowired public UpdateShareAccountCommandHandler(final ShareAccountWritePlatformService shareAccountWritePlatformService) { - this.shareAccountWritePlatformService = shareAccountWritePlatformService ; + this.shareAccountWritePlatformService = shareAccountWritePlatformService; } @Transactional diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/serialization/ShareAccountDataSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/serialization/ShareAccountDataSerializer.java index da660da22..3101e0880 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/serialization/ShareAccountDataSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/serialization/ShareAccountDataSerializer.java @@ -87,28 +87,23 @@ public class ShareAccountDataSerializer { private final ShareProductRepositoryWrapper shareProductRepository; - private final SavingsAccountReadPlatformService savingsAccountReadPlatformService ; + private final SavingsAccountReadPlatformService savingsAccountReadPlatformService; - private static final Set approvalParameters = new HashSet<>(Arrays.asList(ShareAccountApiConstants - .locale_paramname, - ShareAccountApiConstants.dateformat_paramname, ShareAccountApiConstants.approveddate_paramname, - ShareAccountApiConstants.note_paramname)); + private static final Set approvalParameters = new HashSet<>( + Arrays.asList(ShareAccountApiConstants.locale_paramname, ShareAccountApiConstants.dateformat_paramname, + ShareAccountApiConstants.approveddate_paramname, ShareAccountApiConstants.note_paramname)); - private static final Set activateParameters = new HashSet<>(Arrays.asList(ShareAccountApiConstants - .locale_paramname, + private static final Set activateParameters = new HashSet<>(Arrays.asList(ShareAccountApiConstants.locale_paramname, ShareAccountApiConstants.dateformat_paramname, ShareAccountApiConstants.activatedate_paramname)); - private static final Set closeParameters = new HashSet<>(Arrays.asList(ShareAccountApiConstants - .locale_paramname, - ShareAccountApiConstants.dateformat_paramname, ShareAccountApiConstants.closeddate_paramname, - ShareAccountApiConstants.note_paramname)); + private static final Set closeParameters = new HashSet<>( + Arrays.asList(ShareAccountApiConstants.locale_paramname, ShareAccountApiConstants.dateformat_paramname, + ShareAccountApiConstants.closeddate_paramname, ShareAccountApiConstants.note_paramname)); - private static final Set addtionalSharesParameters = new HashSet<>(Arrays.asList(ShareAccountApiConstants - .locale_paramname, + private static final Set addtionalSharesParameters = new HashSet<>(Arrays.asList(ShareAccountApiConstants.locale_paramname, ShareAccountApiConstants.requesteddate_paramname, ShareAccountApiConstants.requestedshares_paramname, ShareAccountApiConstants.purchasedprice_paramname, ShareAccountApiConstants.dateformat_paramname)); - @Autowired public ShareAccountDataSerializer(final PlatformSecurityContext platformSecurityContext, final FromJsonHelper fromApiJsonHelper, final ChargeRepositoryWrapper chargeRepository, final SavingsAccountRepositoryWrapper savingsAccountRepositoryWrapper, @@ -120,7 +115,7 @@ public class ShareAccountDataSerializer { this.savingsAccountRepositoryWrapper = savingsAccountRepositoryWrapper; this.clientRepositoryWrapper = clientRepositoryWrapper; this.shareProductRepository = shareProductRepository; - this.savingsAccountReadPlatformService = savingsAccountReadPlatformService ; + this.savingsAccountReadPlatformService = savingsAccountReadPlatformService; } public ShareAccount validateAndCreate(JsonCommand jsonCommand) { @@ -151,26 +146,28 @@ public class ShareAccountDataSerializer { baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requestedShares).notNull() .longGreaterThanZero(); - if(shareProduct.getMinimumClientShares() != null && requestedShares < shareProduct.getMinimumClientShares()) { - baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requestedShares) - .failWithCode("client.can.not.purchase.shares.lessthan.product.definition", "Client can not purchase shares less than product definition"); + if (shareProduct.getMinimumClientShares() != null && requestedShares < shareProduct.getMinimumClientShares()) { + baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requestedShares).failWithCode( + "client.can.not.purchase.shares.lessthan.product.definition", + "Client can not purchase shares less than product definition"); } - if(shareProduct.getMaximumClientShares() != null && requestedShares > shareProduct.getMaximumClientShares()) { - baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requestedShares) - .failWithCode("client.can.not.purchase.shares.morethan.product.definition", "Client can not purchase shares more than product definition"); + if (shareProduct.getMaximumClientShares() != null && requestedShares > shareProduct.getMaximumClientShares()) { + baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requestedShares).failWithCode( + "client.can.not.purchase.shares.morethan.product.definition", + "Client can not purchase shares more than product definition"); } LocalDate applicationDate = this.fromApiJsonHelper.extractLocalDateNamed(ShareAccountApiConstants.applicationdate_param, element); baseDataValidator.reset().parameter(ShareAccountApiConstants.applicationdate_param).value(applicationDate).notNull(); - Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper.extractBooleanNamed( - ShareAccountApiConstants.allowdividendcalculationforinactiveclients_paramname, element); + Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper + .extractBooleanNamed(ShareAccountApiConstants.allowdividendcalculationforinactiveclients_paramname, element); Integer minimumActivePeriod = this.fromApiJsonHelper.extractIntegerNamed(ShareAccountApiConstants.minimumactiveperiod_paramname, element, locale); - PeriodFrequencyType minimumActivePeriodEnum = extractPeriodType( - ShareAccountApiConstants.minimumactiveperiodfrequencytype_paramname, element); + PeriodFrequencyType minimumActivePeriodEnum = extractPeriodType(ShareAccountApiConstants.minimumactiveperiodfrequencytype_paramname, + element); if (minimumActivePeriod != null) { baseDataValidator.reset().parameter(ShareAccountApiConstants.minimumactiveperiodfrequencytype_paramname) @@ -183,10 +180,12 @@ public class ShareAccountDataSerializer { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); - if(!this.savingsAccountReadPlatformService.isAccountBelongsToClient(clientId, savingsAccountId, DepositAccountType.SAVINGS_DEPOSIT, shareProduct.getCurrency().getCode())) { - throw new SavingsAccountNotFoundException(savingsAccountId) ; + if (!this.savingsAccountReadPlatformService.isAccountBelongsToClient(clientId, savingsAccountId, DepositAccountType.SAVINGS_DEPOSIT, + shareProduct.getCurrency().getCode())) { + throw new SavingsAccountNotFoundException(savingsAccountId); } - SavingsAccount savingsAccount = this.savingsAccountRepositoryWrapper.findOneWithNotFoundDetection(savingsAccountId, DepositAccountType.SAVINGS_DEPOSIT); + SavingsAccount savingsAccount = this.savingsAccountRepositoryWrapper.findOneWithNotFoundDetection(savingsAccountId, + DepositAccountType.SAVINGS_DEPOSIT); final MonetaryCurrency currency = shareProduct.getCurrency(); Set charges = assembleListOfAccountCharges(element, currency.getCode()); @@ -275,8 +274,8 @@ public class ShareAccountDataSerializer { } if (this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.submitteddate_paramname, element)) { - final Date submittedDate = this.fromApiJsonHelper.extractLocalDateNamed(ShareAccountApiConstants.submitteddate_paramname, - element).toDate(); + final Date submittedDate = this.fromApiJsonHelper + .extractLocalDateNamed(ShareAccountApiConstants.submitteddate_paramname, element).toDate(); baseDataValidator.reset().parameter(ShareAccountApiConstants.submitteddate_paramname).value(submittedDate).notNull(); if (account.setSubmittedDate(submittedDate)) { actualChanges.put(ShareAccountApiConstants.submitteddate_paramname, submittedDate); @@ -294,10 +293,11 @@ public class ShareAccountDataSerializer { if (this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.savingsaccountid_paramname, element)) { Long savingsAccountId = this.fromApiJsonHelper.extractLongNamed(ShareAccountApiConstants.savingsaccountid_paramname, element); baseDataValidator.reset().parameter(ShareAccountApiConstants.savingsaccountid_paramname).value(savingsAccountId).notNull() - .longGreaterThanZero(); - if(savingsAccountId != null) { - if(!this.savingsAccountReadPlatformService.isAccountBelongsToClient(account.getClientId(), savingsAccountId, DepositAccountType.SAVINGS_DEPOSIT, shareProduct.getCurrency().getCode())) { - throw new SavingsAccountNotFoundException(savingsAccountId) ; + .longGreaterThanZero(); + if (savingsAccountId != null) { + if (!this.savingsAccountReadPlatformService.isAccountBelongsToClient(account.getClientId(), savingsAccountId, + DepositAccountType.SAVINGS_DEPOSIT, shareProduct.getCurrency().getCode())) { + throw new SavingsAccountNotFoundException(savingsAccountId); } SavingsAccount savingsAccount = this.savingsAccountRepositoryWrapper.findOneWithNotFoundDetection(savingsAccountId); if (account.setSavingsAccount(savingsAccount)) { @@ -306,9 +306,9 @@ public class ShareAccountDataSerializer { } } - Date existingApplicationDate = null ; - List purchaseTransactionsList = new ArrayList<>() ; - Set chargesList = new HashSet<>() ; + Date existingApplicationDate = null; + List purchaseTransactionsList = new ArrayList<>(); + Set chargesList = new HashSet<>(); if (this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.requestedshares_paramname, element) || this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.charges_paramname, element)) { @@ -328,16 +328,16 @@ public class ShareAccountDataSerializer { } actualChanges.put("reversalIds", reveralIds); - Set charges = account.getCharges() ; - for(ShareAccountCharge charge: charges) { - if(charge.isActive()) { + Set charges = account.getCharges(); + for (ShareAccountCharge charge : charges) { + if (charge.isActive()) { charge.setActive(false); ChargeTimeType chargeTime = null; ChargeCalculationType chargeCalculation = null; Boolean status = Boolean.TRUE; - ShareAccountCharge accountCharge = ShareAccountCharge.createNewWithoutShareAccount(charge.getCharge(), charge.percentageOrAmount(), chargeTime, - chargeCalculation, status); - chargesList.add(accountCharge) ; + ShareAccountCharge accountCharge = ShareAccountCharge.createNewWithoutShareAccount(charge.getCharge(), + charge.percentageOrAmount(), chargeTime, chargeCalculation, status); + chargesList.add(accountCharge); } } } @@ -345,40 +345,43 @@ public class ShareAccountDataSerializer { if (this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.requestedshares_paramname, element)) { Long requestedShares = this.fromApiJsonHelper.extractLongNamed(ShareAccountApiConstants.requestedshares_paramname, element); baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requestedShares).notNull(); - Date applicationDate = null ; - purchaseTransactionsList.clear() ; - if(this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.applicationdate_param, element)) { + Date applicationDate = null; + purchaseTransactionsList.clear(); + if (this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.applicationdate_param, element)) { applicationDate = this.fromApiJsonHelper.extractLocalDateNamed(ShareAccountApiConstants.applicationdate_param, element) .toDate(); baseDataValidator.reset().parameter(ShareAccountApiConstants.applicationdate_param).value(applicationDate).notNull(); - }else { - applicationDate = existingApplicationDate ; + } else { + applicationDate = existingApplicationDate; } BigDecimal unitPrice = shareProduct.deriveMarketPrice(applicationDate); ShareAccountTransaction transaction = new ShareAccountTransaction(applicationDate, requestedShares, unitPrice); - purchaseTransactionsList.add(transaction) ; + purchaseTransactionsList.add(transaction); actualChanges.put(ShareAccountApiConstants.requestedshares_paramname, "Transaction"); - if(shareProduct.getMinimumClientShares() != null && requestedShares < shareProduct.getMinimumClientShares()) { - baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requestedShares) - .failWithCode("client.can.not.purchase.shares.lessthan.product.definition", "Client can not purchase shares less than product definition"); + if (shareProduct.getMinimumClientShares() != null && requestedShares < shareProduct.getMinimumClientShares()) { + baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requestedShares).failWithCode( + "client.can.not.purchase.shares.lessthan.product.definition", + "Client can not purchase shares less than product definition"); } - if(shareProduct.getMaximumClientShares() != null && requestedShares > shareProduct.getMaximumClientShares()) { - baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requestedShares) - .failWithCode("client.can.not.purchase.shares.morethan.product.definition", "Client can not purchase shares more than product definition"); + if (shareProduct.getMaximumClientShares() != null && requestedShares > shareProduct.getMaximumClientShares()) { + baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requestedShares).failWithCode( + "client.can.not.purchase.shares.morethan.product.definition", + "Client can not purchase shares more than product definition"); } } - if(!purchaseTransactionsList.isEmpty()) { - ShareAccountTransaction transaction = purchaseTransactionsList.get(0) ; + if (!purchaseTransactionsList.isEmpty()) { + ShareAccountTransaction transaction = purchaseTransactionsList.get(0); account.addTransaction(transaction); account.setTotalPendingShares(transaction.getTotalShares()); } - if (this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.allowdividendcalculationforinactiveclients_paramname, element)) { - Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper.extractBooleanNamed( - ShareAccountApiConstants.allowdividendcalculationforinactiveclients_paramname, element); + if (this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.allowdividendcalculationforinactiveclients_paramname, + element)) { + Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper + .extractBooleanNamed(ShareAccountApiConstants.allowdividendcalculationforinactiveclients_paramname, element); if (account.setAllowDividendCalculationForInactiveClients(allowdividendsForInactiveClients)) { actualChanges.put(ShareAccountApiConstants.allowdividendcalculationforinactiveclients_paramname, allowdividendsForInactiveClients); @@ -402,8 +405,8 @@ public class ShareAccountDataSerializer { } if (this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.minimumactiveperiod_paramname, element)) { - final Integer minimumActivePeriod = this.fromApiJsonHelper.extractIntegerNamed( - ShareAccountApiConstants.minimumactiveperiod_paramname, element, locale); + final Integer minimumActivePeriod = this.fromApiJsonHelper + .extractIntegerNamed(ShareAccountApiConstants.minimumactiveperiod_paramname, element, locale); baseDataValidator.reset().parameter(ShareAccountApiConstants.minimumactiveperiod_paramname).value(minimumActivePeriod) .notNull(); if (account.setminimumActivePeriod(minimumActivePeriod)) { @@ -412,8 +415,8 @@ public class ShareAccountDataSerializer { } if (this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.minimumactiveperiodfrequencytype_paramname, element)) { - PeriodFrequencyType minimumActivePeriod = extractPeriodType( - ShareAccountApiConstants.minimumactiveperiodfrequencytype_paramname, element); + PeriodFrequencyType minimumActivePeriod = extractPeriodType(ShareAccountApiConstants.minimumactiveperiodfrequencytype_paramname, + element); if (account.setminimumActivePeriodTypeEnum(minimumActivePeriod)) { actualChanges.put(ShareAccountApiConstants.minimumactiveperiodfrequencytype_paramname, minimumActivePeriod); } @@ -428,7 +431,7 @@ public class ShareAccountDataSerializer { } } } - if(chargesList != null && !chargesList.isEmpty()) { + if (chargesList != null && !chargesList.isEmpty()) { for (ShareAccountCharge charge : chargesList) { charge.update(account); } @@ -449,7 +452,7 @@ public class ShareAccountDataSerializer { final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("sharesaccount"); JsonElement element = jsonCommand.parsedJson(); - if(!account.status().equals(ShareAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue())) { + if (!account.status().equals(ShareAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue())) { baseDataValidator.failWithCodeNoParameterAddedToErrorCode("is.not.pending.for.approval"); } LocalDate approvedDate = this.fromApiJsonHelper.extractLocalDateNamed(ShareAccountApiConstants.approveddate_paramname, element); @@ -461,10 +464,10 @@ public class ShareAccountDataSerializer { .failWithCodeNoParameterAddedToErrorCode("approved.date.cannot.be.before.submitted.date"); } - Set transactions = account.getShareAccountTransactions() ; - for(ShareAccountTransaction transaction: transactions) { - if(transaction.isActive() && transaction.isPendingForApprovalTransaction()) { - validateTotalSubsribedShares(account, transaction, baseDataValidator) ; + Set transactions = account.getShareAccountTransactions(); + for (ShareAccountTransaction transaction : transactions) { + if (transaction.isActive() && transaction.isPendingForApprovalTransaction()) { + validateTotalSubsribedShares(account, transaction, baseDataValidator); } } @@ -477,24 +480,26 @@ public class ShareAccountDataSerializer { return actualChanges; } - private void validateTotalSubsribedShares(final ShareAccount account, final ShareAccountTransaction transaction, final DataValidatorBuilder baseDataValidator) { - Long totalSubsribedShares = account.getShareProduct().getSubscribedShares() ; - Long requested = Long.valueOf(0) ; - if(transaction.isActive() && transaction.isPendingForApprovalTransaction()) { - requested +=transaction.getTotalShares() ; + private void validateTotalSubsribedShares(final ShareAccount account, final ShareAccountTransaction transaction, + final DataValidatorBuilder baseDataValidator) { + Long totalSubsribedShares = account.getShareProduct().getSubscribedShares(); + Long requested = Long.valueOf(0); + if (transaction.isActive() && transaction.isPendingForApprovalTransaction()) { + requested += transaction.getTotalShares(); } - Long totalSharesIssuable = account.getShareProduct().getSharesIssued() ; - if(totalSharesIssuable == null) { + Long totalSharesIssuable = account.getShareProduct().getSharesIssued(); + if (totalSharesIssuable == null) { totalSharesIssuable = account.getShareProduct().getTotalShares(); } - if(totalSubsribedShares == null) { + if (totalSubsribedShares == null) { totalSubsribedShares = Long.valueOf(0); } - if(totalSubsribedShares+requested > totalSharesIssuable) { + if (totalSubsribedShares + requested > totalSharesIssuable) { baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(requested) - .failWithCodeNoParameterAddedToErrorCode("shares.requested.can.not.be.approved.exceeding.totalshares.issuable"); + .failWithCodeNoParameterAddedToErrorCode("shares.requested.can.not.be.approved.exceeding.totalshares.issuable"); } } + private void updateTotalChargeDerived(final ShareAccount shareAccount) { // Set charges = shareAccount.getCharges() ; Set transactions = shareAccount.getShareAccountTransactions(); @@ -524,7 +529,7 @@ public class ShareAccountDataSerializer { this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), activateParameters); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("sharesaccount"); - if(!account.status().equals(ShareAccountStatusType.APPROVED.getValue())) { + if (!account.status().equals(ShareAccountStatusType.APPROVED.getValue())) { baseDataValidator.failWithCodeNoParameterAddedToErrorCode("is.not.in.approved.status"); } account.undoApprove(); @@ -534,23 +539,23 @@ public class ShareAccountDataSerializer { } private void updateTotalChargeDerivedForUndoApproval(final ShareAccount shareAccount) { - Set purchaseTransactions = shareAccount.getPendingForApprovalSharePurchaseTransactions() ; - //we will have only 1 purchase transaction. Take that - ShareAccountTransaction purchaseTransaction = null ; + Set purchaseTransactions = shareAccount.getPendingForApprovalSharePurchaseTransactions(); + // we will have only 1 purchase transaction. Take that + ShareAccountTransaction purchaseTransaction = null; for (ShareAccountTransaction transaction : purchaseTransactions) { - purchaseTransaction = transaction ; + purchaseTransaction = transaction; } - BigDecimal transactionAmount = BigDecimal.ZERO ; - if(purchaseTransaction != null) { - transactionAmount = purchaseTransaction.amount().subtract(purchaseTransaction.chargeAmount()) ; + BigDecimal transactionAmount = BigDecimal.ZERO; + if (purchaseTransaction != null) { + transactionAmount = purchaseTransaction.amount().subtract(purchaseTransaction.chargeAmount()); + } + Set charges = shareAccount.getCharges(); + for (ShareAccountCharge charge : charges) { + if (charge.isActive() && charge.isSharesPurchaseCharge()) { + charge.update(transactionAmount, charge.percentageOrAmount()); + charge.deriveChargeAmount(transactionAmount, shareAccount.getCurrency()); + } } - Set charges = shareAccount.getCharges() ; - for(ShareAccountCharge charge: charges) { - if(charge.isActive() && charge.isSharesPurchaseCharge()) { - charge.update(transactionAmount, charge.percentageOrAmount()) ; - charge.deriveChargeAmount(transactionAmount, shareAccount.getCurrency()); - } - } Set transactions = shareAccount.getShareAccountTransactions(); for (ShareAccountTransaction transaction : transactions) { if (transaction.isActive()) { @@ -560,6 +565,7 @@ public class ShareAccountDataSerializer { } } } + @SuppressWarnings("unused") public Map validateAndReject(JsonCommand jsonCommand, ShareAccount account) { Map actualChanges = new HashMap<>(); @@ -579,7 +585,7 @@ public class ShareAccountDataSerializer { final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("sharesaccount"); JsonElement element = jsonCommand.parsedJson(); - if(!account.status().equals(ShareAccountStatusType.APPROVED.getValue())) { + if (!account.status().equals(ShareAccountStatusType.APPROVED.getValue())) { baseDataValidator.failWithCodeNoParameterAddedToErrorCode("is.not.in.approved.status"); } LocalDate activatedDate = this.fromApiJsonHelper.extractLocalDateNamed(ShareAccountApiConstants.activatedate_paramname, element); @@ -655,13 +661,12 @@ public class ShareAccountDataSerializer { Map actualChanges = new HashMap<>(); if (StringUtils.isBlank(jsonCommand.json())) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), - addtionalSharesParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), addtionalSharesParameters); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("sharesaccount"); JsonElement element = jsonCommand.parsedJson(); - if(!account.status().equals(ShareAccountStatusType.ACTIVE.getValue())) { - baseDataValidator.failWithCodeNoParameterAddedToErrorCode("is.not.in.active.state") ; + if (!account.status().equals(ShareAccountStatusType.ACTIVE.getValue())) { + baseDataValidator.failWithCodeNoParameterAddedToErrorCode("is.not.in.active.state"); } LocalDate requestedDate = this.fromApiJsonHelper.extractLocalDateNamed(ShareAccountApiConstants.requesteddate_paramname, element); baseDataValidator.reset().parameter(ShareAccountApiConstants.requesteddate_paramname).value(requestedDate).notNull(); @@ -670,26 +675,26 @@ public class ShareAccountDataSerializer { ShareProduct shareProduct = account.getShareProduct(); if (sharesRequested != null) { Long totalSharesAfterapproval = account.getTotalApprovedShares() + sharesRequested; - if(shareProduct.getMaximumClientShares() != null && totalSharesAfterapproval > shareProduct.getMaximumClientShares()) { - baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(sharesRequested) - .failWithCode("exceeding.maximum.limit.defined.in.the.shareproduct", "Existing and requested shares count is more than product definition"); + if (shareProduct.getMaximumClientShares() != null && totalSharesAfterapproval > shareProduct.getMaximumClientShares()) { + baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(sharesRequested).failWithCode( + "exceeding.maximum.limit.defined.in.the.shareproduct", + "Existing and requested shares count is more than product definition"); } } - boolean isTransactionBeforeExistingTransactions = false ; - Set transactions = account.getShareAccountTransactions() ; - for(ShareAccountTransaction transaction: transactions) { - if(!transaction.isChargeTransaction()) { - LocalDate transactionDate = new LocalDate(transaction.getPurchasedDate()) ; - if(requestedDate.isBefore(transactionDate)) { - isTransactionBeforeExistingTransactions = true ; - break ; + boolean isTransactionBeforeExistingTransactions = false; + Set transactions = account.getShareAccountTransactions(); + for (ShareAccountTransaction transaction : transactions) { + if (!transaction.isChargeTransaction()) { + LocalDate transactionDate = new LocalDate(transaction.getPurchasedDate()); + if (requestedDate.isBefore(transactionDate)) { + isTransactionBeforeExistingTransactions = true; + break; } } } - if(isTransactionBeforeExistingTransactions) { - baseDataValidator.reset().parameter(ShareAccountApiConstants.requesteddate_paramname) - .value(requestedDate) - .failWithCodeNoParameterAddedToErrorCode("purchase.transaction.date.cannot.be.before.existing.transactions"); + if (isTransactionBeforeExistingTransactions) { + baseDataValidator.reset().parameter(ShareAccountApiConstants.requesteddate_paramname).value(requestedDate) + .failWithCodeNoParameterAddedToErrorCode("purchase.transaction.date.cannot.be.before.existing.transactions"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } @@ -706,7 +711,8 @@ public class ShareAccountDataSerializer { BigDecimal totalChargeAmount = BigDecimal.ZERO; for (ShareAccountCharge charge : charges) { if (charge.isActive() && charge.isSharesPurchaseCharge()) { - BigDecimal amount = charge.updateChargeDetailsForAdditionalSharesRequest(purchaseTransaction.amount(), account.getCurrency()); + BigDecimal amount = charge.updateChargeDetailsForAdditionalSharesRequest(purchaseTransaction.amount(), + account.getCurrency()); ShareAccountChargePaidBy paidBy = new ShareAccountChargePaidBy(purchaseTransaction, charge, amount); purchaseTransaction.addShareAccountChargePaidBy(paidBy); totalChargeAmount = totalChargeAmount.add(amount); @@ -719,8 +725,7 @@ public class ShareAccountDataSerializer { Map actualChanges = new HashMap<>(); if (StringUtils.isBlank(jsonCommand.json())) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), - addtionalSharesParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), addtionalSharesParameters); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("sharesaccount"); JsonElement element = jsonCommand.parsedJson(); @@ -733,7 +738,7 @@ public class ShareAccountDataSerializer { baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(purchasedSharesId).notBlank(); ShareAccountTransaction transaction = account.retrievePurchasedShares(purchasedSharesId); if (transaction != null) { - validateTotalSubsribedShares(account, transaction, baseDataValidator) ; + validateTotalSubsribedShares(account, transaction, baseDataValidator); totalShares += transaction.getTotalShares().longValue(); transaction.approve(); updateTotalChargeDerivedForAdditonalShares(account, transaction); @@ -769,8 +774,7 @@ public class ShareAccountDataSerializer { Map actualChanges = new HashMap<>(); if (StringUtils.isBlank(jsonCommand.json())) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), - addtionalSharesParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), addtionalSharesParameters); JsonElement element = jsonCommand.parsedJson(); final ArrayList purchasedShares = new ArrayList<>(); if (this.fromApiJsonHelper.parameterExists(ShareAccountApiConstants.requestedshares_paramname, element)) { @@ -794,7 +798,8 @@ public class ShareAccountDataSerializer { return actualChanges; } - private void updateTotalChargeDerivedForAdditonalSharesReject(final ShareAccount shareAccount, final ShareAccountTransaction transaction) { + private void updateTotalChargeDerivedForAdditonalSharesReject(final ShareAccount shareAccount, + final ShareAccountTransaction transaction) { Set paidBySet = transaction.getChargesPaidBy(); if (paidBySet != null && !paidBySet.isEmpty()) { for (ShareAccountChargePaidBy chargePaidBy : paidBySet) { @@ -814,8 +819,7 @@ public class ShareAccountDataSerializer { Map actualChanges = new HashMap<>(); if (StringUtils.isBlank(jsonCommand.json())) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), - addtionalSharesParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), addtionalSharesParameters); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("sharesaccount"); JsonElement element = jsonCommand.parsedJson(); @@ -824,27 +828,26 @@ public class ShareAccountDataSerializer { final Long sharesRequested = this.fromApiJsonHelper.extractLongNamed(ShareAccountApiConstants.requestedshares_paramname, element); baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname).value(sharesRequested).notNull() .longGreaterThanZero(); - boolean isTransactionBeforeExistingTransactions = false ; - Set transactions = account.getShareAccountTransactions() ; - for(ShareAccountTransaction transaction: transactions) { - if(!transaction.isChargeTransaction() && transaction.isActive()) { - LocalDate transactionDate = new LocalDate(transaction.getPurchasedDate()) ; - if(requestedDate.isBefore(transactionDate)) { - isTransactionBeforeExistingTransactions = true ; - break ; + boolean isTransactionBeforeExistingTransactions = false; + Set transactions = account.getShareAccountTransactions(); + for (ShareAccountTransaction transaction : transactions) { + if (!transaction.isChargeTransaction() && transaction.isActive()) { + LocalDate transactionDate = new LocalDate(transaction.getPurchasedDate()); + if (requestedDate.isBefore(transactionDate)) { + isTransactionBeforeExistingTransactions = true; + break; } } } - if(isTransactionBeforeExistingTransactions) { - baseDataValidator.reset().parameter(ShareAccountApiConstants.requesteddate_paramname) - .value(requestedDate) - .failWithCodeNoParameterAddedToErrorCode("redeem.transaction.date.cannot.be.before.existing.transactions"); + if (isTransactionBeforeExistingTransactions) { + baseDataValidator.reset().parameter(ShareAccountApiConstants.requesteddate_paramname).value(requestedDate) + .failWithCodeNoParameterAddedToErrorCode("redeem.transaction.date.cannot.be.before.existing.transactions"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - BigDecimal unitPrice = account.getShareProduct().deriveMarketPrice(requestedDate.toDate()) ; + BigDecimal unitPrice = account.getShareProduct().deriveMarketPrice(requestedDate.toDate()); ShareAccountTransaction transaction = ShareAccountTransaction.createRedeemTransaction(requestedDate.toDate(), sharesRequested, unitPrice); - validateRedeemRequest(account, transaction, baseDataValidator, dataValidationErrors) ; + validateRedeemRequest(account, transaction, baseDataValidator, dataValidationErrors); account.addAdditionalPurchasedShares(transaction); actualChanges.put(ShareAccountApiConstants.requestedshares_paramname, transaction); @@ -853,7 +856,7 @@ public class ShareAccountDataSerializer { } private void validateRedeemRequest(final ShareAccount account, ShareAccountTransaction redeemTransaction, - final DataValidatorBuilder baseDataValidator, final List dataValidationErrors ) { + final DataValidatorBuilder baseDataValidator, final List dataValidationErrors) { if (account.getTotalApprovedShares() < redeemTransaction.getTotalShares()) { baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname) @@ -867,8 +870,8 @@ public class ShareAccountDataSerializer { final PeriodFrequencyType periodType = account.getLockinPeriodFrequencyType(); if (lockinPeriod == null && periodType == null) { return; } Long totalSharesCanBeRedeemed = Long.valueOf(0); - Long totalSharesPurchasedBeforeRedeem = Long.valueOf(0) ; - boolean isPurchaseTransactionExist = false ; + Long totalSharesPurchasedBeforeRedeem = Long.valueOf(0); + boolean isPurchaseTransactionExist = false; Set transactions = account.getShareAccountTransactions(); for (ShareAccountTransaction transaction : transactions) { @@ -883,8 +886,8 @@ public class ShareAccountDataSerializer { } } - if(!purchaseDate.isAfter(redeemDate)) { - isPurchaseTransactionExist = true ; + if (!purchaseDate.isAfter(redeemDate)) { + isPurchaseTransactionExist = true; if (transaction.isPurchasTransaction()) { totalSharesPurchasedBeforeRedeem += transaction.getTotalShares(); } else if (transaction.isRedeemTransaction()) { @@ -893,15 +896,14 @@ public class ShareAccountDataSerializer { } } } - if(!isPurchaseTransactionExist) { - baseDataValidator.reset().parameter(ShareAccountApiConstants.requesteddate_paramname) - .value(redeemDate) - .failWithCodeNoParameterAddedToErrorCode("no.purchase.transaction.found.before.redeem.date"); - }else if (totalSharesPurchasedBeforeRedeem < redeemTransaction.getTotalShares()) { + if (!isPurchaseTransactionExist) { + baseDataValidator.reset().parameter(ShareAccountApiConstants.requesteddate_paramname).value(redeemDate) + .failWithCodeNoParameterAddedToErrorCode("no.purchase.transaction.found.before.redeem.date"); + } else if (totalSharesPurchasedBeforeRedeem < redeemTransaction.getTotalShares()) { baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname) - .value(redeemTransaction.getTotalShares()) - .failWithCodeNoParameterAddedToErrorCode("cannot.be.redeemed.due.to.insufficient.shares.for.this.redeem.date"); - }else if (totalSharesCanBeRedeemed < redeemTransaction.getTotalShares()) { + .value(redeemTransaction.getTotalShares()) + .failWithCodeNoParameterAddedToErrorCode("cannot.be.redeemed.due.to.insufficient.shares.for.this.redeem.date"); + } else if (totalSharesCanBeRedeemed < redeemTransaction.getTotalShares()) { baseDataValidator.reset().parameter(ShareAccountApiConstants.requestedshares_paramname) .value(redeemTransaction.getTotalShares()) .failWithCodeNoParameterAddedToErrorCode("cannot.be.redeemed.due.to.lockinperiod"); @@ -910,27 +912,27 @@ public class ShareAccountDataSerializer { } private LocalDate deriveLockinPeriodDuration(final Integer lockinPeriod, final PeriodFrequencyType periodType, LocalDate purchaseDate) { - LocalDate lockinDate = purchaseDate ; - if(periodType != null) { - switch(periodType) { - case INVALID: //It never comes in to this state. - break ; + LocalDate lockinDate = purchaseDate; + if (periodType != null) { + switch (periodType) { + case INVALID: // It never comes in to this state. + break; case DAYS: - lockinDate = purchaseDate.plusDays(lockinPeriod) ; - break ; + lockinDate = purchaseDate.plusDays(lockinPeriod); + break; case WEEKS: - lockinDate = purchaseDate.plusWeeks(lockinPeriod) ; - break ; + lockinDate = purchaseDate.plusWeeks(lockinPeriod); + break; case MONTHS: - lockinDate = purchaseDate.plusMonths(lockinPeriod) ; - break ; + lockinDate = purchaseDate.plusMonths(lockinPeriod); + break; case YEARS: - lockinDate = purchaseDate.plusYears(lockinPeriod) ; - break ; + lockinDate = purchaseDate.plusYears(lockinPeriod); + break; default: } } - return lockinDate ; + return lockinDate; } private void handleRedeemSharesChargeTransactions(final ShareAccount account, final ShareAccountTransaction transaction) { @@ -969,21 +971,20 @@ public class ShareAccountDataSerializer { LocalDate closedDate = this.fromApiJsonHelper.extractLocalDateNamed(ShareAccountApiConstants.closeddate_paramname, element); baseDataValidator.reset().parameter(ShareAccountApiConstants.approveddate_paramname).value(closedDate).notNull(); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - boolean isTransactionBeforeExistingTransactions = false ; - Set transactions = account.getShareAccountTransactions() ; - for(ShareAccountTransaction transaction: transactions) { - if(!transaction.isChargeTransaction()) { - LocalDate transactionDate = new LocalDate(transaction.getPurchasedDate()) ; - if(closedDate.isBefore(transactionDate)) { - isTransactionBeforeExistingTransactions = true ; - break ; + boolean isTransactionBeforeExistingTransactions = false; + Set transactions = account.getShareAccountTransactions(); + for (ShareAccountTransaction transaction : transactions) { + if (!transaction.isChargeTransaction()) { + LocalDate transactionDate = new LocalDate(transaction.getPurchasedDate()); + if (closedDate.isBefore(transactionDate)) { + isTransactionBeforeExistingTransactions = true; + break; } } } - if(isTransactionBeforeExistingTransactions) { - baseDataValidator.reset().parameter(ShareAccountApiConstants.closeddate_paramname) - .value(closedDate) - .failWithCodeNoParameterAddedToErrorCode("share.account.cannot.be.closed.before.existing.transactions"); + if (isTransactionBeforeExistingTransactions) { + baseDataValidator.reset().parameter(ShareAccountApiConstants.closeddate_paramname).value(closedDate) + .failWithCodeNoParameterAddedToErrorCode("share.account.cannot.be.closed.before.existing.transactions"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/PurchasedSharesReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/PurchasedSharesReadPlatformService.java index 280d7eb00..55c177c24 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/PurchasedSharesReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/PurchasedSharesReadPlatformService.java @@ -23,5 +23,5 @@ import org.apache.fineract.portfolio.shareaccounts.data.ShareAccountTransactionD public interface PurchasedSharesReadPlatformService { - public Collection retrievePurchasedShares(final Long accountId) ; + public Collection retrievePurchasedShares(final Long accountId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/PurchasedSharesReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/PurchasedSharesReadPlatformServiceImpl.java index 927b8fb0e..b60c027d2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/PurchasedSharesReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/PurchasedSharesReadPlatformServiceImpl.java @@ -33,56 +33,55 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class PurchasedSharesReadPlatformServiceImpl implements - PurchasedSharesReadPlatformService { +public class PurchasedSharesReadPlatformServiceImpl implements PurchasedSharesReadPlatformService { private final JdbcTemplate jdbcTemplate; @Autowired public PurchasedSharesReadPlatformServiceImpl(final RoutingDataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource) ; + this.jdbcTemplate = new JdbcTemplate(dataSource); } + @Override - public Collection retrievePurchasedShares( - Long accountId) { - PurchasedSharesDataRowMapper mapper = new PurchasedSharesDataRowMapper() ; + public Collection retrievePurchasedShares(Long accountId) { + PurchasedSharesDataRowMapper mapper = new PurchasedSharesDataRowMapper(); final String sql = "select " + mapper.schema() + " where saps.account_id=? and saps.is_active = 1"; - return this.jdbcTemplate.query(sql, mapper, new Object[] { accountId}); + return this.jdbcTemplate.query(sql, mapper, new Object[] { accountId }); } private final static class PurchasedSharesDataRowMapper implements RowMapper { - private final String schema ; + private final String schema; public PurchasedSharesDataRowMapper() { StringBuilder buff = new StringBuilder() - .append("saps.id, saps.account_id, saps.transaction_date, saps.total_shares, saps.unit_price, ") - .append("saps.status_enum, saps.type_enum, saps.amount, saps.charge_amount as chargeamount, ") - .append("saps.amount_paid as amountPaid") - .append(" from m_share_account_transactions saps "); - schema = buff.toString() ; + .append("saps.id, saps.account_id, saps.transaction_date, saps.total_shares, saps.unit_price, ") + .append("saps.status_enum, saps.type_enum, saps.amount, saps.charge_amount as chargeamount, ") + .append("saps.amount_paid as amountPaid").append(" from m_share_account_transactions saps "); + schema = buff.toString(); } - @Override - public ShareAccountTransactionData mapRow(ResultSet rs, int rowNum) - throws SQLException { - final Long id = rs.getLong("id") ; - final Long accountId = rs.getLong("account_id") ; - final LocalDate purchasedDate = new LocalDate(rs.getDate("transaction_date")) ; - final Long numberOfShares = JdbcSupport.getLong(rs, "total_shares") ; - final BigDecimal purchasedPrice = rs.getBigDecimal("unit_price") ; - final Integer status = rs.getInt("status_enum") ; - final EnumOptionData statusEnum = SharesEnumerations.purchasedSharesEnum(status) ; - final Integer type = rs.getInt("type_enum") ; - final EnumOptionData typeEnum = SharesEnumerations.purchasedSharesEnum(type) ; - final BigDecimal amount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amount") ; - final BigDecimal chargeAmount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "chargeamount") ; - final BigDecimal amountPaid = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amountPaid") ; - return new ShareAccountTransactionData(id,accountId, purchasedDate, numberOfShares, purchasedPrice, statusEnum, typeEnum, amount, chargeAmount, amountPaid); + @Override + public ShareAccountTransactionData mapRow(ResultSet rs, int rowNum) throws SQLException { + final Long id = rs.getLong("id"); + final Long accountId = rs.getLong("account_id"); + final LocalDate purchasedDate = new LocalDate(rs.getDate("transaction_date")); + final Long numberOfShares = JdbcSupport.getLong(rs, "total_shares"); + final BigDecimal purchasedPrice = rs.getBigDecimal("unit_price"); + final Integer status = rs.getInt("status_enum"); + final EnumOptionData statusEnum = SharesEnumerations.purchasedSharesEnum(status); + final Integer type = rs.getInt("type_enum"); + final EnumOptionData typeEnum = SharesEnumerations.purchasedSharesEnum(type); + final BigDecimal amount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amount"); + final BigDecimal chargeAmount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "chargeamount"); + final BigDecimal amountPaid = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amountPaid"); + + return new ShareAccountTransactionData(id, accountId, purchasedDate, numberOfShares, purchasedPrice, statusEnum, typeEnum, + amount, chargeAmount, amountPaid); } public String schema() { - return this.schema ; + return this.schema; } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountChargeReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountChargeReadPlatformService.java index 1ab2b7a0f..3c49f6429 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountChargeReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountChargeReadPlatformService.java @@ -23,5 +23,5 @@ import org.apache.fineract.portfolio.shareaccounts.data.ShareAccountChargeData; public interface ShareAccountChargeReadPlatformService { - Collection retrieveAccountCharges(final Long accountId, final String status) ; + Collection retrieveAccountCharges(final Long accountId, final String status); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountChargeReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountChargeReadPlatformServiceImpl.java index 76c36dc99..0439c36a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountChargeReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountChargeReadPlatformServiceImpl.java @@ -35,24 +35,20 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service -public class ShareAccountChargeReadPlatformServiceImpl implements - ShareAccountChargeReadPlatformService { +public class ShareAccountChargeReadPlatformServiceImpl implements ShareAccountChargeReadPlatformService { private final JdbcTemplate jdbcTemplate; @Autowired - public ShareAccountChargeReadPlatformServiceImpl( - final RoutingDataSource dataSource) { + public ShareAccountChargeReadPlatformServiceImpl(final RoutingDataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override - public Collection retrieveAccountCharges( - Long accountId, String status) { + public Collection retrieveAccountCharges(Long accountId, String status) { final ShareAccountChargeMapper rm = new ShareAccountChargeMapper(); final StringBuilder sqlBuilder = new StringBuilder(); - sqlBuilder.append("select ").append(rm.schema()) - .append(" where sc.account_id=? "); + sqlBuilder.append("select ").append(rm.schema()).append(" where sc.account_id=? "); if (status.equalsIgnoreCase("active")) { sqlBuilder.append(" and sc.is_active = 1 "); } else if (status.equalsIgnoreCase("inactive")) { @@ -60,18 +56,15 @@ public class ShareAccountChargeReadPlatformServiceImpl implements } sqlBuilder.append(" order by sc.charge_time_enum ASC"); - return this.jdbcTemplate.query(sqlBuilder.toString(), rm, - new Object[] { accountId }); + return this.jdbcTemplate.query(sqlBuilder.toString(), rm, new Object[] { accountId }); } - private final static class ShareAccountChargeMapper implements - RowMapper { + private final static class ShareAccountChargeMapper implements RowMapper { private final String schema; public ShareAccountChargeMapper() { - StringBuilder buff = new StringBuilder() - .append("sc.id as id, c.id as chargeId, sc.account_id as accountId, c.name as name, ") + StringBuilder buff = new StringBuilder().append("sc.id as id, c.id as chargeId, sc.account_id as accountId, c.name as name, ") .append("sc.amount as amountDue, sc.amount_paid_derived as amountPaid, ") .append("sc.amount_waived_derived as amountWaived, sc.amount_writtenoff_derived as amountWrittenOff, ") .append("sc.amount_outstanding_derived as amountOutstanding, sc.calculation_percentage as percentageOf, ") @@ -88,58 +81,42 @@ public class ShareAccountChargeReadPlatformServiceImpl implements } @Override - public ShareAccountChargeData mapRow(ResultSet rs, int rowNum) - throws SQLException { + public ShareAccountChargeData mapRow(ResultSet rs, int rowNum) throws SQLException { final Long id = rs.getLong("id"); final Long chargeId = rs.getLong("chargeId"); final Long accountId = rs.getLong("accountId"); final String name = rs.getString("name"); final BigDecimal amount = rs.getBigDecimal("amountDue"); - final BigDecimal amountPaid = JdbcSupport - .getBigDecimalDefaultToZeroIfNull(rs, "amountPaid"); - final BigDecimal amountWaived = JdbcSupport - .getBigDecimalDefaultToZeroIfNull(rs, "amountWaived"); - final BigDecimal amountWrittenOff = JdbcSupport - .getBigDecimalDefaultToZeroIfNull(rs, "amountWrittenOff"); - final BigDecimal amountOutstanding = rs - .getBigDecimal("amountOutstanding"); + final BigDecimal amountPaid = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amountPaid"); + final BigDecimal amountWaived = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amountWaived"); + final BigDecimal amountWrittenOff = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amountWrittenOff"); + final BigDecimal amountOutstanding = rs.getBigDecimal("amountOutstanding"); - final BigDecimal percentageOf = JdbcSupport - .getBigDecimalDefaultToZeroIfNull(rs, "percentageOf"); - final BigDecimal amountPercentageAppliedTo = JdbcSupport - .getBigDecimalDefaultToZeroIfNull(rs, - "amountPercentageAppliedTo"); + final BigDecimal percentageOf = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "percentageOf"); + final BigDecimal amountPercentageAppliedTo = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "amountPercentageAppliedTo"); 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 currencyDecimalPlaces = JdbcSupport.getInteger(rs, - "currencyDecimalPlaces"); - final Integer inMultiplesOf = JdbcSupport.getInteger(rs, - "inMultiplesOf"); + final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); + final Integer currencyDecimalPlaces = JdbcSupport.getInteger(rs, "currencyDecimalPlaces"); + final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, - currencyName, currencyDecimalPlaces, inMultiplesOf, + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDecimalPlaces, inMultiplesOf, currencyDisplaySymbol, currencyNameCode); final int chargeTime = rs.getInt("chargeTime"); - final EnumOptionData chargeTimeType = ChargeEnumerations - .chargeTimeType(chargeTime); + final EnumOptionData chargeTimeType = ChargeEnumerations.chargeTimeType(chargeTime); final int chargeCalculation = rs.getInt("chargeCalculation"); - final EnumOptionData chargeCalculationType = ChargeEnumerations - .chargeCalculationType(chargeCalculation); + final EnumOptionData chargeCalculationType = ChargeEnumerations.chargeCalculationType(chargeCalculation); final Boolean isActive = rs.getBoolean("isActive"); - final BigDecimal chargeamountorpercentage = rs.getBigDecimal("charge_amount_or_percentage") ; + final BigDecimal chargeamountorpercentage = rs.getBigDecimal("charge_amount_or_percentage"); final Collection chargeOptions = null; - return new ShareAccountChargeData(id, chargeId, accountId, name, - currency, amount, amountPaid, amountWaived, - amountWrittenOff, amountOutstanding, chargeTimeType, - chargeCalculationType, percentageOf, - amountPercentageAppliedTo, chargeOptions, isActive, chargeamountorpercentage); + return new ShareAccountChargeData(id, chargeId, accountId, name, currency, amount, amountPaid, amountWaived, amountWrittenOff, + amountOutstanding, chargeTimeType, chargeCalculationType, percentageOf, amountPercentageAppliedTo, chargeOptions, + isActive, chargeamountorpercentage); } public String schema() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountCommandsServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountCommandsServiceImpl.java index 2d7de470e..b9da48efe 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountCommandsServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountCommandsServiceImpl.java @@ -33,52 +33,51 @@ public class ShareAccountCommandsServiceImpl implements AccountsCommandsService private final FromJsonHelper fromApiJsonHelper; - private final ShareAccountDataSerializer shareAccountDataSerializer ; + private final ShareAccountDataSerializer shareAccountDataSerializer; @Autowired public ShareAccountCommandsServiceImpl(final FromJsonHelper fromApiJsonHelper, final ShareAccountDataSerializer shareAccountDataSerializer) { this.fromApiJsonHelper = fromApiJsonHelper; - this.shareAccountDataSerializer = shareAccountDataSerializer ; + this.shareAccountDataSerializer = shareAccountDataSerializer; } @Override public Object handleCommand(Long accountId, String command, String jsonBody) { final JsonElement parsedCommand = this.fromApiJsonHelper.parse(jsonBody); final JsonCommand jsonCommand = JsonCommand.from(jsonBody, parsedCommand, this.fromApiJsonHelper, null, null, null, null, null, - null, null, null, null, null,null,null); - if(ShareAccountApiConstants.APPROVE_COMMAND.equals(command)){ - return approveShareAccount(accountId, jsonCommand) ; - }if(ShareAccountApiConstants.REJECT_COMMAND.equals(command)){ - return rejectShareAccount(accountId, jsonCommand) ; - }else if(ShareAccountApiConstants.APPLY_ADDITIONALSHARES_COMMAND.equals(command)) { - return applyAdditionalShares(accountId, jsonCommand) ; - }else if(ShareAccountApiConstants.APPROVE_ADDITIONSHARES_COMMAND.equals(command)) { - return approveAdditionalShares(accountId, jsonCommand) ; - }else if(ShareAccountApiConstants.REJECT_ADDITIONSHARES_COMMAND.equals(command)) { - return rejectAdditionalShares(accountId, jsonCommand) ; + null, null, null, null, null, null, null); + if (ShareAccountApiConstants.APPROVE_COMMAND.equals(command)) { return approveShareAccount(accountId, jsonCommand); } + if (ShareAccountApiConstants.REJECT_COMMAND.equals(command)) { + return rejectShareAccount(accountId, jsonCommand); + } else if (ShareAccountApiConstants.APPLY_ADDITIONALSHARES_COMMAND.equals(command)) { + return applyAdditionalShares(accountId, jsonCommand); + } else if (ShareAccountApiConstants.APPROVE_ADDITIONSHARES_COMMAND.equals(command)) { + return approveAdditionalShares(accountId, jsonCommand); + } else if (ShareAccountApiConstants.REJECT_ADDITIONSHARES_COMMAND.equals(command)) { + return rejectAdditionalShares(accountId, jsonCommand); } return CommandProcessingResult.empty(); } public Object approveShareAccount(Long accountId, JsonCommand jsonCommand) { - return null ; + return null; } public Object rejectShareAccount(Long accountId, JsonCommand jsonCommand) { - return null ; + return null; } public Object applyAdditionalShares(Long accountId, JsonCommand jsonCommand) { - return null ; + return null; } public Object approveAdditionalShares(Long accountId, JsonCommand jsonCommand) { - return null ; + return null; } public Object rejectAdditionalShares(Long accountId, JsonCommand jsonCommand) { - return null ; + return null; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountDividendReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountDividendReadPlatformServiceImpl.java index 7c6721369..2db6cd0a7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountDividendReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountDividendReadPlatformServiceImpl.java @@ -48,8 +48,7 @@ public class ShareAccountDividendReadPlatformServiceImpl implements ShareAccount private final PaginationHelper paginationHelper = new PaginationHelper<>(); @Autowired - public ShareAccountDividendReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + public ShareAccountDividendReadPlatformServiceImpl(final RoutingDataSource dataSource, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.columnValidator = columnValidator; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountReadPlatformService.java index a5a7438f9..828bca31a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountReadPlatformService.java @@ -35,7 +35,8 @@ public interface ShareAccountReadPlatformService extends AccountReadPlatformServ @Override public Set getResponseDataParams(); - Collection retrieveAllShareAccountDataForDividends(Long productId, boolean fetchInActiveAccounts, LocalDate startDate); + Collection retrieveAllShareAccountDataForDividends(Long productId, boolean fetchInActiveAccounts, + LocalDate startDate); String retrieveAccountNumberByAccountId(Long accountId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountReadPlatformServiceImpl.java index 1d81615b4..5078759a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountReadPlatformServiceImpl.java @@ -121,7 +121,8 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat final Collection clientSavingsAccounts = this.savingsAccountReadPlatformService .retrieveActiveForLookup(clientId, DepositAccountType.SAVINGS_DEPOSIT, productData.getCurrency().code()); toReturn = new ShareAccountData(client.id(), client.displayName(), productData.getCurrency(), charges, marketPrice, - minimumActivePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions, clientSavingsAccounts, productData.getNominaltShares()); + minimumActivePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions, clientSavingsAccounts, + productData.getNominaltShares()); } else { Collection productOptions = service.retrieveAllForLookup(); final Collection chargeOptions = this.chargeReadPlatformService.retrieveSharesApplicableCharges(); @@ -152,14 +153,14 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat ShareAccountMapper mapper = new ShareAccountMapper(charges, purchasedShares); String query = "select " + mapper.schema() + "where sa.id=?"; - ShareAccountData data = (ShareAccountData)this.jdbcTemplate.queryForObject(query, mapper, new Object[] { id }); + ShareAccountData data = (ShareAccountData) this.jdbcTemplate.queryForObject(query, mapper, new Object[] { id }); String serviceName = "share" + ProductsApiConstants.READPLATFORM_NAME; ProductReadPlatformService service = (ProductReadPlatformService) this.applicationContext.getBean(serviceName); final ShareProductData productData = (ShareProductData) service.retrieveOne(data.getProductId(), false); final BigDecimal currentMarketPrice = deriveMarketPrice(productData); data.setCurrentMarketPrice(currentMarketPrice); - if(!includeTemplate) { - Collection dividends = this.retrieveAssociatedDividends(id) ; + if (!includeTemplate) { + Collection dividends = this.retrieveAssociatedDividends(id); data.setDividends(dividends); } if (includeTemplate) { @@ -184,9 +185,9 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat @Override public Page retrieveAll(final Integer offSet, final Integer limit) { - final Collection charges = null ; - final Collection purchasedShares = null ; - ShareAccountMapper mapper = new ShareAccountMapper(charges, purchasedShares) ; + final Collection charges = null; + final Collection purchasedShares = null; + ShareAccountMapper mapper = new ShareAccountMapper(charges, purchasedShares); StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); sqlBuilder.append(mapper.schema()); @@ -199,7 +200,7 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat } final String sqlCountRows = "SELECT FOUND_ROWS()"; - Object[] whereClauseItemsitems = new Object[] {ShareAccountStatusType.ACTIVE.getValue()}; + Object[] whereClauseItemsitems = new Object[] { ShareAccountStatusType.ACTIVE.getValue() }; return this.shareAccountDataPaginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), whereClauseItemsitems, mapper); } @@ -250,11 +251,11 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat private final String schema; - public ShareAccountMapper(final Collection charges, final Collection purchasedShares) { + public ShareAccountMapper(final Collection charges, + final Collection purchasedShares) { this.charges = charges; this.purchasedShares = purchasedShares; - StringBuilder buff = new StringBuilder() - .append("sa.id as id, sa.external_id as externalId, sa.status_enum as statusEnum, ") + StringBuilder buff = new StringBuilder().append("sa.id as id, sa.external_id as externalId, sa.status_enum as statusEnum, ") .append("sa.savings_account_id, msa.account_no as savingsAccNo, ") .append("c.id as clientId, c.display_name as clientName, ") .append("sa.account_no as accountNo, sa.total_approved_shares as approvedShares, sa.total_pending_shares as pendingShares, ") @@ -330,10 +331,10 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat final String closedByLastname = rs.getString("closedByLastname"); final ShareAccountApplicationTimelineData timeline = new ShareAccountApplicationTimelineData(submittedOnDate, - submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, - rejectedByFirstname, rejectedByLastname, approvedOnDate, approvedByUsername, approvedByFirstname, approvedByLastname, - activatedOnDate, activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, - closedByFirstname, closedByLastname); + submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername, rejectedByFirstname, + rejectedByLastname, approvedOnDate, approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate, + activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname, + closedByLastname); final String currencyCode = rs.getString("currencyCode"); final String currencyName = rs.getString("currencyName"); @@ -341,8 +342,8 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final Integer lockinPeriodFrequency = JdbcSupport.getInteger(rs, "lockinPeriod"); EnumOptionData lockinPeriodFrequencyType = null; @@ -362,8 +363,8 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat final String shortProductName = null; final ShareAccountSummaryData summary = new ShareAccountSummaryData(id, accountNo, externalId, productId, productName, shortProductName, status, currency, totalApprovedShares, totalPendingShares, timeline); - return new ShareAccountData(id, accountNo, externalId, savingsAccountId, savingsAccountNumber, clientId, clientName, - productId, productName, status, timeline, currency, summary, charges, purchasedShares, lockinPeriodFrequency, + return new ShareAccountData(id, accountNo, externalId, savingsAccountId, savingsAccountNumber, clientId, clientName, productId, + productName, status, timeline, currency, summary, charges, purchasedShares, lockinPeriodFrequency, lockinPeriodFrequencyType, minimumActivePeriod, minimumActivePeriodType, allowdividendsforinactiveclients); } @@ -443,8 +444,8 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat private final String schema; public PurchasedSharesDataRowMapper() { - StringBuilder buff = new StringBuilder() - .append("saps.id as purchasedId, saps.account_id as accountId, saps.transaction_date as transactionDate, saps.total_shares as purchasedShares, saps.unit_price as unitPrice, ") + StringBuilder buff = new StringBuilder().append( + "saps.id as purchasedId, saps.account_id as accountId, saps.transaction_date as transactionDate, saps.total_shares as purchasedShares, saps.unit_price as unitPrice, ") .append("saps.status_enum as purchaseStatus, saps.type_enum as purchaseType, saps.amount as amount, saps.charge_amount as chargeamount, ") .append("saps.amount_paid as amountPaid "); @@ -465,8 +466,8 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat final BigDecimal amount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "amount"); final BigDecimal chargeAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "chargeamount"); final BigDecimal amountPaid = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "amountPaid"); - return new ShareAccountTransactionData(id, accountId, transactionDate, numberOfShares, purchasedPrice, statusEnum, typeEnum, amount, - chargeAmount, amountPaid); + return new ShareAccountTransactionData(id, accountId, transactionDate, numberOfShares, purchasedPrice, statusEnum, typeEnum, + amount, chargeAmount, amountPaid); } public String schema() { @@ -493,7 +494,7 @@ public class ShareAccountReadPlatformServiceImpl implements ShareAccountReadPlat final Date postedDate = JdbcSupport.getLocalDate(rs, "created_date").toDate(); final BigDecimal postedAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "amount"); final Long savingTransactionId = rs.getLong("savings_transaction_id"); - final Integer status = rs.getInt("status") ; + final Integer status = rs.getInt("status"); final EnumOptionData statusEnum = SharesEnumerations.shareAccountDividendStatusEnum(status); final ShareAccountData shareAccountData = null; return new ShareAccountDividendData(id, postedDate, shareAccountData, postedAmount, statusEnum, savingTransactionId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountSchedularService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountSchedularService.java index 604f34410..08abc8add 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountSchedularService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountSchedularService.java @@ -18,8 +18,6 @@ */ package org.apache.fineract.portfolio.shareaccounts.service; - - public interface ShareAccountSchedularService { void postDividend(final Long dividendDetailId, final Long savingsId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountWritePlatformService.java index e416a6068..8ceef4eed 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountWritePlatformService.java @@ -21,29 +21,27 @@ package org.apache.fineract.portfolio.shareaccounts.service; import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; - public interface ShareAccountWritePlatformService { - public CommandProcessingResult createShareAccount(JsonCommand jsonCommand) ; + public CommandProcessingResult createShareAccount(JsonCommand jsonCommand); - public CommandProcessingResult updateShareAccount(Long accountId, JsonCommand jsonCommand) ; + public CommandProcessingResult updateShareAccount(Long accountId, JsonCommand jsonCommand); - public CommandProcessingResult approveShareAccount(Long accountId, JsonCommand jsonCommand) ; + public CommandProcessingResult approveShareAccount(Long accountId, JsonCommand jsonCommand); - public CommandProcessingResult activateShareAccount(Long accountId, JsonCommand jsonCommand) ; + public CommandProcessingResult activateShareAccount(Long accountId, JsonCommand jsonCommand); public CommandProcessingResult rejectShareAccount(Long entityId, JsonCommand jsonCommand); public CommandProcessingResult undoApproveShareAccount(Long entityId, JsonCommand jsonCommand); - public CommandProcessingResult closeShareAccount(Long accountId, JsonCommand jsonCommand) ; + public CommandProcessingResult closeShareAccount(Long accountId, JsonCommand jsonCommand); - public CommandProcessingResult applyAddtionalShares(final Long accountId, JsonCommand jsonCommand) ; + public CommandProcessingResult applyAddtionalShares(final Long accountId, JsonCommand jsonCommand); - public CommandProcessingResult approveAdditionalShares(Long accountId, JsonCommand jsonCommand) ; + public CommandProcessingResult approveAdditionalShares(Long accountId, JsonCommand jsonCommand); - public CommandProcessingResult rejectAdditionalShares(Long accountId, JsonCommand jsonCommand) ; + public CommandProcessingResult rejectAdditionalShares(Long accountId, JsonCommand jsonCommand); public CommandProcessingResult redeemShares(Long accountId, JsonCommand jsonCommand); } - diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountWritePlatformServiceJpaRepositoryImpl.java index 0b1299896..36883ec27 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/ShareAccountWritePlatformServiceJpaRepositoryImpl.java @@ -68,7 +68,7 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA private final ShareAccountRepositoryWrapper shareAccountRepository; - private final ShareProductRepositoryWrapper shareProductRepository ; + private final ShareProductRepositoryWrapper shareProductRepository; private final AccountNumberGenerator accountNumberGenerator; @@ -82,16 +82,13 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA @Autowired public ShareAccountWritePlatformServiceJpaRepositoryImpl(final ShareAccountDataSerializer accountDataSerializer, - final ShareAccountRepositoryWrapper shareAccountRepository, - final ShareProductRepositoryWrapper shareProductRepository, - final AccountNumberGenerator accountNumberGenerator, - final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository, - final JournalEntryWritePlatformService journalEntryWritePlatformService, - final NoteRepository noteRepository, + final ShareAccountRepositoryWrapper shareAccountRepository, final ShareProductRepositoryWrapper shareProductRepository, + final AccountNumberGenerator accountNumberGenerator, final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository, + final JournalEntryWritePlatformService journalEntryWritePlatformService, final NoteRepository noteRepository, final BusinessEventNotifierService businessEventNotifierService) { this.accountDataSerializer = accountDataSerializer; this.shareAccountRepository = shareAccountRepository; - this.shareProductRepository = shareProductRepository ; + this.shareProductRepository = shareProductRepository; this.accountNumberGenerator = accountNumberGenerator; this.accountNumberFormatRepository = accountNumberFormatRepository; this.journalEntryWritePlatformService = journalEntryWritePlatformService; @@ -105,8 +102,8 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA ShareAccount account = this.accountDataSerializer.validateAndCreate(jsonCommand); this.shareAccountRepository.save(account); generateAccountNumber(account); - journalEntryWritePlatformService.createJournalEntriesForShares(populateJournalEntries(account, - account.getPendingForApprovalSharePurchaseTransactions())); + journalEntryWritePlatformService.createJournalEntriesForShares( + populateJournalEntries(account, account.getPendingForApprovalSharePurchaseTransactions())); this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.SHARE_ACCOUNT_CREATE, constructEntityMap(BusinessEntity.SHARE_ACCOUNT, account)); @@ -118,8 +115,8 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(jsonCommand, throwable, dve); return CommandProcessingResult.empty(); } @@ -159,13 +156,13 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA final ShareAccountTransactionEnumData typeEnum = new ShareAccountTransactionEnumData(type.longValue(), null, null); transactionDto.put("status", statusEnum); transactionDto.put("type", typeEnum); - if(transaction.isPurchaseRejectedTransaction() || transaction.isRedeemTransaction()) { - BigDecimal amount = transaction.amount() ; - if(transaction.chargeAmount() != null) { - amount = amount.add(transaction.chargeAmount()) ; + if (transaction.isPurchaseRejectedTransaction() || transaction.isRedeemTransaction()) { + BigDecimal amount = transaction.amount(); + if (transaction.chargeAmount() != null) { + amount = amount.add(transaction.chargeAmount()); } transactionDto.put("amount", amount); - }else { + } else { transactionDto.put("amount", transaction.amount()); } @@ -204,9 +201,9 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA if (changes.containsKey("reversalIds")) { ArrayList reversalIds = (ArrayList) changes.get("reversalIds"); this.journalEntryWritePlatformService.revertShareAccountJournalEntries(reversalIds, transactionDate); - journalEntryWritePlatformService.createJournalEntriesForShares(populateJournalEntries(account, - account.getPendingForApprovalSharePurchaseTransactions())); - changes.remove("reversalIds") ; + journalEntryWritePlatformService.createJournalEntriesForShares( + populateJournalEntries(account, account.getPendingForApprovalSharePurchaseTransactions())); + changes.remove("reversalIds"); } return new CommandProcessingResultBuilder() // .withCommandId(jsonCommand.commandId()) // @@ -216,8 +213,8 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (final PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (final PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(jsonCommand, throwable, dve); return CommandProcessingResult.empty(); } @@ -270,15 +267,15 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA } Set transactions = account.getShareAccountTransactions(); Set journalTransactions = new HashSet<>(); - Long totalSubsribedShares = Long.valueOf(0) ; + Long totalSubsribedShares = Long.valueOf(0); for (ShareAccountTransaction transaction : transactions) { if (transaction.isActive() && transaction.isPurchasTransaction()) { journalTransactions.add(transaction); - totalSubsribedShares += transaction.getTotalShares() ; + totalSubsribedShares += transaction.getTotalShares(); } } - ShareProduct shareProduct = account.getShareProduct() ; + ShareProduct shareProduct = account.getShareProduct(); shareProduct.addSubscribedShares(totalSubsribedShares); this.shareProductRepository.save(shareProduct); @@ -347,17 +344,17 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA } } - Set transactions = account.getShareAccountTransactions() ; - ArrayList journalEntryTransactions = new ArrayList<>() ; - for(ShareAccountTransaction transaction: transactions) { - if(transaction.isActive() && !transaction.isChargeTransaction()){ - journalEntryTransactions.add(transaction.getId()) ; + Set transactions = account.getShareAccountTransactions(); + ArrayList journalEntryTransactions = new ArrayList<>(); + for (ShareAccountTransaction transaction : transactions) { + if (transaction.isActive() && !transaction.isChargeTransaction()) { + journalEntryTransactions.add(transaction.getId()); } } Date transactionDate = DateUtils.getDateOfTenant(); this.journalEntryWritePlatformService.revertShareAccountJournalEntries(journalEntryTransactions, transactionDate); - journalEntryWritePlatformService.createJournalEntriesForShares(populateJournalEntries(account, - account.getPendingForApprovalSharePurchaseTransactions())); + journalEntryWritePlatformService.createJournalEntriesForShares( + populateJournalEntries(account, account.getPendingForApprovalSharePurchaseTransactions())); return new CommandProcessingResultBuilder() // .withCommandId(jsonCommand.commandId()) // .withEntityId(accountId) // @@ -378,8 +375,8 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA if (!changes.isEmpty()) { this.shareAccountRepository.save(account); } - this.journalEntryWritePlatformService.createJournalEntriesForShares(populateJournalEntries(account, - account.getChargeTransactions())); + this.journalEntryWritePlatformService + .createJournalEntriesForShares(populateJournalEntries(account, account.getChargeTransactions())); return new CommandProcessingResultBuilder() // .withCommandId(jsonCommand.commandId()) // .withEntityId(accountId) // @@ -401,18 +398,18 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA if (!changes.isEmpty()) { this.shareAccountRepository.save(account); ArrayList transactionIds = (ArrayList) changes.get(ShareAccountApiConstants.requestedshares_paramname); - Long totalSubscribedShares = Long.valueOf(0) ; + Long totalSubscribedShares = Long.valueOf(0); if (transactionIds != null) { Set transactions = new HashSet<>(); for (Long id : transactionIds) { ShareAccountTransaction transaction = account.retrievePurchasedShares(id); transactions.add(transaction); - totalSubscribedShares += transaction.getTotalShares() ; + totalSubscribedShares += transaction.getTotalShares(); } this.journalEntryWritePlatformService.createJournalEntriesForShares(populateJournalEntries(account, transactions)); } - if(!totalSubscribedShares.equals(Long.valueOf(0))) { - ShareProduct shareProduct = account.getShareProduct() ; + if (!totalSubscribedShares.equals(Long.valueOf(0))) { + ShareProduct shareProduct = account.getShareProduct(); shareProduct.addSubscribedShares(totalSubscribedShares); this.shareProductRepository.save(shareProduct); } @@ -466,11 +463,12 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA this.shareAccountRepository.save(account); ShareAccountTransaction transaction = (ShareAccountTransaction) changes .get(ShareAccountApiConstants.requestedshares_paramname); - // after saving, entity will have different object. So need to retrieve the entity object + // after saving, entity will have different object. So need to + // retrieve the entity object transaction = account.getShareAccountTransaction(transaction); - Long redeemShares = transaction.getTotalShares() ; - ShareProduct shareProduct = account.getShareProduct() ; - //remove the redeem shares from total subscribed shares + Long redeemShares = transaction.getTotalShares(); + ShareProduct shareProduct = account.getShareProduct(); + // remove the redeem shares from total subscribed shares shareProduct.removeSubscribedShares(redeemShares); this.shareProductRepository.save(shareProduct); @@ -531,7 +529,8 @@ public class ShareAccountWritePlatformServiceJpaRepositoryImpl implements ShareA "Unknown data integrity issue with resource."); } - private Map constructEntityMap(final BusinessEventNotificationConstants.BusinessEntity entityEvent, Object entity) { + private Map constructEntityMap( + final BusinessEventNotificationConstants.BusinessEntity entityEvent, Object entity) { Map map = new HashMap<>(1); map.put(entityEvent, entity); return map; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/SharesEnumerations.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/SharesEnumerations.java index 2e2e6fb23..3779e53f1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/SharesEnumerations.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareaccounts/service/SharesEnumerations.java @@ -126,54 +126,54 @@ public class SharesEnumerations { } public static EnumOptionData minimumActivePeriodFrequencyType(final SharePeriodFrequencyType type) { - final String codePrefix = "shares.minimumactive." ; + final String codePrefix = "shares.minimumactive."; EnumOptionData optionData = new EnumOptionData(SharePeriodFrequencyType.INVALID.getValue().longValue(), SharePeriodFrequencyType.INVALID.getCode(), "Invalid"); switch (type) { case INVALID: break; case DAYS: - optionData = new EnumOptionData(SharePeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + SharePeriodFrequencyType.DAYS.getCode(), "Days"); + optionData = new EnumOptionData(SharePeriodFrequencyType.DAYS.getValue().longValue(), + codePrefix + SharePeriodFrequencyType.DAYS.getCode(), "Days"); break; case WEEKS: - optionData = new EnumOptionData(SharePeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix - + SharePeriodFrequencyType.WEEKS.getCode(), "Weeks"); + optionData = new EnumOptionData(SharePeriodFrequencyType.WEEKS.getValue().longValue(), + codePrefix + SharePeriodFrequencyType.WEEKS.getCode(), "Weeks"); break; case MONTHS: - optionData = new EnumOptionData(SharePeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix - + SharePeriodFrequencyType.MONTHS.getCode(), "Months"); + optionData = new EnumOptionData(SharePeriodFrequencyType.MONTHS.getValue().longValue(), + codePrefix + SharePeriodFrequencyType.MONTHS.getCode(), "Months"); break; case YEARS: - optionData = new EnumOptionData(SharePeriodFrequencyType.YEARS.getValue().longValue(), codePrefix - + SharePeriodFrequencyType.YEARS.getCode(), "Years"); + optionData = new EnumOptionData(SharePeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + SharePeriodFrequencyType.YEARS.getCode(), "Years"); break; } return optionData; } public static EnumOptionData lockinPeriodFrequencyType(final SharePeriodFrequencyType type) { - final String codePrefix = "shares.lockin." ; + final String codePrefix = "shares.lockin."; EnumOptionData optionData = new EnumOptionData(SharePeriodFrequencyType.INVALID.getValue().longValue(), SharePeriodFrequencyType.INVALID.getCode(), "Invalid"); switch (type) { case INVALID: break; case DAYS: - optionData = new EnumOptionData(SharePeriodFrequencyType.DAYS.getValue().longValue(), codePrefix - + SharePeriodFrequencyType.DAYS.getCode(), "Days"); + optionData = new EnumOptionData(SharePeriodFrequencyType.DAYS.getValue().longValue(), + codePrefix + SharePeriodFrequencyType.DAYS.getCode(), "Days"); break; case WEEKS: - optionData = new EnumOptionData(SharePeriodFrequencyType.WEEKS.getValue().longValue(), codePrefix - + SharePeriodFrequencyType.WEEKS.getCode(), "Weeks"); + optionData = new EnumOptionData(SharePeriodFrequencyType.WEEKS.getValue().longValue(), + codePrefix + SharePeriodFrequencyType.WEEKS.getCode(), "Weeks"); break; case MONTHS: - optionData = new EnumOptionData(SharePeriodFrequencyType.MONTHS.getValue().longValue(), codePrefix - + SharePeriodFrequencyType.MONTHS.getCode(), "Months"); + optionData = new EnumOptionData(SharePeriodFrequencyType.MONTHS.getValue().longValue(), + codePrefix + SharePeriodFrequencyType.MONTHS.getCode(), "Months"); break; case YEARS: - optionData = new EnumOptionData(SharePeriodFrequencyType.YEARS.getValue().longValue(), codePrefix - + SharePeriodFrequencyType.YEARS.getCode(), "Years"); + optionData = new EnumOptionData(SharePeriodFrequencyType.YEARS.getValue().longValue(), + codePrefix + SharePeriodFrequencyType.YEARS.getCode(), "Years"); break; } return optionData; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/SharePeriodFrequencyType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/SharePeriodFrequencyType.java index 545ed052f..65cbfe1c3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/SharePeriodFrequencyType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/SharePeriodFrequencyType.java @@ -25,6 +25,7 @@ import java.util.List; * An enumeration of supported calendar periods used in savings. */ public enum SharePeriodFrequencyType { + DAYS(0, "sharePeriodFrequencyType.days"), // WEEKS(1, "sharePeriodFrequencyType.weeks"), // MONTHS(2, "sharePeriodFrequencyType.months"), // diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/api/ShareDividendApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/api/ShareDividendApiResource.java index 92784855a..e8315d359 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/api/ShareDividendApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/api/ShareDividendApiResource.java @@ -52,10 +52,8 @@ import org.springframework.stereotype.Component; @Path("/shareproduct/{productId}/dividend") @Component @Scope("singleton") -@Api(tags = {"Self Dividend"}) -@SwaggerDefinition(tags = { - @Tag(name = "Self Dividend", description = "") -}) +@Api(tags = { "Self Dividend" }) +@SwaggerDefinition(tags = { @Tag(name = "Self Dividend", description = "") }) public class ShareDividendApiResource { private final DefaultToApiJsonSerializer toApiJsonSerializer; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/data/ShareProductData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/data/ShareProductData.java index 32827152a..1db50074f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/data/ShareProductData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/data/ShareProductData.java @@ -182,22 +182,22 @@ public class ShareProductData implements ProductData { final Collection lockinPeriodFrequencyTypeOptions, final Map> accountingMappingOptions) { - return new ShareProductData(data.id, data.name, data.shortName, data.description, data.externalId, data.currency, - data.totalShares, data.totalSharesIssued, data.unitPrice, data.shareCapital, data.minimumShares, data.nominalShares, - data.maximumShares, data.marketPrice, data.charges, data.allowDividendCalculationForInactiveClients, data.lockinPeriod, - data.lockPeriodTypeEnum, data.minimumActivePeriod, data.minimumActivePeriodForDividendsTypeEnum, data.accountingRule, - data.accountingMappings, data.paymentChannelToFundSourceMappings, data.feeToGLAccountMappings, currencyOptions, - chargeOptions, minimumActivePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions, accountingMappingOptions); + return new ShareProductData(data.id, data.name, data.shortName, data.description, data.externalId, data.currency, data.totalShares, + data.totalSharesIssued, data.unitPrice, data.shareCapital, data.minimumShares, data.nominalShares, data.maximumShares, + data.marketPrice, data.charges, data.allowDividendCalculationForInactiveClients, data.lockinPeriod, data.lockPeriodTypeEnum, + data.minimumActivePeriod, data.minimumActivePeriodForDividendsTypeEnum, data.accountingRule, data.accountingMappings, + data.paymentChannelToFundSourceMappings, data.feeToGLAccountMappings, currencyOptions, chargeOptions, + minimumActivePeriodFrequencyTypeOptions, lockinPeriodFrequencyTypeOptions, accountingMappingOptions); } public static ShareProductData withAccountingDetails(final ShareProductData data, final Map accountingMappings, final Collection paymentChannelToFundSourceMappings, final Collection feeToGLAccountMappings) { - return new ShareProductData(data.id, data.name, data.shortName, data.description, data.externalId, data.currency, - data.totalShares, data.totalSharesIssued, data.unitPrice, data.shareCapital, data.minimumShares, data.nominalShares, - data.maximumShares, data.marketPrice, data.charges, data.allowDividendCalculationForInactiveClients, data.lockinPeriod, - data.lockPeriodTypeEnum, data.minimumActivePeriod, data.minimumActivePeriodForDividendsTypeEnum, data.accountingRule, - accountingMappings, paymentChannelToFundSourceMappings, feeToGLAccountMappings, data.currencyOptions, data.chargeOptions, + return new ShareProductData(data.id, data.name, data.shortName, data.description, data.externalId, data.currency, data.totalShares, + data.totalSharesIssued, data.unitPrice, data.shareCapital, data.minimumShares, data.nominalShares, data.maximumShares, + data.marketPrice, data.charges, data.allowDividendCalculationForInactiveClients, data.lockinPeriod, data.lockPeriodTypeEnum, + data.minimumActivePeriod, data.minimumActivePeriodForDividendsTypeEnum, data.accountingRule, accountingMappings, + paymentChannelToFundSourceMappings, feeToGLAccountMappings, data.currencyOptions, data.chargeOptions, data.minimumActivePeriodFrequencyTypeOptions, data.lockinPeriodFrequencyTypeOptions, data.accountingMappingOptions); } @@ -335,4 +335,4 @@ public class ShareProductData implements ProductData { public EnumOptionData getAccountingRule() { return this.accountingRule; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/data/ShareProductMarketPriceData.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/data/ShareProductMarketPriceData.java index b09312f73..0668a5651 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/data/ShareProductMarketPriceData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/data/ShareProductMarketPriceData.java @@ -23,20 +23,20 @@ import java.util.Date; public class ShareProductMarketPriceData { - private final Long id ; + private final Long id; private final Date fromDate; private final BigDecimal shareValue; public ShareProductMarketPriceData(final Long id, final Date fromDate, final BigDecimal shareValue) { - this.id = id ; - this.fromDate = fromDate ; - this.shareValue = shareValue ; + this.id = id; + this.fromDate = fromDate; + this.shareValue = shareValue; } public Long getId() { - return this.id ; + return this.id; } public Date getStartDate() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProduct.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProduct.java index dd8624603..7334ff57b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProduct.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProduct.java @@ -101,7 +101,7 @@ public class ShareProduct extends AbstractAuditableCustom { private Long maximumShares; @OrderBy(value = "fromDate,id") - @OneToMany(cascade = CascadeType.ALL, mappedBy = "product", orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "product", orphanRemoval = true, fetch = FetchType.EAGER) Set marketPrice; @ManyToMany(fetch = FetchType.EAGER) @@ -248,7 +248,7 @@ public class ShareProduct extends AbstractAuditableCustom { public boolean setUnitPrice(BigDecimal unitPrice) { boolean returnValue = false; - if (this.unitPrice.compareTo(unitPrice) == 0 ? Boolean.FALSE:Boolean.TRUE) { + if (this.unitPrice.compareTo(unitPrice) == 0 ? Boolean.FALSE : Boolean.TRUE) { this.unitPrice = unitPrice; returnValue = true; } @@ -286,11 +286,11 @@ public class ShareProduct extends AbstractAuditableCustom { boolean update = true; Set marketPriceTemp = new HashSet(); if (marketPrice != null && marketPrice.size() > 0) { - for (ShareProductMarketPriceData data : marketPrice) { - if (data.getId() == null) { - ShareProductMarketPrice entity = new ShareProductMarketPrice(data.getStartDate(), data.getShareValue()); - entity.setShareProduct(this); - marketPriceTemp.add(entity); + for (ShareProductMarketPriceData data : marketPrice) { + if (data.getId() == null) { + ShareProductMarketPrice entity = new ShareProductMarketPrice(data.getStartDate(), data.getShareValue()); + entity.setShareProduct(this); + marketPriceTemp.add(entity); } else { for (ShareProductMarketPrice priceData : this.marketPrice) { if (priceData.getId().equals(data.getId())) { @@ -314,7 +314,8 @@ public class ShareProduct extends AbstractAuditableCustom { public boolean setAllowDividendCalculationForInactiveClients(Boolean allowDividendCalculationForInactiveClients) { boolean returnValue = false; - if (this.allowDividendCalculationForInactiveClients == null || !this.allowDividendCalculationForInactiveClients.equals(allowDividendCalculationForInactiveClients)) { + if (this.allowDividendCalculationForInactiveClients == null + || !this.allowDividendCalculationForInactiveClients.equals(allowDividendCalculationForInactiveClients)) { this.allowDividendCalculationForInactiveClients = allowDividendCalculationForInactiveClients; returnValue = true; } @@ -363,7 +364,7 @@ public class ShareProduct extends AbstractAuditableCustom { public boolean setshareCapitalValue(BigDecimal shareCapitalValue) { boolean updated = false; - if (this.shareCapital == null || this.shareCapital.compareTo(shareCapitalValue) == 0 ? Boolean.FALSE:Boolean.TRUE) { + if (this.shareCapital == null || this.shareCapital.compareTo(shareCapitalValue) == 0 ? Boolean.FALSE : Boolean.TRUE) { this.shareCapital = shareCapitalValue; updated = true; } @@ -415,29 +416,29 @@ public class ShareProduct extends AbstractAuditableCustom { } public void addSubscribedShares(final Long subscribedShares) { - if(this.totalSubscribedShares == null) { - this.totalSubscribedShares = Long.valueOf(0) ; + if (this.totalSubscribedShares == null) { + this.totalSubscribedShares = Long.valueOf(0); } - this.totalSubscribedShares += subscribedShares ; + this.totalSubscribedShares += subscribedShares; } public void removeSubscribedShares(final Long subscribedShares) { - this.totalSubscribedShares -= subscribedShares ; + this.totalSubscribedShares -= subscribedShares; } public Long getSubscribedShares() { - return this.totalSubscribedShares ; + return this.totalSubscribedShares; } public Long getMinimumClientShares() { - return this.minimumShares ; + return this.minimumShares; } public Long getMaximumClientShares() { - return this.maximumShares ; + return this.maximumShares; } public Long getDefaultClientShares() { - return this.nominalShares ; + return this.nominalShares; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividendPayOutDetails.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividendPayOutDetails.java index ac5b6e304..4940053f7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividendPayOutDetails.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividendPayOutDetails.java @@ -56,7 +56,7 @@ public class ShareProductDividendPayOutDetails extends AbstractAuditableCustom { @Column(name = "status", nullable = false) private Integer status; - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "dividend_pay_out_id", referencedColumnName = "id", nullable = false) private List accountDividendDetails = new ArrayList<>(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividendStatusType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividendStatusType.java index da65e5ca0..4edaf48e5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividendStatusType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividendStatusType.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.portfolio.shareproducts.domain; - public enum ShareProductDividendStatusType { INVALID(0, "shareAccountDividendStatusType.invalid"), INITIATED(100, "shareAccountDividendStatusType.initiated"), APPROVED(300, diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividentPayOutDetailsRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividentPayOutDetailsRepository.java index be74493ed..f7c6a9ac3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividentPayOutDetailsRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividentPayOutDetailsRepository.java @@ -21,7 +21,7 @@ package org.apache.fineract.portfolio.shareproducts.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface ShareProductDividentPayOutDetailsRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface ShareProductDividentPayOutDetailsRepository + extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividentPayOutDetailsRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividentPayOutDetailsRepositoryWrapper.java index 434019996..753e610a6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividentPayOutDetailsRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductDividentPayOutDetailsRepositoryWrapper.java @@ -34,8 +34,8 @@ public class ShareProductDividentPayOutDetailsRepositoryWrapper { } public ShareProductDividendPayOutDetails findOneWithNotFoundDetection(final Long dividendId) { - return this.shareProductDividentPayOutDetailsRepository - .findById(dividendId).orElseThrow(() -> new DividendNotFoundException(dividendId, "share")); + return this.shareProductDividentPayOutDetailsRepository.findById(dividendId) + .orElseThrow(() -> new DividendNotFoundException(dividendId, "share")); } public void save(final ShareProductDividendPayOutDetails shareProductDividendPayOutDetails) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductMarketPrice.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductMarketPrice.java index 642342d34..4be38768a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductMarketPrice.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductMarketPrice.java @@ -42,34 +42,34 @@ public class ShareProductMarketPrice extends AbstractPersistableCustom { private Date fromDate; @Column(name = "share_value", nullable = false) - private BigDecimal shareValue ; + private BigDecimal shareValue; public ShareProductMarketPrice() { } public ShareProductMarketPrice(final Date fromDate, final BigDecimal shareValue) { - this.fromDate = fromDate ; - this.shareValue = shareValue ; + this.fromDate = fromDate; + this.shareValue = shareValue; } public void setShareProduct(final ShareProduct product) { - this.product = product ; + this.product = product; } public Date getStartDate() { - return this.fromDate ; + return this.fromDate; } public BigDecimal getPrice() { - return this.shareValue ; + return this.shareValue; } public void setStartDate(Date date) { - this.fromDate = date ; + this.fromDate = date; } public void setShareValue(BigDecimal value) { - this.shareValue = value ; + this.shareValue = value; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductRepository.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductRepository.java index 522215135..ab2f5fe3e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductRepository.java @@ -21,7 +21,6 @@ package org.apache.fineract.portfolio.shareproducts.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - public interface ShareProductRepository extends JpaRepository, JpaSpecificationExecutor { } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductRepositoryWrapper.java index 07ddbc770..7c107ab06 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/domain/ShareProductRepositoryWrapper.java @@ -25,23 +25,22 @@ import org.springframework.stereotype.Service; @Service public class ShareProductRepositoryWrapper { - private final ShareProductRepository shareProductRepository ; + private final ShareProductRepository shareProductRepository; @Autowired public ShareProductRepositoryWrapper(final ShareProductRepository shareProductRepository) { - this.shareProductRepository = shareProductRepository ; + this.shareProductRepository = shareProductRepository; } public ShareProduct findOneWithNotFoundDetection(final Long productId) { - return this.shareProductRepository.findById(productId) - .orElseThrow(() -> new ProductNotFoundException(productId, "share")); + return this.shareProductRepository.findById(productId).orElseThrow(() -> new ProductNotFoundException(productId, "share")); } public void save(ShareProduct product) { - this.shareProductRepository.save(product) ; + this.shareProductRepository.save(product); } public void saveAndFlush(ShareProduct product) { - this.shareProductRepository.saveAndFlush(product) ; + this.shareProductRepository.saveAndFlush(product); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/exception/DividendNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/exception/DividendNotFoundException.java index ca3780696..d1dd48a7b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/exception/DividendNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/exception/DividendNotFoundException.java @@ -25,4 +25,4 @@ public class DividendNotFoundException extends AbstractPlatformResourceNotFoundE public DividendNotFoundException(final Long id, String type) { super("error.msg.dividend.id.invalid", type + " dividend with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/exception/ShareAccountsNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/exception/ShareAccountsNotFoundException.java index 71b59bc86..94a306fca 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/exception/ShareAccountsNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/exception/ShareAccountsNotFoundException.java @@ -20,8 +20,7 @@ package org.apache.fineract.portfolio.shareproducts.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - -public class ShareAccountsNotFoundException extends AbstractPlatformResourceNotFoundException{ +public class ShareAccountsNotFoundException extends AbstractPlatformResourceNotFoundException { public ShareAccountsNotFoundException(final Long productId) { super("error.msg.shareproduct.shareaccounts.not.defined", " No Share Accounts found for this prodct " + productId, productId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/handler/CreateShareProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/handler/CreateShareProductCommandHandler.java index aaaa26f69..96c67d6d6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/handler/CreateShareProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/handler/CreateShareProductCommandHandler.java @@ -31,11 +31,11 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "SHAREPRODUCT", action = "CREATE") public class CreateShareProductCommandHandler implements NewCommandSourceHandler { - private final ShareProductWritePlatformService shareProductWritePlatformService ; + private final ShareProductWritePlatformService shareProductWritePlatformService; @Autowired public CreateShareProductCommandHandler(final ShareProductWritePlatformService shareProductWritePlatformService) { - this.shareProductWritePlatformService = shareProductWritePlatformService ; + this.shareProductWritePlatformService = shareProductWritePlatformService; } @Transactional diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/handler/UpdateShareProductCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/handler/UpdateShareProductCommandHandler.java index 29ff0eeca..e336229ab 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/handler/UpdateShareProductCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/handler/UpdateShareProductCommandHandler.java @@ -31,11 +31,11 @@ import org.springframework.transaction.annotation.Transactional; @CommandType(entity = "SHAREPRODUCT", action = "UPDATE") public class UpdateShareProductCommandHandler implements NewCommandSourceHandler { - private final ShareProductWritePlatformService shareProductWritePlatformService ; + private final ShareProductWritePlatformService shareProductWritePlatformService; @Autowired public UpdateShareProductCommandHandler(final ShareProductWritePlatformService shareProductWritePlatformService) { - this.shareProductWritePlatformService = shareProductWritePlatformService ; + this.shareProductWritePlatformService = shareProductWritePlatformService; } @Transactional diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/serialization/ShareProductDataSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/serialization/ShareProductDataSerializer.java index a09ca19b0..f83a92edd 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/serialization/ShareProductDataSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/serialization/ShareProductDataSerializer.java @@ -66,30 +66,26 @@ public class ShareProductDataSerializer { private final ChargeRepositoryWrapper chargeRepository; private final PlatformSecurityContext platformSecurityContext; - private static final Set supportedParametersForCreate = new HashSet<>(Arrays.asList( - ShareProductApiConstants.locale_paramname, ShareProductApiConstants.name_paramname, - ShareProductApiConstants.shortname_paramname, ShareProductApiConstants.shortname_paramname, - ShareProductApiConstants.description_paramname, ShareProductApiConstants.externalid_paramname, - ShareProductApiConstants.totalshares_paramname, ShareProductApiConstants.currency_paramname, - ShareProductApiConstants.digitsafterdecimal_paramname, + private static final Set supportedParametersForCreate = new HashSet<>(Arrays.asList(ShareProductApiConstants.locale_paramname, + ShareProductApiConstants.name_paramname, ShareProductApiConstants.shortname_paramname, + ShareProductApiConstants.shortname_paramname, ShareProductApiConstants.description_paramname, + ShareProductApiConstants.externalid_paramname, ShareProductApiConstants.totalshares_paramname, + ShareProductApiConstants.currency_paramname, ShareProductApiConstants.digitsafterdecimal_paramname, ShareProductApiConstants.digitsafterdecimal_paramname, ShareProductApiConstants.inmultiplesof_paramname, ShareProductApiConstants.totalsharesissued_paramname, ShareProductApiConstants.unitprice_paramname, ShareProductApiConstants.minimumshares_paramname, ShareProductApiConstants.nominaltshares_paramname, ShareProductApiConstants.maximumshares_paramname, ShareProductApiConstants.marketprice_paramname, - ShareProductApiConstants.charges_paramname, - ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, + ShareProductApiConstants.charges_paramname, ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, ShareProductApiConstants.lockperiod_paramname, ShareProductApiConstants.lockinperiodfrequencytype_paramname, ShareProductApiConstants.minimumactiveperiodfordividends_paramname, - ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, - ShareProductApiConstants.sharecapital_paramname, ShareProductApiConstants.accountingRuleParamName, - AccountingConstants.SharesProductAccountingParams.INCOME_FROM_FEES.getValue(), + ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, ShareProductApiConstants.sharecapital_paramname, + ShareProductApiConstants.accountingRuleParamName, AccountingConstants.SharesProductAccountingParams.INCOME_FROM_FEES.getValue(), AccountingConstants.SharesProductAccountingParams.SHARES_EQUITY.getValue(), AccountingConstants.SharesProductAccountingParams.SHARES_REFERENCE.getValue(), AccountingConstants.SharesProductAccountingParams.SHARES_SUSPENSE.getValue())); - private static final Set supportedParametersForDivident = new HashSet<>(Arrays.asList( - ShareProductApiConstants.locale_paramname, ShareProductApiConstants.dateFormatParamName, - ShareProductApiConstants.dividendPeriodStartDateParamName, + private static final Set supportedParametersForDivident = new HashSet<>(Arrays.asList(ShareProductApiConstants.locale_paramname, + ShareProductApiConstants.dateFormatParamName, ShareProductApiConstants.dividendPeriodStartDateParamName, ShareProductApiConstants.dividendPeriodEndDateParamName, ShareProductApiConstants.dividendAmountParamName)); @Autowired @@ -103,8 +99,7 @@ public class ShareProductDataSerializer { public ShareProduct validateAndCreate(JsonCommand jsonCommand) { if (StringUtils.isBlank(jsonCommand.json())) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), - supportedParametersForCreate); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), supportedParametersForCreate); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("sharesproduct"); @@ -117,10 +112,9 @@ public class ShareProductDataSerializer { baseDataValidator.reset().parameter(ShareProductApiConstants.shortname_paramname).value(shortName).notBlank() .notExceedingLengthOf(4); - final String description = this.fromApiJsonHelper - .extractStringNamed(ShareProductApiConstants.description_paramname, element); - baseDataValidator.reset().parameter(ShareProductApiConstants.description_paramname).value(description) - .notBlank().notExceedingLengthOf(500); + final String description = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.description_paramname, element); + baseDataValidator.reset().parameter(ShareProductApiConstants.description_paramname).value(description).notBlank() + .notExceedingLengthOf(500); String externalId = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.externalid_paramname, element); // baseDataValidator.reset().parameter(ShareProductApiConstants.externalid_paramname).value(externalId).notBlank(); @@ -129,15 +123,15 @@ public class ShareProductDataSerializer { baseDataValidator.reset().parameter(ShareProductApiConstants.totalshares_paramname).value(totalNumberOfShares).notNull() .longGreaterThanZero(); final Long sharesIssued = this.fromApiJsonHelper.extractLongNamed(ShareProductApiConstants.totalsharesissued_paramname, element); - if(sharesIssued != null && totalNumberOfShares != null && sharesIssued > totalNumberOfShares) { + if (sharesIssued != null && totalNumberOfShares != null && sharesIssued > totalNumberOfShares) { baseDataValidator.reset().parameter(ShareProductApiConstants.totalsharesissued_paramname).value(sharesIssued) - .failWithCodeNoParameterAddedToErrorCode("sharesIssued.cannot.be.greater.than.totalNumberOfShares"); + .failWithCodeNoParameterAddedToErrorCode("sharesIssued.cannot.be.greater.than.totalNumberOfShares"); } final String currencyCode = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.currency_paramname, element); - final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - ShareProductApiConstants.digitsafterdecimal_paramname, element); - final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - ShareProductApiConstants.inmultiplesof_paramname, element); + final Integer digitsAfterDecimal = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(ShareProductApiConstants.digitsafterdecimal_paramname, element); + final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(ShareProductApiConstants.inmultiplesof_paramname, + element); final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf); final BigDecimal unitPrice = this.fromApiJsonHelper.extractBigDecimalNamed(ShareProductApiConstants.unitprice_paramname, element, @@ -174,13 +168,13 @@ public class ShareProductDataSerializer { Set marketPriceSet = asembleShareMarketPrice(element); Set charges = assembleListOfProductCharges(element, currencyCode); - Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper.extractBooleanNamed( - ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, element); + Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper + .extractBooleanNamed(ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, element); - Integer minimumActivePeriod = this.fromApiJsonHelper.extractIntegerNamed( - ShareProductApiConstants.minimumactiveperiodfordividends_paramname, element, locale); - PeriodFrequencyType minimumActivePeriodType = extractPeriodType( - ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, element); + Integer minimumActivePeriod = this.fromApiJsonHelper + .extractIntegerNamed(ShareProductApiConstants.minimumactiveperiodfordividends_paramname, element, locale); + PeriodFrequencyType minimumActivePeriodType = extractPeriodType(ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, + element); if (minimumActivePeriod != null) { baseDataValidator.reset().parameter(ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname) .value(minimumActivePeriodType.getValue()).integerSameAsNumber(PeriodFrequencyType.DAYS.getValue()); @@ -220,8 +214,8 @@ public class ShareProductDataSerializer { Long id = this.fromApiJsonHelper.extractLongNamed(ShareProductApiConstants.id_paramname, arrayElement); LocalDate localDate = this.fromApiJsonHelper.extractLocalDateNamed(ShareProductApiConstants.startdate_paramname, arrayElement); - final BigDecimal shareValue = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - ShareProductApiConstants.sharevalue_paramname, arrayElement); + final BigDecimal shareValue = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(ShareProductApiConstants.sharevalue_paramname, arrayElement); ShareProductMarketPriceData obj = new ShareProductMarketPriceData(id, localDate.toDate(), shareValue); set.add(obj); } @@ -237,8 +231,8 @@ public class ShareProductDataSerializer { for (JsonElement arrayElement : array) { LocalDate localDate = this.fromApiJsonHelper.extractLocalDateNamed(ShareProductApiConstants.startdate_paramname, arrayElement); - final BigDecimal shareValue = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - ShareProductApiConstants.sharevalue_paramname, arrayElement); + final BigDecimal shareValue = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(ShareProductApiConstants.sharevalue_paramname, arrayElement); ShareProductMarketPrice obj = new ShareProductMarketPrice(localDate.toDate(), shareValue); set.add(obj); } @@ -273,8 +267,7 @@ public class ShareProductDataSerializer { if (StringUtils.isBlank(jsonCommand.json())) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), - supportedParametersForCreate); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), supportedParametersForCreate); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("sharesproduct"); @@ -325,24 +318,23 @@ public class ShareProductDataSerializer { if (product.setTotalIssuedShares(sharesIssued)) { actualChanges.put(ShareProductApiConstants.totalsharesissued_paramname, sharesIssued); } - }else { - product.setTotalIssuedShares(sharesIssued) ; + } else { + product.setTotalIssuedShares(sharesIssued); } - if(sharesIssued != null && product.getSubscribedShares() != null && sharesIssued < product.getSubscribedShares()) { + if (sharesIssued != null && product.getSubscribedShares() != null && sharesIssued < product.getSubscribedShares()) { baseDataValidator.reset().parameter(ShareProductApiConstants.totalsharesissued_paramname).value(sharesIssued) - .failWithCodeNoParameterAddedToErrorCode("sharesissued.can.not.be.lessthan.accounts.subscribed.shares"); + .failWithCodeNoParameterAddedToErrorCode("sharesissued.can.not.be.lessthan.accounts.subscribed.shares"); } - if (this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.currency_paramname, element) && this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.digitsafterdecimal_paramname, element) && this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.inmultiplesof_paramname, element)) { final String currencyCode = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.currency_paramname, element); - final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - ShareProductApiConstants.digitsafterdecimal_paramname, element); - final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( - ShareProductApiConstants.inmultiplesof_paramname, element); + final Integer digitsAfterDecimal = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(ShareProductApiConstants.digitsafterdecimal_paramname, element); + final Integer inMultiplesOf = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed(ShareProductApiConstants.inmultiplesof_paramname, element); final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf); if (product.setMonetaryCurrency(currency)) { actualChanges.put(ShareProductApiConstants.currency_paramname, currency); @@ -410,9 +402,10 @@ public class ShareProductDataSerializer { } } - if (this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, element)) { - Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper.extractBooleanNamed( - ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, element); + if (this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, + element)) { + Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper + .extractBooleanNamed(ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, element); if (product.setAllowDividendCalculationForInactiveClients(allowdividendsForInactiveClients)) { actualChanges.put(ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, allowdividendsForInactiveClients); @@ -422,8 +415,8 @@ public class ShareProductDataSerializer { Integer minimumActivePeriod = null; if (this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.minimumactiveperiodfordividends_paramname, element)) { - minimumActivePeriod = this.fromApiJsonHelper.extractIntegerNamed( - ShareProductApiConstants.minimumactiveperiodfordividends_paramname, element, locale); + minimumActivePeriod = this.fromApiJsonHelper + .extractIntegerNamed(ShareProductApiConstants.minimumactiveperiodfordividends_paramname, element, locale); if (product.setminimumActivePeriod(minimumActivePeriod)) { actualChanges.put(ShareProductApiConstants.minimumactiveperiodfordividends_paramname, minimumActivePeriod); } @@ -476,8 +469,7 @@ public class ShareProductDataSerializer { public void validateDividendDetails(JsonCommand jsonCommand) { if (StringUtils.isBlank(jsonCommand.json())) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), - supportedParametersForDivident); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), supportedParametersForDivident); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -485,17 +477,17 @@ public class ShareProductDataSerializer { JsonElement element = jsonCommand.parsedJson(); - final LocalDate dividendPeriodStartDate = this.fromApiJsonHelper.extractLocalDateNamed( - ShareProductApiConstants.dividendPeriodStartDateParamName, element); + final LocalDate dividendPeriodStartDate = this.fromApiJsonHelper + .extractLocalDateNamed(ShareProductApiConstants.dividendPeriodStartDateParamName, element); baseDataValidator.reset().parameter(ShareProductApiConstants.dividendPeriodStartDateParamName).value(dividendPeriodStartDate) .notBlank(); - final LocalDate dividendPeriodEndDate = this.fromApiJsonHelper.extractLocalDateNamed( - ShareProductApiConstants.dividendPeriodEndDateParamName, element); + final LocalDate dividendPeriodEndDate = this.fromApiJsonHelper + .extractLocalDateNamed(ShareProductApiConstants.dividendPeriodEndDateParamName, element); baseDataValidator.reset().parameter(ShareProductApiConstants.dividendPeriodStartDateParamName).value(dividendPeriodEndDate) .notBlank().validateDateAfter(dividendPeriodStartDate); - final BigDecimal dividendAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - ShareProductApiConstants.dividendAmountParamName, element); + final BigDecimal dividendAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(ShareProductApiConstants.dividendAmountParamName, element); baseDataValidator.reset().parameter(ShareProductApiConstants.dividendAmountParamName).value(dividendAmount).notBlank() .positiveAmount(); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductCommandsServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductCommandsServiceImpl.java index 97731ef8f..d5911895c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductCommandsServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductCommandsServiceImpl.java @@ -37,20 +37,18 @@ public class ShareProductCommandsServiceImpl implements ProductCommandsService { this.fromApiJsonHelper = fromApiJsonHelper; } - public CommandProcessingResult postDividends(Long productId, JsonCommand jsonCommand) { - return null ; + return null; } @Override public Object handleCommand(Long productId, String command, String jsonBody) { final JsonElement parsedCommand = this.fromApiJsonHelper.parse(jsonBody); final JsonCommand jsonCommand = JsonCommand.from(jsonBody, parsedCommand, this.fromApiJsonHelper, null, null, null, null, null, - null, null, null, null, null,null,null); + null, null, null, null, null, null, null); if (ShareProductApiConstants.PREIEW_DIVIDENDS_COMMAND_STRING.equals(command)) { - return null ; - } else if (ShareProductApiConstants.POST_DIVIDENdS_COMMAND_STRING.equals(command)) { return postDividends(productId, - jsonCommand); } + return null; + } else if (ShareProductApiConstants.POST_DIVIDENdS_COMMAND_STRING.equals(command)) { return postDividends(productId, jsonCommand); } // throw unknow commandexception return CommandProcessingResult.empty(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDividendAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDividendAssembler.java index 68e29804d..f6d966685 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDividendAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDividendAssembler.java @@ -55,17 +55,16 @@ public class ShareProductDividendAssembler { final LocalDate dividendPeriodStartDate, final LocalDate dividendPeriodEndDate) { ShareProductData product = (ShareProductData) this.shareProductReadPlatformService.retrieveOne(productId, false); - MonetaryCurrency currency = new MonetaryCurrency(product.getCurrency().code(), product.getCurrency().decimalPlaces(), product - .getCurrency().currencyInMultiplesOf()); + MonetaryCurrency currency = new MonetaryCurrency(product.getCurrency().code(), product.getCurrency().decimalPlaces(), + product.getCurrency().currencyInMultiplesOf()); Collection shareAccountDatas = this.shareAccountReadPlatformService.retrieveAllShareAccountDataForDividends( productId, product.getAllowDividendCalculationForInactiveClients(), dividendPeriodStartDate); - if(shareAccountDatas == null || shareAccountDatas.isEmpty()) { - throw new ShareAccountsNotFoundException(product.getId()) ; - } + if (shareAccountDatas == null || shareAccountDatas.isEmpty()) { throw new ShareAccountsNotFoundException(product.getId()); } ShareProductDividendPayOutDetails productDividendPayOutDetails = null; - int minimumActivePeriod = 0 ; - if(product.getMinimumActivePeriod() != null) { //minimum active period may be null + int minimumActivePeriod = 0; + if (product.getMinimumActivePeriod() != null) { // minimum active period + // may be null minimumActivePeriod = product.getMinimumActivePeriod(); } final Map numberOfSharesdaysPerAccount = new HashMap<>(); @@ -99,10 +98,9 @@ public class ShareProductDividendAssembler { long numberOfShares = 0; LocalDate lastDividendAppliedDate = null; for (ShareAccountTransactionData purchasedSharesData : purchasedShares) { - final PurchasedSharesStatusType status = PurchasedSharesStatusType.fromInt(purchasedSharesData.getStatus().getId() - .intValue()); - final PurchasedSharesStatusType type = PurchasedSharesStatusType.fromInt(purchasedSharesData.getType().getId() - .intValue()); + final PurchasedSharesStatusType status = PurchasedSharesStatusType + .fromInt(purchasedSharesData.getStatus().getId().intValue()); + final PurchasedSharesStatusType type = PurchasedSharesStatusType.fromInt(purchasedSharesData.getType().getId().intValue()); if (status.isApproved() && !type.isChargePayment()) { LocalDate shareStartDate = purchasedSharesData.getPurchasedDate(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDividendReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDividendReadPlatformServiceImpl.java index 797dfcf0c..56ae976a3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDividendReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDividendReadPlatformServiceImpl.java @@ -49,8 +49,7 @@ public class ShareProductDividendReadPlatformServiceImpl implements ShareProduct private final PaginationHelper paginationHelper = new PaginationHelper<>(); @Autowired - public ShareProductDividendReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ColumnValidator columnValidator) { + public ShareProductDividendReadPlatformServiceImpl(final RoutingDataSource dataSource, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.columnValidator = columnValidator; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDropdownReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDropdownReadPlatformService.java index ba6a9cd59..f3e48a406 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDropdownReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDropdownReadPlatformService.java @@ -25,5 +25,5 @@ public interface ShareProductDropdownReadPlatformService { Collection retrieveLockinPeriodFrequencyTypeOptions(); - Collection retrieveMinimumActivePeriodFrequencyTypeOptions() ; + Collection retrieveMinimumActivePeriodFrequencyTypeOptions(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDropdownReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDropdownReadPlatformServiceImpl.java index 9f926f846..1f7437a8f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDropdownReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductDropdownReadPlatformServiceImpl.java @@ -36,7 +36,7 @@ public class ShareProductDropdownReadPlatformServiceImpl implements ShareProduct SharesEnumerations.lockinPeriodFrequencyType(SharePeriodFrequencyType.WEEKS), // SharesEnumerations.lockinPeriodFrequencyType(SharePeriodFrequencyType.MONTHS), // SharesEnumerations.lockinPeriodFrequencyType(SharePeriodFrequencyType.YEARS) // - ); + ); return allowedLockinPeriodFrequencyTypeOptions; } @@ -45,7 +45,7 @@ public class ShareProductDropdownReadPlatformServiceImpl implements ShareProduct public Collection retrieveMinimumActivePeriodFrequencyTypeOptions() { final List minimumActivePeriodFrequencyTypeOptions = Arrays.asList( // SharesEnumerations.lockinPeriodFrequencyType(SharePeriodFrequencyType.DAYS) // - ); + ); return minimumActivePeriodFrequencyTypeOptions; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductReadPlatformServiceImpl.java index 21ae1ef64..450acf02a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductReadPlatformServiceImpl.java @@ -80,8 +80,8 @@ public class ShareProductReadPlatformServiceImpl implements ProductReadPlatformS @Override public Page retrieveAllProducts(Integer offSet, Integer limit) { - final Collection shareMarketCollection = null ; - final Collection charges = null ; + final Collection shareMarketCollection = null; + final Collection charges = null; ShareProductRowMapper mapper = new ShareProductRowMapper(shareMarketCollection, charges); StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); @@ -243,8 +243,8 @@ public class ShareProductReadPlatformServiceImpl implements ProductReadPlatformS final String currencyNameCode = rs.getString("currencyNameCode"); final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "currency_multiplesof"); - final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, - currencyDisplaySymbol, currencyNameCode); + final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, + currencyNameCode); final Long totalShares = rs.getLong("total_shares"); final Long issuedShares = JdbcSupport.getLongDefaultToNullIfZero(rs, "issued_shares"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductWritePlatformServiceJpaRepositoryImpl.java index e547649a4..82cf914c0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/shareproducts/service/ShareProductWritePlatformServiceJpaRepositoryImpl.java @@ -86,11 +86,11 @@ public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareP .withCommandId(jsonCommand.commandId()) // .withEntityId(product.getId()) // .build(); - }catch (DataIntegrityViolationException dve) { + } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(jsonCommand, throwable, dve); return CommandProcessingResult.empty(); } @@ -117,11 +117,11 @@ public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareP .withEntityId(productId) // .with(changes) // .build(); - }catch (DataIntegrityViolationException dve) { + } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); - }catch (PersistenceException dve) { - Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; + } catch (PersistenceException dve) { + Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(jsonCommand, throwable, dve); return CommandProcessingResult.empty(); } @@ -132,20 +132,20 @@ public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareP try { this.serializer.validateDividendDetails(jsonCommand); JsonElement element = jsonCommand.parsedJson(); - final LocalDate dividendPeriodStartDate = this.fromApiJsonHelper.extractLocalDateNamed( - ShareProductApiConstants.dividendPeriodStartDateParamName, element); - final LocalDate dividendPeriodEndDate = this.fromApiJsonHelper.extractLocalDateNamed( - ShareProductApiConstants.dividendPeriodEndDateParamName, element); - final BigDecimal dividendAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( - ShareProductApiConstants.dividendAmountParamName, element); + final LocalDate dividendPeriodStartDate = this.fromApiJsonHelper + .extractLocalDateNamed(ShareProductApiConstants.dividendPeriodStartDateParamName, element); + final LocalDate dividendPeriodEndDate = this.fromApiJsonHelper + .extractLocalDateNamed(ShareProductApiConstants.dividendPeriodEndDateParamName, element); + final BigDecimal dividendAmount = this.fromApiJsonHelper + .extractBigDecimalWithLocaleNamed(ShareProductApiConstants.dividendAmountParamName, element); - final ShareProductDividendPayOutDetails dividendPayOutDetails = this.shareProductDividendAssembler.calculateDividends( - productId, dividendAmount, dividendPeriodStartDate, dividendPeriodEndDate); - if (dividendPayOutDetails == null) { throw new DividentProcessingException("eligible.shares.not.found", - "No eligible shares for creating dividends"); } + final ShareProductDividendPayOutDetails dividendPayOutDetails = this.shareProductDividendAssembler.calculateDividends(productId, + dividendAmount, dividendPeriodStartDate, dividendPeriodEndDate); + if (dividendPayOutDetails == null) { + throw new DividentProcessingException("eligible.shares.not.found", "No eligible shares for creating dividends"); + } this.shareProductDividentPayOutDetailsRepository.save(dividendPayOutDetails); - this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.SHARE_PRODUCT_DIVIDENDS_CREATE, constructEntityMap(BusinessEntity.SHARE_PRODUCT, productId)); @@ -165,8 +165,9 @@ public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareP try { ShareProductDividendPayOutDetails dividendPayOutDetails = this.shareProductDividentPayOutDetailsRepository .findOneWithNotFoundDetection(PayOutDetailId); - if (dividendPayOutDetails.getStatus().isApproved()) { throw new DividentProcessingException("alreay.approved", - "Can't approve already appoved dividends "); } + if (dividendPayOutDetails.getStatus().isApproved()) { + throw new DividentProcessingException("alreay.approved", "Can't approve already appoved dividends "); + } dividendPayOutDetails.approveDividendPayout(); this.shareProductDividentPayOutDetailsRepository.save(dividendPayOutDetails); return new CommandProcessingResultBuilder() // @@ -183,8 +184,9 @@ public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareP try { ShareProductDividendPayOutDetails dividendPayOutDetails = this.shareProductDividentPayOutDetailsRepository .findOneWithNotFoundDetection(PayOutDetailId); - if (dividendPayOutDetails.getStatus().isApproved()) { throw new DividentProcessingException("alreay.approved", - "Can't delete already appoved dividends "); } + if (dividendPayOutDetails.getStatus().isApproved()) { + throw new DividentProcessingException("alreay.approved", "Can't delete already appoved dividends "); + } this.shareProductDividentPayOutDetailsRepository.delete(dividendPayOutDetails); return new CommandProcessingResultBuilder() // .withEntityId(PayOutDetailId) // @@ -200,20 +202,20 @@ public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareP "Unknown data integrity issue with resource."); } - private void handleDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { if (realCause.getMessage().contains("'name'")) { final String name = command.stringValueOfParameterNamed(ShareProductApiConstants.name_paramname); - throw new PlatformDataIntegrityException("error.msg.shareproduct.duplicate.name", "Share Product with name `" + name - + "` already exists", "name", name); + throw new PlatformDataIntegrityException("error.msg.shareproduct.duplicate.name", + "Share Product with name `" + name + "` already exists", "name", name); } throw new PlatformDataIntegrityException("error.msg.shareproduct.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); } - private Map constructEntityMap(final BusinessEventNotificationConstants.BusinessEntity entityEvent, Object entity) { + private Map constructEntityMap( + final BusinessEventNotificationConstants.BusinessEntity entityEvent, Object entity) { Map map = new HashMap<>(1); map.put(entityEvent, entity); return map; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxComponentApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxComponentApiResource.java index 6646af182..052f952e4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxComponentApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxComponentApiResource.java @@ -55,10 +55,8 @@ import org.springframework.stereotype.Component; @Path("/taxes/component") @Component @Scope("singleton") -@Api(tags = {"Tax Components"}) -@SwaggerDefinition(tags = { - @Tag(name = "Tax Components", description = "This defines the Tax Components") -}) +@Api(tags = { "Tax Components" }) +@SwaggerDefinition(tags = { @Tag(name = "Tax Components", description = "This defines the Tax Components") }) public class TaxComponentApiResource { private final String resourceNameForPermissions = "TAXCOMPONENT"; @@ -85,7 +83,8 @@ public class TaxComponentApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "List Tax Components", httpMethod = "GET", notes = "List Tax Components") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = TaxComponentApiResourceSwagger.GetTaxesComponentsResponse.class, responseContainer = "List")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = TaxComponentApiResourceSwagger.GetTaxesComponentsResponse.class, responseContainer = "List") }) public String retrieveAllTaxComponents(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -101,8 +100,9 @@ public class TaxComponentApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieve Tax Component", httpMethod = "GET", notes = "Retrieve Tax Component") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = TaxComponentApiResourceSwagger.GetTaxesComponentsResponse.class)}) - public String retrieveTaxComponent(@PathParam("taxComponentId") @ApiParam(value = "taxComponentId") final Long taxComponentId, @Context final UriInfo uriInfo) { + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = TaxComponentApiResourceSwagger.GetTaxesComponentsResponse.class) }) + public String retrieveTaxComponent(@PathParam("taxComponentId") @ApiParam(value = "taxComponentId") final Long taxComponentId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -129,9 +129,12 @@ public class TaxComponentApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a new Tax Component", httpMethod = "POST", notes = "Creates a new Tax Component\n\n" + "Mandatory Fields: name, percentage\n\n" + "Optional Fields: debitAccountType, debitAcountId, creditAccountType, creditAcountId, startDate") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TaxComponentApiResourceSwagger.PostTaxesComponentsRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = TaxComponentApiResourceSwagger.PostTaxesComponentsResponse.class)}) + @ApiOperation(value = "Create a new Tax Component", httpMethod = "POST", notes = "Creates a new Tax Component\n\n" + + "Mandatory Fields: name, percentage\n\n" + + "Optional Fields: debitAccountType, debitAcountId, creditAccountType, creditAcountId, startDate") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TaxComponentApiResourceSwagger.PostTaxesComponentsRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = TaxComponentApiResourceSwagger.PostTaxesComponentsResponse.class) }) public String createTaxCompoent(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createTaxComponent().withJson(apiRequestBodyAsJson).build(); @@ -146,9 +149,12 @@ public class TaxComponentApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update Tax Component", httpMethod = "PUT", notes = "Updates Tax component. Debit and credit account details cannot be modified. All the future tax components would be replaced with the new percentage.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body",dataTypeClass = TaxComponentApiResourceSwagger.PutTaxesComponentsTaxComponentIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = TaxComponentApiResourceSwagger.PutTaxesComponentsTaxComponentIdResponse.class)}) - public String updateTaxCompoent(@PathParam("taxComponentId") @ApiParam(value = "taxComponentId") final Long taxComponentId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TaxComponentApiResourceSwagger.PutTaxesComponentsTaxComponentIdRequest.class) }) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = TaxComponentApiResourceSwagger.PutTaxesComponentsTaxComponentIdResponse.class) }) + public String updateTaxCompoent(@PathParam("taxComponentId") @ApiParam(value = "taxComponentId") final Long taxComponentId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateTaxComponent(taxComponentId).withJson(apiRequestBodyAsJson) .build(); @@ -158,4 +164,4 @@ public class TaxComponentApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxComponentApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxComponentApiResourceSwagger.java index 38d9afa22..c638b45cb 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxComponentApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxComponentApiResourceSwagger.java @@ -27,17 +27,17 @@ import java.util.Set; * Created by Chirag Gupta on 12/20/17. */ final class TaxComponentApiResourceSwagger { - private TaxComponentApiResourceSwagger() { - } + + private TaxComponentApiResourceSwagger() {} @ApiModel(value = "GetTaxesComponentsResponse") public final static class GetTaxesComponentsResponse { - private GetTaxesComponentsResponse() { - } + + private GetTaxesComponentsResponse() {} final class GetTaxesComponentsCreditAccountType { - private GetTaxesComponentsCreditAccountType() { - } + + private GetTaxesComponentsCreditAccountType() {} @ApiModelProperty(example = "2") public Integer id; @@ -48,8 +48,8 @@ final class TaxComponentApiResourceSwagger { } final class GetTaxesComponentsCreditAccount { - private GetTaxesComponentsCreditAccount() { - } + + private GetTaxesComponentsCreditAccount() {} @ApiModelProperty(example = "4") public Integer id; @@ -60,8 +60,8 @@ final class TaxComponentApiResourceSwagger { } final class GetTaxesComponentsHistories { - private GetTaxesComponentsHistories() { - } + + private GetTaxesComponentsHistories() {} } @ApiModelProperty(example = "1") @@ -79,8 +79,8 @@ final class TaxComponentApiResourceSwagger { @ApiModel(value = "PostTaxesComponentsRequest") public final static class PostTaxesComponentsRequest { - private PostTaxesComponentsRequest() { - } + + private PostTaxesComponentsRequest() {} @ApiModelProperty(example = "tax component 1") public String name; @@ -100,8 +100,8 @@ final class TaxComponentApiResourceSwagger { @ApiModel(value = "PostTaxesComponentsResponse") public final static class PostTaxesComponentsResponse { - private PostTaxesComponentsResponse() { - } + + private PostTaxesComponentsResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -109,8 +109,8 @@ final class TaxComponentApiResourceSwagger { @ApiModel(value = "PutTaxesComponentsTaxComponentIdRequest") public final static class PutTaxesComponentsTaxComponentIdRequest { - private PutTaxesComponentsTaxComponentIdRequest() { - } + + private PutTaxesComponentsTaxComponentIdRequest() {} @ApiModelProperty(example = "tax component 2") public String name; @@ -126,12 +126,12 @@ final class TaxComponentApiResourceSwagger { @ApiModel(value = "PutTaxesComponentsTaxComponentIdResponse") public final static class PutTaxesComponentsTaxComponentIdResponse { - private PutTaxesComponentsTaxComponentIdResponse() { - } + + private PutTaxesComponentsTaxComponentIdResponse() {} final class PutTaxesComponentsChanges { - private PutTaxesComponentsChanges() { - } + + private PutTaxesComponentsChanges() {} @ApiModelProperty(example = "15") public Float percentage; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxGroupApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxGroupApiResource.java index c1702e12a..6373445d5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxGroupApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxGroupApiResource.java @@ -55,10 +55,8 @@ import org.springframework.stereotype.Component; @Path("/taxes/group") @Component @Scope("singleton") -@Api(tags = {"Tax Group"}) -@SwaggerDefinition(tags = { - @Tag(name = "Tax Group", description = "This defines the Tax Group") -}) +@Api(tags = { "Tax Group" }) +@SwaggerDefinition(tags = { @Tag(name = "Tax Group", description = "This defines the Tax Group") }) public class TaxGroupApiResource { private final String resourceNameForPermissions = "TAXGROUP"; @@ -84,7 +82,8 @@ public class TaxGroupApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "List Tax Group", httpMethod = "GET", notes = "List Tax Group") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = TaxGroupApiResourceSwagger.GetTaxesGroupResponse.class, responseContainer = "List")}) + @ApiResponses({ + @ApiResponse(code = 200, message = "OK", response = TaxGroupApiResourceSwagger.GetTaxesGroupResponse.class, responseContainer = "List") }) public String retrieveAllTaxGroups(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -100,8 +99,9 @@ public class TaxGroupApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Retrieve Tax Group", httpMethod = "GET", notes = "Retrieve Tax Group") - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = TaxGroupApiResourceSwagger.GetTaxesGroupResponse.class)}) - public String retrieveTaxGroup(@PathParam("taxGroupId") @ApiParam(value = "taxGroupId") final Long taxGroupId, @Context final UriInfo uriInfo) { + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = TaxGroupApiResourceSwagger.GetTaxesGroupResponse.class) }) + public String retrieveTaxGroup(@PathParam("taxGroupId") @ApiParam(value = "taxGroupId") final Long taxGroupId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); @@ -132,9 +132,12 @@ public class TaxGroupApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - @ApiOperation(value = "Create a new Tax Group", httpMethod = "POST", notes = "Create a new Tax Group\n" + "Mandatory Fields: name and taxComponents\n" + "Mandatory Fields in taxComponents: taxComponentId\n" + "Optional Fields in taxComponents: id, startDate and endDate") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TaxGroupApiResourceSwagger.PostTaxesGroupRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = TaxGroupApiResourceSwagger.PostTaxesGroupResponse.class)}) + @ApiOperation(value = "Create a new Tax Group", httpMethod = "POST", notes = "Create a new Tax Group\n" + + "Mandatory Fields: name and taxComponents\n" + "Mandatory Fields in taxComponents: taxComponentId\n" + + "Optional Fields in taxComponents: id, startDate and endDate") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TaxGroupApiResourceSwagger.PostTaxesGroupRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = TaxGroupApiResourceSwagger.PostTaxesGroupResponse.class) }) public String createTaxGroup(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createTaxGroup().withJson(apiRequestBodyAsJson).build(); @@ -149,9 +152,11 @@ public class TaxGroupApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "Update Tax Group", httpMethod = "PUT", notes = "Updates Tax Group. Only end date can be up-datable and can insert new tax components.") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TaxGroupApiResourceSwagger.PutTaxesGroupTaxGroupIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "OK", response = TaxGroupApiResourceSwagger.PutTaxesGroupTaxGroupIdResponse.class)}) - public String updateTaxGroup(@PathParam("taxGroupId") @ApiParam(value = "taxGroupId") final Long taxGroupId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TaxGroupApiResourceSwagger.PutTaxesGroupTaxGroupIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = TaxGroupApiResourceSwagger.PutTaxesGroupTaxGroupIdResponse.class) }) + public String updateTaxGroup(@PathParam("taxGroupId") @ApiParam(value = "taxGroupId") final Long taxGroupId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateTaxGroup(taxGroupId).withJson(apiRequestBodyAsJson).build(); @@ -160,4 +165,4 @@ public class TaxGroupApiResource { return this.toApiJsonSerializer.serialize(result); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxGroupApiResourceSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxGroupApiResourceSwagger.java index 3a50ca935..e2acb9c0b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxGroupApiResourceSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/api/TaxGroupApiResourceSwagger.java @@ -28,21 +28,21 @@ import java.util.Set; * Created by Chirag Gupta on 12/14/17. */ final class TaxGroupApiResourceSwagger { - private TaxGroupApiResourceSwagger() { - } + + private TaxGroupApiResourceSwagger() {} @ApiModel(value = "GetTaxesGroupResponse") public final static class GetTaxesGroupResponse { - private GetTaxesGroupResponse() { - } + + private GetTaxesGroupResponse() {} final class GetTaxesGroupTaxAssociations { - private GetTaxesGroupTaxAssociations() { - } + + private GetTaxesGroupTaxAssociations() {} final class GetTaxesGroupTaxComponent { - private GetTaxesGroupTaxComponent() { - } + + private GetTaxesGroupTaxComponent() {} @ApiModelProperty(example = "7") public Integer id; @@ -66,12 +66,12 @@ final class TaxGroupApiResourceSwagger { @ApiModel(value = "PostTaxesGroupRequest") public final static class PostTaxesGroupRequest { - private PostTaxesGroupRequest() { - } + + private PostTaxesGroupRequest() {} final class PostTaxesGroupTaxComponents { - private PostTaxesGroupTaxComponents() { - } + + private PostTaxesGroupTaxComponents() {} @ApiModelProperty(example = "7") public Integer taxComponentId; @@ -90,8 +90,8 @@ final class TaxGroupApiResourceSwagger { @ApiModel(value = "PostTaxesGroupResponse") public static final class PostTaxesGroupResponse { - private PostTaxesGroupResponse() { - } + + private PostTaxesGroupResponse() {} @ApiModelProperty(example = "1") public Integer resourceId; @@ -99,12 +99,12 @@ final class TaxGroupApiResourceSwagger { @ApiModel(value = "PutTaxesGroupTaxGroupIdRequest") public final static class PutTaxesGroupTaxGroupIdRequest { - private PutTaxesGroupTaxGroupIdRequest() { - } + + private PutTaxesGroupTaxGroupIdRequest() {} final class PutTaxesGroupTaxComponents { - private PutTaxesGroupTaxComponents() { - } + + private PutTaxesGroupTaxComponents() {} @ApiModelProperty(example = "7") public Integer id; @@ -125,16 +125,16 @@ final class TaxGroupApiResourceSwagger { @ApiModel(value = "PutTaxesGroupTaxGroupIdResponse") public final static class PutTaxesGroupTaxGroupIdResponse { - private PutTaxesGroupTaxGroupIdResponse() { - } + + private PutTaxesGroupTaxGroupIdResponse() {} final class PutTaxesGroupChanges { - private PutTaxesGroupChanges() { - } + + private PutTaxesGroupChanges() {} final class PutTaxesGroupModifiedComponents { - private PutTaxesGroupModifiedComponents() { - } + + private PutTaxesGroupModifiedComponents() {} @ApiModelProperty(example = "Apr 22, 2016 12:00:00 AM") public String endDate; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponent.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponent.java index 3225bb139..69e04b547 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponent.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponent.java @@ -74,11 +74,11 @@ public class TaxComponent extends AbstractAuditableCustom { @Temporal(TemporalType.DATE) private Date startDate; - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "tax_component_id", referencedColumnName = "id", nullable = false) private Set taxComponentHistories = new HashSet<>(); - @OneToMany(cascade = CascadeType.DETACH, mappedBy = "taxComponent", orphanRemoval = false, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.DETACH, mappedBy = "taxComponent", orphanRemoval = false, fetch = FetchType.EAGER) private Set taxGroupMappings = new HashSet<>(); protected TaxComponent() { @@ -196,22 +196,18 @@ public class TaxComponent extends AbstractAuditableCustom { return dates; } - public Integer getDebitAccountType() { return this.debitAccountType; } - public GLAccount getDebitAcount() { return this.debitAcount; } - public Integer getCreditAccountType() { return this.creditAccountType; } - public GLAccount getCreditAcount() { return this.creditAcount; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponentHistory.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponentHistory.java index 6afa827bb..7205c11bf 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponentHistory.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponentHistory.java @@ -58,30 +58,27 @@ public class TaxComponentHistory extends AbstractAuditableCustom { return new TaxComponentHistory(percentage, startDate, endDate); } - public LocalDate startDate(){ + public LocalDate startDate() { LocalDate startDate = null; - if(this.startDate != null){ + if (this.startDate != null) { startDate = new LocalDate(this.startDate); } return startDate; } - public LocalDate endDate(){ + public LocalDate endDate() { LocalDate endDate = null; - if(this.endDate != null){ + if (this.endDate != null) { endDate = new LocalDate(this.endDate); } return endDate; } public boolean occursOnDayFromAndUpToAndIncluding(final LocalDate target) { - if(this.endDate == null){ - return target != null && target.isAfter(startDate()); - } + if (this.endDate == null) { return target != null && target.isAfter(startDate()); } return target != null && target.isAfter(startDate()) && !target.isAfter(endDate()); } - public BigDecimal getPercentage() { return this.percentage; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponentRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponentRepositoryWrapper.java index 558bcf2ce..7ea021fc3 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponentRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxComponentRepositoryWrapper.java @@ -33,8 +33,7 @@ public class TaxComponentRepositoryWrapper { } public TaxComponent findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new TaxComponentNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new TaxComponentNotFoundException(id)); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxGroup.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxGroup.java index 5c19abb11..bd31efea0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxGroup.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxGroup.java @@ -44,7 +44,7 @@ public class TaxGroup extends AbstractAuditableCustom { @Column(name = "name", length = 100) private String name; - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "tax_group_id", referencedColumnName = "id", nullable = false) private Set taxGroupMappings = new HashSet<>(); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxGroupRepositoryWrapper.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxGroupRepositoryWrapper.java index e26d4bbad..745e7f2ec 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxGroupRepositoryWrapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/domain/TaxGroupRepositoryWrapper.java @@ -33,7 +33,6 @@ public class TaxGroupRepositoryWrapper { } public TaxGroup findOneWithNotFoundDetection(final Long id) { - return this.repository.findById(id) - .orElseThrow(() -> new TaxGroupNotFoundException(id)); + return this.repository.findById(id).orElseThrow(() -> new TaxGroupNotFoundException(id)); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/exception/TaxMappingNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/exception/TaxMappingNotFoundException.java index d9ce11f18..829ae9722 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/exception/TaxMappingNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/exception/TaxMappingNotFoundException.java @@ -31,4 +31,4 @@ public class TaxMappingNotFoundException extends AbstractPlatformResourceNotFoun super("error.msg.tax.group.id.invalid", "Tax group mapping with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/serialization/TaxValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/serialization/TaxValidator.java index a4ad9a018..9871e3a40 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/serialization/TaxValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/serialization/TaxValidator.java @@ -52,19 +52,19 @@ import org.springframework.stereotype.Component; @Component public class TaxValidator { - final Set supportedTaxComponentCreateParameters = new HashSet<>(Arrays.asList("dateFormat", "locale", - TaxApiConstants.nameParamName, TaxApiConstants.percentageParamName, TaxApiConstants.startDateParamName, - TaxApiConstants.debitAccountTypeParamName, TaxApiConstants.debitAcountIdParamName, TaxApiConstants.creditAccountTypeParamName, - TaxApiConstants.creditAcountIdParamName)); + final Set supportedTaxComponentCreateParameters = new HashSet<>( + Arrays.asList("dateFormat", "locale", TaxApiConstants.nameParamName, TaxApiConstants.percentageParamName, + TaxApiConstants.startDateParamName, TaxApiConstants.debitAccountTypeParamName, TaxApiConstants.debitAcountIdParamName, + TaxApiConstants.creditAccountTypeParamName, TaxApiConstants.creditAcountIdParamName)); final Set supportedTaxComponentUpdateParameters = new HashSet<>(Arrays.asList("dateFormat", "locale", TaxApiConstants.nameParamName, TaxApiConstants.percentageParamName, TaxApiConstants.startDateParamName)); - final Set supportedTaxGroupParameters = new HashSet<>(Arrays.asList("dateFormat", "locale", TaxApiConstants.nameParamName, - TaxApiConstants.taxComponentsParamName)); + final Set supportedTaxGroupParameters = new HashSet<>( + Arrays.asList("dateFormat", "locale", TaxApiConstants.nameParamName, TaxApiConstants.taxComponentsParamName)); - final Set supportedTaxGroupTaxComponentsCreateParameters = new HashSet<>(Arrays.asList(TaxApiConstants.taxComponentIdParamName, - TaxApiConstants.startDateParamName)); + final Set supportedTaxGroupTaxComponentsCreateParameters = new HashSet<>( + Arrays.asList(TaxApiConstants.taxComponentIdParamName, TaxApiConstants.startDateParamName)); final Set supportedTaxGroupTaxComponentsUpdateParameters = new HashSet<>(Arrays.asList(TaxApiConstants.idParamName, TaxApiConstants.taxComponentIdParamName, TaxApiConstants.startDateParamName, TaxApiConstants.endDateParamName)); @@ -96,11 +96,7 @@ public class TaxValidator { final Integer debitAccountType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(TaxApiConstants.debitAccountTypeParamName, element); - baseDataValidator - .reset() - .parameter(TaxApiConstants.debitAccountTypeParamName) - .value(debitAccountType) - .ignoreIfNull() + baseDataValidator.reset().parameter(TaxApiConstants.debitAccountTypeParamName).value(debitAccountType).ignoreIfNull() .isOneOfTheseValues(GLAccountType.ASSET.getValue(), GLAccountType.LIABILITY.getValue(), GLAccountType.EQUITY.getValue(), GLAccountType.INCOME.getValue(), GLAccountType.EXPENSE.getValue()); @@ -113,11 +109,7 @@ public class TaxValidator { final Integer creditAccountType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(TaxApiConstants.creditAccountTypeParamName, element); - baseDataValidator - .reset() - .parameter(TaxApiConstants.creditAccountTypeParamName) - .value(creditAccountType) - .ignoreIfNull() + baseDataValidator.reset().parameter(TaxApiConstants.creditAccountTypeParamName).value(creditAccountType).ignoreIfNull() .isOneOfTheseValues(GLAccountType.ASSET.getValue(), GLAccountType.LIABILITY.getValue(), GLAccountType.EQUITY.getValue(), GLAccountType.INCOME.getValue(), GLAccountType.EXPENSE.getValue()); @@ -228,20 +220,16 @@ public class TaxValidator { supportedTaxGroupTaxComponentsUpdateParameters); final Long taxComponentId = this.fromApiJsonHelper.extractLongNamed(TaxApiConstants.taxComponentIdParamName, taxComponent); - final Long taxMappingId = this.fromApiJsonHelper - .extractLongNamed(TaxApiConstants.taxComponentIdParamName, taxComponent); + final Long taxMappingId = this.fromApiJsonHelper.extractLongNamed(TaxApiConstants.taxComponentIdParamName, + taxComponent); if (taxMappingId == null) { - baseDataValidator - .reset() - .parameter( - TaxApiConstants.taxComponentsParamName + "." + TaxApiConstants.taxComponentIdParamName - + ".at.index." + i).value(taxComponentId).notNull().longGreaterThanZero(); + baseDataValidator.reset().parameter( + TaxApiConstants.taxComponentsParamName + "." + TaxApiConstants.taxComponentIdParamName + ".at.index." + i) + .value(taxComponentId).notNull().longGreaterThanZero(); } else { - baseDataValidator - .reset() - .parameter( - TaxApiConstants.taxComponentsParamName + "." + TaxApiConstants.taxComponentIdParamName - + ".at.index." + i).value(taxComponentId).longGreaterThanZero(); + baseDataValidator.reset().parameter( + TaxApiConstants.taxComponentsParamName + "." + TaxApiConstants.taxComponentIdParamName + ".at.index." + i) + .value(taxComponentId).longGreaterThanZero(); baseDataValidator.reset() .parameter(TaxApiConstants.taxComponentsParamName + "." + TaxApiConstants.idParamName + ".at.index." + i) .value(taxMappingId).longGreaterThanZero(); @@ -278,7 +266,7 @@ public class TaxValidator { baseDataValidator.reset().parameter(TaxApiConstants.endDateParamName).value(mapping.endDate()).ignoreIfNull() .validateDateAfter(existing.startDate()); } - if(mapping.getTaxComponent()!= null && !existing.getTaxComponent().getId().equals(mapping.getTaxComponent().getId())){ + if (mapping.getTaxComponent() != null && !existing.getTaxComponent().getId().equals(mapping.getTaxComponent().getId())) { baseDataValidator.reset().parameter(TaxApiConstants.taxComponentIdParamName).failWithCode("update.not.supported"); } } else if (mapping.endDate() != null) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/service/TaxAssembler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/service/TaxAssembler.java index 27614bac3..a31bdb6f8 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/service/TaxAssembler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/service/TaxAssembler.java @@ -132,8 +132,8 @@ public class TaxAssembler { final JsonObject taxComponent = array.get(i).getAsJsonObject(); final Long mappingId = this.fromApiJsonHelper.extractLongNamed(TaxApiConstants.idParamName, taxComponent); final Long taxComponentId = this.fromApiJsonHelper.extractLongNamed(TaxApiConstants.taxComponentIdParamName, taxComponent); - TaxComponent component = null; - if(taxComponentId != null){ + TaxComponent component = null; + if (taxComponentId != null) { component = this.taxComponentRepositoryWrapper.findOneWithNotFoundDetection(taxComponentId); } LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed(TaxApiConstants.startDateParamName, taxComponent, diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/service/TaxReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/service/TaxReadPlatformServiceImpl.java index 0c566541d..a8c138794 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/service/TaxReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/tax/service/TaxReadPlatformServiceImpl.java @@ -175,8 +175,8 @@ public class TaxReadPlatformServiceImpl implements TaxReadPlatformService { break; } } - return TaxComponentData.instance(id, name, percentage, debitAccountType, debitAccountData, creditAccountType, - creditAccountData, startDate, historyDatas); + return TaxComponentData.instance(id, name, percentage, debitAccountType, debitAccountData, creditAccountType, creditAccountData, + startDate, historyDatas); } public String getSchema() { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/api/TransferApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/api/TransferApiConstants.java index 35e2b09ad..5f73e2da9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/api/TransferApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/api/TransferApiConstants.java @@ -40,4 +40,4 @@ public class TransferApiConstants { public static final String transferClientSavingsExceptionMessage = "error msg caanot transfer client as savings transaction present on or after transfer date"; public static final String transferClientToSameOfficeException = "error.msg.cannot.transfer.clinet.as.selected.office.and.current.office.are.same"; public static final String transferClientToSameOfficeExceptionMessage = "error.msg.cannot.transfer.clinet.as.selected.office.and.current.office.are.same"; -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/data/TransfersDataValidator.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/data/TransfersDataValidator.java index f9c590976..87852d2b6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/data/TransfersDataValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/data/TransfersDataValidator.java @@ -51,24 +51,20 @@ public final class TransfersDataValidator { private static final Set PROPOSE_CLIENT_TRANSFER_DATA_PARAMETERS = new HashSet<>( Arrays.asList(TransferApiConstants.localeParamName, TransferApiConstants.dateFormatParamName, - TransferApiConstants.destinationOfficeIdParamName, TransferApiConstants.transferActiveLoans, - TransferApiConstants.note, TransferApiConstants.transferDate)); + TransferApiConstants.destinationOfficeIdParamName, TransferApiConstants.transferActiveLoans, TransferApiConstants.note, + TransferApiConstants.transferDate)); - private static final Set ACCEPT_CLIENT_TRANSFER_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(TransferApiConstants.newStaffIdParamName, TransferApiConstants.destinationGroupIdParamName, - TransferApiConstants.note)); + private static final Set ACCEPT_CLIENT_TRANSFER_DATA_PARAMETERS = new HashSet<>(Arrays + .asList(TransferApiConstants.newStaffIdParamName, TransferApiConstants.destinationGroupIdParamName, TransferApiConstants.note)); private static final Set PROPOSE_AND_ACCEPT_CLIENT_TRANSFER_DATA_PARAMETERS = new HashSet<>( Arrays.asList(TransferApiConstants.localeParamName, TransferApiConstants.dateFormatParamName, TransferApiConstants.destinationOfficeIdParamName, TransferApiConstants.transferActiveLoans, - TransferApiConstants.newStaffIdParamName, TransferApiConstants.destinationGroupIdParamName, - TransferApiConstants.note)); + TransferApiConstants.newStaffIdParamName, TransferApiConstants.destinationGroupIdParamName, TransferApiConstants.note)); - private static final Set REJECT_CLIENT_TRANSFER_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(TransferApiConstants.note)); + private static final Set REJECT_CLIENT_TRANSFER_DATA_PARAMETERS = new HashSet<>(Arrays.asList(TransferApiConstants.note)); - private static final Set WITHDRAW_CLIENT_TRANSFER_DATA_PARAMETERS = new HashSet<>( - Arrays.asList(TransferApiConstants.note)); + private static final Set WITHDRAW_CLIENT_TRANSFER_DATA_PARAMETERS = new HashSet<>(Arrays.asList(TransferApiConstants.note)); @Autowired public TransfersDataValidator(final FromJsonHelper fromApiJsonHelper) { @@ -84,8 +80,7 @@ public final class TransfersDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, - TRANSFER_CLIENTS_BETWEEN_GROUPS_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, TRANSFER_CLIENTS_BETWEEN_GROUPS_DATA_PARAMETERS); final JsonElement element = this.fromApiJsonHelper.parse(json); final List dataValidationErrors = new ArrayList<>(); @@ -104,8 +99,8 @@ public final class TransfersDataValidator { } if (this.fromApiJsonHelper.parameterExists(TransferApiConstants.inheritDestinationGroupLoanOfficer, element)) { - final Boolean inheritDestinationGroupLoanOfficer = this.fromApiJsonHelper.extractBooleanNamed( - TransferApiConstants.inheritDestinationGroupLoanOfficer, element); + final Boolean inheritDestinationGroupLoanOfficer = this.fromApiJsonHelper + .extractBooleanNamed(TransferApiConstants.inheritDestinationGroupLoanOfficer, element); baseDataValidator.reset().parameter(TransferApiConstants.inheritDestinationGroupLoanOfficer) .value(inheritDestinationGroupLoanOfficer).notNull(); } @@ -126,8 +121,8 @@ public final class TransfersDataValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(ClientApiConstants.CLIENT_RESOURCE_NAME); - final Long destinationOfficeId = this.fromApiJsonHelper - .extractLongNamed(TransferApiConstants.destinationOfficeIdParamName, element); + final Long destinationOfficeId = this.fromApiJsonHelper.extractLongNamed(TransferApiConstants.destinationOfficeIdParamName, + element); baseDataValidator.reset().parameter(TransferApiConstants.destinationOfficeIdParamName).value(destinationOfficeId).notNull() .integerGreaterThanZero(); @@ -176,8 +171,8 @@ public final class TransfersDataValidator { .resource(ClientApiConstants.CLIENT_RESOURCE_NAME); final JsonElement element = this.fromApiJsonHelper.parse(json); - final Long destinationOfficeId = this.fromApiJsonHelper - .extractLongNamed(TransferApiConstants.destinationOfficeIdParamName, element); + final Long destinationOfficeId = this.fromApiJsonHelper.extractLongNamed(TransferApiConstants.destinationOfficeIdParamName, + element); baseDataValidator.reset().parameter(TransferApiConstants.destinationOfficeIdParamName).value(destinationOfficeId).notNull() .integerGreaterThanZero(); @@ -219,8 +214,7 @@ public final class TransfersDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper - .checkForUnsupportedParameters(typeOfMap, json, WITHDRAW_CLIENT_TRANSFER_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, WITHDRAW_CLIENT_TRANSFER_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -237,4 +231,4 @@ public final class TransfersDataValidator { baseDataValidator.reset().parameter(TransferApiConstants.note).value(note).notExceedingLengthOf(1000); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/ClientNotAwaitingTransferApprovalException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/ClientNotAwaitingTransferApprovalException.java index 116463a73..76dfa9f0f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/ClientNotAwaitingTransferApprovalException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/ClientNotAwaitingTransferApprovalException.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class ClientNotAwaitingTransferApprovalException extends AbstractPlatformDomainRuleException { public ClientNotAwaitingTransferApprovalException(final Long clientId) { - super("error.msg.client.not.awaiting.transfer.approval.exception", - "The Client with id `" + clientId + "` is not awaiting transfer", clientId); + super("error.msg.client.not.awaiting.transfer.approval.exception", "The Client with id `" + clientId + "` is not awaiting transfer", + clientId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/ClientNotAwaitingTransferApprovalOrOnHoldException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/ClientNotAwaitingTransferApprovalOrOnHoldException.java index 29d75c0a7..2f909f820 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/ClientNotAwaitingTransferApprovalOrOnHoldException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/ClientNotAwaitingTransferApprovalOrOnHoldException.java @@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR public class ClientNotAwaitingTransferApprovalOrOnHoldException extends AbstractPlatformDomainRuleException { public ClientNotAwaitingTransferApprovalOrOnHoldException(final Long clientId) { - super("error.msg.client.not.awaiting.transfer.approval.or.on.hold.exception", "The Client with id `" + clientId - + "` is neither awaiting a transfer nor on hold", clientId); + super("error.msg.client.not.awaiting.transfer.approval.or.on.hold.exception", + "The Client with id `" + clientId + "` is neither awaiting a transfer nor on hold", clientId); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/TransferNotSupportedException.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/TransferNotSupportedException.java index 9e763f91a..f6638c91b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/TransferNotSupportedException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/exception/TransferNotSupportedException.java @@ -28,6 +28,7 @@ public class TransferNotSupportedException extends AbstractPlatformDomainRuleExc /*** enum of reasons for invalid Journal Entry **/ public static enum TransferNotSupportedReason { + CLIENT_DESTINATION_GROUP_NOT_SPECIFIED, CLIENT_BELONGS_TO_MULTIPLE_GROUPS, SOURCE_AND_DESTINATION_GROUP_CANNOT_BE_SAME, ACTIVE_SAVINGS_ACCOUNT, BULK_CLIENT_TRANSFER_ACROSS_BRANCHES, DESTINATION_GROUP_MEETING_FREQUENCY_MISMATCH, DESTINATION_GROUP_HAS_NO_MEETING; public String errorMessage() { @@ -43,7 +44,9 @@ public class TransferNotSupportedException extends AbstractPlatformDomainRuleExc return "Cannot transfer Clients with active accounts between groups with different meeting frequency"; } else if (name().toString().equalsIgnoreCase("SOURCE_AND_DESTINATION_GROUP_CANNOT_BE_SAME")) { return "Source and destination groups for bulk client transfers should be different"; - } else if (name().toString().equalsIgnoreCase("DESTINATION_GROUP_HAS_NO_MEETING")) { return "Cannot transfer Client with active accounts to a groups with no meeting frequency"; } + } else if (name().toString().equalsIgnoreCase("DESTINATION_GROUP_HAS_NO_MEETING")) { + return "Cannot transfer Client with active accounts to a groups with no meeting frequency"; + } return name().toString(); } @@ -60,7 +63,9 @@ public class TransferNotSupportedException extends AbstractPlatformDomainRuleExc return "error.msg.client.transfers.with.active.accounts.between.groups.with.different.meeting.frequency"; } else if (name().toString().equalsIgnoreCase("SOURCE_AND_DESTINATION_GROUP_CANNOT_BE_SAME")) { return "error.msg.groups.bulk.client.transfers.to.same.group"; - } else if (name().toString().equalsIgnoreCase("DESTINATION_GROUP_HAS_NO_MEETING")) { return "error.msg.client.transfers.with.active.accounts.to.group.with.no.meeting.frequencys"; } + } else if (name().toString().equalsIgnoreCase("DESTINATION_GROUP_HAS_NO_MEETING")) { + return "error.msg.client.transfers.with.active.accounts.to.group.with.no.meeting.frequencys"; + } return name().toString(); } } @@ -69,4 +74,4 @@ public class TransferNotSupportedException extends AbstractPlatformDomainRuleExc super(reason.errorCode(), reason.errorMessage(), defaultUserMessageArgs); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/AcceptClientTransferCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/AcceptClientTransferCommandHandler.java index 67483df65..491567486 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/AcceptClientTransferCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/AcceptClientTransferCommandHandler.java @@ -44,4 +44,4 @@ public class AcceptClientTransferCommandHandler implements NewCommandSourceHandl return this.writePlatformService.acceptClientTransfer(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/ProposeAndAcceptClientTransferCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/ProposeAndAcceptClientTransferCommandHandler.java index 31568a670..cb0297942 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/ProposeAndAcceptClientTransferCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/ProposeAndAcceptClientTransferCommandHandler.java @@ -43,4 +43,4 @@ public class ProposeAndAcceptClientTransferCommandHandler implements NewCommandS public CommandProcessingResult processCommand(final JsonCommand command) { return this.writePlatformService.proposeAndAcceptClientTransfer(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/ProposeClientTransferCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/ProposeClientTransferCommandHandler.java index f04d22ecf..f4e41f7d7 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/ProposeClientTransferCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/ProposeClientTransferCommandHandler.java @@ -44,4 +44,4 @@ public class ProposeClientTransferCommandHandler implements NewCommandSourceHand return this.writePlatformService.proposeClientTransfer(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/RejectClientTransferCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/RejectClientTransferCommandHandler.java index bb40d8c3e..495431aa9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/RejectClientTransferCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/RejectClientTransferCommandHandler.java @@ -44,4 +44,4 @@ public class RejectClientTransferCommandHandler implements NewCommandSourceHandl return this.writePlatformService.rejectClientTransfer(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/TransferClientsBetweenGroupsCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/TransferClientsBetweenGroupsCommandHandler.java index 06b36ee1a..32de92638 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/TransferClientsBetweenGroupsCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/TransferClientsBetweenGroupsCommandHandler.java @@ -44,4 +44,4 @@ public class TransferClientsBetweenGroupsCommandHandler implements NewCommandSou return this.writePlatformService.transferClientsBetweenGroups(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/WithdrawClientTransferCommandHandler.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/WithdrawClientTransferCommandHandler.java index fa913b44a..87cf7929c 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/WithdrawClientTransferCommandHandler.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/handler/WithdrawClientTransferCommandHandler.java @@ -44,4 +44,4 @@ public class WithdrawClientTransferCommandHandler implements NewCommandSourceHan return this.writePlatformService.withdrawClientTransfer(command.entityId(), command); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferEventType.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferEventType.java index fd956227f..5c6b6c6a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferEventType.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferEventType.java @@ -19,8 +19,9 @@ package org.apache.fineract.portfolio.transfer.service; public enum TransferEventType { - PROPOSAL(1, "transferEvent.proposal"), ACCEPTANCE(2, "transferEvent.acceptance"), WITHDRAWAL(3, "transferEvent.withdrawal"), REJECTION( - 4, "transferEvent.rejection"); + + PROPOSAL(1, "transferEvent.proposal"), ACCEPTANCE(2, "transferEvent.acceptance"), WITHDRAWAL(3, + "transferEvent.withdrawal"), REJECTION(4, "transferEvent.rejection"); private final Integer value; private final String code; diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferWritePlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferWritePlatformService.java index 7c8c17cdb..59483abc9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferWritePlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferWritePlatformService.java @@ -35,4 +35,4 @@ public interface TransferWritePlatformService { CommandProcessingResult proposeAndAcceptClientTransfer(final Long clientId, final JsonCommand jsonCommand); -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferWritePlatformServiceJpaRepositoryImpl.java old mode 100755 new mode 100644 index 90f60ea05..c76f870ce --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/transfer/service/TransferWritePlatformServiceJpaRepositoryImpl.java @@ -83,7 +83,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr private final NoteWritePlatformService noteWritePlatformService; private final StaffRepositoryWrapper staffRepositoryWrapper; private final ClientTransferDetailsRepositoryWrapper clientTransferDetailsRepositoryWrapper; - private final PlatformSecurityContext context; + private final PlatformSecurityContext context; @Autowired public TransferWritePlatformServiceJpaRepositoryImpl(final ClientRepositoryWrapper clientRepositoryWrapper, @@ -93,8 +93,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr final NoteWritePlatformService noteWritePlatformService, final StaffRepositoryWrapper staffRepositoryWrapper, final SavingsAccountRepositoryWrapper savingsAccountRepositoryWrapper, final SavingsAccountWritePlatformService savingsAccountWritePlatformService, - final ClientTransferDetailsRepositoryWrapper clientTransferDetailsRepositoryWrapper, - final PlatformSecurityContext context) { + final ClientTransferDetailsRepositoryWrapper clientTransferDetailsRepositoryWrapper, final PlatformSecurityContext context) { this.clientRepositoryWrapper = clientRepositoryWrapper; this.officeRepository = officeRepository; this.calendarInstanceRepository = calendarInstanceRepository; @@ -130,12 +129,16 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr final List clients = assembleListOfClients(jsonCommand); - if (sourceGroupId.equals(destinationGroupId)) { throw new TransferNotSupportedException( - TransferNotSupportedReason.SOURCE_AND_DESTINATION_GROUP_CANNOT_BE_SAME, sourceGroupId, destinationGroupId); } + if (sourceGroupId.equals(destinationGroupId)) { + throw new TransferNotSupportedException(TransferNotSupportedReason.SOURCE_AND_DESTINATION_GROUP_CANNOT_BE_SAME, sourceGroupId, + destinationGroupId); + } /*** Do not allow bulk client transfers across branches ***/ - if (!sourceOffice.getId().equals(destinationGroup.getOffice().getId())) { throw new TransferNotSupportedException( - TransferNotSupportedReason.BULK_CLIENT_TRANSFER_ACROSS_BRANCHES, sourceGroupId, destinationGroupId); } + if (!sourceOffice.getId().equals(destinationGroup.getOffice().getId())) { + throw new TransferNotSupportedException(TransferNotSupportedReason.BULK_CLIENT_TRANSFER_ACROSS_BRANCHES, sourceGroupId, + destinationGroupId); + } for (final Client client : clients) { transferClientBetweenGroups(sourceGroup, client, destinationGroup, inheritDestinationGroupLoanOfficer, staff); @@ -153,7 +156,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr *
    • newStaffId: Optional field with Id of new Loan Officer to be linked * to this client and all his JLG loans for this group
    • * - * ***/ + ***/ @Transactional public void transferClientBetweenGroups(final Group sourceGroup, final Client client, final Group destinationGroup, final Boolean inheritDestinationGroupLoanOfficer, final Staff newLoanOfficer) { @@ -167,9 +170,8 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr * TODO: for now we need to ensure that only one collection sheet * calendar can be linked with a center or group entity
      **/ - final CalendarInstance sourceGroupCalendarInstance = this.calendarInstanceRepository - .findByEntityIdAndEntityTypeIdAndCalendarTypeId(sourceGroup.getId(), CalendarEntityType.GROUPS.getValue(), - CalendarType.COLLECTION.getValue()); + final CalendarInstance sourceGroupCalendarInstance = this.calendarInstanceRepository.findByEntityIdAndEntityTypeIdAndCalendarTypeId( + sourceGroup.getId(), CalendarEntityType.GROUPS.getValue(), CalendarType.COLLECTION.getValue()); // get all customer loans synced with this group calendar Instance final List activeLoanCalendarInstances = this.calendarInstanceRepository .findCalendarInstancesForActiveLoansByGroupIdAndClientId(sourceGroup.getId(), client.getId()); @@ -185,8 +187,9 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr .findByEntityIdAndEntityTypeIdAndCalendarTypeId(destinationGroup.getId(), CalendarEntityType.GROUPS.getValue(), CalendarType.COLLECTION.getValue()); - if (destinationGroupCalendarInstance == null) { throw new TransferNotSupportedException( - TransferNotSupportedReason.DESTINATION_GROUP_HAS_NO_MEETING, destinationGroup.getId()); + if (destinationGroupCalendarInstance == null) { + throw new TransferNotSupportedException(TransferNotSupportedReason.DESTINATION_GROUP_HAS_NO_MEETING, + destinationGroup.getId()); } final Calendar sourceGroupCalendar = sourceGroupCalendarInstance.getCalendar(); @@ -196,10 +199,11 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr * Ensure that the recurrence pattern are same for collection * meeting in both the source and the destination calendar ***/ - if (!(CalendarUtils.isFrequencySame(sourceGroupCalendar.getRecurrence(), destinationGroupCalendar.getRecurrence()) && CalendarUtils - .isIntervalSame(sourceGroupCalendar.getRecurrence(), destinationGroupCalendar.getRecurrence()))) { throw new TransferNotSupportedException( - TransferNotSupportedReason.DESTINATION_GROUP_MEETING_FREQUENCY_MISMATCH, sourceGroup.getId(), - destinationGroup.getId()); } + if (!(CalendarUtils.isFrequencySame(sourceGroupCalendar.getRecurrence(), destinationGroupCalendar.getRecurrence()) + && CalendarUtils.isIntervalSame(sourceGroupCalendar.getRecurrence(), destinationGroupCalendar.getRecurrence()))) { + throw new TransferNotSupportedException(TransferNotSupportedReason.DESTINATION_GROUP_MEETING_FREQUENCY_MISMATCH, + sourceGroup.getId(), destinationGroup.getId()); + } /** map all JLG loans for this client to the destinationGroup **/ for (final CalendarInstance calendarInstance : activeLoanCalendarInstances) { @@ -216,10 +220,12 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr **/ final Staff destinationGroupLoanOfficer = destinationGroup.getStaff(); - /** In case of a loan officer transfer, set the new loan officer value **/ + /** + * In case of a loan officer transfer, set the new loan officer value + **/ if (sourceGroup.getId().equals(destinationGroup.getId()) && newLoanOfficer != null) { client.updateStaff(newLoanOfficer); - }/*** Else default to destination group Officer (If present) ***/ + } /*** Else default to destination group Officer (If present) ***/ else if (destinationGroupLoanOfficer != null) { client.updateStaff(destinationGroupLoanOfficer); } @@ -366,7 +372,6 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr handleClientTransferLifecycleEvent(client, client.getOffice(), TransferEventType.REJECTION, jsonCommand); this.clientRepositoryWrapper.save(client); - return new CommandProcessingResultBuilder() // .withClientId(clientId) // .withEntityId(clientId) // @@ -400,8 +405,8 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr if (loan.isDisbursed() && !loan.isClosed()) { switch (transferEventType) { case ACCEPTANCE: - this.loanWritePlatformService.acceptLoanTransfer(loan, loan.getLastUserTransactionDate(), - destinationOffice, staff); + this.loanWritePlatformService.acceptLoanTransfer(loan, loan.getLastUserTransactionDate(), destinationOffice, + staff); break; case PROPOSAL: this.loanWritePlatformService.initiateLoanTransfer(loan, transferDate); @@ -427,8 +432,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr savingsAccount.retrieveLastTransactionDate(), destinationOffice, staff); break; case PROPOSAL: - this.savingsAccountWritePlatformService.initiateSavingsTransfer(savingsAccount, - transferDate); + this.savingsAccountWritePlatformService.initiateSavingsTransfer(savingsAccount, transferDate); break; case REJECTION: this.savingsAccountWritePlatformService.rejectSavingsTransfer(savingsAccount); @@ -460,8 +464,11 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr if (staff != null) { client.updateStaff(staff); } - }else if(destinationGroup == null) { /** for individual with no groups **/ - if(staff !=null){ client.updateStaff(staff);} + } else if (destinationGroup == null) { + /** for individual with no groups **/ + if (staff != null) { + client.updateStaff(staff); + } } break; case PROPOSAL: @@ -482,10 +489,9 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr this.noteWritePlatformService.createAndPersistClientNote(client, jsonCommand); Date proposedTransferDate = transferDate != null ? transferDate.toDate() : null; - this.clientTransferDetailsRepositoryWrapper - .save(ClientTransferDetails.instance(client.getId(), client.getOffice().getId(), - destinationOffice.getId(), proposedTransferDate, transferEventType.getValue(), - DateUtils.getLocalDateTimeOfTenant().toDate(), this.context.authenticatedUser().getId())); + this.clientTransferDetailsRepositoryWrapper.save(ClientTransferDetails.instance(client.getId(), client.getOffice().getId(), + destinationOffice.getId(), proposedTransferDate, transferEventType.getValue(), + DateUtils.getLocalDateTimeOfTenant().toDate(), this.context.authenticatedUser().getId())); } private List assembleListOfClients(final JsonCommand command) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/scheduledjobs/service/ScheduledJobRunnerService.java b/fineract-provider/src/main/java/org/apache/fineract/scheduledjobs/service/ScheduledJobRunnerService.java index c0f836848..3c632308a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/scheduledjobs/service/ScheduledJobRunnerService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/scheduledjobs/service/ScheduledJobRunnerService.java @@ -38,5 +38,5 @@ public interface ScheduledJobRunnerService { void postDividends() throws JobExecutionException; - void updateTrialBalanceDetails() throws JobExecutionException; + void updateTrialBalanceDetails() throws JobExecutionException; } diff --git a/fineract-provider/src/main/java/org/apache/fineract/scheduledjobs/service/ScheduledJobRunnerServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/scheduledjobs/service/ScheduledJobRunnerServiceImpl.java index b2a1b001d..982a7c9e6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/scheduledjobs/service/ScheduledJobRunnerServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/scheduledjobs/service/ScheduledJobRunnerServiceImpl.java @@ -83,7 +83,8 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService final DepositAccountReadPlatformService depositAccountReadPlatformService, final DepositAccountWritePlatformService depositAccountWritePlatformService, final ShareAccountDividendReadPlatformService shareAccountDividendReadPlatformService, - final ShareAccountSchedularService shareAccountSchedularService, final TrialBalanceRepositoryWrapper trialBalanceRepositoryWrapper) { + final ShareAccountSchedularService shareAccountSchedularService, + final TrialBalanceRepositoryWrapper trialBalanceRepositoryWrapper) { this.dataSourceServiceFactory = dataSourceServiceFactory; this.savingsAccountWritePlatformService = savingsAccountWritePlatformService; this.savingsAccountChargeReadPlatformService = savingsAccountChargeReadPlatformService; @@ -91,7 +92,7 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService this.depositAccountWritePlatformService = depositAccountWritePlatformService; this.shareAccountDividendReadPlatformService = shareAccountDividendReadPlatformService; this.shareAccountSchedularService = shareAccountSchedularService; - this.trialBalanceRepositoryWrapper=trialBalanceRepositoryWrapper; + this.trialBalanceRepositoryWrapper = trialBalanceRepositoryWrapper; } @Transactional @@ -112,10 +113,10 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService updateSqlBuilder.append("SUM(IFNULL(mr.interest_completed_derived,0)) as interest_repaid_derived,"); updateSqlBuilder.append("SUM(IFNULL(mr.interest_waived_derived,0)) as interest_waived_derived,"); updateSqlBuilder.append("SUM(IFNULL(mr.interest_writtenoff_derived,0)) as interest_writtenoff_derived,"); - updateSqlBuilder - .append("SUM(IFNULL(mr.fee_charges_amount,0)) + IFNULL((select SUM(lc.amount) from m_loan_charge lc where lc.loan_id=ml.id and lc.is_active=1 and lc.charge_time_enum=1),0) as fee_charges_charged_derived,"); - updateSqlBuilder - .append("SUM(IFNULL(mr.fee_charges_completed_derived,0)) + IFNULL((select SUM(lc.amount_paid_derived) from m_loan_charge lc where lc.loan_id=ml.id and lc.is_active=1 and lc.charge_time_enum=1),0) as fee_charges_repaid_derived,"); + updateSqlBuilder.append( + "SUM(IFNULL(mr.fee_charges_amount,0)) + IFNULL((select SUM(lc.amount) from m_loan_charge lc where lc.loan_id=ml.id and lc.is_active=1 and lc.charge_time_enum=1),0) as fee_charges_charged_derived,"); + updateSqlBuilder.append( + "SUM(IFNULL(mr.fee_charges_completed_derived,0)) + IFNULL((select SUM(lc.amount_paid_derived) from m_loan_charge lc where lc.loan_id=ml.id and lc.is_active=1 and lc.charge_time_enum=1),0) as fee_charges_repaid_derived,"); updateSqlBuilder.append("SUM(IFNULL(mr.fee_charges_waived_derived,0)) as fee_charges_waived_derived,"); updateSqlBuilder.append("SUM(IFNULL(mr.fee_charges_writtenoff_derived,0)) as fee_charges_writtenoff_derived,"); updateSqlBuilder.append("SUM(IFNULL(mr.penalty_charges_amount,0)) as penalty_charges_charged_derived,"); @@ -131,46 +132,46 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService updateSqlBuilder.append("SET m_loan.principal_disbursed_derived = x.principal_disbursed_derived,"); updateSqlBuilder.append("m_loan.principal_repaid_derived = x.principal_repaid_derived,"); updateSqlBuilder.append("m_loan.principal_writtenoff_derived = x.principal_writtenoff_derived,"); - updateSqlBuilder - .append("m_loan.principal_outstanding_derived = (x.principal_disbursed_derived - (x.principal_repaid_derived + x.principal_writtenoff_derived)),"); + updateSqlBuilder.append( + "m_loan.principal_outstanding_derived = (x.principal_disbursed_derived - (x.principal_repaid_derived + x.principal_writtenoff_derived)),"); updateSqlBuilder.append("m_loan.interest_charged_derived = x.interest_charged_derived,"); updateSqlBuilder.append("m_loan.interest_repaid_derived = x.interest_repaid_derived,"); updateSqlBuilder.append("m_loan.interest_waived_derived = x.interest_waived_derived,"); updateSqlBuilder.append("m_loan.interest_writtenoff_derived = x.interest_writtenoff_derived,"); - updateSqlBuilder - .append("m_loan.interest_outstanding_derived = (x.interest_charged_derived - (x.interest_repaid_derived + x.interest_waived_derived + x.interest_writtenoff_derived)),"); + updateSqlBuilder.append( + "m_loan.interest_outstanding_derived = (x.interest_charged_derived - (x.interest_repaid_derived + x.interest_waived_derived + x.interest_writtenoff_derived)),"); updateSqlBuilder.append("m_loan.fee_charges_charged_derived = x.fee_charges_charged_derived,"); updateSqlBuilder.append("m_loan.fee_charges_repaid_derived = x.fee_charges_repaid_derived,"); updateSqlBuilder.append("m_loan.fee_charges_waived_derived = x.fee_charges_waived_derived,"); updateSqlBuilder.append("m_loan.fee_charges_writtenoff_derived = x.fee_charges_writtenoff_derived,"); - updateSqlBuilder - .append("m_loan.fee_charges_outstanding_derived = (x.fee_charges_charged_derived - (x.fee_charges_repaid_derived + x.fee_charges_waived_derived + x.fee_charges_writtenoff_derived)),"); + updateSqlBuilder.append( + "m_loan.fee_charges_outstanding_derived = (x.fee_charges_charged_derived - (x.fee_charges_repaid_derived + x.fee_charges_waived_derived + x.fee_charges_writtenoff_derived)),"); updateSqlBuilder.append("m_loan.penalty_charges_charged_derived = x.penalty_charges_charged_derived,"); updateSqlBuilder.append("m_loan.penalty_charges_repaid_derived = x.penalty_charges_repaid_derived,"); updateSqlBuilder.append("m_loan.penalty_charges_waived_derived = x.penalty_charges_waived_derived,"); updateSqlBuilder.append("m_loan.penalty_charges_writtenoff_derived = x.penalty_charges_writtenoff_derived,"); - updateSqlBuilder - .append("m_loan.penalty_charges_outstanding_derived = (x.penalty_charges_charged_derived - (x.penalty_charges_repaid_derived + x.penalty_charges_waived_derived + x.penalty_charges_writtenoff_derived)),"); - updateSqlBuilder - .append("m_loan.total_expected_repayment_derived = (x.principal_disbursed_derived + x.interest_charged_derived + x.fee_charges_charged_derived + x.penalty_charges_charged_derived),"); - updateSqlBuilder - .append("m_loan.total_repayment_derived = (x.principal_repaid_derived + x.interest_repaid_derived + x.fee_charges_repaid_derived + x.penalty_charges_repaid_derived),"); - updateSqlBuilder - .append("m_loan.total_expected_costofloan_derived = (x.interest_charged_derived + x.fee_charges_charged_derived + x.penalty_charges_charged_derived),"); - updateSqlBuilder - .append("m_loan.total_costofloan_derived = (x.interest_repaid_derived + x.fee_charges_repaid_derived + x.penalty_charges_repaid_derived),"); - updateSqlBuilder - .append("m_loan.total_waived_derived = (x.interest_waived_derived + x.fee_charges_waived_derived + x.penalty_charges_waived_derived),"); - updateSqlBuilder - .append("m_loan.total_writtenoff_derived = (x.interest_writtenoff_derived + x.fee_charges_writtenoff_derived + x.penalty_charges_writtenoff_derived),"); + updateSqlBuilder.append( + "m_loan.penalty_charges_outstanding_derived = (x.penalty_charges_charged_derived - (x.penalty_charges_repaid_derived + x.penalty_charges_waived_derived + x.penalty_charges_writtenoff_derived)),"); + updateSqlBuilder.append( + "m_loan.total_expected_repayment_derived = (x.principal_disbursed_derived + x.interest_charged_derived + x.fee_charges_charged_derived + x.penalty_charges_charged_derived),"); + updateSqlBuilder.append( + "m_loan.total_repayment_derived = (x.principal_repaid_derived + x.interest_repaid_derived + x.fee_charges_repaid_derived + x.penalty_charges_repaid_derived),"); + updateSqlBuilder.append( + "m_loan.total_expected_costofloan_derived = (x.interest_charged_derived + x.fee_charges_charged_derived + x.penalty_charges_charged_derived),"); + updateSqlBuilder.append( + "m_loan.total_costofloan_derived = (x.interest_repaid_derived + x.fee_charges_repaid_derived + x.penalty_charges_repaid_derived),"); + updateSqlBuilder.append( + "m_loan.total_waived_derived = (x.interest_waived_derived + x.fee_charges_waived_derived + x.penalty_charges_waived_derived),"); + updateSqlBuilder.append( + "m_loan.total_writtenoff_derived = (x.interest_writtenoff_derived + x.fee_charges_writtenoff_derived + x.penalty_charges_writtenoff_derived),"); updateSqlBuilder.append("m_loan.total_outstanding_derived="); updateSqlBuilder.append(" (x.principal_disbursed_derived - (x.principal_repaid_derived + x.principal_writtenoff_derived)) + "); - updateSqlBuilder - .append(" (x.interest_charged_derived - (x.interest_repaid_derived + x.interest_waived_derived + x.interest_writtenoff_derived)) +"); - updateSqlBuilder - .append(" (x.fee_charges_charged_derived - (x.fee_charges_repaid_derived + x.fee_charges_waived_derived + x.fee_charges_writtenoff_derived)) +"); - updateSqlBuilder - .append(" (x.penalty_charges_charged_derived - (x.penalty_charges_repaid_derived + x.penalty_charges_waived_derived + x.penalty_charges_writtenoff_derived))"); + updateSqlBuilder.append( + " (x.interest_charged_derived - (x.interest_repaid_derived + x.interest_waived_derived + x.interest_writtenoff_derived)) +"); + updateSqlBuilder.append( + " (x.fee_charges_charged_derived - (x.fee_charges_repaid_derived + x.fee_charges_waived_derived + x.fee_charges_writtenoff_derived)) +"); + updateSqlBuilder.append( + " (x.penalty_charges_charged_derived - (x.penalty_charges_repaid_derived + x.penalty_charges_waived_derived + x.penalty_charges_writtenoff_derived))"); final int result = jdbcTemplate.update(updateSqlBuilder.toString()); @@ -188,24 +189,24 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService final StringBuilder updateSqlBuilder = new StringBuilder(900); - updateSqlBuilder - .append("INSERT INTO m_loan_paid_in_advance(loan_id, principal_in_advance_derived, interest_in_advance_derived, fee_charges_in_advance_derived, penalty_charges_in_advance_derived, total_in_advance_derived)"); + updateSqlBuilder.append( + "INSERT INTO m_loan_paid_in_advance(loan_id, principal_in_advance_derived, interest_in_advance_derived, fee_charges_in_advance_derived, penalty_charges_in_advance_derived, total_in_advance_derived)"); updateSqlBuilder.append(" select ml.id as loanId,"); updateSqlBuilder.append(" SUM(ifnull(mr.principal_completed_derived, 0)) as principal_in_advance_derived,"); updateSqlBuilder.append(" SUM(ifnull(mr.interest_completed_derived, 0)) as interest_in_advance_derived,"); updateSqlBuilder.append(" SUM(ifnull(mr.fee_charges_completed_derived, 0)) as fee_charges_in_advance_derived,"); updateSqlBuilder.append(" SUM(ifnull(mr.penalty_charges_completed_derived, 0)) as penalty_charges_in_advance_derived,"); - updateSqlBuilder - .append(" (SUM(ifnull(mr.principal_completed_derived, 0)) + SUM(ifnull(mr.interest_completed_derived, 0)) + SUM(ifnull(mr.fee_charges_completed_derived, 0)) + SUM(ifnull(mr.penalty_charges_completed_derived, 0))) as total_in_advance_derived"); + updateSqlBuilder.append( + " (SUM(ifnull(mr.principal_completed_derived, 0)) + SUM(ifnull(mr.interest_completed_derived, 0)) + SUM(ifnull(mr.fee_charges_completed_derived, 0)) + SUM(ifnull(mr.penalty_charges_completed_derived, 0))) as total_in_advance_derived"); updateSqlBuilder.append(" FROM m_loan ml "); updateSqlBuilder.append(" INNER JOIN m_loan_repayment_schedule mr on mr.loan_id = ml.id "); updateSqlBuilder.append(" WHERE ml.loan_status_id = 300 "); updateSqlBuilder.append(" and mr.duedate >= CURDATE() "); updateSqlBuilder.append(" GROUP BY ml.id"); updateSqlBuilder - .append(" HAVING (SUM(ifnull(mr.principal_completed_derived, 0)) + SUM(ifnull(mr.interest_completed_derived, 0)) +"); + .append(" HAVING (SUM(ifnull(mr.principal_completed_derived, 0)) + SUM(ifnull(mr.interest_completed_derived, 0)) +"); updateSqlBuilder - .append(" SUM(ifnull(mr.fee_charges_completed_derived, 0)) + SUM(ifnull(mr.penalty_charges_completed_derived, 0))) > 0.0"); + .append(" SUM(ifnull(mr.fee_charges_completed_derived, 0)) + SUM(ifnull(mr.penalty_charges_completed_derived, 0))) > 0.0"); final int result = jdbcTemplate.update(updateSqlBuilder.toString()); @@ -239,16 +240,19 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService @Override @CronTarget(jobName = JobName.PAY_DUE_SAVINGS_CHARGES) public void applyDueChargesForSavings() throws JobExecutionException { - final Collection chargesDueData = this.savingsAccountChargeReadPlatformService.retrieveChargesWithDue(); + final Collection chargesDueData = this.savingsAccountChargeReadPlatformService + .retrieveChargesWithDue(); List exceptions = new ArrayList<>(); for (final SavingsAccountAnnualFeeData savingsAccountReference : chargesDueData) { try { - this.savingsAccountWritePlatformService.applyChargeDue(savingsAccountReference.getId(), savingsAccountReference.getAccountId()); + this.savingsAccountWritePlatformService.applyChargeDue(savingsAccountReference.getId(), + savingsAccountReference.getAccountId()); } catch (final PlatformApiDataValidationException e) { exceptions.add(e); final List errors = e.getErrors(); for (final ApiParameterError error : errors) { - LOG.error("Apply Charges due for savings failed for account {} with message: {}", savingsAccountReference.getAccountNo(), error.getDeveloperMessage(), e); + LOG.error("Apply Charges due for savings failed for account {} with message: {}", + savingsAccountReference.getAccountNo(), error.getDeveloperMessage(), e); } } catch (final Exception ex) { exceptions.add(ex); @@ -273,7 +277,7 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService resetNPASqlBuilder.append("set loan.is_npa = 0 "); resetNPASqlBuilder.append("where loan.loan_status_id = 300 and mpl.account_moves_out_of_npa_only_on_arrears_completion = 0 "); resetNPASqlBuilder - .append("or (mpl.account_moves_out_of_npa_only_on_arrears_completion = 1 and laa.overdue_since_date_derived is null)"); + .append("or (mpl.account_moves_out_of_npa_only_on_arrears_completion = 1 and laa.overdue_since_date_derived is null)"); jdbcTemplate.update(resetNPASqlBuilder.toString()); @@ -307,7 +311,8 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService } catch (final PlatformApiDataValidationException e) { final List errors = e.getErrors(); for (final ApiParameterError error : errors) { - LOG.error("Update maturity details failed for account: {} with message {}", depositAccount.accountNo(), error.getDeveloperMessage()); + LOG.error("Update maturity details failed for account: {} with message {}", depositAccount.accountNo(), + error.getDeveloperMessage()); } } catch (final Exception ex) { LOG.error("Update maturity details failed for account: {}", depositAccount.accountNo(), ex); @@ -379,8 +384,8 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService List exceptions = new ArrayList<>(); List> dividendDetails = this.shareAccountDividendReadPlatformService.retriveDividendDetailsForPostDividents(); for (Map dividendMap : dividendDetails) { - Long id = null ; - Long savingsId = null ; + Long id = null; + Long savingsId = null; if (dividendMap.get("id") instanceof BigInteger) { // Drizzle is returningBigInteger id = ((BigInteger) dividendMap.get("id")).longValue(); @@ -413,25 +418,24 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService public void updateTrialBalanceDetails() throws JobExecutionException { final JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSourceServiceFactory.determineDataSourceService().retrieveDataSource()); final StringBuilder tbGapSqlBuilder = new StringBuilder(500); - tbGapSqlBuilder.append("select distinct(je.transaction_date) ") - .append("from acc_gl_journal_entry je ") - .append("where je.transaction_date > (select IFNULL(MAX(created_date),'2010-01-01') from m_trial_balance)"); + tbGapSqlBuilder.append("select distinct(je.transaction_date) ").append("from acc_gl_journal_entry je ") + .append("where je.transaction_date > (select IFNULL(MAX(created_date),'2010-01-01') from m_trial_balance)"); final List tbGaps = jdbcTemplate.queryForList(tbGapSqlBuilder.toString(), Date.class); - for(Date tbGap : tbGaps) { + for (Date tbGap : tbGaps) { LocalDate convDate = new DateTime(tbGap).toLocalDate(); int days = Days.daysBetween(convDate, DateUtils.getLocalDateOfTenant()).getDays(); - if(days < 1) { + if (days < 1) { continue; } final String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(tbGap); final StringBuilder sqlBuilder = new StringBuilder(600); sqlBuilder.append("Insert Into m_trial_balance(office_id, account_id, Amount, entry_date, created_date,closing_balance) ") - .append("Select je.office_id, je.account_id, sum(if(je.type_enum=1, (-1) * je.amount, je.amount)) ") - .append("as Amount, Date(je.entry_date) as 'Entry_Date', je.transaction_date as 'Created_Date',sum(je.amount) as closing_balance ") - .append("from acc_gl_journal_entry je WHERE je.transaction_date = ? ") - .append("group by je.account_id, je.office_id, je.transaction_date, Date(je.entry_date)"); + .append("Select je.office_id, je.account_id, sum(if(je.type_enum=1, (-1) * je.amount, je.amount)) ") + .append("as Amount, Date(je.entry_date) as 'Entry_Date', je.transaction_date as 'Created_Date',sum(je.amount) as closing_balance ") + .append("from acc_gl_journal_entry je WHERE je.transaction_date = ? ") + .append("group by je.account_id, je.office_id, je.transaction_date, Date(je.entry_date)"); final int result = jdbcTemplate.update(sqlBuilder.toString(), formattedDate); LOG.info("{}: Results affected by update: {}", ThreadLocalContextUtil.getTenant().getName(), result); @@ -441,27 +445,27 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService String distinctOfficeQuery = "select distinct(office_id) from m_trial_balance where closing_balance is null group by office_id"; final List officeIds = jdbcTemplate.queryForList(distinctOfficeQuery, new Object[] {}, Long.class); - - for(Long officeId : officeIds) { + for (Long officeId : officeIds) { String distinctAccountQuery = "select distinct(account_id) from m_trial_balance where office_id=? and closing_balance is null group by account_id"; - final List accountIds = jdbcTemplate.queryForList(distinctAccountQuery, new Object[] {officeId}, Long.class); - for(Long accountId : accountIds) { - final String closingBalanceQuery = "select closing_balance from m_trial_balance where office_id=? and account_id=? and closing_balance " + - "is not null order by created_date desc, entry_date desc limit 1"; - List closingBalanceData = jdbcTemplate.queryForList(closingBalanceQuery, new Object[] {officeId, accountId}, BigDecimal.class); + final List accountIds = jdbcTemplate.queryForList(distinctAccountQuery, new Object[] { officeId }, Long.class); + for (Long accountId : accountIds) { + final String closingBalanceQuery = "select closing_balance from m_trial_balance where office_id=? and account_id=? and closing_balance " + + "is not null order by created_date desc, entry_date desc limit 1"; + List closingBalanceData = jdbcTemplate.queryForList(closingBalanceQuery, new Object[] { officeId, accountId }, + BigDecimal.class); List tbRows = this.trialBalanceRepositoryWrapper.findNewByOfficeAndAccount(officeId, accountId); BigDecimal closingBalance = null; - if(!CollectionUtils.isEmpty(closingBalanceData)) { + if (!CollectionUtils.isEmpty(closingBalanceData)) { closingBalance = closingBalanceData.get(0); } - if(CollectionUtils.isEmpty(closingBalanceData)) { + if (CollectionUtils.isEmpty(closingBalanceData)) { closingBalance = BigDecimal.ZERO; - for(TrialBalance row : tbRows) { + for (TrialBalance row : tbRows) { closingBalance = closingBalance.add(row.getAmount()); row.setClosingBalance(closingBalance); } } else { - for(TrialBalance tbRow : tbRows) { + for (TrialBalance tbRow : tbRows) { closingBalance = closingBalance.add(tbRow.getAmount()); tbRow.setClosingBalance(closingBalance); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/api/LookupTableApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/spm/api/LookupTableApiResource.java index b39ea6f7b..8fe3c86d2 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/api/LookupTableApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/api/LookupTableApiResource.java @@ -51,10 +51,9 @@ import org.springframework.transaction.annotation.Transactional; @Path("/surveys/{surveyId}/lookuptables") @Component @Scope("singleton") -@Api(tags = {"SPM API - LookUp Table"}) +@Api(tags = { "SPM API - LookUp Table" }) @SwaggerDefinition(tags = { - @Tag(name = "SPM API - LookUp Table", description = "The Apache Fineract SPM API provides the ability to create custom surveys to collect social performance measurentment data or any additional questionnaire a financial institute want to collect.") -}) + @Tag(name = "SPM API - LookUp Table", description = "The Apache Fineract SPM API provides the ability to create custom surveys to collect social performance measurentment data or any additional questionnaire a financial institute want to collect.") }) public class LookupTableApiResource { private final PlatformSecurityContext securityContext; @@ -62,9 +61,8 @@ public class LookupTableApiResource { private final LookupTableService lookupTableService; @Autowired - public LookupTableApiResource(final PlatformSecurityContext securityContext, - final SpmService spmService, - final LookupTableService lookupTableService) { + public LookupTableApiResource(final PlatformSecurityContext securityContext, final SpmService spmService, + final LookupTableService lookupTableService) { super(); this.securityContext = securityContext; this.spmService = spmService; @@ -76,7 +74,7 @@ public class LookupTableApiResource { @Produces({ MediaType.APPLICATION_JSON }) @Transactional @ApiOperation(value = "List all Lookup Table entries", notes = "List all Lookup Table entries for a survey.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = LookupTableData.class, responseContainer = "list")}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = LookupTableData.class, responseContainer = "list") }) public List fetchLookupTables(@PathParam("surveyId") @ApiParam(value = "Enter surveyId") final Long surveyId) { this.securityContext.authenticatedUser(); @@ -84,9 +82,7 @@ public class LookupTableApiResource { final List lookupTables = this.lookupTableService.findBySurvey(survey); - if (lookupTables != null) { - return LookupTableMapper.map(lookupTables); - } + if (lookupTables != null) { return LookupTableMapper.map(lookupTables); } return Collections.emptyList(); } @@ -97,18 +93,16 @@ public class LookupTableApiResource { @Produces({ MediaType.APPLICATION_JSON }) @Transactional @ApiOperation(value = "Retrieve a Lookup Table entry", notes = "Retrieve a Lookup Table entry for a survey.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = LookupTableData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = LookupTableData.class) }) public LookupTableData findLookupTable(@PathParam("surveyId") @ApiParam(value = "Enter surveyId") final Long surveyId, - @PathParam("key") @ApiParam(value = "Enter key") final String key) { + @PathParam("key") @ApiParam(value = "Enter key") final String key) { this.securityContext.authenticatedUser(); findSurvey(surveyId); final List lookupTables = this.lookupTableService.findByKey(key); - if (lookupTables == null || lookupTables.isEmpty()) { - throw new LookupTableNotFoundException(key); - } + if (lookupTables == null || lookupTables.isEmpty()) { throw new LookupTableNotFoundException(key); } return LookupTableMapper.map(lookupTables).get(0); } @@ -117,10 +111,11 @@ public class LookupTableApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Transactional - @ApiOperation(value = "Create a Lookup Table entry", notes = "Add a new entry to a survey.\n" + "\n" + "Mandatory Fields\n" + "key, score, validFrom, validTo") - @ApiResponses({@ApiResponse(code = 200, message = "OK")}) + @ApiOperation(value = "Create a Lookup Table entry", notes = "Add a new entry to a survey.\n" + "\n" + "Mandatory Fields\n" + + "key, score, validFrom, validTo") + @ApiResponses({ @ApiResponse(code = 200, message = "OK") }) public void createLookupTable(@PathParam("surveyId") @ApiParam(value = "Enter surveyId") final Long surveyId, - final LookupTableData lookupTableData) { + final LookupTableData lookupTableData) { this.securityContext.authenticatedUser(); final Survey survey = findSurvey(surveyId); @@ -130,9 +125,7 @@ public class LookupTableApiResource { private Survey findSurvey(final Long surveyId) { final Survey survey = this.spmService.findById(surveyId); - if (survey == null) { - throw new SurveyNotFoundException(surveyId); - } + if (survey == null) { throw new SurveyNotFoundException(surveyId); } return survey; } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/api/ScorecardApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/spm/api/ScorecardApiResource.java index bccb4533a..5f713a0b5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/api/ScorecardApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/api/ScorecardApiResource.java @@ -52,10 +52,8 @@ import org.springframework.transaction.annotation.Transactional; @Path("/surveys/scorecards") @Component @Scope("singleton") -@Api(tags = {"Score Card"}) -@SwaggerDefinition(tags = { - @Tag(name = "Score Card", description = "") -}) +@Api(tags = { "Score Card" }) +@SwaggerDefinition(tags = { @Tag(name = "Score Card", description = "") }) public class ScorecardApiResource { private final PlatformSecurityContext securityContext; @@ -81,7 +79,7 @@ public class ScorecardApiResource { @Produces({ MediaType.APPLICATION_JSON }) @Transactional @ApiOperation(value = "List all Scorecard entries", notes = "List all Scorecard entries for a survey.") - @ApiResponses({@ApiResponse(code = 200, message = "", response = Scorecard.class, responseContainer = "list")}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = Scorecard.class, responseContainer = "list") }) public List findBySurvey(@PathParam("surveyId") @ApiParam(value = "Enter surveyId") final Long surveyId) { this.securityContext.authenticatedUser(); this.spmService.findById(surveyId); @@ -93,9 +91,11 @@ public class ScorecardApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Transactional - @ApiOperation(value = "Create a Scorecard entry", notes = "Add a new entry to a survey.\n" + "\n" + "Mandatory Fields\n" + "clientId, createdOn, questionId, responseId, staffId") - @ApiResponses({@ApiResponse(code = 200, message = "OK")}) - public void createScorecard(@PathParam("surveyId") @ApiParam(value = "Enter surveyId") final Long surveyId, @ApiParam(format = "body", type = "body") final ScorecardData scorecardData) { + @ApiOperation(value = "Create a Scorecard entry", notes = "Add a new entry to a survey.\n" + "\n" + "Mandatory Fields\n" + + "clientId, createdOn, questionId, responseId, staffId") + @ApiResponses({ @ApiResponse(code = 200, message = "OK") }) + public void createScorecard(@PathParam("surveyId") @ApiParam(value = "Enter surveyId") final Long surveyId, + @ApiParam(format = "body", type = "body") final ScorecardData scorecardData) { final AppUser appUser = this.securityContext.authenticatedUser(); final Survey survey = this.spmService.findById(surveyId); final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(scorecardData.getClientId()); @@ -108,7 +108,7 @@ public class ScorecardApiResource { @Produces({ MediaType.APPLICATION_JSON }) @Transactional public List findBySurveyAndClient(@PathParam("surveyId") @ApiParam(value = "Enter surveyId") final Long surveyId, - @PathParam("clientId") @ApiParam(value = "Enter clientId") final Long clientId) { + @PathParam("clientId") @ApiParam(value = "Enter clientId") final Long clientId) { this.securityContext.authenticatedUser(); this.spmService.findById(surveyId); this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/api/SpmApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/spm/api/SpmApiResource.java index b0b9fee25..a4f84aa7f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/api/SpmApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/api/SpmApiResource.java @@ -52,10 +52,8 @@ import org.springframework.transaction.annotation.Transactional; @Path("/surveys") @Component @Scope("singleton") -@Api(tags = {"Spm-Surveys"}) -@SwaggerDefinition(tags = { - @Tag(name = "Spm-Surveys", description = "") -}) +@Api(tags = { "Spm-Surveys" }) +@SwaggerDefinition(tags = { @Tag(name = "Spm-Surveys", description = "") }) public class SpmApiResource { private final PlatformSecurityContext securityContext; @@ -72,14 +70,14 @@ public class SpmApiResource { @Produces({ MediaType.APPLICATION_JSON }) @Transactional @ApiOperation(value = "List all Surveys", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = SurveyData.class, responseContainer = "list")}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = SurveyData.class, responseContainer = "list") }) public List fetchAllSurveys(@QueryParam("isActive") final Boolean isActive) { this.securityContext.authenticatedUser(); final List result = new ArrayList<>(); List surveys = null; - if(isActive != null && isActive){ + if (isActive != null && isActive) { surveys = this.spmService.fetchValidSurveys(); - }else{ + } else { surveys = this.spmService.fetchAllSurveys(); } if (surveys != null) { @@ -96,7 +94,7 @@ public class SpmApiResource { @Produces({ MediaType.APPLICATION_JSON }) @Transactional @ApiOperation(value = "Retrieve a Survey", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = SurveyData.class)}) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = SurveyData.class) }) public SurveyData findSurvey(@PathParam("id") @ApiParam(value = "Enter id") final Long id) { this.securityContext.authenticatedUser(); final Survey survey = this.spmService.findById(id); @@ -107,8 +105,9 @@ public class SpmApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Transactional - @ApiOperation(value = "Create a Survey", notes = "Adds a new survey to collect client related data.\n" + "\n" + "Mandatory Fields\n" + "\n" + "countryCode, key, name, questions, responses, sequenceNo, text, value") - @ApiResponses({@ApiResponse(code = 200, message = "OK")}) + @ApiOperation(value = "Create a Survey", notes = "Adds a new survey to collect client related data.\n" + "\n" + "Mandatory Fields\n" + + "\n" + "countryCode, key, name, questions, responses, sequenceNo, text, value") + @ApiResponses({ @ApiResponse(code = 200, message = "OK") }) public String createSurvey(@ApiParam(value = "Create survey") final SurveyData surveyData) { this.securityContext.authenticatedUser(); final Survey survey = SurveyMapper.map(surveyData, new Survey()); @@ -136,14 +135,14 @@ public class SpmApiResource { @Produces({ MediaType.APPLICATION_JSON }) @Transactional @ApiOperation(value = "Deactivate Survey", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "OK")}) + @ApiResponses({ @ApiResponse(code = 200, message = "OK") }) public void activateOrDeactivateSurvey(@PathParam("id") final Long id, @QueryParam("command") final String command) { this.securityContext.authenticatedUser(); - if(command != null && command.equalsIgnoreCase("activate")){ + if (command != null && command.equalsIgnoreCase("activate")) { this.spmService.activateSurvey(id); - }else if(command != null && command.equalsIgnoreCase("deactivate")){ + } else if (command != null && command.equalsIgnoreCase("deactivate")) { this.spmService.deactivateSurvey(id); - }else{ + } else { throw new UnrecognizedQueryParamException("command", command); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/data/ComponentData.java b/fineract-provider/src/main/java/org/apache/fineract/spm/data/ComponentData.java index 21a1474c2..e3f482546 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/data/ComponentData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/data/ComponentData.java @@ -30,8 +30,7 @@ public class ComponentData { super(); } - public ComponentData(final Long id, final String key, final String text, - final String description, final Integer sequenceNo) { + public ComponentData(final Long id, final String key, final String text, final String description, final Integer sequenceNo) { super(); this.id = id; this.key = key; diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/data/LookupTableData.java b/fineract-provider/src/main/java/org/apache/fineract/spm/data/LookupTableData.java index 466808a8d..c93853e48 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/data/LookupTableData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/data/LookupTableData.java @@ -30,8 +30,7 @@ public class LookupTableData { super(); } - public LookupTableData(final String key, final String description, - final List entries) { + public LookupTableData(final String key, final String description, final List entries) { super(); this.key = key; this.description = description; diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/data/QuestionData.java b/fineract-provider/src/main/java/org/apache/fineract/spm/data/QuestionData.java index f61c23fb2..0038d26e9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/data/QuestionData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/data/QuestionData.java @@ -35,7 +35,7 @@ public class QuestionData { } public QuestionData(final Long id, final List responseDatas, final String componentKey, final String key, - final String text, final String description, final Integer sequenceNo) { + final String text, final String description, final Integer sequenceNo) { super(); this.id = id; this.responseDatas = responseDatas; diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/data/ResponseData.java b/fineract-provider/src/main/java/org/apache/fineract/spm/data/ResponseData.java index ff4be4a8f..f8fc15daa 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/data/ResponseData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/data/ResponseData.java @@ -29,8 +29,7 @@ public class ResponseData { super(); } - public ResponseData(final Long id, final String text, final Integer value, - final Integer sequenceNo) { + public ResponseData(final Long id, final String text, final Integer value, final Integer sequenceNo) { super(); this.id = id; this.text = text; diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/data/ScorecardValue.java b/fineract-provider/src/main/java/org/apache/fineract/spm/data/ScorecardValue.java index 46f7299a1..75845b53b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/data/ScorecardValue.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/data/ScorecardValue.java @@ -66,15 +66,12 @@ public class ScorecardValue { this.value = value; } - public Date getCreatedOn() { return this.createdOn; } - public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } - } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/data/SurveyData.java b/fineract-provider/src/main/java/org/apache/fineract/spm/data/SurveyData.java index ad2c03946..202b057e9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/data/SurveyData.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/data/SurveyData.java @@ -37,9 +37,8 @@ public class SurveyData { super(); } - public SurveyData(final Long id, final List componentDatas, final List questionDatas, - final String key, final String name, final String description, final String countryCode, - final Date validFrom, final Date validTo) { + public SurveyData(final Long id, final List componentDatas, final List questionDatas, final String key, + final String name, final String description, final String countryCode, final Date validFrom, final Date validTo) { super(); this.id = id; this.componentDatas = componentDatas; diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/domain/Survey.java b/fineract-provider/src/main/java/org/apache/fineract/spm/domain/Survey.java index ce5d3c2e0..aeb3ee11e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/domain/Survey.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/domain/Survey.java @@ -36,11 +36,11 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; @Table(name = "m_surveys") public class Survey extends AbstractPersistableCustom { - @OneToMany(mappedBy = "survey", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) + @OneToMany(mappedBy = "survey", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) @OrderBy("sequenceNo") private List components; - @OneToMany(mappedBy = "survey", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) + @OneToMany(mappedBy = "survey", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) @OrderBy("sequenceNo") private List questions; @@ -81,9 +81,9 @@ public class Survey extends AbstractPersistableCustom { } public void setQuestions(List questions) { - if(this.questions != null){ + if (this.questions != null) { this.questions.clear(); - }else{ + } else { this.questions = new ArrayList<>(); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/domain/SurveyValidator.java b/fineract-provider/src/main/java/org/apache/fineract/spm/domain/SurveyValidator.java index c75a6fcbd..2346c931e 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/domain/SurveyValidator.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/domain/SurveyValidator.java @@ -86,9 +86,7 @@ public class SurveyValidator { } private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException(dataValidationErrors); - } + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/exception/SurveyResponseNotAvailableException.java b/fineract-provider/src/main/java/org/apache/fineract/spm/exception/SurveyResponseNotAvailableException.java index a194b6cf3..9c26f990f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/exception/SurveyResponseNotAvailableException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/exception/SurveyResponseNotAvailableException.java @@ -20,11 +20,10 @@ package org.apache.fineract.spm.exception; import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException; - public class SurveyResponseNotAvailableException extends AbstractPlatformDomainRuleException { public SurveyResponseNotAvailableException() { - super("error.msg.no.survey.response","No response available for survey."); + super("error.msg.no.survey.response", "No response available for survey."); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/repository/LookupTableRepository.java b/fineract-provider/src/main/java/org/apache/fineract/spm/repository/LookupTableRepository.java index f5cbb00f1..2004c20c5 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/repository/LookupTableRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/repository/LookupTableRepository.java @@ -26,5 +26,6 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface LookupTableRepository extends JpaRepository { List findBySurvey(final Survey survey); + List findByKey(final String spmKey); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/repository/ScorecardRepository.java b/fineract-provider/src/main/java/org/apache/fineract/spm/repository/ScorecardRepository.java index 5cb74210d..c51bdcab4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/repository/ScorecardRepository.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/repository/ScorecardRepository.java @@ -27,5 +27,6 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface ScorecardRepository extends JpaRepository { List findBySurvey(final Survey survey); + List findBySurveyAndClient(final Survey survey, final Client client); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/service/LookupTableService.java b/fineract-provider/src/main/java/org/apache/fineract/spm/service/LookupTableService.java index ae592a914..367232509 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/service/LookupTableService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/service/LookupTableService.java @@ -33,8 +33,7 @@ public class LookupTableService { private final LookupTableRepository lookupTableRepository; @Autowired - public LookupTableService(final PlatformSecurityContext securityContext, - final LookupTableRepository lookupTableRepository) { + public LookupTableService(final PlatformSecurityContext securityContext, final LookupTableRepository lookupTableRepository) { super(); this.securityContext = securityContext; this.lookupTableRepository = lookupTableRepository; diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardReadPlatformService.java b/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardReadPlatformService.java index b7c9f3750..a2dbc8b9a 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardReadPlatformService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardReadPlatformService.java @@ -21,12 +21,11 @@ package org.apache.fineract.spm.service; import java.util.Collection; import org.apache.fineract.spm.data.ScorecardData; - public interface ScorecardReadPlatformService { Collection retrieveScorecardByClient(final Long clientId); - Collection retrieveScorecardBySurveyAndClient(final Long surveyId,final Long clientId); + Collection retrieveScorecardBySurveyAndClient(final Long surveyId, final Long clientId); Collection retrieveScorecardBySurvey(final Long surveyId); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardReadPlatformServiceImpl.java index 1f5008d77..a0bae9eac 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardReadPlatformServiceImpl.java @@ -134,7 +134,8 @@ public class ScorecardReadPlatformServiceImpl implements ScorecardReadPlatformSe public Collection retrieveScorecardBySurveyAndClient(Long surveyId, Long clientId) { this.context.authenticatedUser(); ScorecardMapper scm = new ScorecardMapper(); - String sql = "select " + scm.schema() + " where sc.survey_id = ? and sc.client_id = ? " + " group by sc.survey_id, sc.client_id, sc.id "; + String sql = "select " + scm.schema() + " where sc.survey_id = ? and sc.client_id = ? " + + " group by sc.survey_id, sc.client_id, sc.id "; Collection scorecardDatas = this.jdbcTemplate.query(sql, scm, new Object[] { surveyId, clientId }); updateScorecardValues(scorecardDatas); return scorecardDatas; diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardService.java b/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardService.java index ae78fa3fe..a23b373b0 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/service/ScorecardService.java @@ -34,8 +34,7 @@ public class ScorecardService { private final ScorecardRepository scorecardRepository; @Autowired - public ScorecardService(final PlatformSecurityContext securityContext, - final ScorecardRepository scorecardRepository) { + public ScorecardService(final PlatformSecurityContext securityContext, final ScorecardRepository scorecardRepository) { super(); this.securityContext = securityContext; this.scorecardRepository = scorecardRepository; diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/service/SpmService.java b/fineract-provider/src/main/java/org/apache/fineract/spm/service/SpmService.java index 177034cdc..8bed42411 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/service/SpmService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/service/SpmService.java @@ -45,9 +45,8 @@ public class SpmService { private final SurveyValidator surveyValidator; @Autowired - public SpmService(final PlatformSecurityContext securityContext, - final SurveyRepository surveyRepository, - final SurveyValidator surveyValidator) { + public SpmService(final PlatformSecurityContext securityContext, final SurveyRepository surveyRepository, + final SurveyValidator surveyValidator) { super(); this.securityContext = securityContext; this.surveyRepository = surveyRepository; @@ -80,9 +79,9 @@ public class SpmService { this.deactivateSurvey(previousSurvey.getId()); } // set valid from to start of today - LocalDate validFrom = DateUtils.getLocalDateOfTenant() ; + LocalDate validFrom = DateUtils.getLocalDateOfTenant(); // set valid to for 100 years - Calendar cal = Calendar.getInstance() ; + Calendar cal = Calendar.getInstance(); cal.setTime(validFrom.toDate()); cal.add(Calendar.YEAR, 100); survey.setValidFrom(validFrom.toDate()); @@ -98,7 +97,7 @@ public class SpmService { } catch (final PersistenceException dve) { handleDataIntegrityIssues(dve, dve, survey.getKey()); } - return survey ; + return survey; } public Survey updateSurvey(final Survey survey) { @@ -131,8 +130,8 @@ public class SpmService { this.securityContext.authenticatedUser(); final Survey survey = findById(id); - LocalDate validFrom = DateUtils.getLocalDateOfTenant() ; - Calendar cal = Calendar.getInstance() ; + LocalDate validFrom = DateUtils.getLocalDateOfTenant(); + Calendar cal = Calendar.getInstance(); cal.setTime(validFrom.toDate()); cal.add(Calendar.YEAR, 100); survey.setValidFrom(validFrom.toDate()); @@ -141,19 +140,20 @@ public class SpmService { this.surveyRepository.save(survey); } - public static DateTime getStartOfToday() { return DateTime.now().withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0); } private void handleDataIntegrityIssues(final Throwable realCause, final Exception dve, String key) { - if (realCause.getMessage().contains("m_survey_scorecards")) { throw new PlatformDataIntegrityException( - "error.msg.survey.cannot.be.modified.as.used.in.client.survey", - "Survey can not be edited as it is already used in client survey", "name", key); } + if (realCause.getMessage().contains("m_survey_scorecards")) { + throw new PlatformDataIntegrityException("error.msg.survey.cannot.be.modified.as.used.in.client.survey", + "Survey can not be edited as it is already used in client survey", "name", key); + } - if (realCause.getMessage().contains("key")) { throw new PlatformDataIntegrityException("error.msg.survey.duplicate.key", - "Survey with key already exists", "name", key); } + if (realCause.getMessage().contains("key")) { + throw new PlatformDataIntegrityException("error.msg.survey.duplicate.key", "Survey with key already exists", "name", key); + } throw new PlatformDataIntegrityException("error.msg.survey.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + realCause.getMessage()); diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/util/LookupTableMapper.java b/fineract-provider/src/main/java/org/apache/fineract/spm/util/LookupTableMapper.java index f6880b710..af331328b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/util/LookupTableMapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/util/LookupTableMapper.java @@ -46,8 +46,8 @@ public class LookupTableMapper { lookupTableData.setDescription(lookupTable.getDescription()); lookupTableData.setEntries(new ArrayList()); } - lookupTableData.getEntries().add(new LookupTableEntry(lookupTable.getValueFrom(), - lookupTable.getValueTo(), lookupTable.getScore())); + lookupTableData.getEntries() + .add(new LookupTableEntry(lookupTable.getValueFrom(), lookupTable.getValueTo(), lookupTable.getScore())); } return List.copyOf(lookupTableDataMap.values()); } diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/util/ScorecardMapper.java b/fineract-provider/src/main/java/org/apache/fineract/spm/util/ScorecardMapper.java index f4d9e26cc..dbf1a4b9b 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/util/ScorecardMapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/util/ScorecardMapper.java @@ -37,31 +37,29 @@ public class ScorecardMapper { super(); } - public static List map(final ScorecardData scorecardData, final Survey survey, - final AppUser appUser, final Client client) { + public static List map(final ScorecardData scorecardData, final Survey survey, final AppUser appUser, final Client client) { final List scorecards = new ArrayList<>(); final List scorecardValues = scorecardData.getScorecardValues(); if (scorecardValues != null && !scorecardValues.isEmpty()) { - for (ScorecardValue scorecardValue : scorecardValues) { - final Scorecard scorecard = new Scorecard(); - scorecards.add(scorecard); - scorecard.setSurvey(survey); - ScorecardMapper.setQuestionAndResponse(scorecardValue, scorecard, survey); - scorecard.setAppUser(appUser); - scorecard.setClient(client); - scorecard.setCreatedOn(DateUtils.getLocalDateOfTenant().toDate()); - scorecard.setValue(scorecardValue.getValue()); - } - }else{ + for (ScorecardValue scorecardValue : scorecardValues) { + final Scorecard scorecard = new Scorecard(); + scorecards.add(scorecard); + scorecard.setSurvey(survey); + ScorecardMapper.setQuestionAndResponse(scorecardValue, scorecard, survey); + scorecard.setAppUser(appUser); + scorecard.setClient(client); + scorecard.setCreatedOn(DateUtils.getLocalDateOfTenant().toDate()); + scorecard.setValue(scorecardValue.getValue()); + } + } else { throw new SurveyResponseNotAvailableException(); } return scorecards; } - private static void setQuestionAndResponse(final ScorecardValue scorecardValue, final Scorecard scorecard, - final Survey survey) { + private static void setQuestionAndResponse(final ScorecardValue scorecardValue, final Scorecard scorecard, final Survey survey) { final List questions = survey.getQuestions(); for (final Question question : questions) { if (question.getId().equals(scorecardValue.getQuestionId())) { @@ -76,4 +74,4 @@ public class ScorecardMapper { } } } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/util/SurveyApiConstants.java b/fineract-provider/src/main/java/org/apache/fineract/spm/util/SurveyApiConstants.java index 454758ae8..25733eebe 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/util/SurveyApiConstants.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/util/SurveyApiConstants.java @@ -18,7 +18,6 @@ */ package org.apache.fineract.spm.util; - public class SurveyApiConstants { public static final String SURVEY_RESOURCE_NAME = "survey"; @@ -33,7 +32,7 @@ public class SurveyApiConstants { public static final String textParamName = "text"; public static final String lengthParamName = "length"; - //to validate length/max value + // to validate length/max value public static final Integer maxCountryCodeLength = 2; public static final Integer maxTextLength = 255; public static final Integer maxNameLength = 255; diff --git a/fineract-provider/src/main/java/org/apache/fineract/spm/util/SurveyMapper.java b/fineract-provider/src/main/java/org/apache/fineract/spm/util/SurveyMapper.java index 42d50a8af..c7dd8ce59 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/spm/util/SurveyMapper.java +++ b/fineract-provider/src/main/java/org/apache/fineract/spm/util/SurveyMapper.java @@ -36,11 +36,9 @@ public class SurveyMapper { } public static SurveyData map(final Survey survey) { - final SurveyData surveyData = new SurveyData( - survey.getId(), SurveyMapper.mapComponents(survey.getComponents()), - SurveyMapper.mapQuestions(survey.getQuestions()), survey.getKey(), survey.getName(), - survey.getDescription(), survey.getCountryCode(), survey.getValidFrom(), survey.getValidTo() - ); + final SurveyData surveyData = new SurveyData(survey.getId(), SurveyMapper.mapComponents(survey.getComponents()), + SurveyMapper.mapQuestions(survey.getQuestions()), survey.getKey(), survey.getName(), survey.getDescription(), + survey.getCountryCode(), survey.getValidFrom(), survey.getValidTo()); return surveyData; } @@ -58,10 +56,8 @@ public class SurveyMapper { final List componentDatas = new ArrayList<>(); if (components != null) { for (final Component component : components) { - componentDatas.add(new ComponentData( - component.getId(), component.getKey(), component.getText(), component.getDescription(), - component.getSequenceNo() - )); + componentDatas.add(new ComponentData(component.getId(), component.getKey(), component.getText(), component.getDescription(), + component.getSequenceNo())); } } return componentDatas; @@ -87,10 +83,9 @@ public class SurveyMapper { final List questionDatas = new ArrayList<>(); if (questions != null) { for (final Question question : questions) { - questionDatas.add(new QuestionData(question.getId(), - SurveyMapper.mapResponses(question.getResponses()), question.getComponentKey(), question.getKey(), - question.getText(), question.getDescription(), question.getSequenceNo() - )); + questionDatas.add( + new QuestionData(question.getId(), SurveyMapper.mapResponses(question.getResponses()), question.getComponentKey(), + question.getKey(), question.getText(), question.getDescription(), question.getSequenceNo())); } } return questionDatas; @@ -118,9 +113,7 @@ public class SurveyMapper { final List responseDatas = new ArrayList<>(); if (responses != null) { for (final Response response : responses) { - responseDatas.add(new ResponseData( - response.getId(), response.getText(), response.getValue(), response.getSequenceNo() - )); + responseDatas.add(new ResponseData(response.getId(), response.getText(), response.getValue(), response.getSequenceNo())); } } return responseDatas; diff --git a/fineract-provider/src/main/java/org/apache/fineract/template/api/TemplatesApiResource.java b/fineract-provider/src/main/java/org/apache/fineract/template/api/TemplatesApiResource.java index 550e346b1..dc616fa74 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/template/api/TemplatesApiResource.java +++ b/fineract-provider/src/main/java/org/apache/fineract/template/api/TemplatesApiResource.java @@ -74,10 +74,13 @@ import org.springframework.stereotype.Component; @Produces({ MediaType.APPLICATION_JSON }) @Component @Scope("singleton") -@Api(tags = {"User Generated Documents"}) +@Api(tags = { "User Generated Documents" }) @SwaggerDefinition(tags = { - @Tag(name = "User Generated Documents", description = "User Generated Documents(alternatively, Templates) are used for end-user features such as custom user defined document generation (AKA UGD). They are based on {{ moustache }} templates. Think of them as a sort of built-in \"mail merge\" functionality.\n" + "\n" + "User Generated Documents (and other types of templates) can aggregate data from several Apache Fineract back-end API calls via mappers. Mappers can even access non-Apache Fineract REST services from other servers. UGDs can render such data in tables, show images, etc. TBD: Please have a look at some of the Example UGDs included in Apache Fineract (or the Wiki page, for now.).\n" + "\n" + "UGDs can be assigned to an entity like client or loan and be of a type like Document or SMS. The entity and type of a UGD is only there for the convenience of user agents (UIs), in order to know where to show UGDs for the user (i.e. which tab). The Template Engine back-end runner does not actually need this metadata.") -}) + @Tag(name = "User Generated Documents", description = "User Generated Documents(alternatively, Templates) are used for end-user features such as custom user defined document generation (AKA UGD). They are based on {{ moustache }} templates. Think of them as a sort of built-in \"mail merge\" functionality.\n" + + "\n" + + "User Generated Documents (and other types of templates) can aggregate data from several Apache Fineract back-end API calls via mappers. Mappers can even access non-Apache Fineract REST services from other servers. UGDs can render such data in tables, show images, etc. TBD: Please have a look at some of the Example UGDs included in Apache Fineract (or the Wiki page, for now.).\n" + + "\n" + + "UGDs can be assigned to an entity like client or loan and be of a type like Document or SMS. The entity and type of a UGD is only there for the convenience of user agents (UIs), in order to know where to show UGDs for the user (i.e. which tab). The Template Engine back-end runner does not actually need this metadata.") }) public class TemplatesApiResource { private final Set RESPONSE_TEMPLATES_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id")); @@ -109,8 +112,11 @@ public class TemplatesApiResource { } @GET - @ApiOperation(value = "Retrieve all UGDs", notes = "Example Requests:\n" + "\n" + "templates\n" + "\n" + "It is also possible to get specific UGDs by entity and type:\n" + "\n" + "templates?type=0&entity=0\n" + "[Entity: Id]\n\n\n\n" + "\n\n" + "client: 0, loan: 1" + "\n\n" + "[Type: Id]\n\n\n\n" + "Document: 0, E-Mail (not yet): 1, SMS: 2" ) - @ApiResponses({@ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.GetTemplatesResponse.class)}) + @ApiOperation(value = "Retrieve all UGDs", notes = "Example Requests:\n" + "\n" + "templates\n" + "\n" + + "It is also possible to get specific UGDs by entity and type:\n" + "\n" + "templates?type=0&entity=0\n" + + "[Entity: Id]\n\n\n\n" + "\n\n" + "client: 0, loan: 1" + "\n\n" + "[Type: Id]\n\n\n\n" + + "Document: 0, E-Mail (not yet): 1, SMS: 2") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.GetTemplatesResponse.class) }) public String retrieveAll(@DefaultValue("-1") @QueryParam("typeId") @ApiParam(value = "typeId") final int typeId, @DefaultValue("-1") @QueryParam("entityId") @ApiParam(value = "entityId") final int entityId, @Context final UriInfo uriInfo) { @@ -132,8 +138,10 @@ public class TemplatesApiResource { @GET @Path("template") - @ApiOperation(value = "Retrieve UGD Details Template", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for UGDs. The UGD data returned consists of any or all of:\n" + "\n" + "ARGUMENTS\n" + "name String entity String type String text String optional mappers Mapper optional\n" + "Example Request:\n" + "\n" + "templates/template") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.GetTemplatesTemplateResponse.class)}) + @ApiOperation(value = "Retrieve UGD Details Template", notes = "This is a convenience resource. It can be useful when building maintenance user interface screens for UGDs. The UGD data returned consists of any or all of:\n" + + "\n" + "ARGUMENTS\n" + "name String entity String type String text String optional mappers Mapper optional\n" + + "Example Request:\n" + "\n" + "templates/template") + @ApiResponses({ @ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.GetTemplatesTemplateResponse.class) }) public String template(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION); @@ -145,9 +153,11 @@ public class TemplatesApiResource { } @POST - @ApiOperation(value = "Add a UGD", notes = "Adds a new UGD.\n" + "\n" + "Mandatory Fields\n" + "name\n\n\n\n" + "Example Requests:\n" + "\n" + "templates/1") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TemplatesApiResourcesSwagger.PostTemplatesRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.PostTemplatesResponse.class)}) + @ApiOperation(value = "Add a UGD", notes = "Adds a new UGD.\n" + "\n" + "Mandatory Fields\n" + "name\n\n\n\n" + "Example Requests:\n" + + "\n" + "templates/1") + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TemplatesApiResourcesSwagger.PostTemplatesRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.PostTemplatesResponse.class) }) public String createTemplate(@ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createTemplate().withJson(apiRequestBodyAsJson).build(); @@ -159,8 +169,9 @@ public class TemplatesApiResource { @GET @Path("{templateId}") @ApiOperation(value = "Retrieve a UGD", notes = "Example Requests:\n" + "\n" + "templates/1") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.GetTemplatesTemplateIdResponse.class)}) - public String retrieveOne(@PathParam("templateId") @ApiParam(value = "templateId") final Long templateId, @Context final UriInfo uriInfo) { + @ApiResponses({ @ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.GetTemplatesTemplateIdResponse.class) }) + public String retrieveOne(@PathParam("templateId") @ApiParam(value = "templateId") final Long templateId, + @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION); @@ -185,9 +196,11 @@ public class TemplatesApiResource { @PUT @Path("{templateId}") @ApiOperation(value = "Update a UGD", notes = "") - @ApiImplicitParams({@ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TemplatesApiResourcesSwagger.PutTemplatesTemplateIdRequest.class)}) - @ApiResponses({@ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.PutTemplatesTemplateIdResponse.class)}) - public String saveTemplate(@PathParam("templateId") @ApiParam(value = "templateId") final Long templateId, @ApiParam(hidden = true) final String apiRequestBodyAsJson) { + @ApiImplicitParams({ + @ApiImplicitParam(value = "body", required = true, paramType = "body", dataType = "body", format = "body", dataTypeClass = TemplatesApiResourcesSwagger.PutTemplatesTemplateIdRequest.class) }) + @ApiResponses({ @ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.PutTemplatesTemplateIdResponse.class) }) + public String saveTemplate(@PathParam("templateId") @ApiParam(value = "templateId") final Long templateId, + @ApiParam(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateTemplate(templateId).withJson(apiRequestBodyAsJson).build(); @@ -199,7 +212,8 @@ public class TemplatesApiResource { @DELETE @Path("{templateId}") @ApiOperation(value = "Delete a UGD", notes = "") - @ApiResponses({@ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.DeleteTemplatesTemplateIdResponse.class)}) + @ApiResponses({ + @ApiResponse(code = 200, message = "", response = TemplatesApiResourcesSwagger.DeleteTemplatesTemplateIdResponse.class) }) public String deleteTemplate(@PathParam("templateId") @ApiParam(value = "templateId") final Long templateId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteTemplate(templateId).build(); @@ -235,4 +249,4 @@ public class TemplatesApiResource { parametersMap.putAll(result); return this.templateMergeService.compile(template, parametersMap); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/template/api/TemplatesApiResourcesSwagger.java b/fineract-provider/src/main/java/org/apache/fineract/template/api/TemplatesApiResourcesSwagger.java index a114c2ffb..702b56e28 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/template/api/TemplatesApiResourcesSwagger.java +++ b/fineract-provider/src/main/java/org/apache/fineract/template/api/TemplatesApiResourcesSwagger.java @@ -27,15 +27,18 @@ import org.apache.fineract.template.domain.TemplateMapper; * Created by sanyam on 21/8/17. */ final class TemplatesApiResourcesSwagger { + private TemplatesApiResourcesSwagger() { } @ApiModel(value = "GetTemplatesResponse") public static final class GetTemplatesResponse { + private GetTemplatesResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Text") @@ -52,9 +55,11 @@ final class TemplatesApiResourcesSwagger { @ApiModel(value = "GetTemplatesTemplateResponse") public static final class GetTemplatesTemplateResponse { + private GetTemplatesTemplateResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Text") @@ -71,9 +76,11 @@ final class TemplatesApiResourcesSwagger { @ApiModel(value = "PostTemplatesRequest") public static final class PostTemplatesRequest { + private PostTemplatesRequest() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Text") @@ -90,9 +97,11 @@ final class TemplatesApiResourcesSwagger { @ApiModel(value = "PostTemplatesResponse") public static final class PostTemplatesResponse { + private PostTemplatesResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; @@ -100,9 +109,11 @@ final class TemplatesApiResourcesSwagger { @ApiModel(value = "GetTemplatesTemplateIdResponse") public static final class GetTemplatesTemplateIdResponse { + private GetTemplatesTemplateIdResponse() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Text") @@ -119,9 +130,11 @@ final class TemplatesApiResourcesSwagger { @ApiModel(value = "PutTemplatesTemplateIdRequest") public static final class PutTemplatesTemplateIdRequest { + private PutTemplatesTemplateIdRequest() { } + @ApiModelProperty(example = "1") public Long id; @ApiModelProperty(example = "Text") @@ -138,9 +151,11 @@ final class TemplatesApiResourcesSwagger { @ApiModel(value = "PutTemplatesTemplateIdResponse") public static final class PutTemplatesTemplateIdResponse { + private PutTemplatesTemplateIdResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; @@ -148,9 +163,11 @@ final class TemplatesApiResourcesSwagger { @ApiModel(value = "DeleteTemplatesTemplateIdResponse") public static final class DeleteTemplatesTemplateIdResponse { + private DeleteTemplatesTemplateIdResponse() { } + @ApiModelProperty(example = "1") public Long resourceId; diff --git a/fineract-provider/src/main/java/org/apache/fineract/template/domain/Template.java b/fineract-provider/src/main/java/org/apache/fineract/template/domain/Template.java index 54f165d6d..4a25a2868 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/template/domain/Template.java +++ b/fineract-provider/src/main/java/org/apache/fineract/template/domain/Template.java @@ -40,7 +40,7 @@ import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; import org.codehaus.jackson.map.annotate.JsonSerialize; @Entity -@Table(name = "m_template", uniqueConstraints = {@UniqueConstraint(columnNames = {"name"}, name = "unq_name")}) +@Table(name = "m_template", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "unq_name") }) public class Template extends AbstractPersistableCustom { @Column(name = "name", nullable = false, unique = true) @@ -59,14 +59,12 @@ public class Template extends AbstractPersistableCustom { @OrderBy(value = "mapperorder") @OneToMany(targetEntity = TemplateMapper.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinTable(name="m_template_m_templatemappers", - joinColumns={@JoinColumn(name="m_template_id", referencedColumnName="id")}, - inverseJoinColumns={@JoinColumn(name="mappers_id", referencedColumnName="id", unique=true)} - ) + @JoinTable(name = "m_template_m_templatemappers", joinColumns = { + @JoinColumn(name = "m_template_id", referencedColumnName = "id") }, inverseJoinColumns = { + @JoinColumn(name = "mappers_id", referencedColumnName = "id", unique = true) }) private List mappers; - public Template(final String name, final String text, - final TemplateEntity entity, final TemplateType type, + public Template(final String name, final String text, final TemplateEntity entity, final TemplateType type, final List mappers) { this.name = StringUtils.defaultIfEmpty(name, null); this.entity = entity; @@ -75,24 +73,21 @@ public class Template extends AbstractPersistableCustom { this.mappers = mappers; } - protected Template() { - } + protected Template() {} public static Template fromJson(final JsonCommand command) { final String name = command.stringValueOfParameterNamed("name"); final String text = command.stringValueOfParameterNamed("text"); - final TemplateEntity entity = TemplateEntity.values()[command - .integerValueSansLocaleOfParameterNamed("entity")]; - final int templateTypeId = command - .integerValueSansLocaleOfParameterNamed("type"); + final TemplateEntity entity = TemplateEntity.values()[command.integerValueSansLocaleOfParameterNamed("entity")]; + final int templateTypeId = command.integerValueSansLocaleOfParameterNamed("type"); TemplateType type = null; switch (templateTypeId) { - case 0 : + case 0: type = TemplateType.DOCUMENT; - break; - case 2 : + break; + case 2: type = TemplateType.SMS; - break; + break; } final JsonArray array = command.arrayOfParameterNamed("mappers"); @@ -100,10 +95,9 @@ public class Template extends AbstractPersistableCustom { final List mappersList = new ArrayList<>(); for (final JsonElement element : array) { - mappersList.add(new TemplateMapper(element.getAsJsonObject() - .get("mappersorder").getAsInt(), element.getAsJsonObject() - .get("mapperskey").getAsString(), element.getAsJsonObject() - .get("mappersvalue").getAsString())); + mappersList.add(new TemplateMapper(element.getAsJsonObject().get("mappersorder").getAsInt(), + element.getAsJsonObject().get("mapperskey").getAsString(), + element.getAsJsonObject().get("mappersvalue").getAsString())); } return new Template(name, text, entity, type, mappersList); @@ -156,4 +150,4 @@ public class Template extends AbstractPersistableCustom { public void setText(final String text) { this.text = text; } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateEntitySerializer.java b/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateEntitySerializer.java index 87eb2ae78..de0bdc182 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateEntitySerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateEntitySerializer.java @@ -27,8 +27,8 @@ import org.codehaus.jackson.map.SerializerProvider; public class TemplateEntitySerializer extends JsonSerializer { @Override - public void serialize(final TemplateEntity value, final JsonGenerator generator, @SuppressWarnings("unused") final SerializerProvider provider) - throws IOException, JsonProcessingException { + public void serialize(final TemplateEntity value, final JsonGenerator generator, + @SuppressWarnings("unused") final SerializerProvider provider) throws IOException, JsonProcessingException { generator.writeStartObject(); generator.writeFieldName("id"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateFunctions.java b/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateFunctions.java index 513c570c7..76a66eee6 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateFunctions.java +++ b/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateFunctions.java @@ -30,4 +30,4 @@ public class TemplateFunctions { return dateFormat.format(date); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateTypeSerializer.java b/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateTypeSerializer.java index a6bb454d2..f6460e2a1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateTypeSerializer.java +++ b/fineract-provider/src/main/java/org/apache/fineract/template/domain/TemplateTypeSerializer.java @@ -27,8 +27,8 @@ import org.codehaus.jackson.map.SerializerProvider; public class TemplateTypeSerializer extends JsonSerializer { @Override - public void serialize(final TemplateType value, final JsonGenerator generator, @SuppressWarnings("unused") final SerializerProvider provider) - throws IOException, JsonProcessingException { + public void serialize(final TemplateType value, final JsonGenerator generator, + @SuppressWarnings("unused") final SerializerProvider provider) throws IOException, JsonProcessingException { generator.writeStartObject(); generator.writeFieldName("id"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/template/exception/TemplateNotFoundException.java b/fineract-provider/src/main/java/org/apache/fineract/template/exception/TemplateNotFoundException.java index fd742f991..5840cd025 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/template/exception/TemplateNotFoundException.java +++ b/fineract-provider/src/main/java/org/apache/fineract/template/exception/TemplateNotFoundException.java @@ -25,4 +25,4 @@ public class TemplateNotFoundException extends AbstractPlatformResourceNotFoundE public TemplateNotFoundException(final Long id) { super("error.msg.template.id.invalid", "Template with identifier " + id + " does not exist", id); } -} \ No newline at end of file +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/template/service/JpaTemplateDomainService.java b/fineract-provider/src/main/java/org/apache/fineract/template/service/JpaTemplateDomainService.java index 21f67b577..cb6e9efe4 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/template/service/JpaTemplateDomainService.java +++ b/fineract-provider/src/main/java/org/apache/fineract/template/service/JpaTemplateDomainService.java @@ -54,8 +54,7 @@ public class JpaTemplateDomainService implements TemplateDomainService { @Override public Template findOneById(final Long id) { - return this.templateRepository.findById(id) - .orElseThrow(() -> new TemplateNotFoundException(id)); + return this.templateRepository.findById(id).orElseThrow(() -> new TemplateNotFoundException(id)); } @Transactional @@ -68,14 +67,12 @@ public class JpaTemplateDomainService implements TemplateDomainService { final Template template = Template.fromJson(command); this.templateRepository.saveAndFlush(template); - return new CommandProcessingResultBuilder().withEntityId( - template.getId()).build(); + return new CommandProcessingResultBuilder().withEntityId(template.getId()).build(); } @Transactional @Override - public CommandProcessingResult updateTemplate(final Long templateId, - final JsonCommand command) { + public CommandProcessingResult updateTemplate(final Long templateId, final JsonCommand command) { // FIXME - no validation here of the data in the command object, is // name, text populated etc // FIXME - handle cases where data integrity constraints are fired from @@ -84,36 +81,31 @@ public class JpaTemplateDomainService implements TemplateDomainService { final Template template = findOneById(templateId); template.setName(command.stringValueOfParameterNamed(PROPERTY_NAME)); template.setText(command.stringValueOfParameterNamed(PROPERTY_TEXT)); - template.setEntity(TemplateEntity.values()[command - .integerValueSansLocaleOfParameterNamed(PROPERTY_ENTITY)]); - final int templateTypeId = command - .integerValueSansLocaleOfParameterNamed(PROPERTY_TYPE); + template.setEntity(TemplateEntity.values()[command.integerValueSansLocaleOfParameterNamed(PROPERTY_ENTITY)]); + final int templateTypeId = command.integerValueSansLocaleOfParameterNamed(PROPERTY_TYPE); TemplateType type = null; switch (templateTypeId) { - case 0 : + case 0: type = TemplateType.DOCUMENT; - break; - case 2 : + break; + case 2: type = TemplateType.SMS; - break; + break; } template.setType(type); final JsonArray array = command.arrayOfParameterNamed("mappers"); final List mappersList = new ArrayList<>(); for (final JsonElement element : array) { - mappersList.add(new TemplateMapper(element.getAsJsonObject() - .get("mappersorder").getAsInt(), element.getAsJsonObject() - .get("mapperskey").getAsString(), element.getAsJsonObject() - .get("mappersvalue").getAsString())); + mappersList.add(new TemplateMapper(element.getAsJsonObject().get("mappersorder").getAsInt(), + element.getAsJsonObject().get("mapperskey").getAsString(), + element.getAsJsonObject().get("mappersvalue").getAsString())); } template.setMappers(mappersList); this.templateRepository.saveAndFlush(template); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withEntityId(template.getId()).build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(template.getId()).build(); } @Transactional @@ -123,8 +115,7 @@ public class JpaTemplateDomainService implements TemplateDomainService { this.templateRepository.delete(template); - return new CommandProcessingResultBuilder().withEntityId(templateId) - .build(); + return new CommandProcessingResultBuilder().withEntityId(templateId).build(); } @Transactional @@ -134,8 +125,7 @@ public class JpaTemplateDomainService implements TemplateDomainService { } @Override - public List